text:
Q: How to save and retrieve Gorm's many2many relationship using Go I want to create a rest API to manage casts using Gorm and Gin. When I add a relation between two of my models and submitting those items to the API, I cannot make that expected relationship between those. and the BornLocations and Nationalities fields are null. Have I missed something here?
My question is: How can I store and retrieve that relationship in my responses?
My Models:
type Cast struct {
    ID            string    `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
    FullName      string    `gorm:"size:150;not null" json:"full_name"`
    NickNames     string    `gorm:"size:250;null;" json:"nick_names"`
    BornLocation  Country   `gorm:"many2many:CastBornLocation;association_foreignkey:ID;foreignkey:ID" json:"born_location"`
    Nationalities []Country `gorm:"many2many:Castnationalities;association_foreignkey:ID;foreignkey:ID" json:"cast_nationalities"`
    MiniBio       string    `gorm:"size:1000;null;" json:"mini_bio"`
    UserRefer     string
}

type Country struct {
    ID        string    `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
    Title     string    `gorm:"size:100;not null" json:"title"`
    CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
    UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
}

And here is the controller:
func (server *Server) CreateCast(c *gin.Context) {
    errList = map[string]string{}

    item := models.Cast{}
    err = json.Unmarshal(body, &item)
    if err != nil {
        errList["Unmarshal_error"] = "Cannot unmarshal body"
        c.JSON(http.StatusUnprocessableEntity, gin.H{
            "status": http.StatusUnprocessableEntity,
            "error":  errList,
        })
        return
    }

    // check the token
    uid, err := auth.ExtractTokenID(c.Request)
    if err != nil {
        errList["Unauthorized"] = "Unauthorized"
        c.JSON(http.StatusUnauthorized, gin.H{
            "status": http.StatusUnauthorized,
            "error":  errList,
        })
        return
    }

    user := models.User{}
    err = server.DB.Debug().Model(models.User{}).Where("id = ?", uid).Take(&user).Error
    if err != nil {
        errList["Unauthorized"] = "Unauthorized"
        c.JSON(http.StatusUnauthorized, gin.H{
            "status": http.StatusUnauthorized,
            "error":  errList,
        })
        return
    }

    item.UserRefer = uid
    item.Prepare()
    errorMessages := item.Validate("")
    if len(errorMessages) > 0 {
        errList = errorMessages
        c.JSON(http.StatusUnprocessableEntity, gin.H{
            "status": http.StatusUnprocessableEntity,
            "error":  errList,
        })
        return
    }

    itemCreated, err := item.SaveCast(server.DB) //Saving the cast!

    if err != nil {
        formattedError := formaterror.FormatError(err.Error())
        errList = formattedError
        c.JSON(http.StatusInternalServerError, gin.H{
            "status": http.StatusInternalServerError,
            "error":  errList,
        })
        return
    }
    c.JSON(http.StatusCreated, gin.H{
        "status":   http.StatusCreated,
        "response": itemCreated,
    })
}

And this is the JSON body I'm submitting to the API:
{
    "full_name": "Cast full_name",
    "nick_names": "nickname1, nickname2",
    "born_location": {
        "ID" :"caf2d6af-c360-4777-85d4-32541094b8be"
    },
    "cast_nationalities": [
        {
        "ID" :"caf2d6af-c360-4777-85d4-32541094b8be"
        },
        {
        "ID" :"064058f4-f4ea-4d28-ad22-f9cf92df3513"
        }
    ],
    "mini_bio": "this is the mini bio of the cast"
}

And now, this is the response:
{
    "response": {
        "ID": "09f6a184-9b6e-4487-85f0-c2dbbce7ee5b",
        "full_name": "Cast full_name",
        "nick_names": "nickname1, nickname2",
        "born": "",
        "born_location": {
            "ID": "e5c431ed-3158-4532-81b6-52d78e5539dc",
            "title": "",
            "created_at": "2020-07-16T13:23:32.579892866Z",
            "updated_at": "2020-07-16T13:23:32.578216004Z",
            "UserRefer": ""
        },
        "cast_nationalities": [
            {
                "ID": "caf2d6af-c360-4777-85d4-32541094b8be",
                "title": "",
                "created_at": "0001-01-01T00:00:00Z",
                "updated_at": "2020-07-16T13:23:32.580620065Z",
                "UserRefer": ""
            },
            {
                "ID": "064058f4-f4ea-4d28-ad22-f9cf92df3513",
                "title": "",
                "created_at": "0001-01-01T00:00:00Z",
                "updated_at": "2020-07-16T13:23:32.58249818Z",
                "UserRefer": ""
            }
        ],
        "mini_bio": "this is the mini bio of the cast",
        "bio": "",
        "avatar": "",
        "height": "",
        "weight": "",
        "created_at": "2020-07-16T13:23:32.576892187Z",
        "updated_at": "2020-07-16T13:23:32.576892346Z",
        "UserRefer": "c0223913-8679-4103-bcb6-66db0b2fed21"
    },
    "status": 201
}

And this is the controller and response for getting all the casts:
func (server *Server) GetCasts(c *gin.Context) {
    //clear previous error if any
    errList = map[string]string{}
    item := models.Cast{}

    // check the token
    uid, err := auth.ExtractTokenID(c.Request)
    if err != nil {
        errList["Unauthorized"] = "Unauthorized"
        c.JSON(http.StatusUnauthorized, gin.H{
            "status": http.StatusUnauthorized,
            "error":  errList,
        })
        return
    }

    items, err := item.FindCasts(server.DB, uid)
    if err != nil {
        errList["No_Items"] = "No Items Found"
        c.JSON(http.StatusInternalServerError, gin.H{
            "status": http.StatusInternalServerError,
            "error":  errList,
        })
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "status":   http.StatusOK,
        "response": items,
    })
}

func (u *Cast) FindCasts(db *gorm.DB, uid string) (*[]Cast, error) {
    var err error
    casts := []Cast{}
    err = db.Debug().Model(&Cast{}).Where("user_refer = ?", uid).Limit(100).Find(&casts).Error
    if err != nil {
        return &[]Cast{}, err
    }
    return &casts, err
}

And the final response for the casts:
{
    "response": [
        {
            "ID": "09f6a184-9b6e-4487-85f0-c2dbbce7ee5b",
            "full_name": "Cast full_name",
            "nick_names": "nickname1, nickname2",
            "born": "",
            "born_location": {
                "ID": "",
                "title": "",
                "created_at": "0001-01-01T00:00:00Z",
                "updated_at": "0001-01-01T00:00:00Z",
                "UserRefer": ""
            },
            "nationalities": null,
            "mini_bio": "this is the mini bio of the cast",
            "bio": "",
            "avatar": "",
            "height": "",
            "weight": "",
            "created_at": "2020-07-16T13:23:32.576892Z",
            "updated_at": "2020-07-16T13:23:32.576892Z",
            "UserRefer": "c0223913-8679-4103-bcb6-66db0b2fed21"
        }
    ],
    "status": 200

A: For fetching data you can use preload child data in gorm
err = db.Preload("BornLocation").Preload("Nationalities").Model(&Cast{})
                  .Where("user_refer = ?", uid).Limit(100).Find(&casts).Error

Or you can use flag
db.Set("gorm:auto_preload", true).Find(&casts).Error

Here you BornLocation seems like OneToMany you can do like this
type Cast struct {
    ...
    BornLocationId string
    BornLocation   Country   `gorm:"association_foreignkey:ID;foreignkey:BornLocationId" json:"born_location"`
    ...
}

A: I found the issue! for this specific issue, I had to add two things.
First, I had to add the relation identifier in the model's prepare function.
u.BornLocation = Country{}

Then, to save the cast entity, I had to change it to:
func (u *Cast) SaveCast(db *gorm.DB) (*Cast, error) {
    var err error
    err = db.Debug().Create(&u).Error
    if err != nil {
        return &Cast{}, err
    }
    if u.ID != 0 {
        err = db.Debug().Model(&Country{}).Where("id = ?", u.BornLocationId).Take(&u.Country).Error
        if err != nil {
            return &Cast{}, err
        }
    }
    return u, nil
}

And now, for retrieving all the entities:
err = db.Set("gorm:auto_preload", true).Find(&casts).Error


text:
Q: Reusable timer class I want to write a timer class that I can use from different activities. This will display a countdown time in the calling activity's TextView.
There are examples of timers on the web but I can't find one that does this very elegantly.
Also, I can't see how to use RunOnUiThread from a common class; whenever I try this based on a Context I get "Context does not contain a definition for RunOnUiThread...".
This is my most recent attempt:
public class myActivity : Activity
{
    private Timer _timer;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.myPage);

        var outputTextView = FindViewById<TextView>(Resource.Id.lblTimer);
        _timer = new Timer(this, outputTextView, 2, 0, 0); // 2 hours, 0 mins, 0 secs

        // define click events now...
    }
}

The class:
public class Timer
{
    private TextView _display;
    private Context _context;

    public bool Active { get; set; }

    public Timer(Context context, TextView display, int hours = 2, int minutes = 0, int seconds = 0)
    {
        _context = context;
        _display = display;
        Active = true;
        StartTimer(hours, minutes, seconds);
    }

    private async void StartTimer(int hours, int mins, int secs)
    {
        while (hours > 0 && _minutes > 0 && secs > 0 & Active)
        {
            await Task.Delay(1000);
            secs -= 1;
            if(secs<0)
            {
                secs += 60;
                mins -= 1;
                if(mins<0)
                {
                    mins += 60;
                    hours -= 1;
                }
            }
            _context.RunOnUiThread(() => _display.Text = $"{hours}:{mins}:{secs}");
        }
    }
}

I appreciate I must be doing this wrong. How should it be done?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Arc parameter equation So, I have the function $y=-x^2+3$, and I'm to generate the parametric equation for the arc that is above $y=x$. I got from $-x^2+3>x$ to  $\frac{1-\sqrt{13}}{-2}<x<\frac{1+\sqrt{13}}{-2}$, but I'm not sure how to proceed from here.

A: Now use the parametrization $(x, -x^2+3)$, and you are done.


