text:
Q: SVG animation not smooth on Smartphone I have animated an SVG with css animation. The animation is smooth on the computer, but on the Android Smartphone it's absolutly not smooth :(
Sadly I didn't find so much informations about svg smoothness on the smartphone :X
I have tried will-change, translate3d and steps but nothing worked and didn't changed anything.

*{
  padding:0;
  margin:0;
}

body{
  background-color: #161616;
}

#stroke_small{
  animation-name: s_small;
  animation-duration: .5s;
  animation-direction: alternate;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
  transform-origin: center;
  will-change: transform,opacity,rotate;
  transform:translate3d(0,0,0);
}

#stroke_big{
  animation-name: s_big;
  animation-duration: .6s;
  animation-direction: alternate;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
  transform-origin: center;
  will-change: transform,opacity,rotate;
  transform:translate3d(0,0,0);
}

@keyframes s_small {
    0%{
      transform: scale(0) rotate(90deg);
      opacity:0;
    }

    95%{
      transform: scale(1.2) rotate(90deg);
    }

    100%{
      transform: scale(1) rotate(90deg);
      opacity: 1;
    }
}

@keyframes s_big {
    0%{
      transform: scale(0);
      opacity: 0;
    }

    80%{
      transform: scale(1.4);
      opacity: 0.3;
    }

    100%{
      transform: scale(1);
      opacity: 1;
    }
}

#wrap{
  height: 500px;
  transform: translate(0,50%);
}

svg{
  height: 100%;
  width: 100%;
}

    <link rel="stylesheet" type="text/css" href="style.css"/>

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 150 150" width="150" height="150">
        <defs>
          <clipPath id="_clipPath_LSwlYo9f2BqiKFIU9xti0kwRpXdFVREV"><rect width="150" height="150"/></clipPath>
        </defs>
        <g clip-path="url(#_clipPath_LSwlYo9f2BqiKFIU9xti0kwRpXdFVREV)">
          <defs>
            <filter id="Wak5toas1V39NqTVjCKE95NQoDAjvIxm" x="-200%" y="-200%" width="400%" height="400%" filterUnits="objectBoundingBox" color-interpolation-filters="sRGB"><feGaussianBlur xmlns="http://www.w3.org/2000/svg" in="SourceGraphic" stdDeviation="4.293609062839028"/><feOffset xmlns="http://www.w3.org/2000/svg" dx="0" dy="0" result="pf_100_offsetBlur"/><feFlood xmlns="http://www.w3.org/2000/svg" flood-color="#000000" flood-opacity="1"/><feComposite xmlns="http://www.w3.org/2000/svg" in2="pf_100_offsetBlur" operator="in" result="pf_100_dropShadow"/><feBlend xmlns="http://www.w3.org/2000/svg" in="SourceGraphic" in2="pf_100_dropShadow" mode="normal" result="_out_rCE9DJXr10m2lurUI4sPvRW8P2VjDGfr"/><feGaussianBlur xmlns="http://www.w3.org/2000/svg" in="_out_rCE9DJXr10m2lurUI4sPvRW8P2VjDGfr" stdDeviation="2.146804531419514"/><feOffset xmlns="http://www.w3.org/2000/svg" dx="0" dy="0" result="pf_101_offsetBlur"/><feFlood xmlns="http://www.w3.org/2000/svg" flood-color="#000000" flood-opacity="1"/><feComposite xmlns="http://www.w3.org/2000/svg" in2="pf_101_offsetBlur" operator="in" result="pf_101_dropShadow"/><feBlend xmlns="http://www.w3.org/2000/svg" in="_out_rCE9DJXr10m2lurUI4sPvRW8P2VjDGfr" in2="pf_101_dropShadow" mode="normal" result="_out_vkz613rCnMiUq3TGHYc6YN9ZfsLARbBU"/>
              <feMerge><feMergeNode in="_out_vkz613rCnMiUq3TGHYc6YN9ZfsLARbBU"/></feMerge>
            </filter>
          </defs>
          <g filter="url(#Wak5toas1V39NqTVjCKE95NQoDAjvIxm)"><circle  cx="75" cy="75" r="57" id="stroke_big" fill="transparent" stroke-width="14" stroke-dasharray="1,34" stroke="rgb(255,255,255)" stroke-linejoin="bevel" stroke-linecap="butt" stroke-miterlimit="3"/><circle vector-effect="non-scaling-stroke" cx="75" cy="75" r="50" id="stroke_big" fill="none"/></g>
          <defs>
            <filter id="kApXcD8xa6moYJmMIkGqbyC7guWaEPtb" x="-200%" y="-200%" width="400%" height="400%" filterUnits="objectBoundingBox" color-interpolation-filters="sRGB"><feGaussianBlur xmlns="http://www.w3.org/2000/svg" in="SourceGraphic" stdDeviation="4.293609062839028"/><feOffset xmlns="http://www.w3.org/2000/svg" dx="0" dy="0" result="pf_100_offsetBlur"/><feFlood xmlns="http://www.w3.org/2000/svg" flood-color="#000000" flood-opacity="1"/><feComposite xmlns="http://www.w3.org/2000/svg" in2="pf_100_offsetBlur" operator="in" result="pf_100_dropShadow"/><feBlend xmlns="http://www.w3.org/2000/svg" in="SourceGraphic" in2="pf_100_dropShadow" mode="normal" result="_out_q38EKtVito3vTzoYDgDggO89qEmheCPw"/><feGaussianBlur xmlns="http://www.w3.org/2000/svg" in="_out_q38EKtVito3vTzoYDgDggO89qEmheCPw" stdDeviation="2.146804531419514"/><feOffset xmlns="http://www.w3.org/2000/svg" dx="0" dy="0" result="pf_101_offsetBlur"/><feFlood xmlns="http://www.w3.org/2000/svg" flood-color="#000000" flood-opacity="1"/><feComposite xmlns="http://www.w3.org/2000/svg" in2="pf_101_offsetBlur" operator="in" result="pf_101_dropShadow"/><feBlend xmlns="http://www.w3.org/2000/svg" in="_out_q38EKtVito3vTzoYDgDggO89qEmheCPw" in2="pf_101_dropShadow" mode="normal" result="_out_rltGqyg0cPUUeAoL2XaPyexknaV3NvJI"/>
              <feMerge><feMergeNode in="_out_rltGqyg0cPUUeAoL2XaPyexknaV3NvJI"/></feMerge>
            </filter>
          </defs>
          <g filter="url(#kApXcD8xa6moYJmMIkGqbyC7guWaEPtb)"><circle  cx="75" cy="75" r="52" id="stroke_small" fill="transparent" stroke-width="4" stroke-dasharray="1,62" stroke="rgb(255,255,255)" stroke-linejoin="bevel" stroke-linecap="butt" stroke-miterlimit="3"/><circle vector-effect="non-scaling-stroke" cx="75" cy="75" r="50" id="stroke_small" fill="none"/></g>
        </g>
      </svg>

A: It's likely the SVG filters you are using.
They don't seem to be doing much. Try removing them.  Also there's a clip path that is pretty useless also.

*{
  padding:0;
  margin:0;
}

body{
  background-color: #161616;
}

#stroke_small{
  animation-name: s_small;
  animation-duration: .5s;
  animation-direction: alternate;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
  transform-origin: center;
  will-change: transform,opacity,rotate;
  transform:translate3d(0,0,0);
}

#stroke_big{
  animation-name: s_big;
  animation-duration: .6s;
  animation-direction: alternate;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
  transform-origin: center;
  will-change: transform,opacity,rotate;
  transform:translate3d(0,0,0);
}

@keyframes s_small {
    0%{
      transform: scale(0) rotate(90deg);
      opacity:0;
    }

    95%{
      transform: scale(1.2) rotate(90deg);
    }

    100%{
      transform: scale(1) rotate(90deg);
      opacity: 1;
    }
}

@keyframes s_big {
    0%{
      transform: scale(0);
      opacity: 0;
    }

    80%{
      transform: scale(1.4);
      opacity: 0.3;
    }

    100%{
      transform: scale(1);
      opacity: 1;
    }
}

#wrap{
  height: 500px;
  transform: translate(0,50%);
}

svg{
  height: 100%;
  width: 100%;
}

    <link rel="stylesheet" type="text/css" href="style.css"/>

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 150 150" width="150" height="150">
        <g>
          <circle  cx="75" cy="75" r="57" id="stroke_big" fill="transparent" stroke-width="14" stroke-dasharray="1,34" stroke="rgb(255,255,255)" stroke-linejoin="bevel" stroke-linecap="butt" stroke-miterlimit="3"/>
          <circle vector-effect="non-scaling-stroke" cx="75" cy="75" r="50" id="stroke_big" fill="none"/>
        </g>
        <g>
          <circle  cx="75" cy="75" r="52" id="stroke_small" fill="transparent" stroke-width="4" stroke-dasharray="1,62" stroke="rgb(255,255,255)" stroke-linejoin="bevel" stroke-linecap="butt" stroke-miterlimit="3"/>
          <circle vector-effect="non-scaling-stroke" cx="75" cy="75" r="50" id="stroke_small" fill="none"/>
        </g>
      </svg>


text:
Q: Error in adding custom table in user identity system I was following this article to add my custom table.
http://www.itorian.com/2013/11/customizing-users-profile-to-add-new.html
In My AccountViewModels.cs, i have tried to add new custom table(UserProfileInfo) something like this---
  public class ApplicationUser : IdentityUser
{
    public string EmailID { get; set; }
    public virtual UserProfileInfo UserProfileInfo { get; set; }
}
public class UserProfileInfo
{
    public int Id { get; set; }
    public string City { get; set; }
    public string MobileNum { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
    public System.Data.Entity.DbSet<UserProfileInfo> UserProfileInfo { get; set; }

}

}
and in my Account Controller's Register action (Post Version), i have tried to update register action like this but you can see in code at city and mobileNum,
its stating -----
xxx.RegisterViewModel' does not contain a definition for 'City' and no extension method 'City' accepting a first argument of type 'xxx.RegisterViewModel' could be found....
  [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName, EmailID = model.EmailID,
                UserProfileInfo = new UserProfileInfo
                { City = model.City,
                  MobileNum = model.ModileNum
                }
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

i dont know what's happening here.plzz help me out.thanks in advance

A: You've created separated table - UserProfileInfo - that isn't part of ApplicationUser one.
What you've to do is:

*

*crate new ApplicationUser

*create new UserProfileInfo

*link each other with proper navigation property or assign foreign keys manually (depending on your configuration)

A: I have seen that article as u mentioned.You will never be able to pass City and mobile number as parameter as u have not defined them in register view model.
If u simply want to just create and another table and wants to save that into database then u can do it like this-------
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            user.HomeTown = model.HomeTown;
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

and change your Dbcontext to something like this----
         public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
    public DbSet<UserProfileInfo> UserProfileInfo { get; set; }
    }

and your Application user class should be something like this-----
      public class ApplicationUser : IdentityUser
  {
    public string HomeTown { get; set; }
    public virtual UserProfileInfo UserProfileInfo { get; set; }
   }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle Jet, Core Router - Reconfigure function In an Oracle Jet APP i'm trying to achieve some resource authorization behavior based on user authentication,
the idea is:

*

*Initiallize Router with only login route

