text:
Q: how to re-define the `__add__` method for `int`? I want to re-define the __add__ method for int so that the usage would be like this:
 >> 1+2
 => "1 plus 2"

 >> (1).__add__(2)
 => "1 plus 2"

I tried this:
 >>> int.__add__ = lambda self, x: str(self)+" plus " + str(x)

However, it throws an exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'int'

Does anyone have ideas about why I can't redefine the __add__ method like this? And is there other way to do this?

A: create your own class which overrides the __add__ method of int class.
In [126]: class myint(int):
    def __add__(self,a):
        print "{0} plus {1}".format(self,a)
   .....:

In [127]: a=myint(5)

In [128]: b=myint(6)

In [129]: a+b
5 plus 6

A: Although not best practice, you could use forbiddenfruit to overwrite the __add__ method. Usage:
>>> from forbiddenfruit import curse
>>> curse(int, '__add__', lambda x, y: f"{x} plus {y}")
>>> 1 + 2
'1 plus 2'


text:
Q: How to register a user with orchard cms So in the User.cshtml file in the bootstrap theme I am setting up 'Register' to navigate to the CheckoutController/Signup() with
 @Html.ActionLink(T("Register").Text, "Signup", new { Controller = "Checkout", Area = "UMACS.FoodPod", ReturnUrl = Request.QueryString["ReturnUrl"] })

which attempts to create a shape with _services (which is private readonly IOrchardServices _services;)
 [Themed]
    public ActionResult Signup()
    {
        var shape = _services.New.Checkout_Signup();
        return new ShapeResult(this, shape);
    }

However it throws an error when trying to create this:
Exception Details: Orchard.OrchardException: Shape type Checkout_Signup not found

I'm not exactly sure what this shape thing is trying to do. I've used this code (which iv just copied over atm) before to create a registration login. which has worked fine in the past and dont know why this error is throwing now...any ideas? on how to debug it?

A: Orchard is looking for the Checkout_Signup shape, which means it is looking for a view called Checkout.Signup.cshtml. So I assume that you have not created this file.
For example, In the LogOn function of the Orchard.Users.Controllers.AccountController, it performs the same function var shape = _orchardServices.New.LogOn() which uses Orchard.Users.Views.LogOn.cshtml to build the shape. Then  it passes this shape to the ShapeResult(). Which then renders the LogOn.cshtml.
So in your module, create a Checkout.Signup.cshtml file in your Views folder.
As to why Checkout_Signup maps to Checkout.Signup.cshtml, please see http://docs.orchardproject.net/Documentation/Alternates

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python printing format in a for loop *if menuInput == '1':
     print("")
     encryptString = input("Please enter string to encrypt:")
     print("")
     offSetValue = int(input("Please enter offset value (1-94):"))
     print("")

     for character in encryptString:
         x = ord(character)
         y = x + offSetValue
         z = chr(y)
         print("Encrypted string:")
         print(z)*

I want the string that has been encrypted to be outputted in this format:
Encrypted string:
abcde

but it comes out in this format:
Encrypted string:
a
Encrypted string:
b
Encrypted string:
c
Encrypted string:
d

I've tried using end and sep but they don't help.

A: I think this is what you want.
print("")
encryptString = input("Please enter string to encrypt:")
print("")
offSetValue = int(input("Please enter offset value (1-94):"))
print("")

print("Encrypted string:")
for character in encryptString:
    x = ord(character)
    y = x + offSetValue
    z = chr(y)
    print(z, end="")

print()

You want print("Encrypted string:") before the loop and use end instead of sep. sep is used to separate multiple arguments in the print. end is the terminating character(s) added to the end of what is printed. Here we terminate with the empty string. The default for end is the newline character, \n. That is why you saw everything printed on a new line.

A: By using fernet, it allows you to encrypt messages more securely than shifting the position of characters in the string.
from cryptography.fernet import Fernet
if menuInput == '1':
    print()
    encryptString = input("Please enter string to encrypt:")
    print()
    key = Fernet.generate_key()
    fernet = Fernet(key)
    encryptedString = fernet.encrypt(encryptString.encode())
    print("Encrypted string:", encryptedString)

A: Here we go.
if menuInput == '1':
 print("")
 encryptString = input("Please enter string to encrypt:")
 print("")
 offSetValue = int(input("Please enter offset value (1-94):"))
 print("")

 print("Encrypted string:")
 for character in encryptString:
     x = ord(character)
     y = x + offSetValue
     z = chr(y)
     print(z, end='')


text:
Q: Why does this Array return as Native Code instead of Object? I have an array titled autosuggest_results which is used for a Typeahead. When I input text into a form field, the autosuggest populates with information. However, I noticed when I entered "POP", I received an error "Cannot read property of length undefined"...I noticed if I enter other JavaScript method names (such as Push, concat) that the error occurs.
Why does the following return as "function pop() { [native code] }" when I enter "POP"? If I enter "Test" for example it returns "[object Object]"
autosuggest_results[trim($(autosuggest_active_field).val()).toLowerCase()]

A:
after seeing more info in a comment just now

wherever autosuggest_results is declared, it NEEDS to be declared as an object, not an array
var autosuggest_results = {};

Your original code will then be fine

autosuggest_results is an ARRAY ... autosuggest_results['pop'] is the pop method of an array ... i.e it is autosuggest_results.pop ... coercing a (native) method to a string results in something like the string
function pop() {
    [native code]
}

What you possibly want is
var arrayOfResults = autosuggest_results.filter(v => ~v.indexOf(trim($(autosuggest_active_field).val()).toLowerCase()))

arrayOfResults will be an array of items in autosuggest_results which include (anywhere in the string, not an exact match) the current value of
trim($(autosuggest_active_field).val()).toLowerCase()