text:
Q: ARM-GAS: how to load address of static array defined in some c-file (PIC and regular code) I have some simple static array defined in c-file (const int data_input[1024];)and I need to access it from my assembly code. What's the right way to do it?
So far, I've been doing it this way:

.global data_input

data_input_ptr:
    .word data_input

my_function:
    adr r1, data_input_ptr
    bx lr

AFAIK, adr is pseudo-op stands to ldr r1, =data_input_ptr or something like that.
To me the way I do it seems not to be very correct: first of all that adr r1, data_input might potentially use pc relative addressing directly if it detected at link time that it's possible.
Another issue is about PIC: what if the code has to be position independent. How then does it work if value of data_input_ptr has to be initialized by the loader (am I correct about that?)

A: The way you are doing it should work, but another way of handling it would be to use the address of the array as a second argument to the assembly function. Something like this:
Call from c-file:
my_function(original_argument, data_input);

my_function.h:
void my_function(void *original_argument, int *array_address);

my_function.S:
my_function:
    /* r1 already contains data_input_ptr since second argument ends up in r1 */
    bx lr


text:
Q: Immersion from sphere to $ \Bbb{R}^{n +1}$. Let $S^n=\{(x_1,\dots,x_{n+1})∈ \Bbb{R}^{n+1}\mid x_1^2+\cdots+x_{n+1}^2=1\}$.
There is natural inclusion from $S^n$ to $ \Bbb{R}^{n +1}$.
 I want to prove this natural inclusion is immersion.
I want to prove this by calculating rank of Jacobi matrix.
But I'm having trouble because I cannot figure out what the Jacobi matrix is.
Thank you for your help.

A: Fix one of the $2(n+1)$ charts of one of the most natural atlants of $S^n$:
$$\phi_i^+\colon U_i^+:=\{x_i>0\} \to B(0,1)\subseteq \mathbb{R}^{n} \text{ by sending } (x_1,\dots, x_{n+1})\mapsto (x_1,\dots \hat{x_i} \dots, x_{n+1})$$
The inverse map sends
$$(t_1,\dots ,t_n)\mapsto (t_1,\dots, \sqrt{1-(t_1^2+\dots t_n^2)}, \dots , t_n)$$
Now that you fixed the atlant, then the inclusion function $i\colon S^n\to \mathbb{R}^{n+1}$ will be locally with respect to the charts $\phi_i^+$
$i\circ (\phi_i^+)^{-1}\colon B(0,1)\to \mathbb{R}^{n+1}$ by sending
$$(t_1,\dots ,t_n)\mapsto (t_1,\dots, \sqrt{1-(t_1^2+\dots t_n^2)}, \dots , t_n)$$
The Jacobian of the function is
$$J=\begin{pmatrix}
1 & \dots &  0\\
0 & 1 & \dots  \\
\dots  & \dots  \\
\frac{-2t_1}{\sqrt{1-(t_1^2+\dots t_n^2)}} & \dots & \dots
\frac{-2t_n}{\sqrt{1-(t_1^2+\dots t_n^2)}}\\
\dots & \dots \\
0& 0 \dots  &1\\
\end{pmatrix}$$
Of course $rk(J)=n$, that shows the differential is injective for any point $U_i^+$ of the chart. You can prove this for each of the $2(n+1)$ charts that cover $S^n$. Hence $i$ is an immersion.


text:
Q: Get Network Interface Names and Set All to DHCP Batch Script I am trying to make a batch that will get all of the Network Interface names (ex. 'Local Area Connection', 'Local Area Connection 2') and set them to DHCP.
This is what I have so far:
set netsh=wmic nic where "netconnectionid like '%%'" get netconnectionid

for %%i in ("%netsh% | FIND /V 'Net'") do (netsh interface ip set address "%%i" dhcp)

My output is:

The filename, directory name, or volume label syntax is incorrect.

Can anyone assist me in fixing this script, or proposing a better way to go about this please?

A: Will this do what you need?
WMIC NICConfig Where "IPEnabled='True' And DHCPEnabled='False'" Call EnableDHCP


text:
Q: How to build an Ionic app without the scroll I am building an Ionic app, but once the page is getting bigger, the app presents an scroll, there is any way to remove the scroll and let the app more native like?
My code has only 2 slides with some products description and category.

A: "Ionic Lab" is a deprecated desktop application, sunsetted in 2016. the Ionic CLI command "ionic serve" lets you serve the app locally in a browser. So it appears you're previewing your application in a web browser. When doing this, it's not going to appear or behave exactly as it will on a real mobile device. If you run a build, open your app in Xcode and test in the iOS simulator, you'll most likely see that no scrollbar is visible.
Testing locally in a browser with ionic serve is very practical and useful but the preview should not be believed to be a 100% accurate native preview.


text:
Q: Azure App Services throws database not found when doing a retrieval I have Azure App services in my Xamarin application, and everything was working 100% until this morning.
After a while, I found, what looks like the SDK removing my database from local storage, as soon as I do the .GetSyncTable() call.
My service looks like this:
private readonly IMobileServiceSyncTable<User> _table;
private readonly IMobileServiceClient _client;
private readonly MobileServiceSQLiteStore _store;
private readonly ICryptography _cryptography;
private readonly ISettings _settings;

public UserService(
    IMobileServiceClient client,
    ICryptography cryptography)
{
    _client = client;
    _cryptography = cryptography;
    _settings = new Settings(cryptography) as ISettings;

    _store = new MobileServiceSQLiteStore(Settings.SyncDb);
    _store.DefineTable<User>();

    _client.SyncContext.InitializeAsync(_store);

    _table = _client.GetSyncTable<User>();
}

and then I do an "All()", which looks like this:
public async Task<List<User>> All()
{
    try
    {
        var users = await _table.ToListAsync(); // <- this throws "table" not defined
        return users;
    }
    catch (SQLiteException sqlex)
    {
        Log.Warning("UserService", sqlex.Message);
    }
    catch (Exception ex)
    {
        Log.Warning("UserService", ex.Message);
    }
}

I have been trying to figure this out, and I'm nowhere closer to a solution.
During my debug, if I land my debugger on the await, and interrogate the _store variable, my "user" table is defined, then a few seconds later, _store no longer contains my table.
I used ADB to download the local store, and viewed it in a SQLite manager, and the table is indeed defined, just, for some reason, it gets "lost"?
Any ideas would be greatly appreciated.

A: Per my understanding, the issue may caused by the InitializeAsync has not been initialized correctly. You just called _client.SyncContext.InitializeAsync(_store); in the constructor of UserService class. And you need to invoke await _client.SyncContext.InitializeAsync(_store); for initializing the store.
The common Offline Sync Initialization would look as follows:
async Task InitializeAsync()
{
     // Short circuit - local database is already initialized
     if (Client.SyncContext.IsInitialized)
         return;

     // Create a reference to the local sqlite store
     var store = new MobileServiceSQLiteStore("offlinecache.db");

     // Define the database schema
     store.DefineTable<TodoItem>();

     // Actually create the store and update the schema
     await Client.SyncContext.InitializeAsync(store);
}

Here is a similar issue about wrapping the operations against Azure Cloud Table. Moreover, you could follow adrian hall's book about An Offline Client.


text:
Q: How Chadwick concluded that the particles are neutrons but not photons? James Chadwick conducted an experiment in which he bombarded Beryllium with alpha particles from the natural radioactive decay of Polonium. How he concluded that the radiation was made up of neutrons and not photons?

A: The WP article I linked summarizes that

In 1931, Walther Bothe and Herbert Becker found that if alpha particle radiation from polonium fell on beryllium, boron, or lithium, an unusually penetrating radiation was produced. The radiation was not influenced by an electric field, so Bothe and Becker assumed it was gamma radiation. The following year Irène Joliot-Curie and Frédéric Joliot-Curie in Paris showed that if this "gamma" radiation fell on paraffin, or any other hydrogen-containing compound, it ejected protons of very high energy.  Neither Rutherford nor James Chadwick at the Cavendish Laboratory in Cambridge were convinced by the gamma ray interpretation.  Chadwick quickly performed a series of experiments that showed that the new radiation consisted of uncharged particles with about the same mass as the proton.

I boldfaced the crucial observation. High energy means MeVs, and at the time physicists were only familiar with X/γ-ray photons scattering off light electrons relativistically, as in the Compton effect. If you think of electrons as bees, mass-wise, you may think of the proton (the Hydrogen nucleus) as a large billiard  ball, and the Nitrogen  nucleus as a bowling ball, 14 times heavier. So his experiments concluded that the effects of the uncharged projectiles were very energetic, but,  by the high-school physics non-relativistic elastic collision argument below, they obeyed classical physics of a heavy object (at the time!). He estimated its mass to be about that of the proton, the billiard ball, as he says in his paper and his Nobel lecture linked above:

Let us suppose that the radiation consists of particles of mass M moving with velocities up to a maximum velocity V. Then the maximum velocity which can be imparted to a hydrogen atom, mass 1, by the impart of such a particle will be
$$
U_p={2M\over M+1} V
$$
and the maximum velocity imparted to a nitrogen atom will be $$ U_n= {2M\over M+14 }V $$
Then $$\frac{M+14}{M+1}=\frac{U_p}{U_n} $$
The velocities $U_p$ and $U_n$  were found by experiment. The maximum range of the protons ejected from paraffin wax was measured and also the ranges of the recoil atoms produced in an expansion chamber filled with nitrogen. From these ranges the velocities $U_p$ and $U_n$ can be deduced approximately:  $U_p\approx 3.7 \times 10^9$ cm/sec, $U_n\approx  4.7 \times  10^8 $cm/sec. Thus we find M = 0.9. We must conclude that the beryllium radiation does in fact consist of particles, and that these particles have a mass about the same as that of a proton.

The velocities are 1% and 0.1% of the speed of light, respectively, so quite non-relativistic.
The first two formulas are derivable from 9th grade physics, from classical energy & momentum conservation in an elastic billiard-ball to billiard-ball collision, and billiard-ball to bowling ball collision, respectively.