This is the code used in AppController:
let navData = [
    { path: '', redirect: 'login' },
    { path: 'login', detail: { label: 'Login', iconClass: 'oj-ux-ico-information-s' } },
  ];

  // Router setup
  this.router = new CoreRouter(navData, {
    urlAdapter: new UrlParamAdapter()
  });

  this.router.sync();

*

*Once user succesfully authenticates update router with protected routes

To achieve this i'm trying to use reconfigure function from Core Router based in this API:
https://www.oracle.com/webfolder/technetwork/jet/jsdocs/CoreRouter.html#reconfigure
In this way
let routes = [
            { path: 'accounts' },
            { path: 'new' },
        ];

        this.router.reconfigure(routes, {path: 'accounts'} );

        this.router.sync();

Unfortunately i get following error:
"Uncaught TypeError: this.router.reconfigure is not a function"
What am i doing wrong?
Thanks


text:
Q: Rails ActiveRecord use join or includes instead of find_by_sql to get attributes of two tables The following gets me the results I want but I am trying to figure out if I could have done this with a join or includes instead.
@items = Item.find_by_sql("SELECT *
    FROM items_with_metadata
    FULL OUTER JOIN items ON items.id = items_with_metadata.item_id")

The result should be that I get all attributes from both tables and the attributes are null wherever the items_with_metadata did not match an item in the items table.
ALSO, I do not have any associations between the two tables, the id of some items just happens to be in both tables
So for example if I have
items table with
 id | name | active
------------------
123 |  a   |   0
456 |  b   |   1

and items_with_metadata has
color | usable | location | item_id
-----------------------------------
 red  |   yes  |   north  |  123

the result of the query will be
id  | name | active | color | usable | location | item_id
--------------------------------------------------------
123 |  a   |   0    |  red  |   yes  |   north  |  123
456 |  b   |   1    |       |        |          |

I was hoping there was a way to do this using ActiveRecord's joins or includes or any other ActiveRecord method that is not find_by_sql

A: How about:
Item.joins('FULL OUTER JOIN items_with_metadata ON items.id = items_with_metadata.item_id')
EDIT:
You could also use:
@items = Item.includes(:items_with_metadata)

This will return only Item models, but will also load all relevant ItemWithMetadata models to the memory which will make them available via:
@items.first.items_with_metadata

The last statement won't cause a DB query, but load the item metadata from the memory.


text:
Q: Deleting a whole word in tkinter text widget Is there any way to delete a whole word in tkinter?
Here's the code:
from tkinter import *

root = Tk()

def delete_whole_word(event):
    # Code to delete a whole word
    pass

text = Text(root, width = 65 , height = 20 , font = "consolas 14")
text.grid(row = 0 , column = 0)

text.insert(1.0 , "This is a text widget")
text.mark_set(INSERT , END)

text.bind("<BackSpace>" , delete_whole_word)

mainloop()

Here when I press the BackSpace key, I want to delete the whole word instead of just deleting one character.
By deleting a whole word, I mean this:

Is there any way to achieve this in tkinter?
It would be great if anyone could help me out.

A: Use:
def delete_whole_word(event):
    text.delete("insert-1c wordstart", "insert")
    return "break"


text:
Q: How to reconcile change of coordinates of dielectric and refractive Index tensors? Consider that one has a refractive index tensor $\boldsymbol{\epsilon}$ and one desires to changes coordinates under the rotation matrix $\boldsymbol{r}$. Under standard tensor transformation rules, the rotated dielectric tensor $\boldsymbol{\epsilon_{\alpha}}$ is given by
$$
\boldsymbol{\epsilon}_{\alpha} = \boldsymbol{r}^T\boldsymbol{\epsilon}\boldsymbol{r}.
$$
For a nonmagnetic material, if one were to desire the refractive index along the first axis for both dielectric tensors, one could take
$$
n_x=\boldsymbol{\epsilon}_{xx}
$$
or
$$
n_{\alpha,x}=\boldsymbol{\epsilon}_{\alpha,xx}.
$$
For a medium with dielectric dressing due to dipoles, this gives the same results as constructing the dielectric tensor along different axes, so I am fairly confident that the above treatment is generally correct.
This noted, the above method is clearly nonequivalent to directly transforming the refractive index tensor $\boldsymbol{n}$ under an equivalent rotation (i.e., $\boldsymbol{r}^T\boldsymbol{n}\boldsymbol{r}$). I have not found anywhere in the literature or online where people transform the refractive index tensor along some coordinate transformation as is commonplace to do to the dielectric tensor, so I was wondering on what basis (as they are both tensors containing equivalent information) this is invalid?


text:
Q: Connecting to host mysql database using via sock I am trying to connect to a mysql database on my host using a docker container (so I can use it in other containers).
I would like to do it this way, because I cannot connect to the database from a docker container -> throws Connection refused because the IP is not allowed.
I tried mounting the sock file using following compose:
version: '3'
services:
  mysql:
    image: mariadb:10.3
    volumes:
      - /var/run/mysqld/mysqld.sock:/var/run/mysqld/mysqld.sock
    networks:
      - database
networks:
  database:
    external: true

but it's failing on (even though the host database already contains many databases):
2022-06-07 20:14:46+00:00 [ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
You need to specify one of MARIADB_ROOT_PASSWORD, MARIADB_ALLOW_EMPTY_ROOT_PASSWORD and MARIADB_RANDOM_ROOT_PASSWORD,

and when I added the volume: - /var/lib/mysql:/var/lib/mysql, I am getting a Connection refused error (as if I was connecting to it normally and not via unix)

A: Here you go, consider checking the documentation before asking thoses types of questions
https://hub.docker.com/_/mariadb
version: 3

services:
  sql:
    image: mariadb:10.3
    container_name: <container_name>
    restart: always
    networks:
      - database
    volumes:
      - <volume>:/var/lib/mysql
      - /var/run/mysqld/mysqld.sock:/var/run/mysqld/mysqld.sock
    environment:
      MARIADB_RANDOM_ROOT_PASSWORD: 1
      MARIADB_USER: <USER_TO_BE_CREATED>
      MARIADB_DATABASE: <DATABASE_TO_BE_CREATED>
      MARIADB_PASSWORD: <PASSWORD_TO_BE_CREATED>

networks:
  database:
    external: true


text:
Q: Wix MSI - Using Listview instead of InstallDirDlg I need to install a file, using MSI, in a specific location. The installation wizard must provide a list (I choosed the Listview control) with locations stored in registry. The installation will be performed into the choosen location from this list.
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <UI>
            <Dialog Id="MyInstallDirDlg" Width="370" Height="270" Title="!(loc.InstallDirDlg_Title)">
                ...
                <Control Id="myRadioGroupLabel" Type="Text" X="20" Y="60" Width="290" Height="30" NoPrefix="yes" />
                <Control Id="myRadioGroup" Type="RadioButtonGroup" Property="buttonGroup" Width="320" Height="100" X="20" Y="100">
                    <RadioButtonGroup Property="buttonGroup">
                        <RadioButton Value="C:\abc" Text="C:\abc" Height="17" Width="320" X="0" Y="0" />
                        <RadioButton Value="C:\def" Text="C:\def" Height="17" Width="320" X="0" Y="40" />
                    </RadioButtonGroup>
                </Control>
                ...
                <!-- Control Id="FolderLabel" Type="Text" X="20" Y="60" Width="290" Height="30" NoPrefix="yes" Text="!(loc.InstallDirDlgFolderLabel)" />
                <Control Id="Folder" Type="PathEdit" X="20" Y="100" Width="320" Height="18" Property="WIXUI_INSTALLDIR" Indirect="yes" />
                <Control Id="ChangeFolder" Type="PushButton" X="20" Y="180" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" / -->
            </Dialog>
        </UI>
    </Fragment>
</Wix>

The is a copy of the original InstallDirDlg.wxs, where the ne wthings are these radio group related lines. How is possible to populate dynamically such a list with data (C:\abc, C:\def)? After selecting one item from it, how can I use it as TARGETDIR? I need the same functionality like the ChangeFolder button has.


text:
Q: What is the proper way to tell the browser not to cache? I have a web page that always needs to stay current. I do not want the browser to cache it.  To that end, this meta tag is embedded with the page:
<meta name="Expires" content="Tue, 01 Jun 1999 19:58:02 GMT">

However, some browsers seem to ignore it.  Chrome is particularly bad at it, though other browsers tend to do the same thing.
When I pick the page from the bookmarks bar, most of the time, it doesn't even hit the server, just loads it from cache.  If I then press F5, it does go to the server and fetch a new copy.
Am I missing something simple?  I thought the expires meta tag is the way it's done.
This is happening on an IIS 5.0 on Windows 2000.

Bottom line: looks like meta tags inside the HTML code pretty much do nothing.  However, setting the expires tags within the HTTP does the trick nicely.

A: Send your expires headers using your server. Specifically, if you're using apache, look at this:
http://httpd.apache.org/docs/2.0/mod/mod_expires.html

A: This should help you:
<meta http-equiv="cache-control" content="no-cache" />

You can also configure the static content cache mechanism through IIS; you can learn how to do so here: http://support.microsoft.com/kb/247404.

A: <meta http-equiv="Cache-Control" content="private, no-store" />

Is really ALL you need, as stated here https://youtu.be/TNlcoYLIGFk?t=654 by Andrew Betts, elected W3C TAG member.
Using this, you will not need pragma or expires. Infact, the above will overwrite the Expires command.

A: You want to send an Expires header set to a date in the past (like your Meta tag).
Expires is the most widely respected cache header, but you can also use things like Last-Modified, or Etags to get more specific control.
Meta tags are a somewhat outdated means of setting caching protocols, and most of the meta cache control properties are fairly deprecated (e.g. NO-CACHE). A lot of user agents ignore them.

A: There is a great article I used to read about browser caching ans caching in general :
http://www.mnot.net/cache_docs/
It explains in high details what works and what does not, what is best to do.
In summary there are a lot of ways  (html tags, HTTP headers) and types of cache (browser proxy, gateways)

A: Send Cache-Control: no-cache to the client within the response headers.
Please specify what platform are you using to make a better response.


text:
Q: Could not find a JavaToKotlinConversionProvider I'm not able to create a new project in the android studio. I am getting a warning message

java.lang.RuntimeException: Could not find a
  JavaToKotlinConversionProvider, even though one should be bundled with
  Studio    at
  com.android.tools.idea.npw.model.JavaToKotlinHandler.getJavaToKotlinConversionProvider(JavaToKotlinHandler.java:56)
    at
  com.android.tools.idea.npw.template.TemplateValueInjector.addKotlinVersion(TemplateValueInjector.java:410)

A: I have the same error, I've juste disabled the kotlin plugin and after restarting the IDE, just re-enable it. After that final restart, every thing works fine.

A: Go to file and the plugin in android studio and update your Kotlin plugin...

A: I opened an old project (by old I mean another project) and did everything Android Studio said to give me a successful build (I faced some errors when I tried to build the project that I could build couple weeks ago and actually I fixed them, updating gradle and stuff like that, not code issues of course).
After that I could create new project same as before.
Update seems like in order to keep Android Studio happy we have to keep Kotlin plugin enabled, interesting.

A: Go to Preferences -> Plugins -> Kotlin and update the Kotlin plugin to the last version even though you don't write your code in Kotlin.

A: I solved this problem by doing this:

*

*File->Settings->Plugins

*Click the Installed tab at the top.

*Search "kotlin" and click the result that shows up.

*Click Enable at the top right

A: settings>plugins>check Kotlin >Apply then Ok solved it for me.

A: It occurred due to migration from Android Studio 3.2 to 3.3
Goto File-->Invalidate Caches/Restart
This will solve the problem.


text:
Q: what's relation between lock info in housekeeping data for object instance and synchronized? what's the function for  lock info in housekeeping data for object instance?
if any relation related with synchronized?
Anybody know it?

A: Since synchronization needs some locking mechanism and you can synchronize on any object (if you don't specify an object to use as semaphore this is used) you need some lock info for each object.

A: The lock info in housekeeping data for an object instance is used for providing low level synchronizations. Please check out following link.
Synchronization under the hood
In short, you need some place to track the information about which are the threads accessing 'this' object and then apply the rules of synchronization on that object. The lock info in housekeeping data is that place.


text:
Q: Prove Taylor's theorem for n=1 using fundamental theorem of calculus So I have been trying to prove Taylor's theorem using the fundamental theorem of calculus:
$$ f(t) = f(a) +  \int_{a}^{t} f'(x) dx $$
Continuing, we can find the same for $ f'(x) $:
$$ f'(x) = f'(a) +  \int_{a}^{x} f''(x_0) dx_0 $$
Let's now set that into the first expression:
$$ f(t) = f(a) +  \int_{a}^{t} \left( f'(a) +  \int_{a}^{x} f''(x_0) dx_0 \right) dx $$
Let's also abuse the fact that integration is linear, and that we are integrating for x and not a at $f'(a)$
$$ f(t) = f(a) + f'(a) \int_{a}^{t} 1 dx + \int_{a}^{t} \int_{a}^{x} f''(x_0) dx_0 dx $$
$$ f(t) = f(a) + f'(a) (t-a) + \int_{a}^{t} \int_{a}^{x} f''(x_0) dx_0 dx $$
So far, so good, it seems to match with Taylor's theorem. What I'm having issue with is the last part $ \int_{a}^{t} \int_{a}^{x} f''(x_0) dx_0 dx $
Is there anything we can do with that?
Our professor came with the following formula:
$$ f(t) = f(a) + f'(a)(t-a) + \int_{a}^{t} (t-s) f''(x)dx $$
Would that correspond to what I got? Or how would I go from mine to that one?

A: By changing the order of integration (and adjusting the bounds of integration accordingly), we can get
$$ \int_{x=a}^{x=t}\int_{x_0=a}^{x_0=x} f''(x_0) \, dx_0 dx = \int_{x_0=a}^{x_0=t}\int_{x=x_0}^{x=t} f''(x_0)\, dx dx_0 = \int_a^t (t - x_0)f''(x_0)\, dx_0.$$


text:
Q: SQL how to determine count and sequence of self-joins given selection criteria I have a key-value table named ATTR, where data related to a single logical record (identified
by a S#) are stored as key-value pairs.
table ATTR:
S#   KEY    VALUE

So, given criteria in psuedo-code:
Select S# Where k1 > 5

becomes
Select t1.S#
from ATTR t1
where t1.KEY = 'k1' AND t1.VALUE > 5

and so on. Practically all of my use cases involve one or more self-joins.
My question is - given a criteria, is there is a scientific approach to
deduce the number of self-joins needed, and how to do so. Does it require
a rearrangement of the criteria (I would like to avoid such rejig - letting the
dbms query optimizer take care of that).
To give some illustrative examples
crit: where k1 > 5 OR k2 > 10
=> no extra join needed
Select t1.S#
from ATTR t1
where (t1.KEY = 'k1' AND t1.VALUE > 5) OR (t1.KEY = 'k2' AND t1.VALUE > 10)

crit: where k1 > 5 AND k2 > 10
=> 1 self-join needed
Select t1.S#
from ATTR t1
inner join ATTR t2 on t1.S# = t2.S#
where (t1.KEY = 'k1' AND t1.VALUE > 5)
        AND
      (t2.KEY = 'k2' AND t2.VALUE > 10)

crit: where k1 > 5 AND k2 > 10 AND k3 > 20
=> 2 self-joins needed
Select t1.S#
from ATTR t1
inner join ATTR t2 on t1.S# = t2.S#
inner join ATTR t3 on t1.S# = t3.S#
where (t1.KEY = 'k1' AND t1.VALUE > 5)
        AND
      (t2.KEY = 'k2' AND t2.VALUE > 10)
        AND
      (t3.KEY = 'k3' AND t3.VALUE > 20)

crit: where (k1 > 5 OR k2 > 10) AND (k1 > 10 OR  K3 > 20)
=> 1 self-join needed
Select t1.S#
from ATTR t1
inner join ATTR t2 on t1.S# = t2.S#
where ( (t1.KEY = 'k1' AND t1.VALUE > 5) OR (t1.KEY = 'k2' AND t1.VALUE > 10) )
        AND
      ( (t1.KEY = 'k1' AND t1.VALUE > 10) OR (t2.KEY = 'k3' AND t2.VALUE > 20) )

crit: where (k1 > 5 AND k2 > 10) or (k1 > 10 OR K3 > k4)
and so on
=> ??

I have no set limitations on number of atomic expressions (i.e. smallest boolean expression), except that they be combined
using only AND OR NOT. But I can happily set a limit (say 10-20 atoms) if that allows some cool algo. I am sure all RDBMS also have some basic limits. I am also thinking the XOR case could be folded into AND, and NOT is not material for the problem.
I am using a columnr database.
Thanks a lot
EDIT#2 -- added some sample data
S#  KEY VALUE
1   k1  1
1   k2  5
1   k3  10
1   k4  20
2   k1  10
2   k2  20
2   k3  30
2   k4  40
2   k5  50
3   k2  11
3   k4  22
3   k6  33
3   k8  44
3   k10 55
and so  on

In about 500 mln rows, there are about 900 distinct keys in total. Most "records" utilize about 50-60 different keys. The actual table has in all about 20 columns, including audit trail info. I have reduced them here to keep the problem focused.

A: In general, every Key-Value criteria (eg Key = 'k1' AND Value > 5) with an AND operand will require a separate table look-up.
Once you work out how to parse your criteria (eg where k1 > 5 AND k2 > 10), you will be able to generate the SQL code required.
You don't have to explicitly use JOIN keyword. You can instead use EXISTS, which may be somewhat simpler to read. Here's an example based on criteria you provided as an example:
where (k1 > 5 OR k2 > 10) AND (k1 > 10 OR K3 > 20)

SELECT t.s#
FROM ATTR t
WHERE 1=1
-- KVP on left side of the AND
AND EXISTS (
    SELECT 1
    FROM ATTR t1
    WHERE t.S# = t1.S# -- Join sub-query to parent query
    AND (
        (t1.Key = 'k1' AND t1.Value > 5)
        OR
        (t1.Key = 'k2' AND t1.Value > 10)
        )
)
-- KVP on right side of the AND
AND EXISTS (
    SELECT 1
    FROM ATTR t1
    WHERE t.S# = t1.S# -- Join sub-query to parent query
    AND (
        (t1.Key = 'k1' AND t1.Value > 10)
        OR
        (t1.Key = 'k3' AND t1.Value > 20)
        )
)


text:
Q: How do I set the Oscillator module in a DSPIC33E? So ive got a DSPIC33EP128GM604 PIC, and Im trying to set the internal fast RC oscillator as the clock source. Ive read the datasheet and the application note both of which tell me to use the macro:
 _FOSCSEL( OPT1_ON & OPT2_OFF & OPT3_PLL )
However, whenever I set the relevant bits, i get the following error during compile time:

computed address for section __FOSCSEL extends beyond MEMORY region FOSCSEL

Ive googled this problem, and searched the Microchip forms but oddly i can find no similar problems and solutions. Ive selected the mentioned PIC in the project and have set up all the relevant header files (i used the DSPIC33E template provided by MPLABX).

A: Sometimes there is a problem with a linker file or include file.  In any case, the syntax you are trying to use doesn't allow for good commenting on what exactly each of the settings means, and gives no indication at all of what other options might have been that you didn't chose.
I always set the config bits in assembler source, and document each bit.  Below is a section from one of my current projects using the 33EP512GM604, which is almost the same chip.  This section is always re-written for each project, and would have to be carefully inspected if the project was moved to a different part.  I'm therefore not that bothered by the fixed starting location, although that wasn't my first choice.  I vaguely remember that I ran into some linker problem using the pre-defined directives, so set the address and started writing program memory words myself.  Either way, the point is how each bit is carefully documented, what was chosen, and some idea of what other choices might have been.

;*******************************************************************************
;
;   Static processor configuration settings.
;
.section .configbits, code, address(0x557EC)

         .pword  0xFFFFFF    ;reserved
         .pword  0xFFFFFF    ;reserved

         .pword  0b111111111111111111001111 ;FICD
                 ; 1111111111111111-------- unused, all 1s makes NOP instruction
                 ; ----------------1------- reserved, must be set to 1
                 ; -----------------1------ unused
                 ; ------------------0----- disable JTAG
                 ; -------------------0---- reserved, must be set to 0
                 ; --------------------1--- reserved, must be set to 1
                 ; ---------------------1-- unused
                 ; ----------------------11 ICD interface uses PGEC1/PGED1

         .pword  0b111111111111111100111111 ;FPOR
                 ; 1111111111111111-------- unused, all 1s makes NOP instruction
                 ; ----------------00------ WDT window is 75% of period
                 ; ------------------1----- IIC2 uses SDA2/SCL2 pins
                 ; -------------------1---- IIC1 users SDA1/SCL1 pins
                 ; --------------------1--- enable brownout reset
                 ; ---------------------111 unused

         .pword  0b111111111111111101111111 ;FWDT
                 ; 1111111111111111-------- unused, all 1s makes NOP instruction
                 ; ----------------0------- WDT not always enabled
                 ; -----------------1------ WDT in non-window mode
                 ; ------------------1----- enable PLL lock
                 ; -------------------1---- WDT prescalser 128, not 32
                 ; --------------------1111 WDT postscaler to max of 32768

         .pword  0b111111111111111101011110 ;FOSC
                 ; 1111111111111111-------- unused, all 1s makes NOP instruction
                 ; ----------------01------ clock switching enabled, failsafe clk disabled
                 ; ------------------0----- allow multiple PPS changes
                 ; -------------------11--- unused
                 ; ---------------------1-- not used with external crystal oscillator
                 ; ----------------------10 primary oscillator mode is HS

         .pword  0b111111111111111100111010 ;FOSCSEL
                 ; 1111111111111111-------- unused, all 1s makes NOP instruction
                 ; ----------------0------- start with selected osc mode, not FRC
                 ; -----------------0------ don't require key sequence for PWM registers
                 ; ------------------111--- unused
                 ; ---------------------010 start with primary osc, not PLL

         .pword  0b111111111111111111111111 ;FGS
                 ; 1111111111111111-------- unused, all 1s makes NOP instruction
                 ; ----------------111111-- unused
                 ; ----------------------1- disable user memory code protection
                 ; -----------------------1 disable user memory write protection

         .pword  0xFFFFFF    ;reserved
         .pword  0xFFFFFF    ;reserved


text:
Q: Conditionally changing value in a cell based on value in another cell Pandas I am trying to apply a condition for changing the values of cells based on the value of another cell in the same column. The data frame reads as below:
    Sample_name  C14-Cer_mean  C16-Cer_mean  C18-Cer_mean  C18:1-Cer_mean
0          1 1      0.124749      0.285659     35.302029        8.173144
1         1 10      0.332976      0.656197     39.220933        6.446620
2         1 13      0.227423      0.272440     26.866943        5.763723
3         1 14      0.128359      0.604903     29.848169        6.801633
4          1 5      0.204000      0.242652     21.354158        4.637632
5          1 6      0.122697      0.412868     25.168258        5.866785
6          1 9      0.161679      0.569781     28.707720        6.525267
7        Blank      0.408713      0.526573      0.531430        0.111025

I want to check if the values in different rows (Sample_name) for columns C14-Cer_mean  C16-Cer_mean  C18-Cer_mean  C18:1-Cer_mean are lower than 2x the value of corresponding "Blank" and if they are - change them to 0. What'd be the best way to do this in Pandas?


text:
Q: Stars and bars with at least 1 group of 2 adjacent bars I am trying to figure out the number of $n$ permutations for $N$ stars and $K \ge{2}$ bars such that there is at least 1 group of 2 adjacent bars.
For example, in this trivial example $N = 1$ and $K = 3$ then $n = 4$
$|||* \\ ||*| \\ |*|| \\ *|||$
This coincides with your typical counting argument $\frac{4!}{3!1!}$. However, for a more non-trivial example where $N = 2$ and $K = 3$, we have $n = 9$.
My initial instinct was to group the 2 bars as a "group" and permute it with the rest of the stars and bars (so for $N = 2$ and $K = 3$, we have $\frac{4!}{1!1!2!} = 12 \ne 9$).
The only counting argument I can come up with is to find the total # of permutations and subtract the # of permutations where there are no adjacent bars ($\frac{5!}{3!2!} - 1 = 9$), but this would involve tedious case work with groups of $*|*$ for the # of perms without adjacent bars. Clearly this does not work when $K > 2N$.

A: HINT: It's probably easiest to count the arrangements that do not have two adjacent bars and subtract from $\binom{N+K}N$, the total number of possible arrangements.
If there are no adjacent bars, of course, we must have $K\ge N-1$. Put one star in each slot between adjacent bars; that leaves $K-(N-1)=K-N+1$ stars to be distributed arbitrarily amongst the $N+1$ possible slots (including the two end slots).

A: think of it as selecting $k$ objects out of $n+k$ such that no two are consecutive.
This can be done in $\binom{n+1}{k}$ ways. (See here )
So the answer is $\binom{n+k}{k}-\binom{n+1}{k}$


text:
Q: Under what conditions does a complex matrix with a real eigenvalue have a corresponding real eigenvector? Under what conditions does a complex matrix with a real eigenvalue have a corresponding real eigenvector?
Say I have a complex matrix, $A$, with eigenvalue $\lambda = 1$, under what conditions, is the corresponding eigenvector strictly real?

A: $A$ has a real eigenvector corresponding to a real eigenvalue corresponding to a real eigenvalue if and only if an eigenvector of its real part (viewed as a matrix in the real matrix space) lies inside the null space of its imaginary part. Say $A=R+iC$ where $R$ and $C$ are real matrices. If $Av=\lambda v$ for some real scalar $\lambda$ and nonzero real vector $v$, then $Rv+iCv=\lambda v$. Hence $Rv=\lambda v$ and $Cv=0$.

A: I'm not sure how much it helps, but here is a condition:
$Av=v$ for a nonzero real vector if and only if there is an invertible real matrix $P$ such that the first column of $P^{-1} A P$ is $(1,0,\ldots, 0)^t$.
Proof: Complete $v$ to a basis of $\mathbb{C}^n$ using real vectors and let $P$ be the corresponding transition matrix.


text:
Q: Insert an element into an array sorted according to frequency, then sort the array by frequency again So I was asked asked to write an O(n) function, insertRanked(int[] list, int item), to insert an element into an array sorted by frequency (I have written a boolean function to check if int[] list is sorted by frequency). After inserting the element into the array, the array is then sorted again by frequency.
For example, insertRanked([65, 65, 65, 65, 1, 1, 1, 8, 8, 987, 987, 2, 2, 40], 2) should produce [65, 65, 65, 65, 1, 1, 1, 2, 2, 2, 8, 8, 987, 987, 40].
Is this possible to do in O(n)? I have thought of storing the elements and their counts into a LinkedHashMap and using Collections.sort() but the time complexity of Collections.sort() is O(n*log(n)).

A: Here's one approach to start you off could be based on count.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;

    public class SortCount {
        public static void main(String[] args) {
            int nums[] = {([65, 65, 65, 65, 1, 1, 1, 8, 8, 987, 987, 2, 2, 40};
            HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();

            for(int i = 0; i < nums.length; i++) {
                if(counts.containsKey(nums[
                    Integer c = counts.get(nums[i]) + 1;
                    counts.put(nums[i], c);
                }
                else {
                    counts.put(nums[i],1);
                }
            }

            ValueComparator<Integer,Integer> bvc = new ValueComparator<Integer,Integer>(counts);
            TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(bvc);
            sortedMap.putAll(counts);

            ArrayList<Integer> output = new ArrayList<Integer>();
            for(Integer i : sortedMap.keySet()) {
                for(int c = 0; c < sortedMap.get(i); c++) {
                    output.add(i);
                }
            }

            System.out.println(output.toString());
        }
    }

//Which uses a Comparator class to compare the values in a Map:

 import java.util.Comparator;
    import java.util.Map;

    public class ValueComparator<T1,T2 extends Comparable<T2>> implements Comparator<T1> {
        Map<T1,T2> base;
        public ValueComparator(Map<T1,T2> base) {
            this.base = base;
        }

        @Override
        public int compare(T1 k1, T1 k2) {
            T2 val1 = base.get(k1);
            T2 val2 = base.get(k2);

            return val1.compareTo(val2);
        }
    }

A: Assuming the array is already sorted by frequency, of course it's possible to do in O(n). Traverse the array once to figure out what the change is in frequency for the element in question (in your example, 2 goes from a frequency of 2 to 3). In the second iteration, insert the numbers one by one into a new array until you reach the last element with the target frequency for the inserted element. Insert the target element the appropriate number of times and continue inserting the rest, skipping the target element.


text:
Q: Why Hello World is not showing up? This is the same code as from the youtube tutorial,
but it's not working for me:
Hello World is not showing up in the browser.
import React from 'react';

function myComponent() {
  return(

Hello World

  );
}

class App extends React.Component {
   render(){
    return(
      <myComponent/>
    );
   }
}

export default App;

A: 1) You must define a component name started by a capital letter. It's the rule of React (https://en.reactjs.org/docs/jsx-in-depth.html)

User-Defined Components Must Be Capitalized When an element type
  starts with a lowercase letter, it refers to a built-in component like
   or  and results in a string 'div' or 'span' passed to
  React.createElement. Types that start with a capital letter like  compile to React.createElement(Foo) and correspond to a component
  defined or imported in your JavaScript file.
We recommend naming components with a capital letter. If you do have a
  component that starts with a lowercase letter, assign it to a
  capitalized variable before using it in JSX.

2) You must insert a enclosed div or React.Fragment for MyComponent in render() of AppComponent/>.
function MyComponent() {
  return(

Hello World

  );
}

class App extends React.Component {
   render(){
    return(

 // OR <React.Fragment>  OR <>
        <MyComponent/>

 // OR </Fragment>  OR </>
    );
   }
}


text:
Q: How to get value of input in Angular ( element.setAttribute("[(ngModel)]", "Title" doesn't work) I am trying to get the value of a dynamically created input on click
this is the code :
Save(form:NgForm){
  const element = document.createElement("input");
  element.setAttribute("type", "text")
  element.setAttribute("placeholder", "Title")
  element.setAttribute("name", "Title")
  element.setAttribute("[(ngModel)]", "Title")
  element.setAttribute("class","appearance-none block w-full bg-white text-gray-700  border border-gray-400 shadow-inner rounded-md py-3 px-4 leading-tight focus:outline-none focus:border-gray-500");
  document.getElementById("title").appendChild(element)
}

I tried this setAttribute but it didn't work
element.setAttribute("[(ngModel)]", "Title")

it says: Failed to execute 'setAttribute' on 'Element': '[(ngModel)]' is not a valid attribute name.

A: I'm not sure I understand the reason why you're trying to doing that. But if you whish to not use any angular capacity, meaning that you aren't using any html file with nicely created <input> tags bound with variable through [(ngModel)], then you shall not assign [(ngModel)] like you do.
Meaning the following isn't working, because it isn't a known attribute from the html input tag.
element.setAttribute("[(ngModel)]", "Title")

For that reason you should set the value like this
element.value = "Title";

Small tips
Here, what you're trying to archive in an Angular manner
if not required, just comment and I'll remove it from my answer
<!-- app.component.html -->
<input [(ngModel)]="title" type="text" placeholder="Title" name="Title" class="appearance-none block w-full bg-white text-gray-700  border border-gray-400 shadow-inner rounded-md py-3 px-4 leading-tight focus:outline-none focus:border-gray-500">

// app.component.ts
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class YourComponent {
  title: string

  save() {
    console.log(this.title)
  }
}

A: Angular not works in this way, you can create a variable (or an array of variables) and use in the .html to create the input. e.g.
//in .ts define an object
inputConfig={type:"text",
             placeholder:"Title",
             name:"Title",
             variable:"title",
             class="appearance-none ..."
};

//in .html
<input [type]="inputConfig.type" [placeholder]="inputConfig.placeholder"
       [name]="inputConfig.name" [ngClass]="inputConfig.class"
       [(ngModel)]="this[inputConfig.variable]">

See how you use in [(ngModel)] this[inputConfig.variable]
a fool stackblitz
To get the variable "title" it's only use in .ts this.title or in .html title


text:
Q: Why does pylint3 not like python-ldap? I'm trying to lint my Python code that uses the python-ldap module however pylint3 always gives the errors below:
No config file found, using default configuration
************* Module python.test
C:  1, 0: Missing module docstring (missing-docstring)
E:  2, 0: No name 'filter' in module 'ldap' (no-name-in-module)
E:  2, 0: Unable to import 'ldap.filter' (import-error)
E:  5,26: Module 'ldap' has no 'filter' member (no-member)

----------------------------------------------------------------------
Your code has been rated at -30.00/10 (previous run: -30.00/10, +0.00)

Here is my test.py file that I ran this on:
import ldap
import ldap.filter

print('ldap:', dir(ldap))
print('ldap.filter:', dir(ldap.filter))

I cannot figure out why it doesn't like this. I have tried using a default pylintrc file with extension-pkg-whitelist=_ldap which I saw other projects do that use python-ldap however that did not change anything. If I run this code with python3 it runs with no errors, so I really don't understand why's going on.
I'm running this on Ubuntu 18.04 if that matters. I installed python-ldap with pip3.


text:
Q: what effect if any does a magnetic/electric field have on a light wave? I understand that if a light wave passes through either an electric or a magnetic filed when it comes out the other side of the field there is no change to the wave.
But what happens to the light wave while inside the field.  For example is the wave amplified at all? or is it reduced?  Are there any other effects to it while in the field that disappear when the field is gone?
I'm a complete layperson with regards to physics so forgive me if the question is not very clear.

A: In purely classical physics, electromagnetic fields obey the principle of superposition.  This means that, if source one produces field $({\vec E_1}, {\vec B_1})$ and source two produces field $({\vec E_2}, {\vec B_2})$, then if you have the two sources, the field will be $({\vec E_1} + {\vec E_2}, {\vec B_1} + {\vec B_2})$.
Since a constant electric or magnetic field is the field due to one distribution of charge, and a wave is the field due to another distribution of charge, when they overlap, the fields will just add, and not otherwise be affected by each other.
In quantum field theory, light can scatter light, which means that a strong enough field, which is just made up of photons in the QFT picture, will be able to scatter light too, and you can therefore get (small) interactions, but this effect is second-order in QFT, and will not be observable under ordinary circumstances.

A: The first premise is not entirely true.
Light is an excitation of the Electromagnetic field. In a linear medium, this excitation will not couple with any other fields due to the property of linear functions: f(aE1+bE2) = af(E1)+bf(E2)
However in a nonlinear medium there is coupling between light and the field and the light is changed. Terms in E1E2 can give rise to sum and frequency generation and a lot of other awesome effects. E.g. A BaBO crystal can be used to turn an Argon laser operating at 488nm in the blue into a UV laser operating at 244 nm due to frequency doubling.


text:
Q: What is set mouse = a for in nvim? I'm not sure I can ask this question, but I can't find information about what mouse = a is for, I just find that it can no longer be copied or pasted with "ctrl + c" and "ctrl + v", however I manage to do as I normally would, I want to know what is the use of set "mouse=a", If it works for me or not, or in which cases it would work for me, because all I find is that error, I could not even find it on the vim page, it would be very good if you could show me a page where I can know what each part of my init.vim shown below thank you very much for your understanding.
I clarify that I just installed neovim on Windows 10, I am completely a noob at this
set mouse=a
set numberwidth=1
set clipboard=unnamed
syntax enable
set showcmd
set ruler
set cursorline
set encoding=utf-8
set showmatch
set signcolumn=yes
set noexpandtab
set tabstop=4 shiftwidth=4

filetype plugin indent on

set list

set relativenumber
so ~/.vim/plugins.vim
so ~/.vim/plugin-config.vim
so ~/.vim/maps.vim

colorscheme gruvbox
let g:gruvbox_contrast_dark = "hard"
"highlight Normal ctermbg=NONE
set laststatus=2
set noshowmode

" Javascript
autocmd BufRead *.js set filetype=javascript.jsx
autocmd BufRead *.jsx set filetype=javascript.jsx
augroup filetype javascript syntax=javascript

"" Searching
set hlsearch                    " highlight matches
set incsearch                   " incremental searching
set ignorecase                  " searches are case insensitive...
set smartcase                   " ... unless they contain at least one capital letter

A: :set mouse=a the 'a' means all vim modes: visual, normal, insert, command line.
This is the help of vim:
'mouse'                 string  (default "", "a" for GUI, MS-DOS and Win32,
                                        set to "a" or "nvi" in defaults.vim)
                        global
        Enable the use of the mouse.  Works for most terminals (xterm, MS-DOS,
        Win32 win32-mouse, QNX pterm, *BSD console with sysmouse and Linux
        console with gpm).  For using the mouse in the GUI, see gui-mouse.
        The mouse can be enabled for different modes:
                n       Normal mode and Terminal modes
                v       Visual mode
                i       Insert mode
                c       Command-line mode
                h       all previous modes when editing a help file
                a       all previous modes
                r       for hit-enter and more-prompt prompt
        Normally you would enable the mouse in all five modes with:
                :set mouse=a
        If your terminal can't overrule the mouse events going to the
        application, use:
                :set mouse=nvi
        The you can press ":", select text for the system, and press Esc to go
        back to Vim using the mouse events.
        In defaults.vim "nvi" is used if the 'term' option is not matching
        "xterm".

        When the mouse is not enabled, the GUI will still use the mouse for
        modeless selection.  This doesn't move the text cursor.


text:
Q: jQuery autocomplete on class, how to get id I have been working on this a while and can't seem to get anywhere.  Basically I have the autocomplete on a bunch of inputs by class, but I need to get the specific inputs id to build the object to post the ajax (I have to use POST for this project not GET).
$(".input_autocomplete").autocomplete({
  source: function( request, response ) {
  // here is where I get the hash from local storage,
  // reference the id and build the object
  // tried this.id, $(this).prop('id'), no luck
  $.ajax({
    url: '/somepath/filename.htm',
    contentType: 'application/json',
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify(obj),
    success: function(json) {
      return {
        label: item.label,
        value: item.label
      }
    },
    error: function() {
      // error handling
    }
   }); // ajax
 } // source
});

A: I tried it out in a project of mine. This worked for me:
$(this.element.get(0)).attr('id');

A: I was in a situation similar to you, user1572796 and this is what worked for me:
$(this).prop("id");

A: Try:
$(this.element).prop("id");

or:
this.element[0].id;

Inside of the source callback, this refers to the widget instance. In order to get the element the widget is attached to, you should use this.element, which is a jQuery object.

A: I just spent a while piecing together a solution for this myself. In case it helps, this works for me:
call this after your class exists ( for most this is on document ready, for myself I had to call this function after a datatable initialized MyClassName)
  $('.MyClassName').each(function(index) {

  MyID = $(this).attr("id")

  $('#'+MyID).autocomplete({

  source: function(request, response) {

        var elementID = this.element[0].id     //!!! This is what did the trick ***

            $.ajax({
                url: "/MyController/MyFunction",
                dataType: "json",
                data: {

                    MySearchTerm: $('#'+elementID).val()
                },
                success: function(data) {
                ...


text:
Q: Order of variables when computing the Jacobian for the purposes of calculating the change of variables factor? Consider the transformation that converts from polar to cartesian coordinates:
\begin{align}
x &= r\cos{\theta} \\
y &= r\sin{\theta}
\end{align}
To compute the change of coordinates, we would take the determinant of the matrix:
\begin{bmatrix} \partial x/\partial r & \partial x/\partial \theta \\ \partial y/\partial r & \partial y/\partial \theta \end{bmatrix}
Or, we could take the determinant of the matrix:
\begin{bmatrix} \partial x/\partial \theta & \partial x/\partial r \\ \partial y/\partial \theta & \partial y/\partial r \end{bmatrix}
One wold give me the factor $r$ and the other $-r$. Which one is "correct"? In general, how does one decide upon the order of variables (i.e. the order of columns and rows of the Jacboian matrix) to calculate the change of variables factor?

A: Both are fine. We take the absolute value of the determinant.


text:
Q: file input size issue in safari for multiple file selection I am experiencing inconsistencies with regard to multiple file upload in Safari 5.1 on Windows Vista (haven't tried other platforms).  The input element has the multiple flag to allow selection of multiple files.  The problem occurs when the user does actually select more then one file.  In this case, each File has a size attribute of 0.  If (still with the multiple flag), the user only chooses one file, the size attribute correctly contains the file size.
The problem can be seen in the following example. Test and view the output of both a single file selection and a multiple file selection.  (You will need to reset between tests).
JsFiddle Test
Does anyone know of a workaround?

A: IT's a Safari bug. No solution for the moment. here is the test i did http://jsfiddle.net/rHd26/6/

A: Workaround for us was to remove multiple option... we got file size of 0, but we also got bad filenames with leading strange character added to the filename. Maybe that is why we get 0 in the size: because the first property (filename) is not split correctly with the presence of that bad character at the end of the filename.

A: Check this hack.
It explains in detail how to remove multiple option for Safari only, leaving other browsers alone.
Any workarounds for the Safari HTML5 multiple file upload bug?

A: A variation of this issue also seems to have infected mobile Safari on iOS 7, which just released.  If you have a "multiple" file input field, and select a video, then the File API returns a file size of 0.  Indeed the jsfiddle at the top of this page, reproduces this.
Selecting one or more photos with the "multiple" option is fine - this only affects videos.


text:
Q: Datetime Display In MySQL I need your help with datetime coversion. Inside my database I have date of comments entered like this:
  Datetime: 2012-05-08 14:44:53

How can I make it display something close to this
  May 15, 2012 2:44PM

Thanks for your time and patience.

A: DATE_FORMAT() is the answer to your question. It has several formats of date on this link
SELECT DATE_FORMAT(NOW(), '%M %d, %Y %h:%i %p') as FormattedDate;

View The Output Here [SQLFiddle]
%M  Month name (January..December)
%d  Day of the month, numeric (00..31)
%Y  Year, numeric, four digits
%h  Hour (01..12)
%i  Minutes, numeric (00..59)
%p  AM or PM

A: You need to use strtotime() to convert to a Unix timestamp.  You can then use date() to display the exact format you need.  Something like this:
$unix = strtotime($datetime);
echo date(F j Y g:iA, $unix);

A: You should use MySQL DATE_FORMAT() function.
Reference:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
Example query:
SELECT DATE_FORMAT(`date`, '%a %d, %Y %l:%s%p') AS `myDate`;


text:
Q: How do I turn off WS_CAPTION style of a window (using user32.dll)? I am embedding a 3rd party app into a panel on a C# Windows form (using SetParent from user32.dll).  I need to then turn off the title bar window style WS_CAPTION so that it looks like a part of the hosting application.
How do I change a window's style to accomplish this?
For sake of example, say _hWnd is the handle of the application to embed.

A: If memory serves, you might be able to do a GetWindowLong on the style, |= ~ WS_CAPTION on that value, and then SetWindowLong.  See those APIs in MSDN.
Also see:  http://www.codeguru.com/forum/showthread.php?t=352963

A: SetWindowLong(_hWnd, GWL_STYLE, GetWindowLong(_hWnd, GWL_STYLE) & ~WS_CAPTION);

A: Take look at WindowInterceptor

A: Use GetWindowLong to retrieve the window style, mask the WS_CAPTION bits and then set the updated style using SetWindowLong:
var style = GetWindowLong(_hWnd, GWL_STYLE);
SetWindowLong(_hWnd, GWL_STYLE, style & ~WS_CAPTION);

and with following helper code:
const int GWL_STYLE = -16;
const int WS_CAPTION = 0x00C00000;

[DllImport ("user32")]
private static extern int GetWindowLong(System.IntPtr hwnd, int nIndex);

[DllImport ("user32")]
private static extern int SetWindowLong(System.IntPtr hwnd, int index, int newLong);


text:
Q: Spatial temporal query in python with many records I have a dataframe of 600 000 x/y points with date-time information, along another field 'status', with extra descriptive information
My objective is, for each record:

*

*sum column 'status' by records that are within a certain spatial temporal buffer

the specific buffer is within t - 8 hours and < 100 meters
Currently I have the data in a pandas data frame.
I could, loop through the rows, and for each record, subset the dates of interest, then calculate a distances and restrict the selection further. However that would still be quite slow with so many records.

*

*THIS TAKES 4.4 hours to run.

I can see that I could create a 3 dimensional kdtree with x, y, date as epoch time. However, I am not certain how to restrict the distances properly when incorporating dates and geographic distances.
Here is some reproducible code for you guys to test on:
Import
import numpy.random as npr
import numpy
import pandas as pd
from pandas import DataFrame, date_range
from datetime import datetime, timedelta

Create data
np.random.seed(111)
Function to generate test data
def CreateDataSet(Number=1):

    Output = []

    for i in range(Number):

        # Create a date range with hour frequency
        date = date_range(start='10/1/2012', end='10/31/2012', freq='H')

        # Create long lat data
        laty = npr.normal(4815862, 5000,size=len(date))
        longx = npr.normal(687993, 5000,size=len(date))

        # status of interest
        status = [0,1]

        # Make a random list of statuses
        random_status = [status[npr.randint(low=0,high=len(status))] for i in range(len(date))]

        # user pool
        user = ['sally','derik','james','bob','ryan','chris']

        # Make a random list of users
        random_user = [user[npr.randint(low=0,high=len(user))] for i in range(len(date))]

        Output.extend(zip(random_user, random_status, date, longx, laty))

    return pd.DataFrame(Output, columns = ['user', 'status', 'date', 'long', 'lat'])

#Create data
data = CreateDataSet(3)
len(data)
#some time deltas
before = timedelta(hours = 8)
after = timedelta(minutes = 1)

Function to speed up
def work(df):

    output = []
    #loop through data index's
    for i in range(0, len(df)):
    l = []
        #first we will filter out the data by date to have a smaller list to compute distances for

        #create a mask to query all dates between range for date i
        date_mask = (df['date'] >= df['date'].iloc[i]-before) & (df['date'] <= df['date'].iloc[i]+after)
        #create a mask to query all users who are not user i (themselves)
        user_mask = df['user']!=df['user'].iloc[i]
        #apply masks
        dists_to_check = df[date_mask & user_mask]

        #for point i, create coordinate to calculate distances from
        a = np.array((df['long'].iloc[i], df['lat'].iloc[i]))
        #create array of distances to check on the masked data
        b = np.array((dists_to_check['long'].values, dists_to_check['lat'].values))

        #for j in the date queried data
        for j in range(1, len(dists_to_check)):
            #compute the ueclidean distance between point a and each point of b (the date masked data)
            x = np.linalg.norm(a-np.array((b[0][j], b[1][j])))

            #if the distance is within our range of interest append the index to a list
            if x <=100:
                l.append(j)
            else:
                pass
        try:
            #use the list of desired index's 'l' to query a final subset of the data
            data = dists_to_check.iloc[l]
            #summarize the column of interest then append to output list
            output.append(data['status'].sum())
        except IndexError, e:
            output.append(0)
            #print "There were no data to add"

    return pd.DataFrame(output)

Run code and time it
start = datetime.now()
out = work(data)
print datetime.now() - start

Is there a way to do this query in a vectorized way? Or should I be chasing another technique.
<3

A: Here is what at least somewhat solves my problem. Since the loop can operate on different parts of the data independently, parallelization makes sense here.
using Ipython...
from IPython.parallel import Client
cli = Client()
cli.ids

cli = Client()
dview=cli[:]

with dview.sync_imports():
    import numpy as np
    import os
    from datetime import timedelta
    import pandas as pd

#We also need to add the time deltas and output list into the function as
#local variables as well as add the Ipython.parallel decorator

@dview.parallel(block=True)
def work(df):
    before = timedelta(hours = 8)
    after = timedelta(minutes = 1)
    output = []

final time 1:17:54.910206, about 1/4 original time
I would still be very interested for anyone to suggest small speed improvements within the body of the function.


text:
Q: Mail.app message selection gets reset when clearing the search box If I search for something in my mailbox, select the message I'm interested in, then clear the search box (because I want to see the other messages that came in around the same time), the selection resets and I lose my selected message.
I thought there was once some option like "View message in mailbox" that could be used to select a given message without filtering out everything else, but I can't find it anywhere.
Am I imagining things?  Does this still exist?
-- Edit --
Trying to clarify with screencaps.

*

*I search for and select a message.

*I clear the search.

*

*The message I had selected has been deselected

*The message list pane has scrolled back to the top

What I want is for the message I had selected to still be selected, or at least visible on the screen.

A: Answering (sort of) my own question.  When making the screenshots I added to the question, I happened to turn off the "Organize by Conversation" option, and it suddenly worked!  When clearing the search box, the selected message remains selected.
Moreover, this also happens:

*

*Turn on "Organize by Conversation"

*Enter some search term

*Select a message

*Clear the search box -- the message will be deselected

*Turn off "Organize by Conversation"

*The previously selected message is reselected
So I guess the "answer" is that "Organize by Conversation" is simply a shoddy feature that Apple bolted onto their mail client without caring too much how well it works.


text:
Q: Add calculated row to pandas DataFrame I have some data like the following and I'd like to add rows that calculate the geometric mean of groups of rows.
F1 F2 F3 Type Val
Y  Y  Y  A    1
Y  Y  Y  B    4
Y  Y  Y  C    7
Y  N  Y  A    3
Y  N  Y  B    2
Y  N  Y  C    5
Y  N  N  A    8
Y  N  N  B    9
Y  N  N  C    3

I'd like to add three rows to the above data frame
Y  Y  Y GeoM 3.04
Y  N  Y GeoM 3.11
Y  N  N GeoM 6.00

@Brenbarn and @chthonicdaemon helped me get close to what I want:
    from scipy.stats import gmean
    import pandas as pd
data = {'F1': ['Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y'],
 'F2': ['Y', 'Y', 'Y', 'N', 'N', 'N', 'N', 'N', 'N'],
 'F3': ['Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'N', 'N', 'N'],
 'Type': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
 'Val': [1, 4, 7, 3, 2, 5, 8, 9, 3]}

df = pd.DataFrame(data)
gb = df.groupby(['F1','F2','F3'])['Val'].apply(gmean).to_frame()
gb.columns = ['Val']
gb['Type'] = 'GeoM'
gb.reset_index(inplace=True)
df.append(gb, ignore_index=True)

      F1 F2 F3  Type       Val
0   Y  Y  Y     A  1.000000
1   Y  Y  Y     B  4.000000
2   Y  Y  Y     C  7.000000
3   Y  N  Y     A  3.000000
4   Y  N  Y     B  2.000000
5   Y  N  Y     C  5.000000
6   Y  N  N     A  8.000000
7   Y  N  N     B  9.000000
8   Y  N  N     C  3.000000
9   Y  N  N  GeoM  6.000000
10  Y  N  Y  GeoM  3.107233
11  Y  Y  Y  GeoM  3.036589

A: You can definitely use groupby to produce the geometric means:
from scipy.stats import gmean

data = {'F1': ['Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y'],
        'F2': ['Y', 'Y', 'Y', 'N', 'N', 'N', 'N', 'N', 'N'],
        'F3': ['Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'N', 'N', 'N'],
        'Type': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
        'Val': [1, 4, 7, 3, 2, 5, 8, 9, 3]}

df = pandas.DataFrame(data)

gmeans = df.groupby(['F1', 'F2', 'F3']).agg(lambda x: gmean(list(x)))

However, I think you should refrain from adding these columns to the original dataframe. It seems to make sense if you're used to adding calculated columns to Excel, but it is unlikely that you really want these new values mixed in with your original data.
If you really must add these as rows, you can do it as follows:
gmeans['Type'] = 'GeoM'

newdata = pandas.concat([data, gmeans.reset_index()], axis=0)


text:
Q: Test Driven Development in PHP without using PHPUnit class TestCase
{
    public function multiply($a,$b)
    {
        return $a*$b;
    }
}

I need to use test cases in PHP. Some websites suggests that to use TDD in PHP, we need to install PHPUnit. For now, I need only knowledge of test cases and using them in PHP to test a program. Is that possible for above PHP code(without installing PHPUnit)?
I have WAMPP to run php.

A: Read this article written by authors of PHPUnit: http://www.phpunit.de/manual/current/en/automating-tests.html
One of the examples from there:

For a newly created array we expect the count() function to return 0. After we add an element, count() should return 1

<?php
    $fixture = array();
    assertTrue(count($fixture) == 0);

    $fixture[] = 'element';
    assertTrue(count($fixture) == 1);

    function assertTrue($condition)
    {
        if (!$condition) {
            throw new Exception('Assertion failed.');
        }
    }
?>

You can reinvent the wheel, but why do you need it?

A: You can try simple test, it's a lightweight TDD framework for PHP projects. In order to test it you just need to include one single file in your PHP script.


text:
Q: Grouping with operands I have a table:
mysql> desc kursy_bid;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| datetime  | datetime    | NO   | PRI | NULL    |       |
| currency  | varchar(6)  | NO   | PRI | NULL    |       |
| value     | varchar(10) | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

I would like to select some rows from a table, grouped by some time interval (can be one day) where I will have the first row and the last row of the group, the max(value) and min(value).
I tried:
select
  datetime,
  (select value order by datetime asc limit 1) open,
  (select value order by datetime desc limit 1) close,
  max(value),
  min(value)
from kursy_bid_test
  where datetime > '2009-09-14 00:00:00'
  and currency = 'eurpln'
group by
  month(datetime),
  day(datetime),
  hour(datetime);

but the output is:
| open   | close  | datetime            | max(value) | min(value) |
+--------+--------+---------------------+------------+------------+
| 1.4581 | 1.4581 | 2009-09-14 00:00:05 | 4.1712     | 1.4581     |
| 1.4581 | 1.4581 | 2009-09-14 01:00:01 | 1.4581     | 1.4581     |

As you see open and close is the same (but they shouldn't be). What should be the query to do what I want?

A: It seems that the LIMIT operation is being performed before to the ORDER BY function. I'm no expert (far from it), but I'm guessing that nesting the nested query should work:
( (SELECT value ORDER BY datetime ASC) LIMIT 1) AS open

But this isn't exactly an elegant way to do it. I'm sure other SO users will have a better solution.

A: SELECT DATE(datetime),
       MIN(value) open,
       MAX(value) close
  FROM kursy_bid
 WHERE DATE(datetime) = '2009-09-14'
   AND currency = 'eurpln'
GROUP BY DATE(datetime)

TIP: DO NOT USE KEYWORDS AS COLUMN NAMES - to zly nawyk :)


text:
Q: Left joining based on a combination of columns in a range of columns I have two tables. In table A I have 36 columns that can be empty or contain a specific product. In table B I have all kinds of combinations of products and an ID per combination (all combinations contain 2 products, such as the following table).

ID
Product
recommendation

1
1
productrec. 1

2
1
productrec. 2

3
1
productrec. 3

4
2
productrec. 1

5
2
productrec. 2

6
2
productrec. 3

I want to join this ID in all the rows of table A that have an corresponding combination of products. The challenge is, however, that the first product of the combination can be in the first column, but the other product of the combination can be in any other column (so not necessarily adjacent).
How would I be able to do this?
Thanks in advance!


text:
Q: How to highlight the submenu item? I've set up a menu and submenu structure in Joomla! 2.5
Car
  Mercedes
  Honda
Bicycle
  Canondale
  Pirelli

I've set up the modules, set the start/end levels etc and it works well. Only the submenuitems for the correct menuitem show.
I've added a CSS rule to highlight the active (sub)menuitem. When I click on a submenuitem, both the submenuitem and the menuitem are highlighted.
Great! Thanks for reading.
Hey, wait.... The menuitems always link to the same articles as their first submenuitems, so when selecting a menuitem, the first submenuitem should be highlighted as well as the menuitem, but only the latter is highlighted.
How can I get both, menuitem and first submenuitem, to be highlighted when a menuitem is clicked?

A: Got it... select Menu Item Type = Menu Item Alias for the menuitem!

A: I believe that you are looking to create one menu with submenus; I hope this link will help you kindly let me know about your status http://help.joomla.org/content/view/1983/278/#Menu.


text:
Q: Why are pattern variables also renamed in macro expansion? While reading Dybvig's paper Syntactic Abstraction in Scheme, I noticed that the algorithm also renames pattern variables.  So it means pattern variables may cause capture.  But I have no idea in what case they would cause capture?  Can someone enlighten me?

A: A macro can expand into a macro definition using patterns. Pattern variables have lexical scope just as normal variables, so they need to be renamed too.
Example of macro expanding into macro definition.
#lang racket
(define-syntax (define-get/put-id stx)
  (syntax-case stx ()
    [(_ id get put!)
     #'(define-syntax id
         (syntax-id-rules (set!)
           [(set! id e) (put! e)]
           [(id a (... ...)) ((get) a (... ...))]
           [id (get)]))]))

(define id 0)
(set! id 42)
(define-get/put-id clock
  (λ()  (displayln "Reading clock") id)
  (λ(x) (displayln "Setting clock") (set! id x) id))

clock
(set! clock 10)
clock

;;; Output
Reading clock
42
Setting clock
10
Reading clock
10


text:
Q: How to make Pyinstaller 3.2 in Python 3.5 work with Matplotlib? I am using matplotlib.pyplot in my python 3.5 script, when I convert my .py to .exe using Pyinstaller 3.2, I got this error:
FileNotFoundError: Path or glob "2100 10" not found or matches no files.

I ran into the same FileNotFoundError today when I tried to use PYINSTALLER to work with XLSXWRITER.
Can anyone help me to resolve this issue?


text:
Q: How do I change gem environment? I'm working on a distributed rails app and want to update a gem.  The problem is on one server it won't update because the gem environment is different.  Specifically, I get two different results when running gem env or bundle exec gem env in rails root.  The latter determines the app's gem environment and it is wrong but I don't know how to change it.  I don't see a .gemrc file anywhere on the server and the .bashrc files I checked, and they don't export any of the gem environment variables.  It uses rvm for ruby.  For example, the GEM PATH I would like to change so I grep'd through the app and rvm to see if that path was in a file somewhere and it isn't.  I'm not sure where the environment is getting set, then.  Any suggestions where to look or how to troubleshoot?

A: looking at the man page for bundle, I discovered 'bundle config'.  It gave me the info I needed to find the problem.  It told me it was getting some settings from /home/rails/.bundle/config .  After examining that file, I found it was setting the BUNDLE_PATH to the incorrect setting.  Moving that file aside allowed me to update the gem I wanted to.  I guess the moral of the story is that 'bundle config' (more specifically, 'bundle exec bundle config') is your friend, and check your system for the settings in .bundle/config files if 'gem env' is giving unexpected results.


text:
Q: creating dynamic li elements from json with typeahead - loop error Using typeahead.js I'm creating li elements from the color item in the json response
Json:
"results": [
                {
                    "title": "The Collection",
                    "attribute": "The Collection",
                    "url": "#/test",
                    "image": "images/products/londonretro-caine.jpg",
                    "color": ["brown", "yellow", "grey"]
                },

The json has a color key that is sometimes a string, and sometimes an array with several colors
I've looped through the response and created a html dynamically
html += '

'

I've added a conditional to check if the item in the json is an array of colors.
If it is an array of colors, I've replaced the html with as many li items, as there are colors in the array
I've tried two methods:
1. One is that I make html equal to the new li elements like so: html += '

...'

*the other is that I've changed html to an array and I pushed the li elements into it replacing the original html : html.push('

')
With method 1, I get the following result:
I get all the colors in a separate li,
but I also get an extra first li with the colors like so:

'brown,yellow,grey'

With method 2, I only get the last li with the last color:

'grey'

I left both solutions in the following code.
Any ideas? Thanks, Ask please if it's unclear..
my typeahead code:
suggestion: function (item) {

        var glassesColor = item.color;
        var html = "
'"+ glassesColor +"'
";
        _.forEach(item.color, function (k) {
          if (typeof item.color === 'object') {
              html += "
'"+ k +"'
";

              html = [];
              html.push("
'" + k + "'
");
              var myhtml = html.join('');
              html = myhtml;
          }
        });
        //console.log(html);
        var output = '
\n';
        output += '';
        output += (item.image ? '' : '');
        output += '' + item.title + '';
        output += (item.attribute ? '' + item.attribute + '' : '');
        output += '
';
        output += html;
        output += '
';
        output += '\n';
        output += '
\n';
        return output;
      }

A: ok so I just created another conditional for the string and put the html equals code there..
otherwise everything was fine
if (typeof item.color === 'string') {
          html = "
'"+ glassesColor +"'
";
        }


text:
Q: derivative of $f(t) = 4.9t^2$, dividing by $h$ I can't figure out where I erred in calculating this derivative:
$$f(t) = 4.9t^2$$
$$f'(t) = \frac {f(t+h) - f(t)} {h} = \frac {4.9(t+h)^2 - 4.9t^2} {h}$$
$$= \frac {4.9(t^2 + h^2 +2ht) - 4.9t^2} {h} = \frac {4.9t^2 + 4.9h
^2 + 9.8ht - 4.9t^2} { h}$$
$$=\frac {4.9h^2 + 9.8ht} { h} = 4.9h+9.8t$$
Obviously the correct answer is $9.8t$. I think my fault was in the last step, for some reason I'm still a bit confused when it comes to dividing the difference by $h$.

A: Your error was simply that
$$f'(t)=\lim_{h\to 0}\frac{f(t+h)-f(t)}{h},$$
not
$$f'(t)=\frac{f(t+h)-f(t)}{h}.$$
Take the limit of the expression you got, $ 4.9h+9.8t$, as $h\to 0$, and you get the correct answer :)


text:
Q: How to make a music video slideshow in OSX I want to make a video that consists of a picture slideshow and background music which I will upload to youtube.
Does OSX come with any apps to do this?

A: The probably most well-known application to do this is Boinx FotoMagico.
If you don't want to spend the 29 USD and have iLife, you could try to do this with iMovie.


text:
Q: plotclick events in flot and enyo 1.0 I am new to programming so please bear with me. I have an app built in enyo 1.0 with a working flot graph. I am trying to register click events on the graph so I can use that info elsewhere in the app. I have set clickable to true and I can see the data points highlight when I click on them so I know that part is working.  How do I get the series and data point I click on into enyo?  I am just having a difficult time figuring out from the different partial examples I can find what I need to put where.  I see reference to enyo.dispatcher.listen(document, "plotclick"); but I am not sure where that goes. Does anyone have a working  example they could share?
Thanks in advance!


text:
Q: post to user wall from facebook tab How can i prompt a user for stream publish and email permissions from a facebook tab? Everything i have found will not let me redirect back to either the current page i have loaded in the iframe or the facebook tab url. Everything I have tried has given me this general Facebook error.
One thing to note is I am not requesting the permissions from the intitial page that is loaded in the tabs iframe. I have a form being filled out and submitted which redirects the iframe to another page, on this second page is where i need to request the permissions. The reason for this is i want the form filled out before possibly scaring the user away because they do not want to allow permissions.
It may be simpler if i can pop up the post to your wall box and have the user click the submit button. This way does not require permissions in advance correct? What would be the code to do it this way?

A: You can just use the Feed dialog:

    <title>My Feed Dialog Page</title>

Post to Feed

It works well within a page tab.


text:
Q: How to get elementID from within another function I have some code:
function new_training() {
document.getElementById("training").style="";
tr++;
var newDiv = $('#training div:first').clone();
newDiv.attr('id', tr);
var delLink = 'This is item ' + tr + '<select name=priority> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <a class="btn btn-danger" style="text-align:right;margin-right:65px" href="javascript:deltr(' + tr + ')" > Delete Item ' + tr + ' </a>';
newDiv.find('tr:first th').text('Item ' + tr);
newDiv.append(delLink);
$('#training').append(newDiv);
newDiv.find('input:text').val('');
}

Which work good.
What i am trying to do is get the id of the element i click form an image map.
<area id="cupandplates" alt="" title="cupandplates" href="javascript:new_training()" shape="rect" coords="212,127,295,196" style="outline:none;" target="_self"     />
<area id="3cups" alt="" title="3cups" href="javascript:new_training()" shape="rect" coords="313,147,415,201" style="outline:none;" target="_self"     />
<area id="beerstines" alt="" title="beerstines" href="javascript:new_training()" shape="rect" coords="200,231,269,290" style="outline:none;" target="_self"     />

If i use this fuction:
function reply_click(clicked_id)
{
alert(clicked_id);
}

And change my area's
<area id="cupandplates" alt="" title="cupandplates" href="javascript:new_training()" onClick="reply_click(this.id)" shape="rect" coords="212,127,295,196" style="outline:none;" target="_self"     />
<area id="3cups" alt="" title="3cups" href="javascript:new_training()" onClick="reply_click(this.id)" shape="rect" coords="313,147,415,201" style="outline:none;" target="_self"     />
<area id="beerstines" alt="" title="beerstines" href="javascript:new_training()" onClick="reply_click(this.id)" shape="rect" coords="200,231,269,290" style="outline:none;" target="_self"     />

It will alert the proper ID
What i get now is:
This is item 1 Delete Item 1
This is item 2 Delete Item 2
This is item 3 Delete Item 3
Im not sure what to change to make it so i get:
This is cupandplates Delete Item 1
This is 3cups Delete Item 2
This is beerstines Delete Item 3
Any help would be great.

A: You need to pass the ref to the element when calling:
<area id="cupandplates" alt="" title="cupandplates" href="javascript:new_training(this)" shape="rect" coords="212,127,295,196" style="outline:none;" target="_self"     />
<area id="3cups" alt="" title="3cups" href="javascript:new_training(this)" shape="rect" coords="313,147,415,201" style="outline:none;" target="_self"     />
<area id="beerstines" alt="" title="beerstines" href="javascript:new_training(this)" shape="rect" coords="200,231,269,290" style="outline:none;" target="_self"     />

Then inside the javascript function, use the ref as:
function new_training(el)
{
  var id = el.getAttribute("id");
  //use the id
}

OR if you directly want to pass the id, then try like this:
<area id="cupandplates" alt="" title="cupandplates" href="javascript:new_training(this.id)" shape="rect" coords="212,127,295,196" style="outline:none;" target="_self"     />

Hope it helps

A: You have almost solved your own problem.
It looks like you are looking for title attribute values from area element
Instead of passing the id pass the event trigger object as a whole
<area id="cupandplates" alt="" title="cupandplates" href="javascript:new_training()" onClick="reply_click(this)" shape="rect" coords="212,127,295,196" style="outline:none;" target="_self"     />
<area id="3cups" alt="" title="3cups" href="javascript:new_training()" onClick="reply_click(this)" shape="rect" coords="313,147,415,201" style="outline:none;" target="_self"     />
<area id="beerstines" alt="" title="beerstines" href="javascript:new_training()" onClick="reply_click(this)" shape="rect" coords="200,231,269,290" style="outline:none;" target="_self"     />

and then access the title by using
function reply_click(element)
{
  alert(element.getAttribute("title"));
}


text:
Q: How can I create a "personality-test" using Rails? This is both a request for existing open-source modules, as well as the "architecture".  The data-gathering part (asking questions) looks like can be done using surveyor or wizard gems.
The part I need help on is...how do you "weight" or "score" the answers to come up with the "personality"?  For example, Myers-Briggs type tests ask multiple questions and then describe one of 16 personalities.
I want to limit my outcomes to four, but I'm not sure how.  The standard "If you scored 10-16, you're a rockstar; if you scored 5-9, go home" I don't think quite works this same way?
This is more of a "design" question, so if there's a better place I can ask it, let me know, but it feels that people may know programmatically how in rails to do this kind of simplified expert-system.

A: You have four personality types, and each user's test creates a rank for each of these types.  (e.g. By the end of the test, the user will have a score of 50 for Type-A, a score for 86 for Type-B, a score of 34 for Type-C, and a score of 60 for Type-D)  The user is designated by whichever personality type has the highest score.  (e.g. Type-B)
Each question in the personality test is multiple choice.  Every answer contributes a certain amount to one or more of the personality types.  (e.g. On question 1, an answer of "D" will contribute 5 points to Type-A, 3 points to Type-B, and 0 points to Type-C and Type-D.)
Each answer for each question would have a 4-digit value attribute, indicating how the math on your back end should be carried out.  For instance:
<input type="radio" name="question_one" value="5400" />
<input type="radio" name="question_one" value="3211" />
<input type="radio" name="question_one" value="5608" />
<input type="radio" name="question_one" value="9006" />

Here's how you might handle the back end in Ruby on Rails.  First, you have a User object named @user, which has four fields, type_a, type_b, type_c, type_d, indicating how well the User aligns with each of the four personality types.  In your User model, include a method like this:
def process_answer(value)
  self.type_a += value[0].chr.to_i
  self.type_b += value[1].chr.to_i
  self.type_c += value[2].chr.to_i
  self.type_d += value[3].chr.to_i

In your controller, pass the form data to your User instance:
  @user.process_answer(params[:question_one])

If the user selects the second option for question_one (corresponding to a value of "3211"), then his personality profile will increase 3 pts for type-A, 2 pts for type-B, 1 pt for type-C, and 1 pt for type-D.


text:
Q: How to create a magnetic vertical scroll using angular and angular-scroll? I have an Angular structure for a site that has a series of pages with sections. Each sections of those pages inherits responsively the width and height of the window frame so that as you scroll vertically they become full spreads.
I would like to recreate the effect found from this site "http://andrewgooch.com/" in terms of the vertical magnetic scroll part. Which keeps the frame in position until a certain threshold has been passed. And am not interested in the representation of the frame position on the right as angular-scroll handles this already pretty nicely.
Therefore could anyone help me figure out how to write that part out for angular?
Here is my code so far:
 $scope.goToSection = function( section ) {
        console.log(' section loaded with section: ', section );
        clearTimeout( $scope.timeout );

        $scope.humanScrolling = false;

        var top = 0;
        var duration = 2000; //milliseconds

        var someElement = angular.element( document.getElementById( section ) );

        $document.scrollToElement( someElement, top, duration);
      };

      $scope.delay = 100; // delay before last scroll action
      $scope.timeout = null;

      $document.on('scroll', function() {
        // console.log('Document scrolled to ', $document.scrollLeft(), $document.scrollTop());

        var topPosition = $document.scrollTop();

        if ( !$scope.directionTracker ) {
          console.log('directionTracker was empty');
          $scope.directionTracker = topPosition;
        } else if ( topPosition === $scope.directionTracker ) {
           // same value so ignore
        } else if ( topPosition > $scope.directionTracker ) {

          if ( topPosition ) {

            console.log('going down');
            $scope.$apply();

            $scope.directionTracker = topPosition;

            if ( $scope.scrolling === false ) {
              // $scope.scrolling = true;
              clearTimeout( $scope.timeout );
              $scope.timeout = setTimeout(function(){
                // alert('scrolling stopped');
                console.log("lastscroll down");

                if ( $scope.humanScrolling ) {
                  $scope.goToSection('container-section-' + ( $scope.currentSection + 1) );
                } else {
                  $scope.timeout = setTimeout(function(){
                    $scope.humanScrolling = true;
                    clearTimeout( $scope.timeout );
                  }, 200 );
                }

              }, $scope.delay );
            }
          }

        } else if ( topPosition < $scope.directionTracker ) {

          if ( topPosition ) {

            console.log('going up');
            $scope.$apply();

            $scope.directionTracker = topPosition;

            if ( $scope.scrolling === false ) {
              // $scope.scrolling = true;
              clearTimeout( $scope.timeout );
              $scope.timeout = setTimeout(function(){
                // alert('scrolling stopped');
                console.log("lastscroll up");

                if ( $scope.humanScrolling ) {
                  $scope.goToSection('container-section-' + $scope.currentSection );
                } else {
                  $scope.timeout = setTimeout(function(){
                    $scope.humanScrolling = true;
                    clearTimeout( $scope.timeout );
                  }, 200 );
                }

              }, $scope.delay );
            }
          }

        }
      });

Thank you for your time and consideration.
Cheers,


text:
Q: How to find and replace the whole word (exact match) from a string in python using "re" package while the string contains the metacharacter? For example,
line = "array[0] is the first element, array[0]some_character, is not a valid element"

I just want to find and replace "array[0]" in the string. In this case, let's assume, I want to replace it with the word "element1". Then the output should be as follows:
line = "element1 is the first element, array[0]some_character, is not a valid element".

Please notice that, in the string, array[0]some_character should be unchanged, it should not be replaced like "element1some_character"
I appreciate anyone's help.

A: Try following
word = "abcd ab[0]c ab[0] class ab[0]d classified ab[0]"
re.sub(r'ab\[0\](\s|$)', r'ahmed\1', word)

Output:
'abcd ab[0]c ahmed class ab[0]d classified ahmed'
Or Using look-ahead
word = "abcd ab[0]c ab[0] class ab[0]d classified ab[0]"
re.sub(r'ab\[0\](?=\s|$)', r'ahmed', word)

Output:
'abcd ab[0]c ahmed class ab[0]d classified ahmed'

A: t = "array[0] is the first element, array[0]some_character, is not a valid element"
re.sub("a[a-z]+\[[0-9]+\](?=[\s]{1})", "Element1", t)

you see at the end of regex - (?=[\s]{1}), no white space followed the second array[0], so it won't be replaced.

A: import re

line = "array[0] is the first element, second is array[0], array[0]some_character, is not valid element array[0]."
res = re.sub(r'\barray\[0\](?!\w)', 'REPL', line)
print res

Output:
REPL is the first element, second is REPL, array[0]some_character, is not valid element REPL.

Explanation:
\b              # word boundary, to not match isarray[0]
array\[0\]      # the string to match
(?!\w)          # negative lookahead, make sure we haven't a word character after

Demo & explanation

A: import re

line = "array[0] is the first element, array[0]some_character, is not a valid element"
re.sub('array\[0\]\s','element1 ',line)

Output:
'element1 is the first element, array[0]some_character, is not a valid element'


text:
Q: C# Directory.GetFiles() with wildcard filter show unpredictable results I am using the following C# code to filter a directory containing multiple files:
files = Directory.GetFiles(SourceDatafiles, @"2022*.txt",SearchOption.TopDirectoryOnly);

The directory contains multiple files for instance files like:
2022-07-21-14.txt
2017-2-2-0.txt
The result of the filter is wrong: It also filters the second file name as a valid name. But it does not contain "2022" !?
Any idea what's wrong?

A: Perhaps you could share more information on your environment, DotNet framework version, OS etc.
When I run the below code using DotNet 6 on Windows I get the expected results, namely it only prints the file 2022-07-14.txt
string SourceDatafiles = @"C:\Temp\Test";
var files = Directory.GetFiles(SourceDatafiles, @"2022*.txt", SearchOption.TopDirectoryOnly);

foreach (var file in files)
{
    Console.WriteLine(file);
}

A: See also:
https://stackoverflow.com/a/39753445/19595774
int count1 = 0;
int count2 = 0;
string pattern = "2022";
foreach (var file in Directory.EnumerateFiles(dir))
{
    if (file.Contains("2022"))
        Console.WriteLine("Index:" + count1++ + "Name:" + file);
    /* OR */
    if (Regex.IsMatch(file, pattern) )
        Console.WriteLine("Index:" + count2++ + "Name:" + file);
}

Enumeration works fine. I think a better approach than Directory.GetFiles(SourceDatafiles, @"2022*.txt",SearchOption.TopDirectoryOnly).
Still wondering why the wild-card filter did not work as expected.


text:
Q: React onClick function doesn't fire I built this toy problem to replicate an issue I am facing in a larger app. Why does handleClick not fire when the button is clicked?
const Button = () => <button type="button">Click me</button>;

export const App = () => {

  const handleClick = () => {
    console.log("clicked");
  };

  return <Button onClick={handleClick} />;
};

A: You pass onClick={handleClick} as a property to Button but the Button component does not use the property.
const Button = () ... // ⚠ no onClick property used

You can fix this by responding to the onClick property -
const Button = ({ onClick }) =>  // ✅
  <button type="button" onClick={onClick}> // ✅
    Click me
  </button>

An obvious improvement would be to respond to the children property as well. This allows the caller of Button to write anything in place of the static Click me -
const Button = ({ onClick, children }) =>
  <button type="button" onClick={onClick}>{children}</button>

<Button onClick={handleRegister}>Register</Button>
<Button onClick={handleLogin}>Login</Button>
<Button onClick={handleSave}>Save</Button>

Note children can be passed as a property. Sometimes you will see components use children in this way. Both examples function identically -
const Button = ({ onClick, children }) =>
  <button
    type="button"
    onClick={onClick}
    children={children}
  />

Another common thing for Button components like this is to automatically prevent the default event for the onClick handler. We can also accept a type property and set the default to "button" if the caller does not otherwise specify -
const Button = ({ type = "button", onClick, children, preventDefault = true }) =>
  <button
    type={type}
    onClick={e => {
      if (preventDefault) e.preventDefault()
      onClick(e)
    }}
    children={children}
  />

<Button type="submit" onClick={handleRegister}>Register</Button>
<Button onClick={handleReset} preventDefault={false} children="Reset" />


text:
Q: Make extension compatible for TYPO3 v8 I have a problem in TYPO3 v8.5.0 dev with own extensions.
After creating a proper composer.json my classes are not found. Installation was done by copy into the typo3conf/ext folder as usual and activating in extension manager. Unfortunally the ext is not in TER, so this is the only way.
After activating, i'm stuck with error:

Oops, an error occurred!
Class 'XXX\ExtKey...' not found

What do I miss so my classes are found again?

A: If your extension is not installed with composer you have to add the autoload settings into the composer.json of the project.
"autoload": {
    "psr-4": {
      "Test\\Yourext\\": "web/typo3conf/ext/yourext/Classes"
    }
  }

Then you have to do a composer update or composer dump-autoload


text:
Q: Can you implement a stacked ActionBar on a tablet? I have implemented an ActionBar with my own custom icons. I have added tabs as well but I want these to appear below the ActionBar. At the moment they are displaying in the ActionBar. According to the Android Developers guide:
http://developer.android.com/guide/topics/ui/actionbar.html

when the screen is wide enough the tabs appear in the action bar
  alongside the action buttons (such as when on a tablet, shown in
  figure 7), while when on a narrow screen they appear in a separate bar
  (known as the "stacked action bar", shown in figure 8)

Is it possible to implement a stacked action bar permanently so that the tabs are constantly displayed below the ActionBar across all devices?

A: If you want the same effect as in that image, you can use tabs. Here is a tutorial on how to implement them.