text:
Q: Are there any MVVM-like frameworks for objective-c on iOS? Are there any MVVM frameworks for Objective-C that are widely used on iOS (iPhone/iPad)?
I'm a .net developer who has just started with iOS (read tutorials, done a couple of simple test apps), and from first perspective iOS's MVC looks to me pretty much like WinForms (correct me please if I'm wrong). WinForms "evolved" to WPF with MVVM, making Separation of Concerns way easier.
Are there something similar to MVVM for iOS? In the MonoTouch world I saw at least mvvmcross applying MVVM. What about Objective-C? Or generally there's no need for this in iOS world?

A: MvvmCross relies heavily on reflection, and on public c# properties and events. I did look at the idea of trying to extend the framework into objC and uikit, but really the structure of its function/selector API didn't seem to lend itself nicely to the databinding part of mvvm


text:
Q: Can't mount or unmount virtual discs- gives option for "force unmounting" I've installed Ubuntu (64-bit version) on a vm through VirtualBox on a Windows 7 64-bit host, but I fear that I've done something wrong. First, when I restart my computer, it just goes straight to Windows 7, as normal. Is there a separate step to have a selection menu at start-up or does this not apply for VirtualBox runs of Ubuntu?
Then, when I go to "Devices-->Install Guest Additions" within Ubuntu (running it by simply starting VB and clicking start on VB GUI for Ubuntu), I get the following error message:
Unable to mount the CD/DVD image C:\Program Files\Oracle\VirtualBox\VBoxGuestAdditions.iso on the machine Ubuntu Desktop 12.04 64-bit. Would you like to force mounting of this medium?
Could not mount the media/drive 'C:\Program Files\Oracle\VirtualBox/VBoxGuestAdditions.iso' (VERR_PDM_MEDIA_LOCKED).
And I get a choice to "Force Unmount" the mounted ISO file within (which is indeed the VBoxGuestAdditions).
Also, when I click on the CD icon on the bottom right of the Ubuntu window so that I can "remove disk from virtual disk", I get a similar error message, except this time it says that it cannot unmount:
Unable to unmount the CD/DVD image C:\Program Files\Oracle\VirtualBox\VBoxGuestAdditions.iso from the machine Ubuntu Desktop 12.04 64-bit. Would you like to force unmounting of this medium?
Could not unmount the currently mounted media/drive (VERR_PDM_MEDIA_LOCKED).
But when I go to the VB GUI and select "Settings" and go to Storage, I guess I can unmount from there because I get no error message. If I unmount there and then go back into Ubuntu, the virtual CD is unmounted. Any help would be awesome!

A:
First, when I restart my computer, it just goes straight to Windows 7, as normal. Is there a separate step to have a selection menu at start-up or does this not apply for VirtualBox runs of Ubuntu?

That's normal. A virtual machine will not come up as an option in the physical host's boot menu. You must start the host OS and the virtual machine manager (hypervisor) before that can happen.

And I get a choice to "Force Unmount" the mounted ISO file within (which is indeed the VBoxGuestAdditions).

*

*Try ejecting the virtual drive from within the OS first:

*

*You can also use sudo umount /media/title-of-cd from the terminal.

*Then try unmounting from VirtualBox. Sometimes that may still give you the warning, but just override it so long as you ejected from Ubuntu first.

.....................


text:
Q: Writing a simple sum with einstein notation Is there any shorthand using the Einstein notation to write a simple sum?
$X = X_1 + X_2 + X_3 ....$
Can I write: $X = X_i$ ?
I don't think so because the definition states that only indices that appear twice is summed over. What is the correct way to write a simple sum like the example above?

A: Such a sum is, as far as I know, not easily expressible in Einstein notation - you could probably write it in a convoluted way, but that would not really be simpler or easier to understand than $X = \sum_i X_i$.
The summation convention is not a shorthand for any sum, but only for certain kinds of sums which arise in linear algebra, such as scalar products, matrix multiplication and so on.
In formal terms, the sums at hand are those corresponding to the application of (multi)linear maps between a vector space, its dual, and powers of these; or to the coordinate representation of vectors and tensors. Some examples are given in the Wikipedia article for the convention.
This is the reason for the requirement of two equal indices.

A: The Einstein summation notation includes repeated indices (i.e. summation notation). For vectors (and tensors), $X$ would usually mean the full object, $X = X^{i} e_{i} = X^{0}e_{0} + X^{1}e_{1}...$ etc. The $X^i=X^i (x)$ are the components of the vector and $e_i$ is some basis. The $i$ deonotes the components, and this is summed in the above equation. But we can talk just about the components $X^i$, which means $(X^0, X^1, ... X^n)$.
So yes, you can write $X^i$, but it doesn't mean what you've written down. This is just four-vector notation, but not specifically Einstein summation notation. The sum you wrote is more like the Euclidean norm, which as the other comment says, it's easiest notated as $\sum_{i}^{n} X^i $.


text:
Q: $P,Q$ are polynomials with real coefficients and for every real $x$ satisfy $P(P(P(x)))=Q(Q(Q(x)))$. Prove that $P=Q$
$P,Q$ are polynomials with real coefficients and for every real $x$ satisfy $P(P(P(x)))=Q(Q(Q(x)))$. Prove that $P=Q$.

I see only that these polynomials are same degree

A: Since one easily messes things up when starting from highest coefficients downward (as I did in my first revision of this answer), we shall consider the function $f(z)=\frac1{P(z^{-1})}$, which allows us nicer acccess to the high coefficients of $P$.
As a matter of notation, write $$f^{\circ k}:=\underbrace{f\circ\ldots\circ f}_{k}$$
for function iteration.
Lemma. Let $n,m,k\in\mathbb N$, $m> k\ge 2$. Let $f$ be holomorphic around $0$ with $f(0)\ne0$. Then there exist $M$ with $k^n<M<k^n(m-k+1)$ and $\alpha\in\mathbb C$ with $\alpha\ne 0$ such that for any  $h$ holomorphic around $0$, we have $$(z^kf+z^mh)^{\circ n}=(z^kf)^{\circ n}+\alpha  h(0)z^M+O(z^{M+1}).$$
Proof.
First observe (e.g., by induction on $n$) that $(z^kf)^{\circ n}$ has a root of order exactly $k^n$ at $z=0$, and $((z^kf)^{\circ n})^r$ has a root of order exactly $ k^nr$ at $z=0$, say $$\tag1((z^kf)^{\circ n})^r=c_{n,r}z^{k^nr}+O(z^{k^nr})$$ with $c_{n,r}\ne0$ depending only on $f,k,n,r$ (but we consider $f,k$ fixed).
Now we show the claim of the lemma by induction on $n$. The claim is clear for $n=1$ with $\alpha=1$ and $M=m$ (which is $<k^1(m-k+1)$!).
Assume that the claim holds for $n$.
For any $r\ge 1$, we have
$$\tag1\begin{align}\left( (z^kf+z^mh)^{\circ n}\right)^r&=\left((z^kf)^{\circ n}+\alpha h(0)z^M+O(z^{M+1})\right)^r\\
&=((z^kf)^{\circ n})^r+r\cdot ((z^kf)^{\circ n})^{r-1}\alpha h(0)z^M+O(z^{k^n(r-1)+M+1}).\end{align}$$
Let $f(z)=a_0+a_1z+a_2z^2+\ldots$.
Then summing $(1)$ using these coefficients we get
$$\begin{align}((z^kf+z^mh)^{\circ n}) &=(z^kf+z^mh)\circ ((z^kf+z^mh)^{\circ n}) \\&=\sum_r a_r(z^kf^{\circ n})^{r+k}+\sum_r a_r(r+k)((z^kf)^{\circ n})^{r+k-1}\alpha h(0)z^M\\
&\quad+h(0)((z^kf)^{\circ n})^m+h(0)m((z^kf)^{\circ n})^{m-1}\alpha h(0)z^M\\&\quad+O(z^{k^n(\min\{m,k\}-1)+M+1})\end{align}$$
Now the first sum is just $(z^kf)^{\circ(n+1)}$.
The second sum is $$a_0kc_{n,k-1}\alpha h(0)z^{k^n(k-1)+M}+O(z^{k^n(k-1)+M+1}).$$
The third summand is $$h(0)z^{k^nm}+O(z^{k^nm+1})=O(z^{k^n(k-1)+M+1}) $$
because $M<k^n(m-k+1) $.
The fourth summand is
$$h(0)^2m\alpha z^{k^n(m-1)+M}+O(z^{k^n(m-1)+M+1}) =O(z^{k^n(k-1)+M+1})$$  because $m>k$.
Thus with $M':=k^n(k-1)+M$ (which is $>k^n(k-1)+k^n=k^{n+1}$ and $<k^n(k-1)+k^n(m-k+1)=k^nm\le k^{n+1}(m-k+1)$) we have
$$(z^kf+z^mh)^{\circ (n+1)}=(z^kf)^{\circ(n+1)}+\alpha'h(0)z^{M'}+O(z^{M'+1}) $$
where
 $\alpha'=a_0kc_{n,k-1}\alpha\ne 0$.
This shows that the claim also holds for $n+1$. $_\square$
Corollary. Let $n,k\in\mathbb N$, $k\ge2$. Let $f,g$ be holomorphic around $0$ with a root of order exactly $k$ at $z=0$. Then $f^{\circ n}=g^{\circ n}$ implies $f=g$.
Proof. Note that we can write $f(z)=z^kf_0(z)$ and $g(z)=z^kf_0(z)+z^mh(z)$ with $m>k\ge 2$. $_\square$
Proposition. Let $P,Q$ be polynomials such that $P(P(P(x)))=Q(Q(Q(x)))$ for all $x\in\mathbb R$. Then $P=Q$.
Proof.
By the condition, the polynomials $P^{\circ 3}$ and $Q^{\circ 3}$ are the same. If $P(x)=a_nx^n+\ldots$, then $P^{\circ 3}(x) = a_n^{n^2+n+1}x^{n^3}+\ldots$.
We conclude that we can read $\deg P$  from $P^{\circ 3}$, namely $\deg P=\sqrt[3]{\deg P^{\circ 3}}$, and we also obtain $a_n$ because $n^2+n+1$ is odd and odd powers are bijective maps $\mathbb R\to\mathbb R$.
Hence $P,Q$ have the same degree and the same leading coefficient.
In the case $n=0$, we are already done.
In the case $n=1$, say $P(x)=ax+b$, $Q(x)=ax+c$, we have $P(P(P(x)))=a^3x+(a^2+a+1)b$ and $Q(Q(Q(x)))=a^3x+(a^2+a+1)c$. Since for $a\in\mathbb R$ we have $a^2+a+1=(a+\frac12)^2+\frac34>0$, we conclude $b=c$, i.e., $P=Q$ also in this case.
In the case $n\ge 2$, we can consider $f(z)=\frac1{P(z^{-1})}$ and $g(z)=\frac1{Q(z^{-1})}$, which match the conditions of the corollary as both are $\frac1{a_n}z^n+O(z^{n+1})$. $_\square$

A: It is easy to see that $P$ and $Q$ have the same leading term.  Without loss of generality, assume that both are monic.  Note that $P$ and $Q$ also have the same constant term. (Note: as zhw has pointed out, this part is not so obvious.  I'll try to update with an argument shortly.)
Suppose that $P\neq Q$.  Since $P-Q$ is not a constant, it is unbounded.  Without loss of generality, there is some $t$ such that $P$ and $Q$ are strictly increasing on $[t,\infty)$, and, for all $a\geq t$, we have $P(a)>Q(a)\geq a$.
Then we have $P(P(P(t))) > P(P(Q(t)) > P(Q(Q(t))) > Q(Q(Q(t)))$, a contradiction.

A: Slade, I had the same approach but I'm not sure how you got the constant terms equal so quickly. But if the degree is $1$ that part is easy and you're done. Otherwise, if $p\ne q,$ then $|p_2(x)-q_2(x)|$ blasts off to $\infty$ as $x\to \infty.$ Because the leading coefficients of $p$ and $q$ agree, this would imply $|p_3(x)-q_3(x)|\to \infty,$ contradiction.


text:
Q: Android MarketPlace: reserve namespace I have heard the best way to stop someone stealing/publishing your signed .apk before you publish it yourself to the Google Android markeyplace is to upload a dummy release .apk with the same namespace /name, ahead of the publish date. I have done this but it is in an 'unpublished' state. Does anyone know if this is sufficient to stop anyone else using the same app name or namespace or will this only be the case if it is actually published?

A: Just saving the apk is enough ;-)


text:
Q: Writing a plugin using NPAPI + D3D. It works on Firefox, but the browser blacks out. Why? I'm writing a plugin, using NPAPI and D3D. I just simply put a D3D sample from DXSDK and NPAPI together. I receive a HWND when the plugin starts up, and I passed it to D3D to draw.
It works though. the control(a 400 * 300 rectangle) on the test page DOES show what I expected.
But all other area in FireFox window is black, including the menu bar. All other contents on the test page cannot be seen.
I tried just InitDevice(D3D) with the HWND and do NO rendering at all. But still got the same problem.
Can anyone help me out here plz?

A: I've seen this happen a few times before; there are two different situations where I encountered it.  The first is when I had something weird with my D3D initialization which aparently conflicted with firefox -- but I'm still not sure what I changed to get it working.
The second, which I hope is what you are encountering, is when I was initializing D3D and attempting to draw on the main thread.  My theory (unproven) is that Firefox is actually creating its own DX context of some sort and so creating another one on the same thread conflicts.  When we moved the init and drawing code to another thread it all started working.
This is one reason that FireBreath has so much code to help make things threadsafe and allow cross-thread calls back to javascript -- every time I've tried to do drawing on the main thread with OGL or DX I've run into problems somewhere.
Hope that helps!


text:
Q: Retrieving single direct message and waiting for people to message using Tweepy Am having a problem here where I get Twitter rate limit so quickly and I don't get the new DMs quick
This is the code please help me.
def getDM():

           last_seen_id = retrieve_last_seen_id(FILE_NAME)
           last_dms = api.list_direct_messages(1)

           for messages in last_dms:
               last_seen_id = messages.id #messages.message_create['sender_id']
               store_last_seen_id(last_seen_id, FILE_NAME)
               print("ID is : " + str(messages.id) + " || " + " Messaged : " +
               str(messages.message_create['message_data']['text']))
               api.destroy_direct_message(messages.id)

A: An approach is to implement a thread which fetches the DMs every 60 seconds, if you try more often you do exceed the limit
class TwitterThread():
   def start(self):
      self.interval = 60  # interval

      thread = threading.Thread(target=self.run, args=())
      thread.daemon = True  # Daemonize thread
      logging.info(f'TwitterThread runs every {self.interval} seconds')
      thread.start()

   def run(self):
      while True:
         try:
            last_dms = api.list_direct_messages(1)
            for messages in last_dms:
               # process DM

               api.destroy_direct_message(messages.id)

         except Exception as e:
            logging.exception(e)

        time.sleep(self.interval)  # sleep to wait 60 sec


text:
Q: Insert into two tables that are in one to one relationslip laravel I have 2 tables that are in one to one relationship:
tours :
id|title|content

featured_image:
id|tour_id|name|path

My models FeaturedImage.php:
class FeaturedImage extends Model
{
public function tour()
 {
    return $this->hasOne('App\Tour');
 }
}

Tour.php
class Tour extends Model
{
  public function featuredimage()
  {
    return $this->belongsTo('App\FeaturedImage');
  }
}

I want to save tour_id in  featured_image table when tour is created. I'm using same form to fill tours table and to upload featured_image.
This is my store method looks like:
    public function store(Request $request)
{

    //validate the date
    $this->validate($request, [
            'title'    => 'required|max:255',
            'content'  => 'required'
        ]);
    //store the date
    $tour = new Tour;

    $tour->title   = $request->title;
    $tour->content = $request->trip_code;

    $tour->save();

    $featured_image= new FeaturedImage;
    // save featured_image
    if($request->hasFile('featured_image')){
        $image = $request->file('featured_image');
        $filename = $image->getClientOriginalName();
        $location = public_path('images/featured_image/'.$filename);
        Image::make($image)->resize(800, 600)->save($location);

     $featured_image->path= $location;
     $featured_image->tour()->associate($tour);
     $featured_image->save();
    }

    //redirect to
    Session::flash('success','Tour is successfully created !');
    return redirect()->route('tours.show',$tour->id);
}

I'm successful to save data into tours table but unable to save in featured_image table. I 'm getting this error:
Call to undefined method Illuminate\Database\Query\Builder::associate()

I would be thankful if anyone can help me out.

A: You can user Mass Assignment to create your entries into DB like this:
$this->validate(request()->all(), [
    'title'    => 'required|max:255',
    'content'  => 'required'
]);

$tour_inputs = array_only(
    $tour_inputs.
    [
        'title',
        'content',
    ]
);

$tour = Tour::create($tour_inputs);

if($request->hasFile('featured_image')) {
    $image = $request->file('featured_image');
    $filename = $image->getClientOriginalName();
    $location = public_path('images/featured_image/'.$filename);
    Image::make($image)->resize(800, 600)->save($location);

    $featuredImage = $tour->featuredImage()->save(new FeaturedImage([
        'name' => $filename,
        'path' => $location,
    ]));
}

Remember to define the $fillables inside your models, your models should look like this,
do check your relations, that you've made in the models, according to me they aren't correct:

class Tour extends Model
{
    protected $fillables = [
        'title',
        'content',
    ];

    public function featuredImage()
    {
      return $this->hasOne('App\FeaturedImage');
    }
}

class FeaturedImage extends Model
{
    protected $fillables = [
        'name',
        'path',
        'tour_id',
    ];

    public function tour()
    {
      return $this->belongsTo('App\Tour');
    }
}

Hope this helps!

A: From your code the relationships that you have defined are in reverse order.
I mean logically, a Tour has one FeaturedImage and a FeaturedImage belongs to a Tour.
class Tour extends Model
{
    //Mass Assignable fields for the model.
    $fillable = ['title', 'content'];

    public function featuredimage()
    {
        return $this->hasOne('App\FeaturedImage');
    }
}

and
class FeaturedImage extends Model
{

    //Mass Assignable fields for the model
    $fillable = ['tour_id', 'name', 'path'];

     public function tour()
     {
        return $this->belongsTo('App\Tour');
     }
}

Then in your controller
public function store(Request $request)
{

    //validate the data
    $this->validate($request, [
        'title'    => 'required|max:255',
        'content'  => 'required'
    ]);
    //store the data

    $tour = Tour::firstOrCreate([  //protection against duplicate entry
        'title' => $request->get('title'),
        'content' => $request->get('trip_code')
    ]);

    if($tour)  //if the Tour exists then continue
    {
        // save featured_image
        if($request->hasFile('featured_image')){
            $image = $request->file('featured_image');
            $filename = $image->getClientOriginalName();
            $location = public_path('images/featured_image/'.$filename);
            Image::make($image)->resize(800, 600)->save($location);

           $featured_image = $tour->featuredimage()->create([
                'path' => $location,
                'name' => $filename //if you have this field on your FeaturedImage
        }
        //you could also have an else block to redirect back if the input doesn't have a file

        //redirect to
        Session::flash('success','Tour is successfully created !');
        return redirect()->route('tours.show',$tour->id);
    }
    else
    {
        //if there occurs any error display the error message and redirect back - probably with validation errors or exception errors
        Session::flash('error','Error message');
        return redirect()->back()->withInput()->withErrors();
    }

}

And don't forget to add the mass assignable fields to the $fillable array on your models.
UPDATE
For cases where a single form submission includes database transactions in multiple tables, you should use a try{}catch{} to ensure that either all related transactions run without any issue or neither of the transactions go through - to avoid data discrepancy.
You can rewrite your controller code as
public function store(Request $request)
{

    //validate the data
    $this->validate($request, [
        'title'    => 'required|max:255',
        'content'  => 'required'
    ]);
    //store the data

    //use the DB::beginTransaction() to manually control the transaction
    //You would ideally want to persist the data to the database only if the input provided by the user
    //has valid inputs for Tour as well as FeaturedImage, in case if any one invalid input you do not
    //want to persist the data
    DB::beginTransaction();

    try
    {
        //firstOrCreate gives protection against duplicate entry for tour with same title and content
        $tour = Tour::firstOrCreate([
            'title' => $request->get('title'),
            'content' => $request->get('trip_code')
        ]);

        //proceed further only if $tour exists
        if($tour)
        {
            // get featured_image
            if($request->hasFile('featured_image')){
                $image = $request->file('featured_image');
                $filename = $image->getClientOriginalName();
                $location = public_path('images/featured_image/'.$filename);
                Image::make($image)->resize(800, 600)->save($location);

            //save the featured_image
               $featured_image = $tour->featuredimage()->create([
                    'path' => $location,
                    'name' => $filename //if you have this field on your FeaturedImage
            }

       }
    }
    catch(\ValidationException $e)
    {
        //In case of validation error, rollback the database transactions to avoid data discrepancy.
        DB::rollBack();

        $errors = $e->getMessage();
        Session::flash('error', 'Whoops.. Please check the provided inputs');
        return redirect()->back()->withInput()->withErrors['errors', $errors];
    }
    catch(\Exception $e)
    {
        //In case of any other error, rollback the database transactions to avoid data discrepancy.
        DB::rollBack();

        $errors = $e->getMessage();
        Session::flash('error', 'Whoops.. Something went wrong. Please try again');
        return redirect()->back()->withInput()->withErrors['errors', $errors];
    }

    //If both the transactions to the database i.e. saving the Tour as well as FeaturedImage ran without problem
    //Commit to the database
    DB::commit();

    //redirect to
    Session::flash('success','Tour is successfully created !');
    return redirect()->route('tours.show',$tour->id);

}

Hope this helps.


text:
Q: How to parse emojis and convert to images? I'm sure there is already a ruby gem that supports this...I want to parse a string which could potentially contain an emoji and replace it with an HTML image. How can I do this?

A: See gemoji-parser.
While many libs provide raw emoji data, they tend to be a bit underwhelming on parsing firepower that actually transforms emoji between symbol types (unicode, tokens, emoticons, images, etc). The above is a parser extension for gemoji data.

A: The Emoji gem
The first section here does what you want.

A: You can take a look at gemoji by the Github team.

A: You can look at the source of Twemoji's source code, bascially it builds up a huge emoji pattern, match, replace with image.


text:
Q: Show that $AB=0 \iff A=A^2$ and $B=B^2$ Let $n$ be a positive integer and let $\Bbb F$ be a field.
Let $A,B \in M_{n\times n} (\Bbb F)$ satisfy $A+B=I$.
Show that $AB=0 \iff A=A^2$ and $B=B^2$ where $0$ is the zero matrix.
If $A,B$ are matrices that add to be the identity matrix, does this mean that they are inverses of each other, or does this problem require transpose properties?
I'm in need of a serious refresher and am trying to grasp this problem.

A: We have: $A+B=I\,\;\;\;(1)$.
Suppose $A^2=A$ and $B^2=B$.

*

*We have from $(1)$, $A(A+B)=AI=A$ then $A^2+AB-A=0$ hence $AB=0$.

*Also from $(1)$, $(A+B)B=IB=B$ then $AB+B^2-B=0$ hence $AB=0$.
Suppose $AB=0$.

*

*We have from $(1)$, $B=I-A$, then $B^2=(I-A)B=B-AB$, hence $B^2=B$.

*Also from $(1)$, $A=I-B$, then $A^2=A(I-B)=A-AB$, hence $A^2=A$.

A: $B=I-A\implies AB=A(A-I)=A^2-A=A-A=0$

A: We have $0=AB=A(I-A)=A-A^2$ and $0=AB=(I-B)B=B-B^2$

A: Suppose $A+B=I.$ We will show:
$$AB=0⟺A=A^2 \mbox{ and } B=B^2$$
$(\Rightarrow)$. Since $AB=0$, hence $A(I-A)=0$, thus $A-A^2=0$. So $A=A^2$.
$(\Leftarrow)$. Since $B=B^2$, hence $AB = AB^2$, so $AB = (I-B)B^2$, so $AB = B^2-B^3,$ so $AB=B^2-B^2$ (check this), therefore $AB=0$.


text:
Q: How to reorder column values in a table? When I delete some rows from a table it looks like the following table after removing:
+-----+--------+----------+
| ID  |  Name  | Address  |
+-----+--------+----------+
| 1   | name1  | address1 |
| 2   | name2  | address2 |
| 8   | name8  | address8 |
| 9   | name9  | address9 |
+-----+--------+----------+

The problem is the ID isn't ordered properly.
I need it to be reordered like this:
+----+---------+----------+
| ID |  Name   | Address  |
+----+---------+----------+
| 1   | name1  | address1 |
| 2   | name2  | address2 |
| 3   | name8  | address8 |
| 4   | name9  | address9 |
+-----+--------+----------+

Is there a command to reorder the column like shown?
I'm using sqlite

A: I think this type of query should do that:
UPDATE yourTable
SET ID = (SELECT COUNT(*) FROM yourTable ti WHERE ti.ID <= yourTable.ID)


text:
Q: function() takes 0 positional arguments but 1 was given error for function calling I'm a beginner Python programmer and I'm trying to understand functions properly. I want to understand why this function is not working and what the error message means.
def input():
    loop = True

    while loop == True:
        userInput = input('> ').lower()

        if userInput == 'help':
            help()

def main():
    input()

main()

This is a small section cut from my source code.
I expect this to simply ask for user input and if it is 'help' run the help function which is defined elsewhere in my code.
The problem is that I am receiving an error message that states the following:

TypeError: input() takes 0 positional arguments but 1 was given

I'm not exactly sure what a type error is or why this is happening here.

A: You are facing this issue because input is a built-in function in python. Kindly rename input to input_1 and it would work

A: You are redifining the input built-in funtion, simply rename yours:
def my_input():
    loop = True
    while loop == True:
        userInput = input('> ').lower()
        if userInput == 'help':
            help()

def main():
    my_input()

main()

A: In the first line of your code you define input to be a function that takes no arguments. This shadows the builtin input function of python.

A: You redefined python's built-in input function as a function which takes 0 arguments when you defined your input function. Consider using a different name for your function.

A: The line userInput = input('> ').lower() calls the function input with the argument '> '

A: Since input is a function already defined in python, it is throwing an error. Try
def input_func():
    loop = True

    while loop == True:
        userInput = input('> ').lower()

        if userInput == 'help':
            help()

def main():
    input_func()

main()


text:
Q: mysql complicated join I have run into some troubles while writing a query for MySQL. I don't know how to describe my problem well enough to search the web for it, so sorry if my question is stupid.
I have 3 tables:
CREATE TABLE posts( id INT, author INT );
CREATE TABLE users( id INT, nick varchar(64) );
CREATE TABLE groups( id INT, name varchar(64) );
CREATE TABLE membership (user INT, group INT, date INT ) ;

Membership contains info about users that have joined some groups. "Date" in the membership table is the time when a user joined that group.
I need a query which will return a post, its author's nick and the name of the group with the least joining date.
All I have currently is:
SELECT p.id, u.nick, g.name
FROM posts AS p
    LEFT JOIN users AS u ON u.id = p.author
    LEFT JOIN membership AS m ON m.user = p.author
    LEFT JOIN groups AS g ON g.id = m.group
WHERE 1;

but of course it returns a random group's name, not the one with earliest joining date.
I also tried the following variant:
SELECT p.id, u.nick, g.name
FROM posts AS p
    LEFT JOIN users AS u ON u.id = p.author
    LEFT JOIN
              (SELECT * FROM membership WHERE 1 ORDER BY date ASC)
              AS m ON m.user = p.author
    LEFT JOIN groups AS g ON g.id = m.group
WHERE 1;

but it gave me same result.
I would appreciate even pointers to where I could start, because at the moment I have no idea what to do with it.

A: Something like this
SELECT p.id, u.nick, g.name
  FROM posts p,
       users u,
       membership m,
       groups g
 WHERE p.author = u.id
   AND m.user = u.id
   AND m.group = g.id
 ORDER BY m.date ASC
 LIMIT 1;

Take care to have good indexes when joining these 4 tables.

A: I don't know why you want what you do, however, if you want the information for the earliest membership date (since there's no date for posting itself), no problem.  Now, we have the earliest membership which will always point to the same one person as you are not asking for a specific group.. (or did you want the earliest person PER membership group -- which is what I'll write the query for).  Now, we have the earliest user and can link to the posts table (by apparently the author), but what if someone has 20 posts under their name... Do you also want the FIRST ID for that author.
Just copying from your supplied tables as a reference...
posts: id (int), author(int)
users: id (int), nick (varchar)
groups: id (int), name (varchar)
membership: user (int), group (int), date (int)
select
      u1.nick,
      m2.date,
      g1.name,
      p1.id as PostID
   from
      ( select m.group,
               min( m.date ) as EarliestMembershipSignup
           from
              Membership m
           group by
              m.group ) EarliestPerGroup

      join Membership m2
         on EarliestPerGroup.Group = m2.Group
        AND EarliestPerGroup.EarliestMembershipSignup = m2.Date

         join groups g1
            on m2.group = g1.id

         join users u1
            on m2.user = u1.ID

            join posts p1
               on u1.id = p1.author

A: I'd recommend moving your date column from the membership table into your groups table since that seems to be where you're tracking that information.  The membership table is just an intersection table for the many-to-many users<->groups tables.  It should only contain user ID and the group ID columns.
What about this?
SELECT p.id, u.nick, g.name
FROM
  users u,
  posts p,
  groups g
INNER JOIN membership m
  ON u.id = m.user
INNER JOIN groups
  ON m.group = groups.id
ORDER BY g.timestamp DESC
LIMIT 1;


text:
Q: c++ with ndk platform error help '_IOR' was not declared in this scope anyone can tell me why i get this error when compile cpp code with ndk:
C:/ndk/samples/fmservice/src/jni/JFmRxNative.cpp:304:24: error: expected primary-expression before 'struct'
C:/ndk/samples/fmservice/src/jni/JFmRxNative.cpp:304:24: error: '_IOR' was not declared in this scope
line 304 : res = ioctl(radio_fd,VIDIOC_QUERYCAP,&cap); character 24: VIDIOC_QUERYCAP

nd i used C:\ndk\platforms\android-14 files

A: seams i need to add this #include <sys/ioctl.h>


text:
Q: Get elements of a sublist in python based on indexes of a different list I have two lists of lists.
I want to get the elements from second list of lists, based on a value from the first list of lists.
I if I have simple lists, everything go smooth, but once I have list of list, I'm missing something at the end.
Here is the code working for two lists (N = names, and V = values):
N = ['name 1', 'name 2','name 3','name 4','name 5','name 6','name 7','name 8','name 9','name 10']

V = ['val 1', 'val 2','val 3','val 4','val 5','val 6','val 7','val 8','val 9','val 10']

bool_ls = []
NN = N
for i in NN:
        if i == 'name 5':
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)

# GOOD INDEXES = GI

GI = [i for i, x in enumerate(bool_ls) if x == 'y']

# SELECT THE GOOD VALUES = "GV" FROM V

GV = [V[index] for index in GI]

if I define a function, works well applied to the two lists:
def GV(N,V,name):
    bool_ls = []
    NN = N
    for i in NN:
        if i == name:
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)
    GI = [i for i, x in enumerate(bool_ls) if x == 'y']
    GV = [V[index] for index in GI]

    return GV

Once I try "list of list", I cannot get the similar results. My code looks like below so far:
NN = [['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3']]

VV = [['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3']]

def GV(NN,VV,name):
    bool_ls = []
    NNN = NN
    for j in NNN:
        for i in j:
            if i == name:
                i = 'y'
            else:
                i = 'n'
            bool_ls.append(i)

# here is where I'm lost

Help greatly appreciated! Thank you.

A: You can generate pair-wise combinations from both list using zip and then filter in a list comprehension.
For the flat lists:
def GV(N, V, name):
    return [j for i, j in zip(N, V) if i==name]

For the nested lists, you'll add an extra nesting:
def GV(NN,VV,name):
    return [j for tup in zip(NN, VV) for i, j in zip(*tup) if i==name]

In case you want a list of lists, you can move the nesting into new lists inside the parent comprehension.

A: There's an easier way to do what your function is doing, but, to answer your question, you just need two loops (one for each level of lists): the first list iterates over the list of lists, the second iterates over the inner lists and does the somewhat odd y or n thing to chose a value.


text:
Q: Executing a .jar which makes use of native libraries (Java , .dll) I have 2 different projects in java and I need to do the following with them:
After a certain button from the program A is pressed, the program B is loaded and the program A is closed.
Even though both projects have classes and dlls in common, I really do not want to merge everything into one single project.
I have done some searching and I found out that one possible solution would be to load the program B from a .jar using the following example of code:
btnMyButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        try {
            Runtime.getRuntime().exec("java.exe -jar \\url\\ProgramB.jar");
        } catch (IOException e1) {
                e1.printStackTrace();
        }
    }
});

I tried many variations of this (without the ".exe", for instance), and I made sure that the ProgramB.jar was in the same folder of its dlls, but nothing of this seemed to work.
So, I tried to open the ProgramB.jar directly (via Windows), and apparently everything was ok.
Later on, I tried to execute the ProgramB.jar via cmd (because I thought that the command "java.exe -jar \\url\\ProgramB.jar" could be executed on it).
Even though I have set the library path (java -Djava.library.path=\\url\\ -jar \\url\\ProgramB.jar), an UnsatisfiedLinkError was thrown every time(X.dll->cannot find dependent libraries).
(Note: I won't be able to provide all the exception messages for a while because by the moment I do not have the program with me...)
Anyway, I am not sure exactly what I am doing wrong, but apparently there aren't any problems with the dlls implementation,
since I was able to execute the program at least once. Any ideas are welcome.

A: The problem is java does not recognize the dll if is not in java.path
So first solution:
 put your dll in a java.path for example in windows C:\Windows\System32

Second solution
Set a new java variable which indicating the path where exist .dll file.

Also VMoption must be like:
-Djava.library.path="path_to_dll"
This is not correct -Djava.library.path=path_to_dll\\dllname.dll


text:
Q: How to update div color dynamically everythime php function is re-run in html page I am trying to have a div which will show the server status with green or red background color.
The background color should change when the php function sets a $status variable to green or red, which will be used in the div to set the background-color parameter!
This is working when I reload the webpage but I would like to run the php function in intervals and update the color of the div field automatically without reloading the webpage.
See what I have till now:
<!DOCTYPE HTML>

Measurements - graphs

<?php
function getStatus() {
    $status = "#008000";
    $latestFile = '/my/web/logs/logging_rotation.out';

    if (file_exists($latestFile)) {
        $fileTime = filectime($latestFile);
        $now = microtime(true);
        $timediff = $now - $fileTime;
    }
    if ($timediff < 60) {
            $status = "#008000";
    } else {
        $status = "#FF0000";
    }
    return $status;
}
?>
<div style="height: 20px; background-color: <?php echo getStatus()?>;">
Server status

So, what I miss now is a way to run php getStatus in intervals and that should update the background-color and it should update the div field. Is there a way to do that?
After some first suggestions I modified my code to:

Server status

But, it seems that the doSomething() is not executed because I don't see any of the console.log printouts!
All the above page is saved as mypage.php and I test this in two ways:

*

*reload the mypage.php in a browser.

*execute the mypage.php via php command:

php mypage.php > test.html

In both cases I don't get any of the printouts in doSomething().
Is this the correct way to test this kind of php pages?
Update after some further tries and now it works, no changes in the status.php, the issue was the path to status.php:

Measurements - graphs

Server status

Both below answers and solutions are working!
Regarding the second solution I modified it to:

Measurements - graphs

Server status

status.php:
<?php
    $status = "#008000";
    $latestFile = '/my/web/logs/logging_rotation.out';
    if (file_exists($latestFile)) {
        $fileTime = filectime($latestFile);
        $now = microtime(true);
        $timediff = $now - $fileTime;
    }
    if ($timediff < 60) {
        $status = "#008000";
    } else {
        $status = "#FF0000";
    }
    exit($status); //return the result to the JS
?>

I do like both solutions, because one is using asynchronous programming and the other one is really compact! I guess in my case the asynchronous programming has more a knowledge benefit then actually for my website and just checking if my server is still up & running by checking if the elapsed time of last modification of the log file is under 60s.
Thanks again

A: You will need 2 javascript functions.

*

*setTimeout()
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
This will call a function at an interval

*fetch()
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
This
make an http call to the server

Example

or if you are feeling adventurous:
const myDiv = document.getElementById('serverStatus');
setInterval(async () =>
  myDiv.style.backgroundColor = await (await fetch('status.php')).text(),
  1000 // ms
);

your status.php only needs to return the color code

A: You can do this using javascript.
Add an ID to your
, lets say <div id="serverStatus" style="height: 20px; background-color: <?php echo getStatus()?>;">, and then add a timed function to a

Then create the js for calling the PHP function and updating the background color:

This will use the Fetch API to run a function in a PHP file called "myPhpFile.php".
I formulated this as below, using your PHP from above and only adding checks to see that this is the function you are calling:
<?php
    If(isset($_POST['function'])) { //checks that the parameter function is set
        if($_POST['function']=="serverStatus") { //checks that this is the function asked for
            $status = "#008000";
            $latestFile = '/my/web/logs/logging_rotation.out';

            if (file_exists($latestFile)) {
                $fileTime = filectime($latestFile);
                $now = microtime(true);
                $timediff = $now - $fileTime;
            }
            if ($timediff < 60) {
                $status = "#008000";
            } else {
                $status = "#FF0000";
            }
            exit($status); //return the result to the JS
        }
    }
?>

I'll note that I have not tested the PHP function you are using to get the filetime, but the javascript is one that is in use, as well as the basic model of the php.


text:
Q: Remove array element when subarray has certain values I have an array that contains any number of subarrays, each containing exactly two values.
i.e: interestArray[[1, 5], [3, 8] ... ]

How do I remove say the subarray containing the values [3, 8]?
My code is:
$('td', container).click(function(){
      if(!$(this).hasClass('purchased') && !$(this).hasClass('manu'))
      {
        var manuId = $(this).parent().children('td:first-child').data('manu-id');
        var typeId = $(this).data('type-id');
        if($(this).hasClass('interest'))
        {
          $(this).removeClass('interest');
          $(this).parent().children('td.manu').removeClass('interest');
          var index = interestArray.indexOf([manuId, typeId]);
          interestArray.splice(index, 1);
        } else {
          $(this).addClass('interest');
          $(this).parent().children('td.manu').addClass('interest');

          interestArray.push([manuId, typeId]);
        }
      //updateSurvey(interestsArray);
      console.log(interestArray)
      }
    })

The below section does not work, and simply removes the first subarray.
var index = interestArray.indexOf([manuId, typeId]);
interestArray.splice(index, 1);

A: Here's a generic approach with your requirements:
var arr = [[1,2],[3,4],[5,6]];
var remove = [3,4];

for (var i=0; i<arr.length; i++) {
  if (arr[i][0] == remove[0] && arr[i][1] == remove[1]) {
    arr.splice(i, 1);
    break;
  }
}

console.log(arr); //=> [[1,2],[5,6]]

A: For a general approach, you can filter the array:
var reducedArray = interestArray.filter(function (item) {
    return item[0] != manuId || item[1] != typeId;
});

You cannot use indexOf because that looks for the identical object (not merely an equivalent one).
If you're running an earlier version of JS that doesn't have Array.filter, there's a nice shim on the filter doc page linked to above.

A: Here is my personal solution more complete to avoid multiple entry issue and the break; thing seen above, it also avoids an issue if the array is after entry removal (it is jquery based but you can make a regular loop if you feel more comfy with it):
    $.each( answers, function( index, value ){
        if (typeof answers[index] != "undefined")
        {
            if(answers[index]["question_id"]==answer_to_del)
            {
                delete answers[index];
            }
        }

    });
    //Clean answer array from empty values created above
    answers = answers.filter(function(n){ return n != undefined });


text:
Q: Run bash command with json parameters from jq How can I run a bash command for every json object in a json array using jq? So far I have this:
cat credentials.json | jq -r '.[] | .user, .date, .email' | mycommand -u {user} -d {date} -e {email}

This doesn't seem to work. How can I take the parameters out of the json array into my command?
My json file looks something like this:
[
   "user": "danielrvt",
   "date": "11/10/1988",
   "email": "myemail@domain.com",
   ...
]

A: Here is an solution based on my answer to a similar question on Stack Overflow.
#!/bin/bash
json='
[
  {
   "user": "danielrvt",
   "date": "11/10/1988",
   "email": "myemail@domain.com"
  },
  {
   "user": "anotheruser",
   "date": "1/1/1970",
   "email": "anotheruser@domain.com"
  }
]
'

jq -M -r '
    .[] | .user, .date, .email
' <<< "$json" | \
while read -r user; read -r date; read -r email; do
   echo "$user $date $email"
done

Example output
danielrvt 11/10/1988 myemail@domain.com
anotheruser 1/1/1970 anotheruser@domain.com

In your case you could replace the use of <<< "$json" with < credentials.json and the echo "$user $date $email" with mycommand -u "$user" -d "$date" -e "$email" as appropriate but this should make clear the basic idea.

A: you can use a for loop, for example
#!/bin/bash

JSONARRAY=$(cat credentials.json | jq -r '.[] | .user, .date, .email' | mycommand -u {user} -d {date} -e {email} | grep -v "[\|]")
for line in $JSONARRAY; do
    some command
done


text:
Q: UltraGrid MouseDown event separate column resize from other left clicks I have an infragistics ultragrid component that shows some data. One of the events that is captured is the MouseDown event.
When the left mouse button is pressed, this could either mean that the user has selected an item, or is currently dragging the column headers.
The element is identified by use of the ElementFromPoint Method (see below). But when I resize the column header, this method will still return the first data element in the list. I need to know when the user modifies the column width as opposed to selecting or dragging an item. Is this possible at this point?
Private Sub ugTask_MouseDown1(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ugTask.MouseDown

        Select Case e.Button
            Case MouseButtons.Left
                Try

                    Dim aUIElement As Infragistics.Win.UIElement = ugTask.DisplayLayout.UIElement.ElementFromPoint(New Point(e.X, e.Y))

                    m_aRow = aUIElement.GetContext(GetType(Infragistics.Win.UltraWinGrid.UltraGridRow))

A: It's not perfect, but I found a way around this by checking the cursor type. The only time the cursor will change is when I try to resize a column. So now I can do
If Not cursor.Current = Cursors.Default Then
    Return
End If


text:
Q: Регулярное выражение для получения атрибутов запроса Вот код:
var query = "id  INT    (10)  AUTO_INCREMENT  KEY,  name  VARCHAR( 255 ),  info  VARCHAR    ( 255)  DEFAULT('your text' )  DEFAULT('your text' ) AUTO_INCREMENT, text ,   age INT(2), date DATETIME DEFAULT(NOW()), counter INT(10) DEFAULT(10)".split(',');
var regular = /\w+([\s]*\((.*?)\)(\s|$)|(\s|$))/g;

for(var i=0, matches; i < query.length; i++) {
    query[i] = query[i].trimLeft();

    matches = query[i].match(regular);

    console.log(query[i]);
    console.log(matches);
}

Как видно, я парсю query запрос на значения и атрибуты. Скорость парсинга должна быть большой, поэтому экономлю на спичках. Как оптимизировать регулярку?
Пример в живую: http://jsfiddle.net/2ZnjL/
A: Короче говоря было написано:
var parse_expression = "id  INT  (10)  AUTO_INCREMENT  KEY,  \
name  VARCHAR( 255 ),  \
info  VARCHAR    ( 255)  DEFAULT('your text' )  DEFAULT('your text' ) AUTO_INCREMENT, \
text ,   \
age INT(2), \
date DATETIME DEFAULT(NOW()), \
counter INT(10) DEFAULT(10), \
other varchar(255) DEFAULT ('your (mine) text'),\
other2 varchar(255) DEFAULT ('use close braket - ) to finish condition string '),\
other3 varchar(255) DEFAULT ('stop,the split,) ')";

var div = document.getElementById('b');

var len = parse_expression.length;
var tokens = [];
var compiler_tokens = {};
var tags = ["'", '"', '(', ')'];
var token = '';
var ifOpenTokens;

for(var pos = 0, last_cut = 0; pos < len; pos++, ifOpenTokens = false) {
    if(tags.indexOf(parse_expression[pos]) != -1) {

        if(!(parse_expression[pos-1] != undefined
            && parse_expression[pos-1] == '\\'  // если предыдущий символ - обратный слеш
            && parse_expression[pos-2] != undefined
            && parse_expression[pos-2] != '\\')
            || parse_expression[pos-1] != '\\'// если предыдущий символ - не слеш, то обрабатываем
        ) {

            if(compiler_tokens[parse_expression[pos]] == undefined || !compiler_tokens[parse_expression[pos]]) {
                if((parse_expression[pos] == '(' || parse_expression[pos] == ')')
                    && (compiler_tokens['"'] == undefined || !compiler_tokens['"'])
                    && (compiler_tokens["'"] == undefined || !compiler_tokens["'"])
                ) {
                    compiler_tokens[parse_expression[pos]] = 1;
                }
                else if(parse_expression[pos] == '(' || parse_expression[pos] == ')') {
                    continue;
                }
                else {
                    compiler_tokens[parse_expression[pos]] = true;
                }
            }
            else {
                if((parse_expression[pos] == '(' || parse_expression[pos] == ')')
                    && (compiler_tokens['"'] == undefined || !compiler_tokens['"'])
                    && (compiler_tokens["'"] == undefined || !compiler_tokens["'"])
                ) {
                    compiler_tokens[parse_expression[pos]]++;
                }
                else if(parse_expression[pos] == '(' || parse_expression[pos] == ')') {
                    continue;
                }
                else {
                    compiler_tokens[parse_expression[pos]] = false;
                }
            }
        }
    }

    if(parse_expression[pos] == ',') {
        // check for open tokens
        console.log(compiler_tokens['"'], compiler_tokens['\'']);

        if(compiler_tokens['('] != compiler_tokens[')']
        && (!compiler_tokens['"'] && !compiler_tokens["'"])) {
            throw new Error("Remained unclosed tags in query '"
                + parse_expression.substring(last_cut, pos));
        }
        else {
            if(compiler_tokens['"'] || compiler_tokens["'"]) {
                ifOpenTokens = true;
            }
        }

        if(!ifOpenTokens) {
            token = parse_expression.substring(last_cut, pos);
            tokens.push(token);
            last_cut += token.length + 1;
        }
    }

    if(pos == len - 1) {
        token = parse_expression.substring(last_cut, pos + 1);
        tokens.push(token);
    }
}

if (compiler_tokens['"'] || compiler_tokens["'"]) {
    throw new Error("Remained unclosed tags in query '"+ parse_expression);
}

:D Собака убежала, вроде годно работает. Скрипт также будет разбирать данные в INSERT.


text:
Q: ARANGODB ensureIndex to create full text not working I have events collection inserted with a below record in ARANGODB. ( I am new to Arango )
INSERT {
    "source": "ABC",
    "target": "ZYX",
    "tranno": "ABCDEF",
    "type": "REST",
    "attributes" : { "myID" : "12345"}
} INTO events

But trying to create full text index on attributes, resulting in error as given below. It would be great if you could help with this.
events.createIndex ({ type: "fulltext", fields: [ "attributes" ], minLength: 3 })

Query: AQL: syntax error, unexpected identifier near 'events.createIndex ({ type: "ful...' at position 1:1 (while parsing)

A: Unlike SQL, AQL is a language used for data selection and data manipulation.
It is not a data definition language, so you can't use AQL to create indexes.
In order to create an index, please use ArangoDB's web interface (Collections => target collection => Indexes => "+" icon) or the ArangoShell. The ArangoShell is a separate executable that is shipped with all ArangoDB packages.
In the ArangoShell you can use the command
db.events.createIndex ({ type: "fulltext", fields: [ "attributes" ], minLength: 3 })

to create the index.


text:
Q: pgfplots multiple plots in one file In pgfplots is it possible to have several plots in one datafile?
The goal is to add about 20 plots, which has different number of points and not the same x-value, to the same axis. (app. 350 points)

One posible solution is to have the plots in separate column, and then use loads of 'nan' because of the different x values:
    x  p1   p2  P3  ...
    1  3    nan nan ...
    2  nan  5   nan ...
    6  4    8   nan ...
    8  7    nan nan ...
    ...

I do not like this solution:o(

The gnuplot solution is nice: the different plots are separated in the datafile by two newlines, and they are selected by 'index'. Does something similar exist in pgfplots? or any other solution?

A: You can use gnuplot in the background by using \addplot gnuplot [raw gnuplot] {<gnuplot commands>};:

\documentclass{article}
\usepackage{pgfplots}
\usepackage{filecontents}

\begin{filecontents*}{data.txt}
1 1
2 4
3 9
4 16
5 25

1 1
2.5 5
6 12
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot gnuplot [raw gnuplot] {plot 'data.txt' index 0};
\addplot gnuplot [raw gnuplot] {plot 'data.txt' index 1};
\end{axis}
\end{tikzpicture}
\end{document}

A: You can use the \addplot command multiple times on the same axes. The files that the different \addplots take can be the same or different, and different columns etc.
\pgfplotsset{width=6cm,compat=newest}
\begin{axis}[
    scale only axis,
    xlabel={$\tau$ ($\mu$s)},
    ylabel={P(bitflip)},
    ymin=0,
    ymax=1,
    xmin=0,
    xmax=125.66,
]
\addplot[color=red]
    table[x=time,y=fidelity] {data1.txt};
\addplot[color=black]
    table[x=time,y=fidelity] {data1.txt};
\end{axis}
\end{tikzpicture}

It's not so clear here, but I used data from two sample files to plot this

The data files here are indexed by column headers, but you can also do this by number. One of the files begins with the following lines:
time    fidelity
0.00000000e+00  0.00000000e+00
2.02874597e-01  9.75413405e-05
5.19896845e-01  4.76482130e-04
8.36998426e-01  7.26895359e-04
1.15410184e+00  7.52986468e-04
1.47115744e+00  8.85559658e-04

You can put multiple columns in one file, and gaps (just whitespace) are tolerated. In the following plot one data file is used with four columns, and there are clear gaps in the time and amplitude entries for the red plot.

\pgfplotsset{width=6cm,compat=newest}
\begin{tikzpicture}
\begin{axis}[
    scale only axis,
    xlabel={$\tau$ (ns)},
    ylabel={Negativity},
    ymin=-1,
    ymax=1,
    xmin=0,
    xmax=6.3,
    legend style={font=\small,at={(0.5,0.96)},anchor=north,style={nodes={right}}},
]
\addplot[color=black]
    table[x index=0,y index=1] {data.txt};
\addplot[color=red]
    table[x index=2,y index=3] {data.txt};
\end{axis}
\end{tikzpicture}

Note that there are no column headers this time (just for variety). Gaps look like
2.28479466e+00  7.55749574e-01  -6.54860734e-01 2.28479466e+00
2.34826118e+00  7.12694171e-01  -7.01474888e-01 2.34826118e+00
2.41172769e+00  6.66769001e-01  -7.45264450e-01 2.41172769e+00
2.47519421e+00  6.18158986e-01
2.53866073e+00  5.67059864e-01
2.60212725e+00  5.13677392e-01
2.66559377e+00  4.58226522e-01
2.72906028e+00  4.00930535e-01
2.79252680e+00  3.42020143e-01
2.85599332e+00  2.81732557e-01
2.91945984e+00  2.20310533e-01
2.98292636e+00  1.58001396e-01
3.04639288e+00  9.50560433e-02
3.10985939e+00  3.17279335e-02
3.17332591e+00  -3.17279335e-02
3.23679243e+00  -9.50560433e-02
3.30025895e+00  -1.58001396e-01
3.36372547e+00  -2.20310533e-01
3.42719199e+00  -2.81732557e-01
3.49065850e+00  -3.42020143e-01
3.55412502e+00  -4.00930535e-01
3.61759154e+00  -4.58226522e-01 -8.88835449e-01 3.61759154e+00
3.68105806e+00  -5.13677392e-01 -8.57983413e-01 3.68105806e+00
3.74452458e+00  -5.67059864e-01 -8.23676581e-01 3.74452458e+00
3.80799110e+00  -6.18158986e-01 -7.86053095e-01 3.80799110e+00

It should also be fine to have uneven columns, provided the number of tabs or commas is correct.

A: The other answers weren't immediately clear to me. After struggling for a bit, I found that it's very easy to draw multiple lines from the same file.
You can simply put white lines in your data file and you're done:
\documentclass[]{article}
\usepackage{filecontents,pgfplots}

\begin{filecontents}{test.dat}
x   y
1   0.5
2   0.5
2   1
1   1
1   0.5

1   2.5
2   2.5
2   3
1   3
1   2.5
\end{filecontents}

\begin{document}
\begin{tikzpicture}[scale=1]
\begin{axis}
[
    axis lines=left, axis line style={->},
    xmin=0,xmax=5,
    ymin=0,ymax=5
]
\addplot [] table [x=x, y=y] {test.dat};    % Plot all shapes in data file
\end{axis}
\end{tikzpicture}
\end{document}

Which gives two separately drawed lines:

Hope this speeds up someone's search for an answer ;)


text:
Q: web.cors.allowed-origins in application.properties isn't allowing the CORS for specific urls I'm trying to enable the CORS throughout the app for "http://localhost/4200". Since I'm using Springboot 2 and accord. to its docs, I just have to add this property in application.properties file:
management.endpoints.web.cors.allowed-origins=http://localhost:4200

But this doesn't work. Secondly since there is a request I'm making through a restController, for the testing purpose, I tried to add the inline :
CrossOrigin(origins = "http://localhost:4401")

This allowed the flow of data through 4401 port too.

A: It is not possible to set CORS settings from the application.properties file.
The property management.endpoints.web.cors.allowed-origins is related to Spring Actuator.
If you want to use the setting for a specific endpoint, you can use the @CrossOrigin annotation as you mentioned in your question.
If you want to set a global policy for your application, you can add a configuration class / bean for setting the CORS settings.
See: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors
Related question:
Spring Boot enabling CORS by application.properties


text:
Q: Clickonce installation fails to download I had made a Clickonce deployemnt to my application set the installation folder and publishing folder the same that is a network share  and then it work perfect for my development machine
Then when I went to on client machine opened the network share and I tried to install the application using that setup file i got tht message like below

And in details  Iam getting the below message
LATFORM VERSION INFO
Windows             : 6.1.7601.65536 (Win32NT)
Common Language Runtime     : 4.0.30319.586
System.Deployment.dll       : 4.0.30319.1 (RTMRel.030319-0100)
clr.dll             : 4.0.30319.586 (RTMLDR.030319-5800)
dfdll.dll           : 4.0.30319.1 (RTMRel.030319-0100)
dfshim.dll          : 4.0.31106.0 (Main.031106-0000)

SOURCES
    Deployment url          : file://it-dept/Project/mycutorderlast/CutorderFresh.application
    Deployment Provider url     : http://it-dept/CutorderFresh/CutorderFresh.application

ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of \\it-dept\Project\mycutorderlast\CutorderFresh.application resulted in exception. Following failure messages were detected:
        + Downloading http://it-dept/CutorderFresh/CutorderFresh.application did not succeed.
        + The remote server returned an error: (404) Not Found.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [08/10/2013 14:03:25] : Activation of \\it-dept\Project\mycutorderlast\CutorderFresh.application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [08/10/2013 14:03:30] System.Deployment.Application.DeploymentDownloadException (Unknown subtype)
        - Downloading http://it-dept/CutorderFresh/CutorderFresh.application did not succeed.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
            at System.Deployment.Application.SystemNetDownloader.DownloadAllFiles()
            at System.Deployment.Application.FileDownloader.Download(SubscriptionState subState)
            at System.Deployment.Application.DownloadManager.DownloadManifestAsRawFile(Uri& sourceUri, String targetPath, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadManifest(Uri& sourceUri, String targetPath, IDownloadNotification notification, DownloadOptions options, ManifestType manifestType, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirect(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.FollowDeploymentProviderUri(SubscriptionStore subStore, AssemblyManifest& deployment, Uri& sourceUri, TempFile& tempFile, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
        --- Inner Exception ---
        System.Net.WebException
        - The remote server returned an error: (404) Not Found.
        - Source: System
        - Stack trace:
            at System.Net.HttpWebRequest.GetResponse()
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

Can anyone suggest what was the issue As Iam using clickonce for the first time

A: Check values of 'Publish Location' or 'Installation URL' on Publish tab of properties. According to your current settings, you should have published files accessible by this path: http://it-dept/CutorderFresh/CutorderFresh.application and it looks like they're not available by this path.
Here you can read how to set proper 'Publish Location' and 'Installation URL' values

A: I had this same issue and it was driving me mad.  I knew I had the proper permissions set up on the network's shared folder.  I couldn't even install my application from my own machine via the network share.  After searching long and hard for an answer I figured it out myself.
On the Publish tab of properties I only filled in the "Publishing Folder Location" with:
\servername\share\Application Folder
I left the "Installation Folder URL" section blank.
Somehow a field in the "Application Updates" section (via clicking "Updates" button on Publish tab) got filled in with a different value than what my network share was.  Not sure if I did this myself or if it was set by default.  I cleared out the "Update Location (if different than the publish location)" field and that fixed this issue for me.  Here is a screen shot of where I changed the field:
I would post a screen shot of the form that was causing me trouble but for some reason I need 10 reputation points to post a picture.

A: I resolved my problem like yours.
I don't know that "Publishing Folder Location" of my application (below "formtest" App.) is different from "Installation Folder URL".
In fact, two folders of former WEB server for click once deployment were not different. So, I was confused after WEB server was changed.

*

*Publishing Folder Location: \12.39.526.272\root\formtest\

*Installation Folder URL: http://12.39.526.272:8080/formtest/

*Application Updates section   "Update Location (if different than the publish location)" field : http://12.39.526.272:8080/formtest/
I'm so sorry My native language is not English.

A: I had the same error, but resolved it a different way.  Somehow I had accidentially unchecked something in the Options.
On the Publish tab, select "Options".  Under Deployment, make sure "Use .deploy file extension" is checked.  Once I checked that and republished, the error went away.


text:
Q: How do I assign a HTML title to different pages? I am developing a website with oure PHP and HTML on an Apache server. No CMS.
All of my website's pages from the main directory and its subdirectories call one header.php file.
I have now run into an issue with all of the page <title>'s, as these are obviously defined in the header, so now I don't know how to set a different title for each page.
Can anyone help?

A: The simplest way to do this is to have a variable that you set on the main page, before you include the header.php file, and then in the header.php file, use that title.
page.php
<?php

$title = "My Title";
include "header.php";

header.php
<title>

    // Default Title will be set if you forget to set the $title variable in page.php
    <?php echo isset($title) ? $title : "Default Title"; ?>

</title>

A: What I usually do is have the title tag like this:
<title><? echo $titleIs ?></title>

Then, on each page, before the header include, set the title:
<? $titleIs='Page Title' ?>


text:
Q: How can i run a task at particular time ? I need to silent the phone at the user given time I need to silent the phone at a particular time.The time is given by the user.
I am new to android.

A: Here is the code to set alarm manager:
private void settingAlarmManager (){

int requestCode = 12345

            calendar.set(selectedYear, selectedMonth - 1, selectedDay, selectedHour, selectedMinutes, 0); // For giving Date and Time for alert \\
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent notificationIntent = new Intent(AddTaskActivity.this, AlarmReceiver.class);
            PendingIntent broadcast = PendingIntent.getBroadcast(AddTaskActivity.this,
                    requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, broadcast);

        }

Here is the manifest Code:
<receiver android:name=".alarm.AlarmReceiver"/>

Here is the Alarm Receiver class:
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        //am.setRingerMode(0); // For Silent \\
        am.setRingerMode(1); // For Vibrate \\
        //am.setRingerMode(2); // For Ringer \\

    }
}

A: Use PendingIntent for triggering event at specified time and use AudioManager for changing the ringer mode like this:
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);


text:
Q: Is there a way to emulate an android application within a windows program? I realize it is an odd request, but I'm trying to enable an android app running within a windows program. It doesn't technically need to run within the program, but I would like to display the android app interface within my program along with being able to interact with the app. Anyone ever tried anything like this or could point me in the right direction? If it helps, I'm looking to do this within either a unity or unreal engine simulation.

A: Did you have a look at BlueStacks? It allows you to run Android app on Windows or Mac. You can try then to interact with it in a standard for Win/Mac way. But, since BlueStacks doesn't provide any API to access the application, you'll have to inject hooks on display related WinApi functions by yourself. And that's not the simplest task.
As an alternative I can suggest you to run Android app inside VirtualBox and use its SDK to access the app output and display it where you like to. You may also check the AndroVM project (predecessor of Genymotion) and its SDL player.


text:
Q: Как сделать редирект если заблокирована аналитика(трекер)? Помогите не могу сделать редирект на другую страницу на своем сайте если у пользователя заблокирована аналитика?

A: У вас вот здесь ошибка синтаксиса (нет закрывающего знака } )

Не понятно что вы хотите сделать с объектом content и его высотой? Он разве тут нужен?
Ну и window.location для перенаправления надо заменить на window.location.href

Это должно сработать. Проверьте.


text:
Q: An effective enumeration of recursive sets in increasing order Definition: We call a set recursive if its characteristic function is recursive.
Claim: If the set $A\subset\mathbb N$ is recursive then $A=Range(f)$ for some recursive and increasing function.
Proof: If $A$ is infinite define $h$ by
$$h(0)=\mu z[\chi_A(z)=1]$$
$$h(x+1)=\mu z[\chi_A(z)=1\land z>h(x)]$$
Here $\mu,\chi_A$ are the minimization operator and $A$'s characteristic function respectively.
If $A$ is finite then $A=\{a_1,\dots a_n\}$ with $a_1<a_2\dots<a_n$. Now define $h$ by
$h(i)=\begin{cases}
a_i & i<n \\
a_n & i\geq n\\
\end{cases}$
Clearly in each case the function $h$ satisfies the conditions of the theorem.
Questions:
1) Unless we can effectively decide on the ordinality of sets, the above procedure is ineffective. What is an effective procedure for enumerating recursive sets in increasing order?
2) If the set $A$ is infinite can we choose a strictly monotone enumeration function that is primitive recursive?

A: Okay, so a couple of things.
Suppose that you know the index $e$ such that $\varphi_e$ is the indicator function for a nonempty recursive set $A$ (so we are promised that $\varphi_e$ is total recursive and not identically zero).  Then:
- If you don't mind repeating elements, take $f(e,n) = n$ if $\varphi_e(n) = 1$ and $f(e, n) = f(e, n-1)$ otherwise, while $f(e, 0) = \mu x(\varphi_e(x) =1)$.
- If you don't like repeating elements in your enumeration of infinite recursive sets, you are out of luck.  Determining whether $\varphi_e$ is eventually $0$ (i.e., $A$ is finite) is not a computable task, nor is determining whether it is identically zero.  You could solve the halting problem if you could solve this.
This function of course doesn't converge for most $n$ when $\varphi_e$ is not total recursive (or when $\phi_e$ is never $1$).  If you need $f(e,n)$ to be an increasing enumeration when $\varphi_e$ is total recursive and the indicator function for a nonempty recursive set, and also be a total recursive function, you are again out of luck.  Once again this would solve the halting problem.

A: For (2), obviously not -- given an infinite decidable subset of $\mathbb N$, there is exactly one strictly monotone function that enumerates it, and that function does not have to be primitive recursive, as for example with
$$ \{n\mid \exists k<n: n=\mathsf A(k,k)\} $$
where $\mathsf A$ is Ackermann's function, which by construction is not primitive recursive.
For (1), it sounds like you want a procedure that takes an (always halting) program and a produces different program that enumerates its accept set in non-decreasing order. Once you accept repetitions (which is necessary to deal with finite sets), this should be as easy as creating a program that computes
$$ f(n) = \max\bigl( (A \cap \{ 0,1,\ldots,n \})\cup\{\min A\} \bigr)$$
... as long as $A$ is not empty, of course.


text:
Q: How is SecureString "encrypted" and still usable? According to MSDN SecureString contents is encrypted for additional safety so that if the program is swapped to disk the string contents can't be sniffed.
How is such encryption possible I wonder? The algorithm would be fixed and therefore either well-known or deductible (say one of seven widely used in industry algorithms) and there must be a key somewhere in the program. So the attacker could fetch the encrypted string, fetch the key and decrypt the data.
How can such encryption be useful?

A: As others have already answered, the contents of SecureString are encrypted using DPAPI, so the keys aren't stored in your application, they're part of the OS.  I'm not 100% positive, but I would assume that SecureString uses a user-specific key, so that even if another process gains access to the block of memory, it would have to be running under the same credentials in order to simply decrypt the content using the DPAPI.  Even if not, the machine key (in theory) prevents the string from being readily decrypted if transferred to another system.
More important with SecureString is how & when you use it.  It should be used to store string data that needs to be retained in memory for "extended" periods of time, but which are not frequently needed in their decrypted form.  At some point, you're going to have to decrypt it into a regular old System.String, or a System.Char[].  This is when it's most vulnerable in memory.  If you do this too often, then you have multiple copies of the decrypted string floating around in memory waiting to be collected.
As a general rule, if I'm reading encrypted data (say login credentials) that I need to retain for infrequent use (PayPal or Amazon API interaction, for instance), then I store/cache those credentials as SecureString, then decrypt it as-needed only long enough to make the web service calls, and ensure that the lifespan of any decrypted copy is only a few lines of code.
It's probably also wise to use critical blocks or similar to hint to the CLR that it should not context-switch while the decrypted string is in use, to improve the chances that any decrypted copies are collected before the memory is cached or swapped.

A: By the magic of DPAPI:

This class stores its data using the Data Protection API (DPAPI) protected memory model. In other words, data is always in its encrypted form while it is stored inside of a SecureString. The encryption key is managed by the local security authority subsystem (LSASS.EXE), and through the DPAPI, the data can be decrypted via interprocess communication.

A: I'm quoting from an article about the DPAPI which is used to derive the key. This should answer most questions that you have about SecureString.
And yes, SecureString has drawbacks and is not completely secure, there are ways to access to data, for example, injecting Hawkeye into the process is mentioned on MSDN as a way to extract the SecureString. I have not personally verifed this assertation.
DAPI Key Management

DAPI is a symmetric based encryption technique, which means it uses the same key to both encrypt and decrypt data. Before getting to some examples of how to use DAPI it's worth covering how DAPI manages its key. For the most part DAPI key management process is invisble and you generally don't need to worry about it, which is the main reason why DAPI is a good approach.
In the introduction I wrote that the master key is generated from the user's login password. This isn't the complete picture. What actually happens is Windows uses the user's login password to generate a master key. This master key is protected using the user's password and then stored along with the user's profile. This master key then gets used to derive a number of other keys and it's these other keys that are used to protect the data.
The reason why Windows does this is it allows applications to add additional information, called entropy, to the process of generating the individul keys. You see if every application running under the user's login account used the same key then every application could unprotect DAPI protected data. Sometimes you might want applications to be able to share DAPI protected data; however, sometimes you won't. By letting the application contribute entropy to the generation of a key then that key becomes application specific and any data that is protected by that application can only be unprotected again if they know the entropy.
Although generating a master key, and then using that master key to generate other keys to do the actual encryption, might seem like a long winded approach it does have one major advantage. Since there is an additional level of abstraction between the user password protected master key and the actual keys used to protect the data it means that when the user changes their password then only the master key need to be re-protected; none of the protected data needs to be re-protected. Since the master key is much smaller in size than the data then a significant performance saving is made.
When the user's password changes then of course a new master key is generated. This new master key is then used to generate new individual keys. However, since all the previously generated individual keys were derived from the old master key then Windows needs to store all previous master keys, which it does. Windows never forgets a master key and all protected data is marked with a GUID that indicates which master key was used to protect the data. So in terms of adaptability DAPI is able to cope with changes to users' passwords, while ensuring a) that protected data doesn't need to be re-protected, and b) that keys used to previously protect data as still available, and c) it does all this automatically for you.
Unless the computer is a member of a domain DAPI can only unprotected data on the same machine that was used to protect it.
As well as allowing user level protection, in that master keys are based on user passwords and protected data for one user cannot be unprotected by another user, DAPI also provides machine level protection, in that the master keys are based on machine specific information. Machine level master keys allow applications to store protected data so that it can be unprotected by all users of the application. The only difference in the process already described is the master key is generated from machine specific information not user specific information.

A: I looked at one point into the code for it and it uses Windows's advapi32 to do its dirty work. So the key isn't stored in the application's memory.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static int SystemFunction040([In, Out] SafeBSTRHandle pDataIn, [In] uint cbDataIn, [In] uint dwFlag)

Which is better known as RtlEncryptMemory.
It decrypts with RtlDecryptMemory (SystemFunction041).
I'm sure the compiler does something with the SecurityCriticalAttribute as well.
edit this was reflected using 4.0. other versions might different.


text:
Q: Best tool to create a full screen slide show from the web I need to create a slide show of some images that can go full screen so it can be displayed via S-Video out.
The software is delivered via the web so a web-based option is needed.
The list of images is dynamic, and I would like to show them in order. The list of photos can change while the slideshow is running, and I would like to add the new photos to the slideshow.
I see two options:

*

*Build it using JavaScript and then use a browser plugin to go full screen. I have a prototype of this, however it displays photos in random order.

*Build it using Flash. I know nothing about Flash so I am looking for slideshows that can go full screen.
What would be best? Are there any good, customizable Flash slideshows?

A: For those interested, I ended up making an Adobe AIR application using HTML and JavaScript. Adobe AIR can go full screen and I was able to leverage the knowledge of HTML and JavaScript I already have. It has worked out pretty well, though there was a rather steep learning curve for the native AIR classes and how to use them.

A: If you're using Flash, SlideShowPro is a good option that you may recognize from sites like ESPN.

A: when you say "fullscreen", do you mean taking up ENTIRE screen? if so, javascript is not a tool to use, it must live inside the browser, so you will always have some chrome visible from the browser.
flash can do full screen, on the other hand.

A: Most browsers allow you to go full screen (even hiding the chrome) with the F11 key (requires user input). Then it's just a matter of scaling the image in javascript to the size of the viewport. If it doesn't exists, it could be written easily enough probably from a preexisting gallery script.
Also, this answer may be helpful
Hope that helps.


text:
Q: Why is $P(x)$ allowed to have other variables than $x$ free? Using the common definition of a propositional function $P(x)$ as "a WFF which would be either true or false were it not for a variable $x$, with other variables also allowed to be free".
For example, if we have a propositional function $P(x)$ with $x$ and $y$ free, then if we only specify $x$, $P(x)$ can still take either "true" or "false" value depending on $y$.
What is the reason for this notation and definition?
Why not define $P(x)$ as "a WFF which would be either true or false were it not for a variable $x$, with no other variables allowed to be free". It would seem much more intuitive if the truth value of $P(x)$ depended on $x$, the truth value of $P(x,y)$ on both $x$ and $y$, etc.
What are the advantages of the former definition over the latter?

A: From :

*

*Stephen Cole Kleene, Mathematical logic (1967, also Dover ed), page 74:

Consider the proposition (expressed by the sentence) "Socrates is a
  man". The part of this proposition (expressed by) "— is a man" or "$x$ is
  a man" is a predicate; "Socrates" is a subject. Read "$x$ is a man", using
  the mathematical notation of a variable, the predicate is seen to be a
  propositional function, i.e. for each value of the (independent) variable "$x$", it becomes (or takes as value) a proposition, true for example when $x$ is Socrates, false in Greek mythology when $x$ is Chiron, and in the Kleene
  household when $x$ is Fleck.

Of course, a propositional function may have more than one variable free, like a mathematical function of more than one variable, but it will have a definite truth-value only if a value (or reference) is assigned to all its free variables.
"$x$ is father of $y$" is a propositional function of $x$ and $y$, while "$x$ is father of John" is a propositional function of $x$ alone.
Only "Tom is father of John" is a proposition, i.e. has a truth-value, because it has no more "unsaturated" slots.


text:
Q: Increment an onscreen counter with a ruby/gosu window I am trying to make a very simple click counter and I am stuck on getting the click  counter to increment, both onscreen and in the code itself.
require 'rubygems'
require 'gosu'

module ZOrder
    BACKGROUND, MIDDLE, TOP = *0..2
end

WIN_WIDTH = 640
WIN_HEIGHT = 400

class GameWindow < Gosu::Window
    def initialize
        super(WIN_WIDTH, WIN_HEIGHT, false)
        @background = Gosu::Color::WHITE
        @button_font = Gosu::Font.new(20)
        @info_font = Gosu::Font.new(15)
    end

    def needs_cursor?
        true
    end

    def draw
        Gosu.draw_rect(0, 0, WIN_WIDTH, WIN_HEIGHT, @background, ZOrder::BACKGROUND, mode=:default)

        Gosu.draw_rect(50, 50, 100, 50, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)
        Gosu.draw_rect(50, 150, 100, 50, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)

        @button_font.draw("Click me", 65, 65, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
        @button_font.draw("Reset", 75, 165, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)

        @info_font.draw("Clicks: #{counter}", 160, 50, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
    end

    def counter
        i += 1
        i
    end

    def mouse_over_button?(mouse_x, mouse_y)
        if ((mouse_x > 50 and mouse_x < 150) and (mouse_y > 50 and mouse_y < 100))
          true
        else
          false
        end
    end

    def button_down(id)

        case id
        when Gosu::MsLeft
          if mouse_over_button?(mouse_x, mouse_y)
            counter
          else
            counter
          end
        end
    end

end

GameWindow.new.show

I am aware that my issue most likely lies in the 'counter' function and the 'button_down' function however I have been unable to figure out how to make it work. Any help would be appreciated, thanks.

A: You were so close to having it! You need to add @counter = 0 to initialize. Then change your def counter to that shown bellow
def counter
    @counter += 1
end

To get your reset button to work we can now make another procedure called def reset as shown bellow
def reset
    @counter = 0
end

Then to make it all work change your def mouse_over_button?(mouse_x, mouse_y) to the following:
def mouse_over_button?(mouse_x, mouse_y)
    if  ((mouse_x > 50 and mouse_x < 150) and (mouse_y > 50 and mouse_y < 100))
      return_value = 1
      return return_value
    elsif ((mouse_x > 50 and mouse_x < 150) and (mouse_y > 150 and mouse_y < 200))
      return_value = 2
      return return_value
    end
end

Finally change the def button_down(id) to the following:
def button_down(id)
    case id
    when Gosu::MsLeft
     if mouse_over_button?(mouse_x, mouse_y) == 1
        counter
      elsif  mouse_over_button?(mouse_x, mouse_y) == 2
        reset
      end
    end
end

All the right ideas were there! Nice work! If you are unsure why any of this was done, please just let me know and I am happy to explain it further! Hope I helped :)


text:
Q: How to asynchronously call a function with setTimeout twice I'm trying to create a typewriter effect with setTimeout().
My code for the typewriter function is as follows:
function typeWriter(toWrite,isDelete=false){
    if(!isDelete && i<toWrite.length){
        document.getElementById("typewrite").innerHTML+=toWrite.charAt(i);
        i++;
        speed=Math.random()*100+100;
        setTimeout(typeWriter,speed,toWrite,false);
    }
    else if(isDelete && i<toWrite.length){
        var typewrite=document.getElementById("typewrite");
        typewrite.innerHTML=typewrite.innerHTML.slice(0,-1);
        i++;
        speed=100;
        setTimeout(typeWriter,speed,toWrite,true);
    }
}

And I want to call the code twice, once to write a string, and then a second time to delete a part of it.
My grasp on promises is still very shaky, and my attempt (below) didn't really change anything:
const intro=new Promise((resolve,reject)=>{
    resolve();
})

intro
    .then(typeWriter("hello world"))
    .then(typeWriter("world",true))

When I run the code, instead of having "Hello world" get typed and then delete the "world". Both functions start going synchronously and the final output is "world".
I've been banging my head on this for longer than I'm comfortable admitting, I would appreciate any help.

A: to be chainable, typeWriter has to return a function.
e.g.
function typeWriter(toWrite,isDelete=false) {
   return new Promise((resolve, reject) => {

   })
}

If you were to use a setTimout, and you want to wait for the function to be called before going to the next of the chain, place the resolve in the settimeout.
e.g.
function typeWriter(toWrite,isDelete=false) {
   return new Promise((resolve, reject) => {
      setTimeout(() => {
          resolve("hello i am done")
      }, 1000)

   })
}

A: Note, I'm using the same syntax as you - e.g
.then(typeWriter("hello world"))

But in this case, typeWriter returns a function, so it's legit

const typeWriter = (toWrite, isDelete) => {
    const typewrite=document.getElementById("typewrite");
    if (!isDelete) {
        const fn = async (position = 0) => {
            if (position < toWrite.length) {
                typewrite.innerHTML += toWrite.charAt(position);
                await new Promise(resolve => setTimeout(resolve, Math.random()*100 + 100));
                return fn(position+1);
            }
        };
        return () => fn(0);
    } else {
        const fn = async (position) => {
            if (position < toWrite.length) {

                typewrite.innerHTML = typewrite.innerHTML.slice(0,-1);
                await new Promise(resolve => setTimeout(resolve, 100));
                return fn(position + 1);
            }
        };
        return () => fn(0);
    }
};
Promise.resolve()
.then(typeWriter("hello world"))
.then(typeWriter("world",true))

A: You're calling typeWriter immediately, while you really intended to pass that call to the then method, and have that only called when the relevant promise resolves. You can do that by passing () => typeWriter(......) as anonymous function to then.
Secondly, typeWriter will then have to return a promise, so the next chained then callback will only be called when that promise resolves.
I would also change the signature of your function a bit, so that it first deletes a given number of characters (can be 0) and then inserts the given string.
Here is how that looks:

// Promisify setTimeout:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

// Make async, so it returns a promise:
const typeWriter = async (numDelete, toWrite) => {
    const typewrite = document.getElementById("typewrite");
    // First delete a given number of characters
    while (numDelete-- > 0) {
        typewrite.textContent = typewrite.textContent.slice(0, -1);
        await delay(100);
    }
    // Then append new characters
    for (const letter of toWrite) {
        typewrite.textContent += letter;
        await delay(Math.random()*100 + 100);
    }
};

Promise.resolve()
       // Pass a callback -- don't call typeWriter yourself
       .then(() => typeWriter(0, "hello world"))
       .then(() => typeWriter(5, ""));


text:
Q: Открыть доступ к методу api Возможно-ли в yii2 при использовании аутентификатора, открыть доступ к какому-либо методу(-ам)(в моем случае actionParents) для неаутентифицированного пользователя

namespace app\modules\api\controllers;

use app\models\Department;
use app\models\User;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\filters\auth\HttpBasicAuth;
use yii\rest\ActiveController;

class DepartmentController extends ActiveController
{
    public $modelClass = 'app\models\Department';

    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'basicAuth' => [
                'class' => HttpBasicAuth::class,
                'auth' => function ($u, $p) {
                    $user = User::findOne(['username' => $u]);
                    return $user->validatePassword($p) ? $user : null;
                }
            ],
            'access' => [
                'class' => AccessControl::class,
                'only' => ['parents'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['parents'],
                        'roles' => ['?'], // тут как бы должно произойти чудо, но нет
                    ],
                ]
            ],
        ]);
    }

    public function actionParents($id)
    {
        return new ActiveDataProvider([
            'query' => Department::find()->parents($id)
        ]);
    }
}

Сейчас неаутентифицированный пользователь видит:
{
    "name": "Unauthorized",
    "message": "Your request was made with invalid credentials.",
    "code": 0,
    "status": 401,
    "type": "yii\\web\\UnauthorizedHttpException"
}