text:
Q: Nginx compressing 5B data to 1.03 KB how to discard this compression? I have used gzip compression in my Nginx with compression level 9.
Then I can see 5B data is compressed to  1KB?
Could not know the reason and how to avoid to discard compress for less than 10B ?
Firefox Origianl and Compressed size ration

A: You can use gzip_min_length directive to avoid compressing small objects. Default minimal size is 20.


text:
Q: Why fsize variable is cleared if global? I am trying to calculate the shannon entropy of a file in python.
So, I have written the following code to achieve this.
But  it doesn't work as expected.
I think all is right, but the fsize variable is cleared.
I don't understand why because it holds global scope.
Can you give a hand or explanation ?
Thanks
from __future__ import division
import sys
import os
import math

def get_chunks(file_size, chunk_size = 4096):

    chunk_start = 0

    while chunk_start + chunk_size < file_size:
        yield(chunk_start, chunk_size)
        chunk_start += chunk_size

    final_chunk_size = file_size - chunk_start
    yield(chunk_start, final_chunk_size)

def read_file_chunked(file_path):

    file_size = os.path.getsize(file_path)
    fsize = file_size # <------------------------------this var
    print('File size: {}'.format(file_size))

    with open(file_path,'rb') as file_:

        progress = 0

        for chunk_start, chunk_size in get_chunks(file_size):

            file_chunk = file_.read(chunk_size)

            # byte count
            for b in file_chunk:
                freqs[ord(b)]+=1

            progress += len(file_chunk)
            print '{0} of {1} bytes read ({2}%)'.format( progress, file_size, int(progress / file_size * 100))

        #calculate the frequency of each byte
        for idx, f in enumerate(freqs):
            freqs[idx] = float(f / file_size)
        print

freqs = [0] * 256
fsize = 0 #<------------------ this var

if len(sys.argv) != 2:
    print "Usage entropy [file]"
    sys.exit()

if __name__ == '__main__':

    read_file_chunked(sys.argv[1])

    # print byte frequencies
    for idx,f in enumerate(freqs):
        print hex(idx),f

    # calculate Shannon entropy
    ent = 0.0
    for f in freqs:
        if f > 0:
            ent += f * math.log(f,2)
    ent = -ent

    print 'Shannon entropy ( min bits per byte-character )'
    print ent
    print
    print 'Min possible file size assuming max compression efficiency'
    print (ent * fsize), ' in bits' #------------------- here fsize is 0
    print (ent * fsize) / 8, ' in bytes' #-------------- here fsize is 0

A: assigning to fsize in read_file_chunked creates a new local variable that is deleted when the function returns. In order to assign to the global variable fsize, declare it explicitly as such:
def read_file_chunked(file_path):
    global fsize
    file_size = os.path.getsize(file_path)
    fsize = file_size # <------------------------------this var

Alternatively, have read_file_chunked return the file size.

A: In your read_file_chunked function you are creating a new variable fsize within the scope of the function, you don't modify your global variable at all. Consider the following demonstration:
>>> x = 0
>>> def foo():
...     x = 1
...
>>> foo()
>>> x
0

What you are missing to make that piece of code work the way you intend to is the global keyword:
>>> x = 0
>>> def foo():
...     global x
...     x = 1
...
>>> foo()
>>> x
1

Having said that I question your usage of the global variable. Why don't you just return fsize from your function?


text:
Q: Match all words with a specific length I want to make a regex that matches all words with a specific length.
Example of the string I have:
"I ABCDE FGH IG KLMNOPQ RS T"
I want to match all words having length less than 3 letters (In this case I, IG, RS and T).
Here are the alternatives that I made:
Alt1:
Regex: ( |^)([A-Z]{1,2})( |$): Link1
Explanation: Matching any word with a length of 2 or 1 uppercase letters that is preceded by a space or in the beginning of the string (( |^)) and followed by a space or at the end of the string (( |$)).
The problem is that I get positive match for the blank spaces which I don't want. And I don't get match for the T.
Alt2:
Regex: \w{1,2}\b: Link2
Explanation:

match a word of at most 2 characters as long as its the only contents of the string
  (I found it in this answer)

The problem is that I get matches of every last 2 letters from every word (DE, GH and PQ) which is wrong in my case.

A: You're close! Just add a \b boundary to the front as well:
\b\w{1,2}\b

Matches:
I ABCDE FGH IG KLMNOPQ RS T
~           ~~         ~~ ~

A: If you have to take the whitespaces into account, you could match 1 or 2 uppercase digits and use lookarounds to assert what is directly on the left and on the right is not a non whitspace char \S
If the uppercase characters are surrounded by for example$AB# they will not be matched.
(?<!\S)[A-Z]{1,2}(?!\S)

Regex demo


text:
Q: Calculated column that ignores row context I'm trying to calculate the Total Price per Order number. It specifically needs to be a column, because I'll be needing it for further calculations.
Can someone help me write code that calculates the total per Order Number, instead of line amount as it does now?

A: Since it's a calcualted column, just avoiding any context transition gives a straightforward solution
Total Price Per Order =
VAR CurrentOrder = SalesDetail[Order Number]
RETURN
    SUMX (
        FILTER (
            SalesDetail,
            SalesDetail[Order Number] = CurrentOrder
        ),
        SalesDetail[Unit Price] * SalesDetail[Quantity]
    )


text:
Q: Cisco CallManager AXL SQL Toolkit - Retrieve directory number and user ID I have the below SQL query to retrieve the list of userid and their telephonenumber using Cisco CallManager AXL SQL Toolkit:
sql query="select d.name as deviceName, e.userid, e.telephonenumber from device d
left outer join endUser e on d.fkenduser=e.pkid where e.telephonenumber is not null"

How can I modify the above query to also retrieve the "Directory Number" of the returned results? I'm not sure what table and column to join!

A: The following query will return the line information:
SELECT d.name AS deviceName, e.userid, e.telephonenumber, n.dnorpattern AS directoryNumber
FROM device d
INNER JOIN enduser e on d.fkenduser=e.pkid
INNER JOIN devicenumplanmap dmap on dmap.fkdevice=d.pkid
INNER JOIN numplan n on dmap.fknumplan=n.pkid

I'm not sure if you know what you're asking for here...  As this returns results based on the association of Owner UserId attribute on the phone (in d.fkenduser). It doesn't show the results of phones associated to end users.  This is mapped in the enduserdevicemap table.  It's not part of your original question, but mentioned for posterity.

A: Can't say for sure, but try to look here:
RUNNING SQL QUERIES ON CUCM 6X/7X USING AXL SOAP TOOLKIT – PART 1

In Query 4 we have two examples of how tables are linked by foreign keys.  The deviceNumPlanMap table is one example of a table that actually joins values from multiple tables.  We can "marry up" the relationship between a phone and a directory number using multiple joins:

 inner join devicenumplanmap as dmap on dmap.fkdevice=d.pkid
       inner join numplan as n on dmap.fknumplan = n.pkid

The numplan table is responsible for storing all digit patterns in the dial plan.  For example, it stores all directory numbers programmed in the system.  You may recall that directory numbers have call forwarding configurations.


text:
Q: playing audio sounds in Cordova application I'm using Cordova media plugin for playing audio sound in my mobile application
I tried many codes but I didn't figure out what I'm doing wrong at the bottom I put two piece of code that I tried them
the first code (js code in a separate file)
   var app = {
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {

        var myMedia = new Media("../sounds/clapping.mp3");
        myMedia.play();

    }
};

app.initialize();

the second code  (js code in a script tag) :
     document.addEventListener("deviceready", function(){

   var myMedia = null;
    function playAudio() {

    var src = "sounds/clapping.mp3";

    if(myMedia === null) {
    myMedia = new Media(src, onSuccess, onError);

    function onSuccess() {
    console.log("playAudio Success");
    }

    function onError(error) {
    console.log("playAudio Error: " + error.code);
    }

    }

    myMedia.play();
    }

    document.getElementById("playAudio").addEventListener("click", playAudio);
    });

with a button :
<button id ="playAudio">PLAY</button>

How can I solve this problem ?

A: Wasted 2 hours on this, sharing it here:
This should not be this difficult. No full example at: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/
Simple step by step details:

*

*Put my file in www:

Example at:  www/audio/button-1.mp3

*Install plugin:
cordova plugin add cordova-plugin-media

*Copy paste code below:
`
  function getFullMediaURL(s) {
    return cordova.file.applicationDirectory + 'www/audio/button-1.mp3'
  }

  function playMP3() {
    let src = getFullMediaURL();
    var myMedia =
      new Media(src,
        function () { },
        function (e) { alert('Media Error: ' + JSON.stringify(e)); }
      );
    myMedia.play();
    myMedia.setVolume('1.0');
  }

`
Step 4: Call below where you need play sound:
playMP3();

A: To answer your question, you can find the working sample of cordova app using Media Plugin in the following github page.
As mentioned in the sample project's README, you gotta install cordova device plugin as well to check the device platform.
Also to clarify the doubt you mentioned in the comment, android_asset refers to the project's root folder.


text:
Q: Creating a template out of HTML Elements lets say i have a parent-div. And in this div-container, i want to display 5 elements which have all the same structure. For example:

Is there a way to make an object or prototype out of it, so i dont have to generate every single HTML Element with their classes and src values with the appendChild-function and Dot-Notations in a for-loop?
Im thinking of something like:
for(let i = 0; i<=5;i++){
var element = new element(class,src1,src2 ...);
}

And the "element" is defined in a external class file or something familiar.
Im a beginner, so please show mercy :)

A: You'll need to clone the node from the template's content. For example:

const templateElement = document.querySelector("#someTemplate")
  .content
  .querySelector(".element");

// create an Array of nodes (so in memory)
const fiveNodes = [];

for (let i = 0; i < 5; i += 1) {
  const nwNode = templateElement.cloneNode(true);
  //                                       ^ clone the whole tree
  nwNode.querySelector("p.name").textContent += ` #${i + 1}`;
  fiveNodes.push(nwNode);
}

// append the nodes to document.body
// this is faster than appending every element in the loop
fiveNodes.forEach(el => document.body.append(el));
<template id="someTemplate">

I am node

</template>


text:
Q: High CPU utilization during oracle group by I had a doubt on oracle group by clause.
Is group by a CPU intensive operation?
We have a query on a table with 32M rows and no index column which does group by on 7-8 columns and aggregates on 3 columns and inserts into another table. Occasionally we are seeing total CPU being utilized by oracle processes as 100%.
The query looks something like this:
insert into temp_table select col1, col2, col3, col4, col5, col6, col7, col8,
 sum(col10), sum(col11), count(*) from orig_table group by col1, col2,
 col3, col4, col5, col6, col7, col8 ;

As far as my understanding goes,
To group by we will have to sort and then group. Will this result in high CPU utilization? Also, what about the aggregates? Can they result in high CPU?
Thanks in advance.

A: The explain plan would be interesting see, as always, and also if you query v$sql_workarea you'll see whether the group by is spilling to disk.
It is not only the number of rows that you are querying that is important, but also the number of rows which will be output and the average column widths for included columns, as this largely determines how much memory is required to perform the aggregation and therefore whether the sort will spill to disk. If it does then you might need increased PGA memory allocation, either set manually or by varying the total PGA size. Check the PGA and SGA buffer advisories to see whether they are in general well sized.
You might also fall victim to recent trends in server technology, which often feature CPU's with many relatively weak cores. Unless you are running parallel query you'll be confined to a single core.

A: You are using an aggregate function. If the table has 32 Million rows and you are attempting to aggregate all values in these columns, what were you expecting Oracle to do?
Sit in an Idle state?
An aggregate on this much data is going to take time!!!
The time taken for the group by clause is dependent on the number of distinct values in columns 1 to 8.
Before the group by is performed, the database would first have to retrieve all values for these columns and then order it "nicely" as you have requested, then insert it. Furthermore the query looks bad in general. Why would you do the aggregate sum on each column, only to potentially lose the value when doing the group by?
E.G if you have duplicate values in columns 1-8 the sum *may * be calculated more than once for no reason.
Since you have provided no explain statement the simple answer is that with this much data being selected the aggregate "would certainly take a significant amount of time" the group by is dependent on your data. I'd be surprised if Oracle were NOT using this much CPU simply based on the number of rows you'd have to go through to retrieve a result from a table with 32Million records.
Without seeing the execution plan it's impossible to say what time is being spent where.


text:
Q: Rotating screen on Fedora I run Fedora 19 under KDE and would want to configure two 27" screens rotated 90 degrees. My problem is that while I can go to:
System Settings -> Display and Monitor
and rotate them 90 degrees, this setting does not work in the login screen. Therefore, my desktop is correctly rotated, but in the login screen I have to bend sideways to look at the screen.
A plus would also be a way to get the output rotated in the text mode console. I'm sure that this won't be doable for the kernel boot output, but once login terminals are loaded I should be able to instruct the framebuffer somehow to rotate the output.

A: I'm not sure exactly what login manager Fedora 19 uses by default - you haven't said which you happen to be using, if not the default. Regardless, I know that the LightDM display manager (Ubuntu's current default) is usable in Fedora, so here is an answer for LightDM. Other login managers should have something equivalent.
With that in mind...
There should be a directory called /etc/lightdm/lightdm.conf.d which is where custom configurations can be stored. You can create a new file in that directory (you'll need to be root) called 20-startup-script.conf:
[SeatDefaults]
display-setup-script=/usr/local/bin/rotate-screen

In the script /usr/local/bin/rotate-screen, you can write a script which rotates the screen, and LightDM will run this script before it displays the login screen. In order to rotate the screen, you'll need to use a tool called xrandr.
You'll have to play around with xrandr on the command line to get an idea of what options you should be using, but you can do something like this:
$ xrandr
Screen 0: ...
LVDS1 connected ...
    1366x768 ...
    ...
VGA1 disconnected ...
....

Names like LVDS1 and VGA1 are output names, and you'll want to keep these in mind. You can figure out which display name corresponds to the monitor you want to rotate by doing the following:
$ xrandr --output LVDS1 --rotate left

If the screen rotates, then you've found the right display name (in this case, LVDS1).
You can then write the following script into /usr/local/bin/rotate-screen (requires root access):
#!/bin/sh
xrandr --output LVSD1 --rotate left

You can then chmod +x /usr/local/bin/rotate-screen (also requires root), and then log out. If you did it correctly, the login screen should be rotated, and LightDM will rotate the screen before every login.


text:
Q: managing resources on a debian server We have a debian server shared by all group members to run their memory/cpu (64GB RAM and 23 cores) intensive codes on it.  The problem is sometime one code overload the whole server and no one else is able to do anything. I want to ask if there is any known solution for that? for example limiting the amount of memory use by each user and killing the process if it goes beyond the limit? any better suggestion?

A: You could have a look in /etc/security/limits.conf. You will be able to limit resources by user or group (ie: max number of opened files, memory limit and so on...).
User will be able to see his "limits" by running ulimit -a. If you specify a soft limit for him, he will be able to change it using this same command.
You can also change the nice priority of their process.
See:
man ulimit
man limits.conf


text:
Q: What do you call the phenomenon where a rectangle □ is shown because a font lacks a glyph? Is there a name to describe the situation where a particular character is shown on a computer screen in a particular font, but this font does not have a glyph for this particular character?
Usually, the result looks like this: □
A kind of empty rectangle. Sometimes it shows the code for that character within the rectangle.

What do yo call this phenomenon?
If there is no name, is there a common term referring to this "rectangle"?
Some Japanese people call this "tofubake" because rectangles look like tofu.
(It is not mojibake. Mojibake happens when character encoding meta-information is lost. It is not the problem here. Using a better font solves this phenomenon, but does not solve mojibake. Selecting a character encoding solves mojibake, but does not solve this phenomenon.)

A: Google calls them 'tofu', too. They have a Google Font called Noto which is named (see the link) for 'no to tofu'.

When text is rendered by a computer, sometimes there will be characters in the text that can not be displayed, because no font that supports them is available to the computer. When this occurs, small boxes are shown to represent the characters. We call those small boxes "tofu," and we want to remove tofu from the Web.

A: Glyph Replacement is too general a description (sorry, Unicode). That could mean that a font replaces 'HEAVY BLACK HEART'❤ with 'BLACK HEART SUIT' ♥ or even ampersand with plus. The phenomenon is not replacement, it is Glyph Failure.  In practice, the □ codepoint is used as a Failure Glyph.

A: The Unicode standard calls it a replacement glyph.


text:
Q: do postback then re-direct to a page I'm trying to do a javascript postback and then re-direct to a different page but it keeps posting back to the current page
Here's my code
$(this).prepend('Check availability »');

And here's my SetSess postback command
Sub SetSess()

Session("TenHolStDateNewCheck") = "%"

response.redirect("searchresults/default.aspx")

End Sub

Anyone got any ideas?
Thanks
Jamie

A: __doPostBack the first parameter populates the __EVENTTARGET parameter...  I could be wrong, but I wasn't aware that it automatically invoked methods.  I think you have to do that yourself by doing in Load event:
if (request.Form["__EVENTTARGET"] = "SetSess") Then
    SetSess()
End if

HTH.

A: You need to have a hidden button link so the page product the permission to accept this post back
    <asp:LinkButton ID="LinkButton1" runat="server"
         onclick="LinkButton1_Click" style="display:none;"></asp:LinkButton>

Then you can call your post back.
__doPostBack('<%=LinkButton1.ClientID%>','');

and your code be something like that.
$(this).prepend('<a class="booknow2 sidelink sidelinkNew"
    href="javascript:__doPostBack(\'<%=LinkButton1.ClientID%>\',\'\')">
    Check availability »');

... and the function on code behind
protected void LinkButton1_Click(object sender, EventArgs e)
{
 // Here the work and the redirect of you
}

Hope this work.

A: I used the jquery ajax function to call a page which set the session and then re-directed
Thanks for the help though


text:
Q: Set up activex combobox in excel always triggers dirty flag I have an activex combobox that is filled as the sheet opens.  However, despite my best efforts it always triggers the dirty flag and asks the user to save even if no changes have been made.  Here is the relevant code:
Private Sub Workbook_Open()
    Application.EnableEvents = False ' => disable events
    'set up dropdown menu on topics tab
    mbEvents = False
    With Sheets("Do Now Topic")
    'Set up combobox1
        With .ComboBox1
            .Clear
            .List = getUniqueArray(Sheets("Questions").Range("D2:D" & LastRow.Row))
            .Text = Sheets("Questions").Cells(Sheets("Questions").Range("A2:A" & LastRow.Row).Find(What:=Sheets("Do Now Topic").Cells(3, 13), LookAt:=xlWhole, SearchDirection:=xlNext, matchCase:=False).Row, 4)
        End With
    End With
    mbEvents = True
    Application.EnableEvents = True ' => enable events
    ActiveWorkbook.Saved = True
End Sub

Here is the event handler for the combobox
Dim RecalculateAll As Boolean

'Combobox change event
Private Sub ComboBox1_Change()
    If Not mbEvents Then
        Exit Sub
    End If

    Sheets("Do Now Topic").Cells(3, 13) = Sheets("Questions").Cells(Sheets("Questions").Range("D2:D" & LastRow.Row).Find(What:=ComboBox1.Value, LookAt:=xlWhole, SearchDirection:=xlNext, matchCase:=False).Row, 1)
    Sheets("Do Now Topic").Cells(3, 16) = Sheets("Questions").Cells(Sheets("Questions").Range("D2:D" & LastRow.Row).Find(What:=ComboBox1.Value, LookAt:=xlWhole, SearchDirection:=xlPrevious, matchCase:=False).Row, 1)

    RecalculateAll = True
    Sheets("Data").Calculate
    Sheets("Do Now Topic").Calculate
    RecalculateAll = False

End Sub

I am not sure why it is setting the dirty flag when the worksheet opens.  It is definitely to do with the combobox though.


text:
Q: What is the proper way to handle image rotations for iphone/ipad? I have 2 images, one in portrait mode, and the other in landscape mode.
What is the best way to switch these images when a mobile device view rotation takes place?
Currently I just display the portrait image. And when the device rotates to landscape mode the portrait image is simply stretched.
Should I be checking within the orientation rotation handler and simply reset the image to the proper orientational image (i.e. set it manually based on the orientation)??
Thanks!

A: I found three ways.I think the last one is better
1: Autoresizing
Example:
UIImageView *myImageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourImage.png"]];
myImageView.frame = self.view.bounds;
myImageView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight
myImageView.contentMode = UIViewContentModeScaleAspectFill;
[self.view addSubview:myImageView];
[imageView release];

2: CGAffineTransformMakeRotation
Example:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                        duration:(NSTimeInterval)duration {
  if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
                myImageView.transform = CGAffineTransformMakeRotation(M_PI / 2);
  }
  else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
                myImageView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
  }
  else {
             myImageView.transform = CGAffineTransformMakeRotation(0.0);
  }
}

3:Set autosizing of myImageView as  auto fill the screen in Interface Builder
Example:
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight)){
    myImageView.image = [UIImage imageNamed:@"myImage-landscape.png"];
} else  if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown)){
    myImageView.image = [UIImage imageNamed:@"myImage-portrait.png"];
} }

see more solutions here
developer.apple solution is here


text: Q: Sending new added Bookmarks from Pixiv through a webhook in a discord channel This is probably going to be the most complex thing that I've ever asked here. As the title says I want to figure a way to automate a webhook which sends my new added bookmarks from my Pixiv Account into a discord channel. I sadly don't know much about coding, only basic things like batch scripts and ahk. I would use ifttt at this point but it doesn't support Pixiv, so I am completely clueless and don't know what to do or where to start. I hope someone has a nice Idea


text:
Q: How to use one filter in install4j FileChooser I'm trying to find a way to start a FileChooser in install4j which filters for a special name.
I've set the option "Use file filter" and set a "File filter name" and a "Filtered file extension" on a FileChooser Form Component.
When opening the dialog during the setup I'm getting two filters:

*

*"All files" as default selection and

*"My Filter" as a second one.

How can I change this behaviour to use my file filter as default?
The filter itself works fine, when I change to it.

A: This is a bug in install4j, which will be fixed in 5.1.7. Please contact support@ej-technologies.com to get an interim build which contains this fix.


text:
Q: C# keeping cookies and sessions across webpages I've tried many examples both here, and from Google and still cannot get my login saved. I've debugged and seen that it sends the 302 redirect and my login is successful. I believe. Then I send it to the next page, but keep the cookies gained from the login response. But I am still logged out. Here is my code aside from urls and login info. I've verified my POST parameters. I ask for the session cookie first, then login then proceed to the redirect page.  All help is majorly appreciated, this is a huge headache.
    HttpWebRequest GetRequest(string Site, CookieContainer Cookies, string SendType)
    {

        HttpWebRequest request = WebRequest.Create(Site) as HttpWebRequest;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
        request.CookieContainer = Cookies; // Assign it some cookies
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = SendType;
        return request;
    }

    private string GetLoggedInPage(string username, string password, string loginPage, string redirectPage)
    {

        string formParams = string.Format("login={0}&password={1}", username, password);

        // cookies to use for multiple requests
        var cookies = new CookieContainer(); // Create cookies!

        var request= GetRequest(loginPage, cookies, "POST");

        //Send params off
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);

        using (Stream loginStream = request.GetRequestStream())
        {
            loginStream.Write(bytes, 0, bytes.Length);
        }

        request.GetResponse().Dispose(); // removed some code here, no need to read response manually

        request= GetRequest(redirectPage, cookies, "GET");

        using (WebResponse getResponse = request.GetResponse())
        {
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                var result = sr.ReadToEnd();//Read logged in webpage
                return  Convert.ToString(result);
            }

        }

        return ""; //Return blank page in case the using above didn't work correctly.

    }

The below code is refactored and working. I followed the advice of KoBE below, but it still wasn't working. The issue turned out to be targeting framework 4.5.2 I targeted the 4.0 and the below functions work. just send GetLoggedInPage your username, pass, and login url and target url and it'll give you a string back. I'm going to turn this into a class and use that.
Remember to save your cookies people!
void WriteParams(string Params, HttpWebRequest webrequestStream)
{
    byte[] bytes = Encoding.ASCII.GetBytes(Params);

    using (Stream requestStream = webrequestStream.GetRequestStream())
    {
        requestStream.Write(bytes, 0, bytes.Length);
    }

}

 HttpWebRequest GetRequest(string Site, ref CookieContainer Cookies, string SendType)
{

    HttpWebRequest request = WebRequest.Create(Site) as HttpWebRequest;
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
    request.CookieContainer = Cookies; // Assign it some cookies
    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = SendType;
    return request;
}

private string GetLoggedInPage(string username, string password, string loginPage, string redirectPage)
{

    string formParams = string.Format("login={0}&password={1}", username, password);

    // cookies to use for multiple requests
    var cookies = new CookieContainer(); // Create cookies!

    HttpWebRequest request= GetRequest(loginPage, ref cookies, "POST");

    //Send params off

    WriteParams(formParams, request);

    request.GetResponse();// .Dispose(); // removed some code here, no need to read response manually

    request= GetRequest(redirectPage, ref cookies, "GET");

    using (WebResponse getResponse = request.GetResponse())
    {
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            var result = sr.ReadToEnd();//Read logged in webpage
            return  Convert.ToString(result);
        }

    }

    return ""; //Return blank page in case the using above didn't work correctly.

}

A: Edit: I've finally looked at your code. Looks like you're simply missing the user-agent. See your modified code at the bottom.
First thing, I would change is this:
var cookies = new CookieContainer(); // Create cookies!
TheRequest.CookieContainer = new CookieContainer();

To this:
var cookies = new CookieContainer(); // Create cookies!
TheRequest.CookieContainer = cookies;

That will prevent you from needing:
foreach (Cookie c in TheResponse.Cookies)//Get response cookie
{
    cookies.Add(c);
}
TheRequest.CookieContainer = cookies;

There is no need to create two cookie containers, then copy from one to the other, only to set the original to the copied version.
I'm not sure, but this could solve your problems depending on how much work the CookieContainer actually does in the background as far as Uri specific cookies, or what have you.
Is https://www.pucatrade.com/dashboard the url you're using? Also, why are you attempting to log in multiple times?
Modified Code

string username = "your-user";
string pass = "your-pass";
string loginPage = "https://pucatrade.com/login";
string redirectPage = "https://pucatrade.com/dashboard";
string formParams = string.Format("login={0}&password={1}", username, pass);

// cookies to use for multiple requests
var cookies = new CookieContainer(); // Create cookies!

var request = WebRequest.Create(loginPage) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
request.CookieContainer = cookies; // Assign it some cookies
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
request.ContentLength = bytes.Length;
using (Stream loginStream = request.GetRequestStream())
{
    loginStream.Write(bytes, 0, bytes.Length);
}

request.GetResponse().Dispose(); // removed some code here, no need to read response manually

request = WebRequest.Create(redirectPage) as HttpWebRequest; //we know we get redirected too here, so just go there.
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
request.CookieContainer = cookies; // Assign it some cookies
request.Method = "GET";

using (WebResponse getResponse = request.GetResponse())
{
    using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
    {
        var result = sr.ReadToEnd();//Read logged in webpage
    }
}


text:
Q: What is the easiest way to develop Firefox extension? I'm planning to develop a simple Firefox extension that will shorten URL of a currently active tab, display a popup with the shortened URL, and place it into the clipboard.
In Google Chrome, this would be pretty easy (according to http://developer.chrome.com/extensions/getstarted.html) -- pure JavaScript plus a few calls to JavaScript API-s of interacting with the browser's UI.
However, after searching around for a good Firefox extensions tutorial, the most officially-looking links I found are:

*

*https://developer.mozilla.org/en-US/docs/Extensions

*https://developer.mozilla.org/en-US/docs/Building_an_Extension

*How do I write a Firefox Addon?
According to them, it looks like I will have to learn the XUL language for even the simplest interactions with the browser's UI. On top of that, I will have to set up custom Firefox profile so as not to hose my default profile during development, create complicated directory structure, write manifest in obscure XML, figure out how to package and test whatever I implement, etc.
It's 2013, isn't there an easier way of building Firefox extensions?

A:
It's 2013, isn't there an easier way of building Firefox extensions?

Yes there is!
The links you provided in the question are unbelievably outdated. There is a new, much better way of developing Firefox extensions -- Firefox Add-on SDK.
However it's pretty hard to stumble upon it by just googling along the lines of 'firefox addon tutorial'. I'm amazed Mozilla doesn't advertise it more aggressively, or at least mention it on those pages you found.
Steps to get started (Mac/Linux, but should be pretty similar for PC):

*

*Download the SDK from https://addons.mozilla.org/en-US/developers/builder, unpack it.

*Quickly glance over the README file (always useful).

*Execute source bin/activate from the SDK dir (the same dir the README file is in).

*Execute cfx docs -- this bootstraps local copy of SDK docs and opens it in your browser.

*Leave the SDK dir, create an empty dir for your extension.

*Execute cfx init inside the extensions dir -- this generates all the necessary files/directories.

*Follow the rest of getting-started-with-cfx page:

*

*Update lib/main.js with just a few lines of JS to place a custom widget onto add-on bar.

*Execute cfx run -- this opens fresh Firefox instance with your new shiny extension in it.

All in all, it took me just a few hours to read the documentation, get familiar with the SDK API-s, find SDK module to place a widget onto a navigation bar instead of add-on bar, and develop fully-functional extension in just about 50 lines of JavaScript.
HTH!
Update
There is a new standard, called WebExtensions
From MDN

There are currently several toolsets for developing Firefox add-ons, but WebExtensions will become the standard by the end of 2017.
If you are writing a new add-on, we recommend that you write a WebExtension.

A: There are two official ways for developing add-ons, each of them has pros and cons:
1- WebExtensions (newer method):
WebExtensions are the future of Firefox add-ons. If you can use the WebExtensions API, it's the best choice. You can develop and publish WebExtensions right now, but they're still in an early state.
2- Add-on SDK (older method):
The Add-on SDK provides APIs for developing Firefox add-ons, and a tool for developing, testing, and packaging them.

A: I made a tutorial on developing extensions using the Firefox addon SDK:
How to develop a Firefox extension with the addon SDK

A: As of https://blog.mozilla.org/addons/2016/11/23/add-ons-in-2017/, the only way going forward will be to use WebExtensions. The last SDK extensions will be accepted for Firefox 52, while Firefox 57 will end all other extension support, supporting only WebExtensions.
Firefox copied Google Chrome's extension API. So you could just use your Chrome extension and see if all the APIs are already supported in Firefox (they should be as of now).
Programmers such as NoScript's Giorgio Maone actively support the  change to WebExtensions.
To develop a WebExtension, you need

*

*either the web-ext-tool that can be installed via
npm install --global web-ext

*or simply use Firefox's about:debugging or Chromium's chrome:extensions to temporarily load the webextension.
Either way, you need a manifest.json file in a directory created by you, which glues all functionality together. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_first_WebExtension for a first example. Or the Google docs at https://developer.chrome.com/getstarted.

A: Yes there are three different techniques you can use to build extensions:

*

*Add-on SDK-based extensions

*manually bootstrapped restartless extensions

*overlay extensions
You can read comparison between here

If you can, it's advisable to use the Add-on SDK, which uses the
restartless extension mechanism but simplifies certain tasks and
cleans up after itself. If the Add-on SDK isn't sufficient for your
needs, implement a manual restartless extension instead.

Steps to get started with Add-on SDK-based extensions

*

*Installation

*

*Installation on OS X, FreeBSD, Linux

*Installation on OS X using Homebrew

*Installation on Windows

*Create user interfaces

*Interact with the browser


text:
Q: App for iOS AND Android in Facebooks app center - do I need to create two apps? I have a mobile app working for iOS and Android, that I want to display in the facebook app center. Much more important: I want to promote the app for both systems via mobile ads. Facebook told me, that I have to create two different apps in the developers center, because for promoting Facebook can't recognize, which system should be promoted. But if I create two apps, two apps will displayed in the app center, isn't it correct? Which means, if I create one app in the developers center with all information to both systems, mobile ads won't work? The app is working with Facebook login on both systems.
Thanks for helping!

A: It is not Necessary to create a two apps in facebook for Android and iOS you can you use one API ID for both, But you need to provide necessary inputs for individual platforms. "https://developers.facebook.com/"
For iOS
Bundle ID:
iPhone App storeID:
iPad App storeID:
For Android
keyhashes:
To create keyhashes for android refer http://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/


text:
Q: LINQ: Not Any vs All Don't Often I want to check if a provided value matches one in a list (e.g. when validating):
if (!acceptedValues.Any(v => v == someValue))
{
    // exception logic
}

Recently, I've noticed ReSharper asking me to simplify these queries to:
if (acceptedValues.All(v => v != someValue))
{
    // exception logic
}

Obviously, this is logically identical, perhaps slightly more readable (if you've done a lot of mathematics), my question is: does this result in a performance hit?
It feels like it should (i.e. .Any() sounds like it short-circuits, whereas .All() sounds like it does not), but I have nothing to substantiate this. Does anyone have deeper knowledge as to whether the queries will resolve the same, or whether ReSharper is leading me astray?

A: If you take a look at the Enumerable source you'll see that the implementation of Any and All is quite close:
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
    if (source == null) throw Error.ArgumentNull("source");
    if (predicate == null) throw Error.ArgumentNull("predicate");
    foreach (TSource element in source) {
        if (predicate(element)) return true;
    }
    return false;
}

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
    if (source == null) throw Error.ArgumentNull("source");
    if (predicate == null) throw Error.ArgumentNull("predicate");
    foreach (TSource element in source) {
        if (!predicate(element)) return false;
    }
    return true;
}

There is no way that one method be significantly faster than the other since the only difference lies in a boolean negation, so prefer readability over false performance win.

A: According to this link

Any – Checks for at least one match
All – Checks that all match

A: You might find these extension methods make your code more readable:
public static bool None<TSource>(this IEnumerable<TSource> source)
{
    return !source.Any();
}

public static bool None<TSource>(this IEnumerable<TSource> source,
                                 Func<TSource, bool> predicate)
{
    return !source.Any(predicate);
}

Now instead of your original
if (!acceptedValues.Any(v => v == someValue))
{
    // exception logic
}

you could say
if (acceptedValues.None(v => v == someValue))
{
    // exception logic
}

A: Implementation of All according to ILSpy (as in I actually went and looked, rather than the "well, that method works a bit like ..." I might do if we were discussing the theory rather than the impact).
public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (predicate == null)
    {
        throw Error.ArgumentNull("predicate");
    }
    foreach (TSource current in source)
    {
        if (!predicate(current))
        {
            return false;
        }
    }
    return true;
}

Implementation of Any according to ILSpy:
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (predicate == null)
    {
        throw Error.ArgumentNull("predicate");
    }
    foreach (TSource current in source)
    {
        if (predicate(current))
        {
            return true;
        }
    }
    return false;
}

Of course, there could be some subtle difference in the IL produced. But no, no there isn't. The IL is pretty much the same but for the obvious inversion of returning true on predicate match versus returning false on predicate mismatch.
This is linq-for-objects only of course. It's possible that some other linq provider treats one much better than the other, but then if that was the case, it's pretty much random which one got the more optimal implementation.
It would seem that the rule comes down solely to someone feeling that if(determineSomethingTrue) is simpler and more readable than if(!determineSomethingFalse). And in fairness, I think they've a bit of a point in that I often find if(!someTest) confusing* when there's an alternative test of equal verbosity and complexity that would return true for the condition we want to act upon. Yet really, I personally find nothing to favour one over the other of the two alternatives you give, and would perhaps lean very slightly toward the former if the predicate were more complicated.
*Not confusing as in I don't understand, but confusing as in I worry that there's some subtle reason for the decision that I don't understand, and it takes a few mental skips to realise that "no, they just decided to do it that way, wait what was I looking at this bit of code for again?..."

A: Both would have identical performance because both stop enumeration after the outcome can be determined - Any() on the first item the passed predicate evaluates to true and All() on the first item the predicate evaluates to false.

A: All short circuits on the first non-match, so it's not a problem.
One area of subtlety is that
 bool allEven = Enumerable.Empty<int>().All(i => i % 2 == 0);

Is true. All of the items in the sequence are even.
For more on this method, consult the documentation for Enumerable.All.

A: All() determines whether all elements of a sequence satisfy a condition.
Any() determines whether any element of a sequence satisfies the condition.
var numbers = new[]{1,2,3};

numbers.All(n => n % 2 == 0); // returns false
numbers.Any(n => n % 2 == 0); // returns true

A: As other answers have well covered: this is not about performance, it's about clarity.
There's wide support for both of your options:
if (!acceptedValues.Any(v => v == someValue))
{
    // exception logic
}

if (acceptedValues.All(v => v != someValue))
{
    // exception logic
}

But I think this might achieve broader support:
var isValueAccepted = acceptedValues.Any(v => v == someValue);
if (!isValueAccepted)
{
    // exception logic
}

Simply computing the boolean (and naming it) before negating anything clears this up a lot in my mind.


text:
Q: ROS2 `colcon build` could not generate hpp files I followed the tutorial: https://docs.ros.org/en/foxy/Tutorials/Custom-ROS2-Interfaces.html to create custom msg and srv, and use colcon build to compile the package, however, I found there is no hpp file generated to use in other packages. For example, I have package agv_interfaces to maintain custom msg and srv. I have CMakeLists.txt as:
cmake_minimum_required(VERSION 3.5)
project(agv_interfaces)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 14)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rosidl_default_generators REQUIRED)

rosidl_generate_interfaces(${PROJECT_NAME}
  "msg/AgvJoy.msg"
  "srv/JoyLimit.srv"
)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # uncomment the line when a copyright and license is not present in all source files
  #set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # uncomment the line when this package is not in a git repo
  #set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

and its package.xml is as:
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>agv_interfaces</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="zhoudingjiang@gmail.com">taipan</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>
  <build_depend>rosidl_default_generators</build_depend>
  <exec_depend>rosidl_default_runtime</exec_depend>
  <member_of_group>rosidl_interface_packages</member_of_group>
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

The command:
colcon build --packages-select agv_interfaces

is able to build this package, however, there is no *.hpp file be generated. The official tutorial does not mention this neither. Follow the tutorial, I can use command:
ros2 interface show agv_interfaces/msg/AgvJoy

to see how is my message defined, so far so good.
So I tried to use this interface in other packages joystick, I have CMakeLists.txt:
cmake_minimum_required(VERSION 3.5)
project(joystick)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++17
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 17)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(agv_interfaces REQUIRED)

include_directories(./include/)

# --------------------------------
add_executable(
  joy_node
  "src/joy.cpp"
  "src/joy-node.cpp"
)

ament_target_dependencies(
  joy_node
  rclcpp
  agv_interfaces
)

install(TARGETS joy_node
  DESTINATION lib/${PROJECT_NAME}
)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

and package.xml:
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>joystick</name>
  <version>0.0.0</version>
  <description>AGV Joystick</description>
  <maintainer email="zhoudingjiang@gmail.com">ros2-agv</maintainer>
  <license>MIT</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <depend>agv_interfaces</depend>
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>
  <member_of_group>rosidl_interface_packages</member_of_group>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

Then I use colon build, I see error:
In file included from /home/taipan/ros2-ws/src/joystick/src/joy.cpp:1:
/home/taipan/ros2-ws/src/joystick/./include/joystick/joy.h:3:10: fatal error: agv_interfaces/msg/agvjoy.hpp: No such file or directory
    3 | #include "agv_interfaces/msg/agvjoy.hpp"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/joy_node.dir/build.make:63: CMakeFiles/joy_node.dir/src/joy.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
In file included from /home/taipan/ros2-ws/src/joystick/src/joy-node.cpp:1:
/home/taipan/ros2-ws/src/joystick/./include/joystick/joy.h:3:10: fatal error: agv_interfaces/msg/agvjoy.hpp: No such file or directory
    3 | #include "agv_interfaces/msg/agvjoy.hpp"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/joy_node.dir/build.make:76: CMakeFiles/joy_node.dir/src/joy-node.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:78: CMakeFiles/joy_node.dir/all] Error 2
make: *** [Makefile:141: all] Error 2

Some official ROS2 document says I should use rosidl_generator_cpp instead of rosidl_default_generators, but how?

A: Just complementing @zhoudingjang's answer, in case it helps someone, cause it took me forever.
In my case, I had a "custom_msgs/msg/RadarOdometry.msg" custom msg, but when trying to include it, I had to include it as
#include "custom_msgs/msg/radar_odometry.hpp"

Apparently, ros2 does a renaming thingy when compiling messages.

A: #include "agv_interfaces/agv_joy.hpp" is the solution.


text:
Q: Change height of ui:inputSelect I am successfully using the following code to collect a user's multiple input selections.  I don't like how the select box is a certain height regardless of the # of options displayed.  I would like to alter the height of the input box.  Ideally I would do this based on the # of options available, but just being able to make it shorter will be sufficient.  Thoughts?
        <lightning:layoutItem size="12">
        <ui:inputSelect aura:id="filterByOrganization"
                        class="multiple"
                        multiple="true"
                        value="{!v.selection}"
                        change="{!c.selectOrganization}">
            <aura:iteration items="{!v.values}" var="item">
                <ui:inputSelectOption text="{!item.key}"
                                      label="{!item.value}"/>
            </aura:iteration>
        </ui:inputSelect>
    </lightning:layoutItem>

A:  got its style from HTML you need to use important in CSS to override is below is the example
<aura:application extends="force:slds" >
    <ui:inputSelect class="single" aura:id="InputSelectSingle" change="{!c.onSingleSelectChange}">

            <ui:inputSelectOption text="Any"/>
            <ui:inputSelectOption text="Open" value="true"/>
            <ui:inputSelectOption text="Closed"/>
            <ui:inputSelectOption text="Closed Won"/>
            <ui:inputSelectOption text="Prospecting"/>
            <ui:inputSelectOption text="Qualification"/>
            <ui:inputSelectOption text="Needs Analysis"/>
            <ui:inputSelectOption text="Closed Lost"/>
    </ui:inputSelect>
</aura:application>

and the CSS
.THIS.single{
    height : 50px !important;
}

Please let me know if you are looking for this. UI:# elements are deprecated so please do not use unless no other options are available.

A: As as alternative to ui:inputSelect you can use lightning:dualListbox for building multi select picklist. lightning:dualListbox component has size attribute that can be used to control the height of the component based on number of options available.
<aura:attribute name ="len" type="integer" default="2"/>

<lightning:dualListbox name="languages"
                           label= "Select Languages"
                           sourceLabel="Available"
                           selectedLabel="Selected"
                           fieldLevelHelp="Select your preferred languages"
                           options="{!v.options}"
                           size="{!v.len}"/>

lightning:dualListbox documentation : https://developer.salesforce.com/docs/component-library/bundle/lightning:dualListbox/specification
in case, dualListBox is not the one you want as per the UI design, then maybe you can use HTML select and options tag.
I tried that in my dev org and the size can be set from an aura:attribute but working with selected elements from this select element will be adding complexity.


text:
Q: What is the difference between alphabetic and numeric types in the CSS symbols() function? Can you explain me please, What is the difference between of that two types in css symbols() function? When I try separately each of them, I has'nt seen any difference, only one - numbering start from 0 and first symbol doesn't show first in the list.

div {
  margin: 70px 70px;
}

ol {
  list-style: symbols(numeric "○" "●" "□")
}

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

A: For numeric, the symbols represent the digits of a number system, where the number of symbols represents the base. The list starts at 1, and when it runs out of symbols, it continues to 10.

ol {
  list-style: symbols(numeric "0" "1" "2" "3" "4" "5" "6" "7" "8" "9");
}

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

For alphabetic, the list is constructed in the same way, but without the assumption that the first symbol represents 0. When the list runs out of symbols, it continues with 00 instead of 10.

ol {
  list-style: symbols(alphabetic "0" "1" "2" "3" "4" "5" "6" "7" "8" "9");
}

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

symbols() - CSS: Cascading Style Sheets | MDN


text:
Q: Extricating and sorting data from attribute table in QGIS I download shapefile of Alberta from GEOFABRIK in order to work with the roads shapefile.
The problem was that I get an attribute table with 94,644 rows that was slowing down the computer, additionally to the fact that I get every small road and just the main one as I wanted.

I looked in the attribute table and found that the road type are classified in the fclass column. As described here I use the categorized function to classify the different road types, so I was able to display only the primary roads.

Also, it is possible to change the line style, by clicking the "Symbel" bar.

However, it was only a partial solution, I still have a lot of unnecessary data seem to slowing down me computer.
I was looking for a way to extract the data in need, and to work with this kind of big database.

A: In order of extricating data I used the "Split vector layer" function.

I choose the layer I was working on and in the "unique ID field" I choose the fdass column that have the different roads type classification.

It took some time, but at the end I head diffrent shapefiles for each road type. Know I was able to work only with the road type I needed, and if needed to upload more road layers. It was much easier in compared of working with one big attribute table.


text:
Q: Strange output of Tikz-Feynman I used the hello,world example of tikz-feynman, which should draw a horizontal Feynman diagram
\documentclass{standalone}

\usepackage{tikz}
\usepackage{tikz-feynman}

\begin{document}

\feynmandiagram [horizontal=a to b] {
 i1 -- [fermion] a -- [fermion] i2,
 a -- [photon] b,
 f1 -- [fermion] b -- [fermion] f2,
};

\end{document}

But got a strange output like

Can you help me?


text:
Q: C# initialize a generic type using a strategy-pattern-provided constructor I have a class that operates on a generic type:
public class Operation<I> where I : IAnimal

and I define IAnimal as the following:
public interface IAnimal
{
    string Name { get; }
}

I define a class as the following:
public class Dog : IAnimal
{
    string Name { get; private set; }

    public Dog(string name)
    {
        Name = name;
    }
}

If I want to use Dog in the Operation class, since the Dog class does not have a parameter-less constructor, I leverage strategy pattern as the following:
public interface IConstructor
{
    IAnimal Construct(string name);
}

public class DogConstructor : IConstructor
{
    IAnimal Construct(string name)
    {
        return new Dog(name);
    }
}

public class Operation<I> where I : IAnimal
{
    public Operation() : this(new DogConstructor())
    { }

    public Operation(IConstructor constructor)
    {
        I animal = constructor.Construct("myDog"); // <<<<<<<< Error here!
    }
}

At the market place, I receive Cannot implicitly convert type 'IAnimal' to 'I'. An explicit conversion exists (are you missing a cast?)
Of course if I case like I animal = (I)constructor.Construct("myDog");, all works. However, I am wondering why do I need to cast while I have where I : IAnimal.

A:
However, I am wondering why do I need to cast while I have where I : IAnimal.

Yes, you did guarantee that I will be a subclass of IAnimal or IAnimal itself, but what would Construct return? Construct might return a different subclass from I.
Whenever you are using generics, you should remember that the generic parameter types are provided by the client code of your class/method, not the class/method. Here you are forcing I to be Dog by using a DogConstructor if not arguments were passed in. If you are doing this, then it probably means that generics is not suitable here. Try removing it:
public class Operation
{
    public Operation() : this(new DogConstructor())
    { }

    public Operation(IConstructor constructor)
    {
        IAnimal animal = constructor.Construct("myDog");
    }
}

Now if you insist on using generics, you can't just assume a DogConstructor by default, and IConstructor should probably be generic as well:
public interface IConstructor<T> where I: IAnimal
{
    T Construct(string name);
}

public class DogConstructor : IConstructor<Dog>
{
    Dog Construct(string name)
    {
        return new Dog(name);
    }
}

public class Operation<I> where I : IAnimal
{
    public Operation(IConstructor<I> constructor)
    {
        I animal = constructor.Construct("myDog");
    }
}

public class DogOperation: Operation<Dog> {
    public DogOperation() : base(new DogConstructor()) {}
}

since the Dog class does not have a parameter-less constructor

Another solution might be to constrain I so that it must have a parameterless constructor, and add one to Dog:
class Operation<I> where I : IAnimal, new() {

A: Issue is compiler does not know the what Class you are going to pass in place of I. Suppose you create another class Cat derived from Animal similar to Dog. Now you pass Cat in Operation in place of I, which is fine as per the code. But constructor.Construct("myDog") is returning Dog which is a sibling of Cat, and can not be parsed into Cat. So error will come. See the code
public interface IAnimal
{
        string Name { get; }
}

public class Dog : IAnimal
{
        public string Name { get; set; }

        public Dog(string name)
        {
            this.Name = name;
        }
}

public class Cat : IAnimal
{
        public string Name { get; set; }

        public Cat(string name)
        {
            this.Name = name;
        }
}

public class Operation<I> where I : IAnimal
{
        public Operation() : this(new DogConstructor())
        { }

        public Operation(IConstructor constructor)
        {
            I animal = constructor.Construct("myDog"); // <<<<<<<< Error here!
        }
}

Check the below code. You are passing Cat and you want it to be mapped with Dog. That could not work.
public class XYZ
{
       public void MyMethod()
       {
            var obj = new Operation<Cat>();
       }
}

If you know it will constructor.Construct("myDog") returns animal then replace I with IAnimal. That way compiler is sure about the reference in which returned object from constructor.Construct("myDog") to be set
public class Operation<I> where I : IAnimal
{
        public Operation() : this(new DogConstructor())
        { }

        public Operation(IConstructor constructor)
        {
            IAnimal animal = constructor.Construct("myDog"); // <<<<<<<< Error here!
        }
}

A: The problem is that there is no guarantee that your IConstructor will return the same class as I. You could have an Operation<Cat>, and pass to the constructor a DogConstructor.
You can solve this by making the IConstructor generic too, and make the Operation constructor to receive an IConstructor<I>.

A: i faced same problem and i used Activator.CreateInstance(Type type, params object[] args)
static void Main()
{
    var operation = new Operation<Dog>("Jack");
    Console.WriteLine(operation.Animal.Name);
    Console.ReadLine();
}

public interface IAnimal
{
    string Name { get; }
}

public class Dog : IAnimal
{
    public string Name { get; private set; }

    public Dog()
    {
    }

    public Dog(string name)
    {
        Name = name;
    }
}

public class Operation<T> where T : IAnimal, new()
{
    public T Animal { get; private set; }

    public Operation()
    {
        Animal = new T();
    }

    public Operation(params object[] args)
    {
        Animal = (T)Activator.CreateInstance(typeof(T), args);
    }
}


text:
Q: Is the second, third, and nth standard deviation an established concept? Of course the first standard deviation is a measure that shows the level of variation among a set of values, and is of course derived by taking the sqrt of mean squared differences of the values to their mean.
But what if you needed to know the level of variation OF the variation of the set of values. This would be the second standard deviation, and would be derived by taking the sqrt of mean squared differences of the residuals to their standard deviation. And in the same way: the third, fourth, and nth standard deviation.


text:
Q: How to setup an Android development environment using STS, Android SDK, Maven and Spring Android
*

*Install latest STS (currently 3.4.0)

*Setup your Android development environment in STS as per the normal Android development setup steps for an existing IDE: http://developer.android.com/sdk/installing/index.html

*For the above step, you could save time by copying the "android-sdk" folder from another developer who has already setup their environment, and point your STS to that android folder (Window-->Preferences-->Android-->SDK Location)

*Install m2e-android as per: http://rgladwell.github.io/m2e-android/
Create a sample Android application using Maven

*

*In STS, click on File-->New-->Maven Project

*Select your workspace location and Click Next

*For the Maven Archetype, select "android-quickstart" and click Next. This archetype should exist if you added the Archetype according to: http://rgladwell.github.io/m2e-android/

*Fill in your desired Maven project details and click Next.

*In pom.xml, set the "platform.version" tag value to 4.1.1.4

*Right click on the project and select Build Project.

*Right click on the project and select Run As  Android Application.

*It should start up your Android emulator and deploy the 'Hello World' application.

Making use of Spring Android libraries in an Android application:

*

*As we are using Maven, follow the instructions here to configure your dependencies: http://projects.spring.io/spring-android

*There seems to be an error is using the above dependencies as is. The error is given when trying to run the Android application in STS, it says "Multiple dex files define Lorg/springframework/core/ErrorCoded".  This means that duplicate classes are referenced on the classpath.  To avoid this error, remove the maven dependency element "spring-android-auth".

Using RestTemplate from the Spring Android libraries:

*

*The reference documentation gives you everything you need: http://docs.spring.io/spring-android/docs/1.0.1.RELEASE/reference/html/rest-template.html

*Remember that your Android application must register the correct message converter. Eg: restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

*Note that your Android application must include uses-permission "android.permission.INTERNET" to allow network calls.


text:
Q: Logic apps Ip Restriction I need to set my Azure app service's outbound IPs to my logic app IP restriction whitelist, so that nobody can call the logic app except through my api app.
But the problem is that logic app restriction list only accepts IPs in range format
x.x.x.x/x
and I need to allow a set of 5 different IPs which is my API's app outbound IPs.
App Service Ips

A: Looking at the documentation:

*

*Secure access in Azure Logic Apps
Logic App allows you to specify ip address + network mask.
/32 is a network mask of 255.255.255.255
So xxx.xxx.xxx.xxx/32 = ip address of xxx.xxx.xxx.xxx
if you use the /32 network mask, you will be able to add the specific ip addresses you want.

A: It seems that it's hard to assign a dedicated static outbound IP to a Logic App now.
Here is an issue that you could vote up it to promote the realization of this feature.


text:
Q: Ruby / Rails - File naming conventions and dealing with uppercase model names (i.e. CSV vs Csv) So I'm using a model to track CSV uploads. When using FactoryGirl in my specs, OR when trying to access the model via an association (i.e. user.csv_uploads) I get the following error when trying to use the linter.
Failure/Error: FactoryGirl.lint

LoadError:
  Unable to autoload constant CsvUpload, expected .../APP_NAME/app/models/csv_upload.rb to define it

user.csv_uploads

LoadError: Unable to autoload constant CsvUpload, expected .../APP_NAME/app/models/csv_upload.rb to define it

That file does define a model called CSVUpload, but strictly following naming conventions, I guess it should be CsvUpload. Currently the model loads correctly, and typing something like CSVUpload.new in the console works as expected. But certain other situations have the load error. I assume this is when trying to convert a symbol or filename into a class name, and then trying to use that. i.e. :csv_upload.to_s.camelize.constantize. Is there a simple way to fix this? Or will a be a constant uphill battle that is best fixed by going with CsvUpload?

A: Rails uses the ActiveSupport::Inflector for things like constantize-ing strings, so you can tell the inflector that csv should be an acronym and not a part of the usual "first character uppercase and the rest lowercase" that is used for most things. You do this in an initializer (looks to be there by default config/initializers/inflections.rb) by using the following code:
ActiveSupport::Inflector.inflections(:en) do |inflect|
   inflect.acronym 'CSV'
end


text:
Q: MVC Controller POST does not work with custom parameter *Answered! Solution at the bottom of the question *
Hi I'm starting to toy with MVC 4 and I've quickly hit a wall.
Note: I'm using Newtonsoft.JSON for all JSON related stuff.
I'm trying to POST a json to my controller that looks like this (in fiddler):
POST http://localhost:10187/api/Account/Login/ HTTP/1.1
User-Agent: Fiddler
Host: localhost:10187
Content-Length: 63
ContentType: "application/json"

{
   "username" : "blahblah",
   "password" : "mypassw0rd"
}

Here is my controller:
public class AccountController : ApiController
{
    [HttpPost]
    public PostLoginResponse Login(PostLoginModel model)
    {
        return new PostLoginResponse()
        {
            Status = model.Username,
            Token = model.Password
        };
    }
}

and here are the two models used:
public class PostLoginModel
{
    [JsonProperty(PropertyName = "username")]
    [Required(ErrorMessage = "Username is required")]
    public string Username { get; set; }

    [JsonProperty(PropertyName = "password")]
    [Required(ErrorMessage = "Password is required")]
    public string Password { get; set; }
}

public class PostLoginResponse
{
    [JsonProperty(PropertyName = "status")]
    public string Status { get; set; }

    [JsonProperty(PropertyName = "token")]
    public string Token { get; set; }
}

Now what seems to happen is that my controller doesn't seem to convert the JSON body sent in my request to a PostLoginRequest. If I check in my controller if (model == null) is always true.
What am I missing here? I've tried to read on Model Binding but could not get anything working. If I replace the return statement to use strings like the following:
return new PostLoginResponse()
{
    Status = "Hahaha",
    Token = "It WORKS!"
};

It works flawlessly.
Any pointer or help will help.
@Update:
Tried with:
[HttpPost]
public PostLoginResponse Post([FromBody]PostLoginModel model)
{
    if (model == null)
    {
        Console.WriteLine("It's null");
    }

    if (!ModelState.IsValid)
    {
        Console.WriteLine("It's invalid");
    }

    return new PostLoginResponse()
    {
        Status = model.Username,
        Token = model.Password
    };
}

And I'm getting the same errors. It seems the model is null but it is valid.
I get the It's null but not the It's invalid. And tried with both "application/json" and application/json as contenttype with no success (same thing happens in both cases)
@Update 2:
Screw me... Thanks to haim770 for making me look at the content-type header.
It's Content-Type not ContentType!
Changing the header to Content-Type: application/json made everything work like a charm.
Thanks a bunch guys.

A: First, try naming your action after the HTTP verb in play, i.e. PostLogin instead of Login. If that doesn't work or alternatively try adding [FromBody] to your action argument:
public PostLoginResponse Login([FromBody]PostLoginModel model)


text:
Q: COPY command not found in postgres dockerize I am trying to COPY data from CSV to container
From postgres container shell
$COPY
copy command not found

also tried \copy
but createdb and dropdb works for me.

A: COPY is not a bash shell command, it's a command run within the psql database query shell.


text:
Q: FOR JSON PATH in CASE statement When I use a variable (or a field from a table) in a case statement with "FOR JSON PATH", the JSON provided is not well formed.
Ex:
declare @MyValue nvarchar(50)
set @MyValue='1'
select CASE WHEN @MyValue='1' THEN (select 'ROLE_CLIENT_READONLY' as id   FOR JSON PATH) end as [Role]  FOR JSON PATH

Return
[{"Role":"[{\"id\":\"ROLE_CLIENT_READONLY\"}]"}]

But if I put this, it's works:
select CASE WHEN '1'='1' THEN (select 'ROLE_CLIENT_READONLY' as id   FOR JSON PATH) end as [Role]  FOR JSON PATH

Return
[{"Role":[{"id":"ROLE_CLIENT_READONLY"}]}]

Any idea on the reason for this behavior?
How can I fix this in the first scenario?

A: Not sure why it treats one different than the other.  I certainly would not expect the difference in JSON between using a variable in the query and a string literal.
Interestingly
CASE WHEN CAST(N'1' AS NVARCHAR(MAX)) = CAST(N'1' AS NVARCHAR(MAX))
also produces the problematic JSON, however
CASE WHEN CAST(N'1' AS NVARCHAR(50)) = CAST(N'1' AS NVARCHAR(50))
does not.
This seems to work as a workaround for using the variable in the query:
WITH ids AS (
    SELECT CASE WHEN @MyValue = '1' THEN 'ROLE_CLIENT_READONLY' END id
)
SELECT (SELECT id FROM ids FOR JSON PATH) AS [Role] FOR JSON PATH;