text:
Q: Backbone Collection.create() with arbitrary parameters I'm using Backbone with RESTful persistence.
Is it possible to define some arbitrary input parameters for a Backbone Collection create() method? Normally, Backbone expects corresponding model as input parameter.
Example:
Model "Adder" has the following attributes: "id", "date" and "sum"
I would like to create an instance of these model (via corresponding collections' create() method) by passing 3 parameters: a, b, c. Backend would then calculate the sum=a+b+c and create a record with a calculated sum. It should return a valid Model object and add it to collection.
So...
POST api/adder 1, 2, 3

Retured JSON:
{
    "id": 153235,
    "date": "11/11/11",
    "sum": 6
}

UPDATE:
Maybe will this, less extreme eample help.
How can I send additional parameters to a POST method, besider the model's atts?
If a model is:
{
   a: 1,
   b: 2,
   c:3
}

I would like to send one parameter more, something like calculation_mode, that does not exist in the model itself.
Can I do that?

A: It sounds to me like your problem is that you need computed parameters stored and altered on the client-side that you don't necessarily want sent to the server through your POST and PUT requests. Essentially you want to save / create a subset of your model attributes.
For this situation, a good pattern is to define a serverAttrs property in your model - a hash of attributes that represents the properties you want to persist to the server.
You can then override Backbone's save method in your model or in a Base Model that your model extends from (a better approach).
var MyModel = Backbone.Model.extend({

    idAttribute: 'id',

    serverAttrs: [
        'id',
        'label',
        'fullName',
    ],

    defaults: {
        label: 'My Default Label',
        fullName: '',
        firstName: 'John',
        lastName: 'Smith'
    },

    initialize: function(options){
        this.updateFullName();

        this.on('change:firstName change:lastName', this.updateFullName);
    },

    updateFullName: function(){
        this.set('fullName', this.get('firstName') + ' ' + this.get('lastName'));
    },

    save: function(attrs, options) {
        attrs = attrs || this.toJSON();
        options = options || {};

        if (this.serverAttrs) {
            attrs = _.pick(attrs, this.serverAttrs);
        }

        return Backbone.Model.prototype.save.call(this, attrs, options);
    }

});

In our save method we check for the existence of the serverAttrs property, if it exists we pluck out only those attributes and persist them to the server.
So, in conclusion - you can store whatever attributes you want in your model (within reason) and then send only the attributes you want persisted to the server by defining a serverAttrs property.


text:
Q: retrofit Delete request changes to Get request in Android I send a Delete request by retrofit but it results in Get request response.
it should return response code 204 but it returns 200 instead.
note: In postman it returns 204 but in android it returns 200
My request code is like below:
api.DeleteProduct("JWT " + token, productId, new Callback<JsonObject>() {
    @Override
    public void success(JsonObject jsonObject, Response response) {
        Log.e(TAG, "body "+response.getStatus());
        finish();
    }

    @Override
    public void failure(RetrofitError error) {

    }
});

and its interface is like below:
@DELETE("/products/{productId}")
public void DeleteProduct(@Header("Authorization") String authorization, @Path("productId") String productId, Callback<JsonObject> callback);

A: It appears that Django framework wants a slash at the end of the url for patch and delete requests.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fatal error: Class 'Abraham\TwitterOAuth\Config' not found in twitteroauth.php on line 15 I am using twitterauth.php for getting twitter data in codeigniter php. It gives me error
Fatal error: Class 'Abraham\TwitterOAuth\Config' not found in C:\xampp\htdocs\twitter\application\config\twitteroauth.php on line 15

Line 15 is
13 namespace Abraham\TwitterOAuth;
14 use Abraham\TwitterOAuth\Util\JsonDecoder;

15 class TwitterOAuth extends Config

A: You are missing Library's in our Codeigniter Project
You can Download correct files and add this in relevant path as mentioned.

File path - ./application/
Folder - config
    file name - twitter.php

Folder - controllers
    file name - twtest.php

Folder - libraries
    file name - twconnect.php
    folder name - twitteroauth
        File name - OAuth.php
        File name - twitteroauth.php


text:
Q: Create, lock and unlock a directory in Linux I am developing in Linux environment and run some test scripts concurrently.
Each test script will save temporary results to a its own directory. By temporary, it means if the test is run again, it will overwrite/modify previous results instead of creating new files. This is for the sake of space, otherwise I need to schedule a new job to delete files regularly.
What I want to do in a shell script is: given a path for example A/B/C.

*

*Check if directory A exists, if not, create directory A

*Check if directory A/B exists, if not, create directory B under A

*Check if directory A/B/C exists, if not, create directory C under B, and create a lock inside C.

*Grab/wait the lock in C. Run tests and save results to C. Release the lock in C.

Please note:

*

*There are multiple users running tests on the same box. To hack the permissions, I run chmod 666 * >/dev/dnull 2>/dev>null at the end of each test, is there a better way to change permission to 666 when I create directories?

*Tests are written in python script and is likely to crash. Be sure to avoid deadlock.

*The path can be arbitrary, A/B1/B2/..../Bn/C, I only want to lock the innermost directory C.

Thank you!


text:
Q: Does Eperi Gateway for Databases still exist? Is Eperi Gateway for Databases still offered and maintained?
We are interested in implementing TDE (transparent data encryption) on our MariaDB servers in order to have encryption of data at rest. MariaDB's documentation https://mariadb.com/kb/en/eperi-key-management-encryption-plugin/ indicates that key management for TDE is available using a plugin they provide to Eperi Gateway for Databases. I can't find the latter on Eperi's website, or find an authoritative source at Eperi via Googling, and they haven't responded to a query about it from a week ago. When I contacted MariaDB via chat they indicated that it was no longer available, but they had a paid product that would provide key management for TDE.
We would prefer not to have to migrate from MariaDB to Percona, though Percona's TDE that relies on Hashicorp Vault looks like a suitable combination.


text:
Q: bundle install failed I am getting this error on bundle install
Gem::InstallError: devise_invitable requires RubyGems version ~> 1.3.6. Try 'gem update --system' to update RubyGems itself.
An error occured while installing devise_invitable (0.4.rc), and Bundler cannot continue.
Make sure that `gem install devise_invitable -v '0.4.rc'` succeeds before bundling.

but when i see the version of rubygems i have
gem -v
1.8.10

any ideas on how to fix this....here is the top of my gemfile
gem 'rails', '3.0.3'
gem 'devise', "1.2.rc"
gem 'devise_invitable', '0.4.rc'

A: In the gemspec for devise_invitable, they explicitly require rubygems, ruby and bundler with specific version constraints. While they look like they should be ok since they are using >=, the fact that it comes out in your console as ~> is telling.
The requirement of ~> 1.3.6 means you need to have a version of rubygems installed that is 1.3.6 <= x < 1.4.0.

*

*You could try running bundle install to get compatible gem versions

*But if that doesn't work, try installing the version explicitly gem install rubygems -v 1.3.6


text:
Q: ¿Como crear una url personalizada en htaccess? Estoy intentando usar una url personalizada parecida a algo que tiene wordpress para un sitio web que estoy creando.
La url actual es:
https://www.example.com/single-page.php?slug=example-page-slug
Y la quiero mostrar asi:
https://www.example.com/example-page-slug
Esto es posible? como lo puedo hacer?
He probado esta rule pero no me funciona:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)$ /single-page.php/?slug=$1&%{QUERY_STRING} [L]

A: Options -Multiviews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

así me funciona a mi al trabajandolo en mvc.
el index.php es mi plantilla en tu caso usarias single-page.php


text:
Q: Convergence in a finite metric space Let's look at a metric space $(X,d)$
So we know that a set $A$ is closed iff for each convergent sequence $x_n\rightarrow x$ from $A$,
we have $x\in A$
However, if $X$ is finite, how can we look at such defenition?

A: A finite metric space is discrete (every set is open), so every set is closed.
This means the only convergent sequences are those that are eventually constant. Since all $x_n\in A$, then $x\in A$ because $x_n=x$ for all sufficiently large $n$.


text:
Q: C# Complex Login Im looking for advice, tutorials and general help on this issue.
I current have a simple login system where the user types a username/password verify it on the database then I use [Authorize] tag's to set what pages can be used when a user logged in/logged out.
But rather than host 5 different system for 5 different clients i wanted to merge them.
So the client could log in using Username, Password and then choose there company.
I would require the company detail to be available at every controller so i could say "Pull users for this company", "Pull invoices for this company".
Am i going about this the wrong way. I just think one system would be easier to support, maintain and develop against.
Thanks

A: For this purposes I have AllowFor attribute. It looks like:
public class AllowFor : ActionFilterAttribute
{
    private UserType userTypes = UserType.NotAuthenticated;

    public AllowFor(UserType userTypes)
    {
        this.userTypes = userTypes;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!(filterContext.Controller is ApplicationController))
            throw new Exception("AllowFor attribute is acceptable only for ApplicationController");

        var controller = (ApplicationController)filterContext.Controller;

        if (!userTypes.HasFlag(controller.CurrentUserType))
            filterContext.Result = new ViewResult
            {
                ViewName = "AccessRestricted"
            };
        else
            base.OnActionExecuting(filterContext);
    }
}

ApplicationController is just my class inherited from Contoller.
public abstract class Application : Controller
{
    public UserType CurrentUserType
    {
        get
        {
            return currentUser.UserType;
        }
    }

    // singleton for current user

    protected User __currentUser = null;
    protected User currentUser
    {
        get
        {
            if (__currentUser == null && HttpContext != null && HttpContext.User.Identity.IsAuthenticated)
            {
                // access to sql based on:
                // HttpContext.User.Identity.IsAuthenticated
                // HttpContext.User.Identity.Name
                // etc
            }
            return __currentUser;
        }
    }

    // singleton for EF context

    private MyAppContext __context = null;
    protected MyAppContext context
    {
        get
        {
            if (__context == null)
            {
                __context = new MyAppContext();
            }
            return __context;
        }
    }
}

You don't need it actually, but I find it quite useful. Just inherit your controller from ApplicationContoller and you're able to retrieve context and other objects with singleton pattern.
The usage of attribute is very easy, just mark your action with attribute:
[Authorize, AllowFor(UserType.Company)]
public ActionResult Index()
{
    // ...
}

You can make your AllowFor attribute more useful and apply it to classes (controllers, for instance) instead of actions:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,
                AllowMultiple = false, Inherited = true)]
public class AllowFor : ActionFilterAttribute { ... }

If you want to fetch the user from your database based on forms authentication, you can follow one of two ways:

*

*Fetch by email

*Fetch by provider user key

It's quite easy to fetch by email, but this approach has several disadvantages:

*

*You must ensure that your membership provider requires unique email address (must set requiresUniqueEmail property of your Membership provider in Web.config to true)

Example:
<membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="15">
  <providers>
    <clear />
    <add name="MyMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MembershipConnection" applicationName="GeekJob" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="1" maxInvalidPasswordAttempts="100" passwordAttemptWindow="1440" />
  </providers>
</membership>

*

*You must keep in mind that user@server.com is not User@server.com. If you need to fetch the user from database by email, you must have additional column LoweredEmail in your table. Also, don't forget about table index on LoweredEmail column. Also, don't forget to mark it with [StringLength(450)] attribute (in case if you use MS SQL Server, because string columns can't exceed 450 unicode symbols if you apply index on them).

*What if the user decides to change his email? You'll need to modify membership and your entities table. Sounds like we're on the way to code smell.
So I recommend to link membership and existing tables on ProviderUserKey property (you will also need additional column and index).
Now you can fetch the user easily by doing:
if (HttpContext != null && HttpContext.User.Identity.IsAuthenticated)
{
    MembershipUser mu = Membership.GetUser(HttpContext.User.Identity.Name);
    return context.Users.Where(u => u.UserKey == (Guid)mu.ProviderUserKey).FirstOrDefault();
}


text:
Q: custom chapter numbering with decimals I would like to start a report with the Chapter 3.6 (and consecutive) until 3.9. I have been looking for these types of commands, but they are not working as I want.
Please help

A: \renewcomand\thechapter{3.\arabic{chapter}}
\setcounter{chapter}{5}

in the preamble should make the first \chapter 3.6

A: Principally it's possible to set the counters of chapter andsection` accordingly, but it will look a little bit strange.
Since the section counter is reset each time the chapter counter is increased, the setting of section counter must be done after \chapter is called.
\documentclass{report}

\usepackage{blindtext}

\setcounter{chapter}{2}

\begin{document}
\tableofcontents

\chapter{My real first chapter}
\setcounter{section}{5}

\section{A section}

\blindtext[5]

\section{A} % Will be 3.7
\section{B} % 3.8
\section{c} % 3.9

\chapter{Second chapter}  % Sections are set to 1, chapter is 4 now
\section{Start over with 1}

\end{document}

A: Class with chapters
If the class contains chapters and the "3" in "3.6" means the chapter number:
\documentclass{report}

\setcounter{chapter}{3}
\setcounter{section}{5}

\begin{document}
\tableofcontents
\section{First section}
\subsection{First subsection}
\subsubsection{First subsubsection}
\section{Second section}
\section{Third section}
\section{Forth section}
\end{document}

Class without chapters
If the class does not contain chapters such as article, then the appearance of the section counter can be prefixed with 3.. The longer section number also requires more place in the table of contents, see the following example:
\documentclass{article}

\usepackage{etoolbox}

\pretocmd\thesection{3.}{}{%
  \errmessage{Patching \noexpand\thesection failed}%
}
\setcounter{section}{5}

% Extra place is needed for the section number in the table of contents
\makeatletter
\patchcmd\l@section{1.5em}{2.3em}{}{%
  \errmessage{Patching \noexpand\l@section failed}%
}
\makeatother

\begin{document}
\tableofcontents
\section{First section}
\subsection{First subsection}
\subsubsection{First subsubsection}
\section{Second section}
\section{Third section}
\section{Forth section}
\end{document}


text:
Q: grub2-install can't find lvm device I am in the process of moving from Arch to Fedora and simplifying my partitioning scheme in the process (by using LVMs raid options instead of layering it on an mdadm array). I have this LVM scheme:
$ lvscan
  ACTIVE            '/dev/dragon/fedora' [20.00 GiB] inherit
  ACTIVE            '/dev/dragon/swap' [32.00 GiB] inherit
  ACTIVE            '/dev/dragon/home' [3.59 TiB] inherit

All three LVs are raid10 across four 2TB harddrives. Fedora has installed with minimal pain, except that it didn't install a bootloader on to any of the four PVs. So, I am attempting to install it manually by chrooting into the installed system from the live USB. I get this recurring error:
# grub2-install /dev/sdb
Installing for i386-pc platform.
grub2-install: error: disk 'lvmid/uCln3P-NLvn-Hfj8-11nF-2R3l-prtW-goyTVJ/FpF3b4-LYI9-chju-Tcwc-uTSv-D6ZU-DAQIui' not found.

It get the same error from grub2-mkconfig, but it generates the config file anyway. grub2-install does not appear to write to the MBR following this error.
This is my /etc/default/grub, although it appears to not make a difference - I get the same error if GRUB_PRELOAD_MODULES is empty, non existent, or contains nonsense:
GRUB_PRELOAD_MODULES="lvm mdraid1x"

The UUIDs in the lvmid disk name correctly match those on the VG and the LV. Why can't grub find the logical volume?

A: i'm currently working on a similar problem in SLES12.1 and noticed that changing the device map to the corresponding PV makes grub2-install find the right disk:
$ cat /boot/grub2/device.map
(hd0)   /dev/vda
$ grub2-install /dev/vda --target=i386-pc
Installing for i386-pc platform.
Installation finished. No error reported.

In your case vda would be sdb
HTH


text:
Q: WCF & Network Bandwidth Throttling I have a client application calling a method of a WCF service. Sometimes one of the parameter of this method call is close to 10MB. This causes a problem when the client is in a really slow network. When the 10MB data is being transferred to the server, other users in the network experience severe slowdown. Is there a way to throttle bandwidth usage per method call?
Searching high and low, only options seems to be writing a custom channel.
I am not able to find any decent documentation on how to write a custom channel.
Any pointer would really help

A: I would say your best bet is to look at the infrastructure side. Firewalls or networking appliances, load ballancers.

A: Set a really small socket send buffer, say 1k. Check the result too, the system may modify what you passed. Set it as low as you can. The objective is to get it smaller than the bandwidth*delay product, so your send can't 'fill the pipe', leaving room for other users.


text:
Q: Running a Python script through the Terminal that uses CSV as dataset I have a python script that imports MatPlotLib and plots stock prices.
import sys
import matplotlib.pyplot as plt

vals = [float(line.split(',')[7]) for line in sys.stdin]

plt.plot(vals)
plt.title('Stock Price Data')
plt.ylabel('Adjusted Closing Price')
plt.xlabel('Trading Day')
plt.show()

I want to run this script in the terminal by importing a file named 2015_goog_sorted.csv (which is 2015 Google stock prices, sorted) as the values to be sorted.
I'm on a Mac and using Atom
I'm in the process of learning commands using unix and terminal, but I know there should be a relatively easy way to do this.
Thanks in advance :)

A:   1 import csv
  2
  3 with open('test.csv','r') as f:
  4     a = csv.reader(f)
  5     for row in a:
  6         print(row)

The output
wirelessprv-10-194-17-39:python Bobby$ python3 te.py
['1', '1', '1', '1']
['2', '2', '2', '2']

You can do anything with row

A: If you just wanted to run the script as-is, you can hardcode the path to the input file:
import sys
import matplotlib.pyplot as plt
import csv

with open('/path/to/2015_goog_sorted.csv', 'r') as f:
    reader = csv.reader(f)
    vals = [float(row[7]) for row in reader]

plt.plot(vals)
plt.title('Stock Price Data')
plt.ylabel('Adjusted Closing Price')
plt.xlabel('Trading Day')
plt.show()

if you want to use unix style piping to send in the input you can do the following:
import sys
import matplotlib.pyplot as plt
import csv

reader = csv.reader(sys.stdin)
vals = [float(row[7]) for row in reader]

plt.plot(vals)
plt.title('Stock Price Data')
plt.ylabel('Adjusted Closing Price')
plt.xlabel('Trading Day')
plt.show()


text:
Q: load row database on variable in php I am new about php and mysql.
I start a project for make a little application, and it's work like this:

*

*Load API facebook

*if the ID of user doesn't exist on database, insert ID and username on a specific table of database.

*after that, load the row of the user where the ID facebook is equal on the database.

the problem is on the third step!!
This is the code:
            if ( $loadspecific == "caricadati" ) {
        $query =array() ==  "SELECT * UIDfacebook FROM tabletest WHERE UIDfacebook = $id";
        $result = mysql_query(mysql_real_escape_string($query)) or die (mysql_error());

        while($row = mysql_fetch_array($result))
        {
            echo "{$row['UIDfacebook']} <br>" ;
        }

        }else{
            echo $result;

            }

    mysql_close($dblink);

    //Close off the MySQL connection to save resources.
 ?>

thank you so much!!!

A: Change this
$query =array() ==  "SELECT * UIDfacebook FROM tabletest WHERE UIDfacebook = $id";

to
$query = "SELECT UIDfacebook FROM tabletest WHERE UIDfacebook = $id";

or
$query = "SELECT * FROM tabletest WHERE UIDfacebook = $id";


text:
Q: CORS blocking javascript fetch request with same origin I made a javascript app that fetch a JSON file when the page load. Everything is working fine for me and most users. But for some people, the fetch request is blocked by CORS because the 'Access-Control-Allow-Origin' header has a value that is not equal to the supplied origin.

you can try here : https://limeshark.dev/editor
My fetch request :
var t = await fetch('https://limeshark.dev/t/', {method: 'GET'});

(I am making the same request on another page (i.e https://limeshark.dev/editor/Neutron) and no one reported this issue)
here is my Express header
app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'https://limeshark.dev/');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, content-type, Access-Control-Allow-Origin');
    res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

and here is my nginx config
add_header 'Access-Control-Allow-Origin' 'https://limeshark.dev/';
add_header 'Access-Control-Allow-Methods' 'GET, POST';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

Of course i noticed that in the error the origin 'https://limeshark.dev' is different from the header value 'https://limeshark.dev/' but i do not know why
thank you in advance :)

A: As suggested by Nick, making the request with a relative path fixed the issue
var t = await fetch('/t', {method: 'GET'});

A: I could not 'comment' but Nick's answer solved my issue!
Hoodathunk switching the URL would get rid of the dreaded CORS issue...
THANKS NICK!
@Nick https://stackoverflow.com/users/6525724/nick


text:
Q: lazy-sequence with recursion: stack-overflow on certain cases with repl I play with clojure, more precisely with lazyness.
I tried this chunk of code:
(defn even-numbers
  ([] (even-numbers 0))
  ([n] (cons n (lazy-seq (even-numbers (+ n 2))))))
(take 1 (even-numbers 0))

It's quite idiomatic, I don't think there is something wrong with this.
The problem is I use cider within emacs. If I first evaluate the defn and afterwards evaluate the function call I get a stack overflow. Evaluating the whole buffer is OK.
I suspect that enlighten mode is to be blamed since I don't get the overflow when I disable it. I just want to understand what happens here.
[EDIT] I'm quite sure the issue is related to the enlighten mode of cider. disabling it I never get a stack overflow.
To dig a little bit into it, considering the slightly modified excerpt:
(ns clojure-noob.bizarerrie)

(defn even-numbers
  ([] (even-numbers 0))
  ([n] (do (println (even-numbers (+ n 2)))
           (cons n (lazy-seq (even-numbers (+ n 2)))))))
(take 1 (even-numbers 0))

which also gives a stack overflow in every cases. Since enlighten mode try to resolves expression to output it during execution on the fly; Intuitively I'd say it tries to print the (even-numbers (+ n 2)) form (like the println I just added), which cause the stack overflow.

A: you have the cons and lazy-seq switched in the lazy sequence definiton:
Here it is with the cons inside the lazy-seq
user> (defn even-numbers [n]
        (do
          (lazy-seq (cons (do
                            (printf "creating value %s for lazy sequence" n)
                            n)
                          (even-numbers (+ n 2))))))
#'user/even-numbers

And again with the cons outside the lazy-seqwhich creates an almost lazy sequence
user> (defn even-numbers-not-really-lazy [n]
        (do
          (cons (do
                  (printf "creating value %s for lazy sequence" n)
                  n)
                (lazy-seq (even-numbers (+ n 2))))))

A proper lazy sequence should to no work when it's created, let's test both of these:
#'user/even-numbers-not-really-lazy
user> (def lazy-even-numbers
        (even-numbers 0))
#'user/lazy-even-numbers

Yep, that one looks good, now with the cons on the outside:
user> (def not-lazy-even-numbers
        (even-numbers-not-really-lazy 0))
creating value 0 for lazy sequence
#'user/not-lazy-even-numbers

hmmm looks like we did some work when we created the cons cell.

A: You get a stack overflow are running out of heap space, because you are trying to realize the infinite lazy sequence. You need to specify how many values you want realized in that sequence by calling function called take
(take 10 (even-numbers 0)) ; if you want to realize first 10 values


text:
Q: Gridview Update is not working protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                    string Createid =((Label)GridView1.Rows[e.RowIndex].FindControl("lblID")).Text;
                    string Client_Name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtClientName")).Text;
                    string Client_Contact_Name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtContactPerson")).Text;
                    string Client_Contact_Role = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPosition")).Text;
                    string Client_Contact_Email_ID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtMailID")).Text;
                    string Phone_Number = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPhNumber")).Text;
                    string No_of_Openings = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOpenings")).Text;
                    string Technology = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtTech")).Text;
                    string Status = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtStatus")).Text;
                    string Op_Start_Date = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtStrtDate")).Text;
                    string Op_End_Date = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEndDate")).Text;
            con.Open();

                    SqlCommand cmd = new SqlCommand("UPDATE Client_Det set Client_Name=@Client_Name, " + " Client_Contact_Name= @Client_Contact_Name, " + " Client_Contact_Role= @Client_Contact_Role, " + " Client_Contact_Email_ID = @Client_Contact_Email_ID , " + " Phone_Number= @Phone_Number , " + "No_of_Openings=@No_of_Openings ,  " + "Technology=@Technology, " + "Status=@Status, " + " Op_Start_Date=@Op_Start_Date , " + " Op_End_Date=@Op_End_Date where Createid= @Createid", con);
                    cmd.ExecuteNonQuery();

                    con.Close();
                    GridView1.EditIndex = -1;
                    gvbind();

                }

My table datatypes

The above are the table datatype.
After Clicking on update button it is not even showing any errors
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" align="center"
             DataKeyNames="Createid" OnPageIndexChanging="GridView1_PageIndexChanging"
             OnRowCancelingEdit="GridView1_RowCancelingEdit"
             OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
                EnableViewState="False" AllowPaging="True" PageSize="5">
    <Columns>

<asp:TemplateField ItemStyle-Width = "30px"  HeaderText = "ID">
    <ItemTemplate>
        <asp:Label ID="lblID" runat="server"
        Text='<%# Eval("Createid")%>'></asp:Label>
    </ItemTemplate>

</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Client">
    <ItemTemplate>
        <asp:Label ID="lblClientName" runat="server"
                Text='<%# Eval("Client_Name")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtClientName" runat="server"
            Text='<%# Eval("Client_Name")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtClientName" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Contact Person">
    <ItemTemplate>
        <asp:Label ID="lblContactPerson" runat="server"
                Text='<%# Eval("Client_Contact_Name")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtContactPerson" runat="server"
            Text='<%# Eval("Client_Contact_Name")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtContactPerson" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Position">
    <ItemTemplate>
        <asp:Label ID="lblPosition" runat="server"
                Text='<%# Eval("Client_Contact_Role")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtPosition" runat="server"
            Text='<%# Eval("Client_Contact_Role")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtPosition" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Mail ID">
    <ItemTemplate>
        <asp:Label ID="lblMailID" runat="server"
                Text='<%# Eval("Client_Contact_Email_ID")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtMailID" runat="server"
            Text='<%# Eval("Client_Contact_Email_ID")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtMailID" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Phone Number">
    <ItemTemplate>
        <asp:Label ID="lblPhNumber" runat="server"
                Text='<%# Eval("Phone_Number")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtPhNumber" runat="server"
            Text='<%# Eval("Phone_Number")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtPhNumber" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "No of Openings">
    <ItemTemplate>
        <asp:Label ID="lblOpenings" runat="server"
                Text='<%# Eval("No_of_Openings")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtOpenings" runat="server"
            Text='<%# Eval("No_of_Openings")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtOpenings" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Technology">
    <ItemTemplate>
        <asp:Label ID="lblTech" runat="server"
                Text='<%# Eval("Technology")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtTech" runat="server"
            Text='<%# Eval("Technology")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtTech" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Status">
    <ItemTemplate>
        <asp:Label ID="lblStatus" runat="server"
                Text='<%# Eval("Status")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtStatus" runat="server"
            Text='<%# Eval("Status")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtStatus" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Start Date">
    <ItemTemplate>
        <asp:Label ID="lblStrtDate" runat="server"
                Text='<%# Eval("Op_Start_Date","{0:dd-MM-yyyy}")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtStrtDate" runat="server"
            Text='<%# Eval("Op_Start_Date","{0:dd-MM-yyyy}")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtStrtDate" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "End Date">
    <ItemTemplate>
        <asp:Label ID="lblEndDate" runat="server"
                Text='<%# Eval("Op_End_Date","{0:dd-MM-yyyy}")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtEndDate" runat="server"
            Text='<%# Eval("Op_End_Date","{0:dd-MM-yyyy}")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>

        <asp:CommandField ShowEditButton="true" />

        </Columns>

</asp:GridView>

This my source code for the gridview...
Have i done anything wrong in providing correct fields .. please let me know

A: You are doing it wrong. Your Update query doesn't do anything. Either you should assign it as parameter or you should give the variable name directly.
Option 1

SqlCommand cmd = new SqlCommand("UPDATE Client_Det set Client_Name='"+ Client_Name +"', Client_Contact_Name='"+ Client_Contact_Name +"', Client_Contact_Role='"+Client_Contact_Role+"', Client_Contact_Email_ID ='"+ Client_Contact_Email_ID+"', Phone_Number='"+Phone_Number+"', No_of_Openings='"+No_of_Openings+"', Technology='"+Technology+"', Status='"+Status+"', Op_Start_Date='"+ Op_Start_Date +"', Op_End_Date='"+Op_End_Date+"' where Createid='"+Createid+"'", con);

There variables where not properly referred. So the values were not getting attached into query.

PS - This is very bad way to write query in perspective of security. Your code keep space open to SQL injection attack. Option 2 will be a better way to write queries

Option 2

Through Command parameters
So this is basically you are assigning values to parameters and parameter name given to command parameters should be equal to the parameter name given in the query. So below is just a glimpse of how you can achieve.
string sql = "UPDATE Client_Det set Client_Name=@Client_Name, Client_Contact_Name= @Client_Contact_Name, Client_Contact_Role= @Client_Contact_Role, Client_Contact_Email_ID = @Client_Contact_Email_ID , Phone_Number= @Phone_Number ,No_of_Openings=@No_of_Openings, Technology=@Technology,Status=@Status,Op_Start_Date=@Op_Start_Date, Op_End_Date=@Op_End_Date where Createid= @Createid";

SqlCommand cmd = new SqlCommand(sql, con);

cmd.Parameters.AddWithValue("@Client_Name", Client_Name);
cmd.Parameters.AddWithValue("@Client_Contact_Name",Client_Contact_Name)
/*Add for remaining param values*/

cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
gvbind();

1st parameter on each AddValueWith i.e. @Client_Name and @Client_Contact_Name should be same as given in update query and 2nd parameter i.e. Client_Name and Client_Contact_Name are value fetched from GridView Controls like TextBox, Label etc.,


text:
Q: use resources from jar (Facebook SDK as jar) I'm using Facebook SDK project on my own project by adding it as a library inside my workspace, like:
Project properties ->  Android -> Add.. -> Facebook SDK
Like this i have access to classes and resources inside this project. For example in one of my layout files i have:
android:drawable="@drawable/com_facebook_loginbutton_blue_normal"

But if i want to change the way i use this Facebook SDK project, and simple export it as jar file, and add it to libs folder in my app, i have the error:
error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/com_facebook_loginbutton_blue_normal').

How to access the resources inside my jar file?

A: The short answer is, you can't. The Facebook SDK is an android library, and is being shipped as such, and should be used as such. Trying to import it as just a jar file will not work. Do you have a specific use case that requires you to only use jar libraries?

A: From what i can understand..
That,s because that drawable resource is in different package than yours, try accessing it with full package name
EDIT
What I meant was add
android:drawable="@packageName:drawable/com_facebook_loginbutton_blue_normal"

Like this:-
android:drawable="@com.google.android:drawable/com_facebook_loginbutton_blue_normal"

I don't know what package name is defined in Android SDk so change package name accordingly.
Hope this helps.


text:
Q: How to sort a dictionary by attribute value? I have a Dictionary like
{'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}}

How would I be able to sort this by the "frequency" attribute?

A: sorted(a, key=lambda x: (a[x]['frequency']))
To keep it ordered by request from the comments:

from collections import OrderedDict
OrderedDict(sorted(a.items(), key=lambda x: x[1]['frequency']))

A: dictionaries are not order in python. if you need to order the dictionary . better to use OrderedDict from collections modules
In [24]: from collections import OrderedDict
    ...: d = {'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}}
    ...:
    ...: ord_a = OrderedDict(sorted(ord_d.items(), key = lambda x: x[1]['frequency']))
    ...:
    ...:

In [25]:

In [25]: print(ord_a)
OrderedDict([('B', {'frequency': 2}), ('A', {'frequency': 4}), ('C', {'frequency': 7})])


text:
Q: captured row with a user's code in several columns. each column is task. I need to export each instance of the users code to another table My row and headers look like this (Asignments Table):
Codigo|Tienda|Apertura|Cierre_20_00|Cierre_20_30|Cierre_21_00|Sanitarios|Barrer_Mat|Barrer_Vesp|Trapear_Mat|Trapear_Vesp|Limpiar_Ventanales_y_Vitrinas|Encargada|Supervisora

2     |1010  |2010    |0           |0           |2010        |3010      |3010      |2010       |2010       |3010        |3010                         |2010     |1102

Each task besides Codigo, Encargada and Supervisora has a user code asigned to it.
Now I need to export each instance for each task to another table where each task has specific timeframes to complete.
as in table Tareas (Tasks):
Asignacion |Tiempo_Inicio   |Tiempo_Limite  |Empleado   |Supervisor

Apertura   |11:00:00 AM     |11:10:00 AM    |           |

What code can I run after each Asignment capture is completed?
I believe it has to be an UPDATE, but how to pick each Assignment from that row and export it to each Empleado Column under Tasks table on SUBMIT?


text:
Q: ASP.NET Cookie Update Value Without Updating Expiration? Is it possible to update an ASP.NET cookies value without also having to update the expiration time?  I have found that if I try and update a Cookie without also updating the expiration, that cookie no longer exists.  I have the following code which I am try to modify.  What's the point of having an expiration, if every time the cookie value is updated, so is the expiration?
        HttpCookie cookie = HttpContext.Current.Request.Cookies[constantCookie];

        if (cookie == null)
            cookie = new HttpCookie(constantCookie);

        cookie.Expires = DateTime.Now.AddYears(1);
        cookie.Value = openClose;
        HttpContext.Current.Response.Cookies.Set(cookie);

A: The ASP.NET HttpCookie class can not initialize the Expires property upon reading in a cookie from an HTTP request (since the HTTP specification doesn't require the client to even send the Expiration value to the server in the first place). And if you don't set the Expires property before you set the cookie back in the HTTP Response, than it turns it into a session cookie instead of a persistent one.
If you really must keep the expiration, than you could set the initial expiration date as part of the cookie value, then when you read the cookie in, parse out the value and set the new expiration to match.
An example that doesn't include any other data so the cookie isn't really helpful -- you would have to serialize it somehow with the actual data you want to store:
HttpCookie cookie = HttpContext.Current.Request.Cookies[constantCookie];
DateTime expires = DateTime.Now.AddYears(1);

if (cookie == null) {
    cookie = new HttpCookie(constantCookie);
} else {
    // cookie.Value would have to be deserialized if it had real data
    expires = DateTime.Parse(cookie.Value);
}

cookie.Expires = expires;
// save the original expiration back to the cookie value; if you want to store
// more than just that piece of data, you would have to serialize this with the
// actual data to store
cookie.Value = expires.ToString();

HttpContext.Current.Response.Cookies.Set(cookie);


text:
Q: How to unpivot table with dynamic columns I'm trying to transpose a table called CHECK_CARD. It looks like this:
 _________________________________________________________________
|       anc_report_date       |  RiskSignal  | group_company_attr |
|_____________________________|______________|____________________|
| 2019-01-01 00:00:00.0000000 | NoRiskSignal |       4894543      |
| 2016-07-01 00:00:00.0000000 |  RiskSignal  |       1242151      |

I want it to look like this:
 ____________________________________________________________________________
|   anc_report_date  |2019-01-01 00:00:00.0000000|2016-07-01 00:00:00.0000000|
|____________________|___________________________|___________________________|
| RiskSignal         |        NoRiskSignal       |        RiskSignal         |
| group_company_attr |          1242151          |          1242151          |

The number of rows in anc_report_date is dynamic so what I'm trying to do is:
DECLARE @Column NVARCHAR(MAX)
SET @Column
  = 'SELECT cc.anc_report_date
        from CHECK_CARD cc
        inner join CHECK_CARD chc on cc.group_company_attr=chc.group_company_attr and cc.anc_report_date<=chc.anc_report_date and chc.id=1832307
    where cc.status=1'
exec sp_executesql @Column

Here I collect all column names.
DECLARE @Column NVARCHAR(MAX)
SET @Column
  = 'SELECT cc.anc_report_date
        from CHECK_CARD cc
        inner join CHECK_CARD chc on cc.group_company_attr=chc.group_company_attr and cc.anc_report_date<=chc.anc_report_date and chc.id=1832307
    where cc.status=1'
DECLARE @Transpose as NVARCHAR(MAX)
set @Transpose
  = 'SELECT RiskSignal, group_company_attr
     from CHECK_CARD
     unpivot
     (
        kek
        for anc_report_date in ('+ @Column +')
     ) u'

exec sp_executesql @Transpose;

But when I use it all together it returns "Incorrect syntax near the keyword 'SELECT'."
I think this line ('+ @Columns +') is the reason.
Any ideas?
     PRINT @Transpose;
[2019-09-19 18:54:42] [S0001] SELECT RiskSignal, group_company_attr
[2019-09-19 18:54:42] from CHECK_CARD
[2019-09-19 18:54:42] unpivot
[2019-09-19 18:54:42] (
[2019-09-19 18:54:42] kek
[2019-09-19 18:54:42] for anc_report_date in (SELECT cc.anc_report_date
[2019-09-19 18:54:42] from CHECK_CARD cc
[2019-09-19 18:54:42] inner join CHECK_CARD chc on cc.group_company_attr=chc.group_company_attr and cc.anc_report_date<=chc.anc_report_date and chc.id=1832307 where cc.status=1)
[2019-09-19 18:54:42] ) u
[2019-09-19 18:54:42] completed in 3 ms

A: Made it, Thanks all!
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(cc.id)
from CHECK_CARD cc
         inner join CHECK_CARD chc
                    on cc.group_company_attr = chc.group_company_attr and cc.anc_report_date <= chc.anc_report_date and
                       chc.id = 1832307
where cc.status = 1
      group by cc.id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = N'SELECT AttrName,' + @cols + N' from
(
  select id, AttrName, value
  from CHECK_CARD
  cross apply
  (
select ''RiskSignal'', cast(RiskSignalas varchar(50)) union all
select ''group_company_attr'', cast(group_company_attr varchar(50))
  ) c(AttrName, value)
) d
pivot
(
  max(value)
  for id in (' + @cols + N')
) piv';

exec sp_executesql @query;


text:
Q: C# COM Library: How to Decorate Interop Function Lines for ActiveX / COM Visibility I have not seen the answer on StackOverflow yet. This is in a C# library project with the interfaces defined below (and project settings) so it is visible as a COM component.
The goal is to make the functions/methods in the interop lines visible through the COM interface. The interop lines provide visibility to the functions in an older C library/dll.
The problem is shown through the interop line for Convert in the NativeCalls class below. It includes "static extern". If these (i.e. "static extern") are included in the interface section that is above the class definition (as shown), I get the errors:

*

*The modifier 'extern' is not valid for this item

*The modifier 'static' is not valid for this item

If I remove "extern static", "Convert" as in the interface section will not be found in the class.
How can I decorate the "Convert" line in the interface section so I do not need to write additional methods within the NativeCalls class to wrap every single interop line (i.e. those starting with "public static extern" such as that for "Convert". If I need to do this, I have hundreds to wrap - maybe a nice macro program is in order :). What is a better/shorter way? Thanks for any help.
[ComVisible(true)]
[Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83D")]
  public interface IComNativeCallsInterface
{
    [DispId(1)]
    static extern int Convert(ref formatfile fptr); // leaving "static extern" on front causes errors. Removing "static extern" will cause the call "Convert" to not be found in the class.
}

[Guid("7BD20046-DF8C-44A6-8F6B-687FAA26FA7D"),
    InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComNativeCallsEventsInterface
{
}

[ComVisible(true)]
[Guid("0D53A3E8-E51A-49C7-944E-E72A2064F93D"),
    ClassInterface(ClassInterfaceType.None),
    ComSourceInterfaces(typeof(IComNativeCallsEventsInterface))]
public class NativeCalls : IComNativeCallsInterface
{
    /// Return Type: int
    ///fptr: formatfile*
    [System.Runtime.InteropServices.DllImportAttribute("coldlib.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Convert")]
    public static extern int Convert(ref formatfile fptr);

...
}

A: An interface method cannot be static or extern. It doesn't make any sense. In COM in particular, an interface always requires a class instance obtained from IClassFactory::CreateInstance(), etc. That's just the way COM works. In C# in turn, a static method cannot be an implementation of an interface method, even if it has the right parameters and name, for the same reason: a C# interface reference is obtained from casting an object (instance) reference to the interface.
And it makes total sense! Remember that underlying every interface method call there is a hidden (By C++ and C#) this argument that references the object instance. The method signatures don't really match, even if it looks that way on the surface.
If you need to expose the same method both as a COM method and as a plain C external symbol, you will need two copies of the method declaration: the static extern one which implements the functionality, and a second copy that forwards the call, which is declared as public int IComNativeCallsInterface.Convert(ref formatfile fptr). If I remember correctly (I don't have a computer with VS at hand), by declaring the second method as an explicit interface implementation you will be able to have the two declarations match name and formal arguments exactly without a conflict.


text:
Q: How to do polling using lightning/uiRecordApi? I want to query Batch Job status every 5 seconds to show user the progress of batch job.
Is it possible through lightning/uiRecordApi or do I have to put query inside Apex method?


text:
Q: Can not change text after Locale has changed I try to use two languages in my application.I have different string.xml files in my project.
I try to change language like this
public class LocaleManager {

public static final String LANGUAGE_ENGLISH   = "en";
public static final String LANGUAGE_GEORGIAN = "ka";
private static final String LANGUAGE_KEY       = "language_key";

public static Context setLocale(Context c) {
    return updateResources(c, getLanguage(c));
}

public static Context setNewLocale(Context c, String language) {
    persistLanguage(c, language);
    return updateResources(c, language);
}

public static String getLanguage(Context c) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
    return prefs.getString(LANGUAGE_KEY, LANGUAGE_ENGLISH);
}

@SuppressLint("ApplySharedPref")
private static void persistLanguage(Context c, String language) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    prefs.edit().putString(LANGUAGE_KEY, language).commit();
}

private static Context updateResources(Context context, String language) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(new Locale(language));
        context.getApplicationContext().createConfigurationContext(configuration);
    } else {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Configuration config = context.getResources().getConfiguration();
        config.locale = locale;
        context.getResources().updateConfiguration(config,
                context.getResources().getDisplayMetrics());
    }
    return context;
}

public static Locale getLocale(Resources res) {
    Configuration config = res.getConfiguration();
    return Build.VERSION.SDK_INT >= 24 ? config.getLocales().get(0) : config.locale;
}

I'm using my class like this in button onClick
 flagImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!LocaleManager.getLanguage(LauncherActivity.this).equals(LocaleManager.LANGUAGE_ENGLISH))
                    LocaleManager.setNewLocale(LauncherActivity.this, LocaleManager.LANGUAGE_ENGLISH);
                else
                    LocaleManager.setNewLocale(LauncherActivity.this, LocaleManager.LANGUAGE_GEORGIAN);

                Intent i = new Intent(LauncherActivity.this, LauncherActivity.class);
                startActivity(i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                overridePendingTransition(R.anim.fade_in_dialog, R.anim.fade_out_dialog);

            }
        });

I have a two questions:
1) I tested it and locale is changing successfully but I can't change setText. Is it a possible to change setText without refresh activity?
2) After locale has changed I try to use my setText in onCreate method, but still can't change it
How I can solve this problem?


text:
Q: Chrome обманывает? Есть таблица. Стала задача создать элемент, с точно таким же размерам столбца.
Эксперимент 1 - скрин на картинке, показана метрика у th и у div. Ширина задавалась через скрипт. Ширины выводятся на div, они одинаковые, но в метрике, ширина у th неожиданно на 1 значение больше.
Эксперимент 2
Chrome обманывает?
Как можно создать точно такую же таблицу, в позиции absolute, чтобы ширина столбцов совпадала?


text:
Q: Using DATEPART to CASE in SQLServer to check the month and days only SELECT CAST(
             CASE
                  WHEN n_asset_acquisitionDate = GETDATE()
                     THEN .../*UPDATE SOMETHING*/
             END AS float) as Depreciation, *
FROM normal_asset

hi i'm new to using CAST and really needed this kind of approach, what will happen is that I just want the WHEN n_asset_acquisitionDate to just check the GETDATE() only per month and day so that every month it will do the update. Any comment, methods, advice, approach is fine,
P.S.:
I've read in this [thread][1] that using CASE is bad? I really don't understand.
[1]: http://weblogs.sqlteam.com/jeffs/archive/2003/11/14/513.aspx EDIT:
What happens is that I am incrementing a numeric column. So that every month(day of the inserted month) it will increment. So for example
n_asset_acquisitionDate   n_asset_ul
2017-2-13                 1
2017-2-13                 4
2017-2-15                 4

So in March 13 when I run the query it will go like this
n_asset_acquisitionDate   n_asset_ul
2017-2-13                 2
2017-2-13                 5
2017-2-15                 4

A: You can just update with a where clause::
UPDATE normal_asset
SET n_asset_ul = n_asset_ul + 1
WHERE n_asset_acquisitionDate = convert(date, GETDATE())


text:
Q: How do I get clicked elements model in View - Ember I have a view with number of divs in rows. When I click on a div the current clicked element should be selected. Below is the code I have used.
{{#each}}
    <div {{action target="view" on="click" allowedKeys="shift"}} {{bind-attr class=':user isActive'}} >
        {{test}}
    </div>
{{/each}}

My view is backed by a model as:
model: function() {
    return [{'test':'1'}, {'test' :'2'}, {'test': '3'}, {'test': '4'}];
}

In my view I handled the click handler.
click: function( e ) {
    if( e.shiftKey ){
        this.modelFor("index").send('changeBgSelection', {'test' :'2'} ); // Here I could not get the current clicked elements model.
    }

    // Here I need to get the current clicked elements model. When I click the second element I need to get as  "{'test' :'2'}". But I could not get the current elements model. Instead I can get the whole model.

}

In my Route,
Here the clicked element is made active.
actions:{
    changeBgSelection: function (params) {
        var select = this.get("controller").objectAt(this.modelFor("index").indexOf(params));
        select.set('isActive', true)
    }
}

So how do I get the current clicked elements model in my View? So that I can pass the model to my Route to make the clicked div active with Shift key is pressed.
Edited: Jsbin Link

A: There are two ways to respond to a mouse click in Ember:

*

*Call an action

*Handle it in a view

It seems you tried to combine the two and it became a mess. I'm sure there's a way to make it work, but I can't find it. Instead, allow me to propose an alternative.
In general, if there's something fancy going on with javascript or event handling (like the SHIFT key in your example), I like to deal with it in a localized view. Here, each 'TestView' is tied to a single model instance, which it manipulates based on user input.
  <script type="text/x-handlebars" data-template-name="index">
    {{#each}}
      {{#view App.TestView content=this}}
        {{this.test}}
      {{/view}}
    {{/each}}
  </script>

App = Ember.Application.create();

function wrap(ob) {
  return Ember.Object.create(ob);
}

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
      wrap({'test':'1', 'isActive':false}),
      wrap({'test' :'2', 'isActive':false}),
      wrap({'test': '3', 'isActive':false}),
      wrap({'test': '4', 'isActive':false})
    ];
  }
});

App.TestView = Ember.View.extend({
  classNames: ["user"],
  classNameBindings: ["content.isActive:is-active"],
  click: function(e) {
    if (e.shiftKey) {
      this.get("content").toggleProperty("isActive");
    }
  }
});

This can be cleaned up some more, but you get the gist. Live demo here.


text:
Q: Angular/ChromeHeadless unit tests fail on Visual Studio Online I have a Angular7 application with UnitTests. I'm running them succesfully on my local machine with
ng test --source-map=false --watch=false --browsers=ChromeHeadless"

But when I run the CI pipline on VisualStudioOnline (AzureDevOps), the same command just returns with
2018-11-06T10:50:29.3023236Z ##[error]Error: Npm failed with return code: 1

The only (small) difference is the node/npm version
Local: Node 8.11.1 / NPM 6.1.0
VSOnline: Node 8.12.0 / NPM 6.4.1

A: Well, to close this issue...
Always be aware about all the console.log's in Chrome. With headless in Azure, it's not the most comfortable way to analyize this. But running the tests locally with browser support makes it easier.


text:
Q: PySpark and time series data: how to smartly avoid overlapping dates? I have the following sample Spark dataframe
import pandas as pd
import pyspark
import pyspark.sql.functions as fn
from pyspark.sql.window import Window

raw_df = pd.DataFrame([
    (1115, dt.datetime(2019,8,5,18,20), dt.datetime(2019,8,5,18,40)),
    (484, dt.datetime(2019,8,5,18,30), dt.datetime(2019,8,9,18,40)),
    (484, dt.datetime(2019,8,4,18,30), dt.datetime(2019,8,6,18,40)),
    (484, dt.datetime(2019,8,2,18,30), dt.datetime(2019,8,3,18,40)),
    (484, dt.datetime(2019,8,7,18,50), dt.datetime(2019,8,9,18,50)),
    (1115, dt.datetime(2019,8,6,18,20), dt.datetime(2019,8,6,18,40)),
], columns=['server_id', 'start_time', 'end_time'])
df = spark.createDataFrame(raw_df)

which result in
+---------+-------------------+-------------------+
|server_id|         start_time|           end_time|
+---------+-------------------+-------------------+
|     1115|2019-08-05 18:20:00|2019-08-05 18:40:00|
|      484|2019-08-05 18:30:00|2019-08-09 18:40:00|
|      484|2019-08-04 18:30:00|2019-08-06 18:40:00|
|      484|2019-08-02 18:30:00|2019-08-03 18:40:00|
|      484|2019-08-07 18:50:00|2019-08-09 18:50:00|
|     1115|2019-08-06 18:20:00|2019-08-06 18:40:00|
+---------+-------------------+-------------------+

This indicates the usage date ranges of each server. I want to convert this into a time series of non-overlapping dates.
I would like to achieve this without using UDFs.
This is what I'm doing now, which is wrong
w = Window().orderBy(fn.lit('A'))
# Separate start/end date of usage into rows
df = (df.withColumn('start_end_time', fn.array('start_time', 'end_time'))
    .withColumn('event_dt', fn.explode('start_end_time'))
    .withColumn('row_num', fn.row_number().over(w)))
# Indicate start/end date of the usage (start date will always be on odd rows)
df = (df.withColumn('is_start', fn.when(fn.col('row_num')%2 == 0, 0).otherwise(1))
    .select('server_id', 'event_dt', 'is_start'))

which gives
+---------+-------------------+--------+
|server_id|           event_dt|is_start|
+---------+-------------------+--------+
|     1115|2019-08-05 18:20:00|       1|
|     1115|2019-08-05 18:40:00|       0|
|      484|2019-08-05 18:30:00|       1|
|      484|2019-08-09 18:40:00|       0|
|      484|2019-08-04 18:30:00|       1|
|      484|2019-08-06 18:40:00|       0|
|      484|2019-08-02 18:30:00|       1|
|      484|2019-08-03 18:40:00|       0|
|      484|2019-08-07 18:50:00|       1|
|      484|2019-08-09 18:50:00|       0|
|     1115|2019-08-06 18:20:00|       1|
|     1115|2019-08-06 18:40:00|       0|
+---------+-------------------+--------+

But the end result I would like to achieve is the following:
+---------+-------------------+--------+
|server_id|           event_dt|is_start|
+---------+-------------------+--------+
|     1115|2019-08-05 18:20:00|       1|
|     1115|2019-08-05 18:40:00|       0|
|     1115|2019-08-06 18:20:00|       1|
|     1115|2019-08-06 18:40:00|       0|
|      484|2019-08-02 18:30:00|       1|
|      484|2019-08-03 18:40:00|       0|
|      484|2019-08-04 18:30:00|       1|
|      484|2019-08-09 18:50:00|       0|
+---------+-------------------+--------+

So for server_id 484 I have the actual start and end dates without all the noise in between.
Do you have any suggestion on how to achieve that without using UDFs?
Thanks

A: IIUC, this is one of the problems which can be resolved by using Window lag(), sum() function to add a sub-group label for ordered consecutive rows which match some specific conditions. Similar to what we do in Pandas using shift()+cumsum().

*

*Set up the Window Spec w1:
w1 = Window.partitionBy('server_id').orderBy('start_time')

and calculate the following:

*

*max('end_time'): the max end_time before the current row over window-w1

*lag('end_time'): the previous end_time

*sum('prev_end_time < current_start_time ? 1 : 0'): the flag to identify the sub-group

The above three items can be corresponding to Pandas cummax(), shift() and cumsum().

*Calculate df1 by updating df.end_time with max(end_time).over(w1) and setting up the sub-group label g, then doing groupby(server_id, g) to calculate the min(start_time) and max(end_time)
df1 = df.withColumn('end_time', fn.max('end_time').over(w1)) \
        .withColumn('g', fn.sum(fn.when(fn.lag('end_time').over(w1) < fn.col('start_time'),1).otherwise(0)).over(w1)) \
        .groupby('server_id', 'g') \
        .agg(fn.min('start_time').alias('start_time'), fn.max('end_time').alias('end_time'))

df1.show()
+---------+---+-------------------+-------------------+
|server_id|  g|         start_time|           end_time|
+---------+---+-------------------+-------------------+
|     1115|  0|2019-08-05 18:20:00|2019-08-05 18:40:00|
|     1115|  1|2019-08-06 18:20:00|2019-08-06 18:40:00|
|      484|  0|2019-08-02 18:30:00|2019-08-03 18:40:00|
|      484|  1|2019-08-04 18:30:00|2019-08-09 18:50:00|
+---------+---+-------------------+-------------------+

*After we have df1, we can split the data using two selects and then union the resultset:
df_new = df1.selectExpr('server_id', 'start_time as event_dt', '1 as is_start').union(
         df1.selectExpr('server_id', 'end_time as event_dt', '0 as is_start')
)

df_new.orderBy('server_id', 'event_dt').show()
+---------+-------------------+--------+
|server_id|           event_dt|is_start|
+---------+-------------------+--------+
|      484|2019-08-02 18:30:00|       1|
|      484|2019-08-03 18:40:00|       0|
|      484|2019-08-04 18:30:00|       1|
|      484|2019-08-09 18:50:00|       0|
|     1115|2019-08-05 18:20:00|       1|
|     1115|2019-08-05 18:40:00|       0|
|     1115|2019-08-06 18:20:00|       1|
|     1115|2019-08-06 18:40:00|       0|
+---------+-------------------+--------+


text:
Q: IOS 13.3 - it refreshes the pages when clicking the back button need help.
I'am using react boiler plate to create pages, just a problem, in IOS 13.3 (iphone), it refreshes the pages when clicking the back button.
I need to retain the pages when clicking the back button without refreshing the page.
Thanks


text:
Q: How to remove a null object from json I am new in Bootstrap JS. I have a table made with Bootsrap JS, whose data came from a Json file. Here is The Code-

                            UID
                            Name
                            Address
                            Tags
                            Edit tags

function showAll(){
   $.ajax({
      url: "showAll",
      dataType:"json",
      success:function(data){
            $('#user_table tr:gt(0)').remove();
            jQuery.each(data['Payload'], function(index, value) {
            var row = '
'
                   + ''+ value['uid']+ '	'
                   + ''+ value['name']+ '	'
                   + ''+ value['address']+ '	'
                   + ''+ value['tag1']+ ',' + value['tag2']+ ',' + value['tag3']+'	' + ''+ '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '
';

            $('#user_table').append(row);
      });
     }
});

Now This Payload is the name of my json, which came from a servlet where I call the database.
Now let, there is 3 tags. But some of rows have 2 tags. So, when I put the values in json the Json looks like-
{"Payload":[{"uid":"u01","name":"Subho","address":"Dumdum","tag1":"aircel","tag2":"vodafone","tag3":"airtel"},{"uid":"u02","name":"Jeet","address":"Baruipur","tag1":"airtel","tag2":"","tag3":"aircel"},{"uid":"u03","name":"Diba","address":"Jadavpur","tag1":"vodafone","tag2":"aircel","tag3":"airtel"},{"uid":"u04","name":"Tommy","address":"Baguihati","tag1":"aircel","tag2":"vodafone","tag3":""},{"uid":"u05","name":"Jonty","address":"Rahara","tag1":"","tag2":"vodafone","tag3":"airtel"},{"uid":"u06","name":"Gourav","address":"Tripura","tag1":"aircel","tag2":"vodafone","tag3":"airtel"}]}

Now You can see, that for UID=U02 there is 2 tags. And the output looks like picture attached. How can I remove the blank values or null values???? Please anyone help me...

A: I think, you are saying about the extra , in the tags column... one messy solution is
$.ajax({
    url: "showAll",
    dataType: "json",
    success: function (data) {
        $('#user_table tr:gt(0)').remove();
        jQuery.each(data['Payload'], function (index, value) {
            var tags = $.map([value.tag1, value.tag2, value.tag3], function (value) {
                return value || undefined;
            });

            var row = '
' + '' + value['uid'] + '	' + '' + value['name'] + '	' + '' + value['address'] + '	' + '' + tags + '	' + '' + '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '
';

            $('#user_table').append(row);
        });
    }
});

As @Alnitak said
var tags = [value.tag1, value.tag2, value.tag3].filter(function (value) {
    return value !== undefined;
});
console.log(tags)


text:
Q: How to use debounce with redux-form correctly? I have a search input.
const { searchMails } = this.props;
searchMails(keyword);

I added the lodash's debounce based on this answer on Stack Overflow.
const { searchMails } = this.props;

const debounceSearchMails = debounce(searchMails, 1000);
debounceSearchMails(keyword);

The action
export const searchMails = keyword => ({ type: SEARCH_MAILS, payload: keyword });

However, after adding debounce, when I type "hello", it will still trigger 5 times searchMails after 1 second. The payload are
h
he
hel
hell
hello

How can I use debounce correctly? Thanks
UPDATE 1: add full codes
import React, { PureComponent } from 'react';
import { Field, reduxForm, reset } from 'redux-form';
import { Form } from 'reactstrap';
import debounce from 'lodash/debounce';

class Search extends PureComponent {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit(values) {
    const { searchMails } = this.props;

    const debounceSearchMails = debounce(searchMails, 1000);
    debounceSearchMails(values.keyword);
  }

  render() {
    const { handleSubmit, keyword } = this.props;

    return (
      <Form onSubmit={handleSubmit(this.onSubmit)}>
        <Field name="keyword" component="input" type="search" onChange={() => setTimeout(handleSubmit(this.onSubmit))} />
      </Form>
    );
  }
}

function validate(values) {
  const errors = {};
  return errors;
}

export default reduxForm({
  validate,
  form: 'searchForm'
})(Search);

UPDATE 2:
I changed my action to
const searchMails0 = keyword => ({ type: SEARCH_MAILS, payload: keyword });
export const searchMails = debounce(searchMails0, 1000);

But still same.
UPDATE 3: this time I changed to this, but still same.
class Search extends PureComponent {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
    this.debouncedSubmit = debounce(this.onSubmit, 1000);
  }

  onSubmit(values) {
    const { searchMails } = this.props;
    searchMails(values.keyword);
  }

  render() {
    const { handleSubmit, keyword } = this.props;
    return (
      <Form onSubmit={handleSubmit(this.debouncedSubmit)}>
        <Field name="keyword" component="input" type="search" onChange={() => setTimeout(handleSubmit(this.debouncedSubmit))} />
      </Form>
    );
  }
}

UDPATE 4:
I found the issue is somehow related with setTimeout, if I have that like below, debounce won't work. If I remove setTimeout, debounce will work. But then onChange will always return last value. So I do need have it because of redux-form's this "issue"
<Field component="input" type="search" onChange={() => setTimeout(handleSubmit(debounce(this.onSubmit, 1000)))}/>

A: First big thank you for @zerkms. Without his guide to the right direction, I cannot make it.

You should only create the debounced function once and then use it. It is debounced function that holds internally the state necessary for debouncing. At the moment you recreate it on every keystroke. – zerkms

After checking onChange's type, this is final working code:
class Search extends PureComponent {
  constructor(props) {
    super(props);

    this.onSubmit = this.onSubmit.bind(this);
    this.onChange = this.onChange.bind(this);
    this.debouncedOnChange = debounce(this.onChange, 1000);
  }

  onSubmit(values) {
    const { searchMails } = this.props;
    searchMails(values.keyword);
  }

  onChange(event, newValue, previousValue) {
    const { searchMails } = this.props;
    searchMails(newValue);  // the second parameter is new value
  }

  render() {
    const { keyword } = this.props;
    return (
      <Form onSubmit={handleSubmit(this.onSubmit)}>
        <Field component="input" type="search" onChange={this.debouncedOnChange}/>
      </Form>
    );
  }
}

Lessons learned:

*

*I never thought I can do something like this.debouncedSubmit = debounce(this.onSubmit, 1000); in constructor.

*And I always thought I have to use handleSubmit from redux-form, but turns out it is not for all cases.

*Need go deep.


text:
Q: Matlab print -dmeta command clips the wrong figure to the clipboard. How to fix? I have a MATLAB GUI project developed using the GUIDE tool under R2012a under Windows 7. It uses code like
function pushbutton1_Callback(hObject, eventdata, handles)
  h = figure()
  t = linspace(1,10,200);
  plot(t,sin(t))
  figure(1)
  save2word('myfile.doc')

This should save the figure to the windows clipboard. What actually happens is that the clipboard contains an image of the calling program.
If I change the code as follows, the expected image appears on the clipboard.
function pushbutton1_Callback(hObject, eventdata, handles)
  h = figure()
  t = linspace(1,10,200);
  plot(t,sin(t))
  figure(1)
  save2word('myfile.doc', '-f1')

Using save2word in this way solves my problem, but I am puzzled why something that used to work changed. Could it be a Java update?

A: The save2word function provides a second argument which you could use to specify the figure to "print":
save2word('file.doc','-f1')

which ends up calling:
print -dmeta -f1

to copy the figure to clipboard.
Of course you can build the string programmatically: sprintf('-f%d',hFig) where hFig is the figure handle.

A: To use save2word you need to call save2word, which I don't see you doing in this instance.  print -demta as you have it here just simply copies the active figure to the clipboard.  If you want to save it to a file you have to use print -dmeta 'filename'.
I guess it's possible that I don't fully understand what you're asking/saying here.  Are you saying that save2word uses print -dmeta in order to place the given figure into a word document?  It's important to note that save2word doesn't support saving multiple figures at once to a word document and that you will need to call it each time for each figure you want to save.


text:
Q: how to display text on label in single line I want to dispaly label text in one line on horizontal bar in highcharts. below is the code.I want to dispaly label text in one line on horizontal bar in highcharts. below is the code
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

There is a better example of what I want to accomplish
I want to dispaly label text in one line on horizontal bar in highcharts. below is the code.I want to dispaly label text in one line on horizontal bar in highcharts. below is the code

A: You need to set an width for your labels
...
style: {
            fontSize: '1em',
            color:'#fff',
            width:'500px'
        }

Fiddle
As you can see the 4th bar is too short so you will have to set the width for a second line appear

A: Try to use below property in label
label{
display:block
}


text:
Q: IntelliJ 12.0.1 - Grails 2.3.X Distribution in specified path is broken I am struggling to configure grails 2.3.X in IntelliJ idea 12.0.1. Grails 2.2.X is configured successfully.
Grails 2.3.2 is working properly from terminal. I can compile, test, run my application. But while trying to configure it in IntelliJ so that dependencies get resolved,  I get the IntelliJ shouting straight to me(as pictured below).

Looks like Grails Distribution in specified path is broken. Cannot
  determinate version.

What I see is changes in grails-2.3.x/dist/ to earlier version's grails-2.2.x/dist/.
Is this because there's no support for newer version(2.3.x) of grails in IntelliJ 12 or what ?
I want nothing else but my application (jar) dependencies to be resolved in the IDE.

A: Make sure you are running the latest version of IntelliJ IDEA - v12.1.6. There was a "Grails 2.3.0 not working" bug fixed in 12.1.6.
You may also want to take a look at the Grails SDK is not configured question. One of the IntelliJ IDEA developers has a detailed answer in that question that may help.
Also, this thread on the IntelliJ IDEA forum may be useful.

A: For Information to reload the dependencies in IntelliJ 12.1.6 , following path works fine.

      Tools
           -> Grails
               -> Synchronize Grails settings


text:
Q: Double integration in a region extending below the x-axis For area under a curve, we separately calculated areas above vs below the x-axis, taking the absolute value for the latter to add to the former.
I'm not sure how this translates to the double integration case. First of all, sorry for asking something can be done by trial but the question I'm working on does not have worked solutions so since I can't get the exact final answer I'm spending hours working blindly.
I have a triangle bounded by $y_1 -1 \leq y_2\leq -y_1+1$ and $0 \leq y_1 \leq 1$. This is where the equation to integrate is $f(y_1, y_2) = 6y_1^2 y_2$ is defined. I'm asked to integrate doubly over $y_1 < \frac{1}{2}, y_2 < \frac{1}{2}$ (this is a probability question where the equation is a pdf and the ask is to find the joint probability of $y_1 < \frac{1}{2}, y_2 < \frac{1}{2}$).
I am guessing the need to take absolute values is different and more complex because although the "area" below x-axis is negative, the z-level is not necessarily negative. Therefore I'm not quite sure how it works.
I've attempted an all-at-once approach which I didn't expect to work and it didn't e.g.
$$
\int_0^{1/2} \int_{y_1 -1}^{1/2} 30y_1^2 y_2 dy_2 dy_1
$$
I've also tried separately doing the parts above and below the x-axis:
$$
\int_{0}^{1/2} \int_{0}^{1/2} 30y_1^2 y_2 dy_2 dy_1 + \int_{0}^{1/2} \int_{y_1 -1}^{0} 30y_1^2 y_2 dy_2 dy_1
$$
But it doesn't seem to be working. Perhaps my algebra is wrong but again with no worked solutions and so far having not found any errors, I have no idea what's going on.
PS the answer is 9/16

A: I found the answer!!
My method of
$$
\int_0^{1/2} \int_{y_1 -1}^{1/2} 30y_1^2 y_2 dy_2 dy_1
$$
was supposed to work, I must have made an algebraic error.
Would like to hear an explanation about how $y_2$ cannot be negative though, since I still don't really understand how I got the right answer and what it would mean conceptually.


text:
Q: how does a swing timer work? hello i am having trouble trying to understand swing timers. to help me could someone show me a simple flickering animation? i have looked arround on the internet but still dont fully understand how they work. it would be so helpful if someone could give me an example like this:
say if i created a circle:
g.setColor(colors.ORANGE);
g.fillOval(160, 70, 50, 50);

how could i then use a swing timer to change the color from orange to say Gray using a swing timer with a delay?
thank you so much for helping me understand :)

A: First of all, you wouldn't hard-code your color use like this:
g.setColor(colors.ORANGE);
g.fillOval(160, 70, 50, 50);

Since this prevents all ability to change the color's state. Instead use a class field to hold the Color used, and call it something like ovalColor:
private Color ovalColor = SOME_DEFAULT_COLOR; // some starting color

And then use that color to draw with:
g.setColor(ovalColor);
g.fillOval(160, 70, 50, 50);

I'd then give my class an array of Color or ArrayList<Color> and an int index field:
private static final Color[] COLORS = {Color.black, Color.blue, Color.red,
       Color.orange, Color.cyan};
private int index = 0;
private Color ovalColor = COLORS[index]; // one way to set starting value

Then in the Swing Timer's ActionListener I'd increment the index, I'd mod it by the size of the array or of the ArrayList, I'd get the Color indicated by the index and call repaint();
index++;
index %= COLORS.length;
ovalColor = COLORS[index];
repaint();

Also here's a somewhat similar example.
Also please look at the Swing Timer Tutorial.

A: maybe this would help:
public class object{
Color color = Color.GREEN;
Timer timer;
public object() {

timer = null;
timer = new Timer(5000, new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        if (color.equals(Color.GREEN)) {
            color = Color.RED;
            timer.setDelay(2000);
        } else {
            color = Color.GREEN;
            timer.setDelay(8000);
        }
        repaint();
    }
});
timer.start();}}

A: I think a paint method would work.like this:
public void paint(Graphics g){
super.paint(g);

g.setColor(Color.green);
g.filloval(30,40,50,50);
 }


text:
Q: onclick event onjavascript img tag not working I am trying to call a function on onclick event from img tag. But it appears it's not calling the function at all.

Image List

        <%-- <asp:ImageButton id="imagelist" ImageUrl="~/Admin1/images/refresh-6.png"
        style="height:30px; width:30px; margin-left:10px; cursor:pointer;" runat="server"
        OnClick="imagelist_Click" Height="26px" />  --%>

javascript code:
    function Load() {
            window.location("NewDesign.aspx");
    }

A: Use this Instead..
function Load() {

            window.location.href = "NewDesign.aspx";
    }

http://jsbin.com/agiHAgI/1/

A: Its seems that you should change this
function Load()
{
      window.location = "NewDesign.aspx";
}

A: To modify the URL try any of these method
document.location = "NewDesign.aspx";

or
window.location = "NewDesign.aspx";

A: Onclick event for ImageButton of asp.net control is used for server side call.
You must use OnClientClick event of imageButton
OnClientClick="Load();"


text:
Q: Groovy Script for JIRA-actions Нужна помощь по написанию groovy скрипта. Необходим скрипт, который устанавливает исполнителя по задаче, если при создании задачи исполнитель не указан. Как смог написал, но он не работает.
if (issue.assignee == null) {
  issue.setassigneeID("admin")
}

A: Вам необязательно для такой простой вещи писать Groove-скрипт
В настройках проекта в Users and Roles вы можете указать опцию Default Assignee, и все задачи без исполнителя будут ставиться на выбранного пользователя.
А на будущее, для отладки Groovy-скриптов, в том же Script Runner'е есть консоль.
Чтобы получить там issue, надо сделать вот так:
def issue = issueManager.getIssueObject('ISSUE_ID')


text:
Q: Setting PathAnnotation on SSIS path from code I have been trying lately to create SSIS packages from .NET code rather than using drag and drop in Visual Studio. As part of the package documentation, I would like to be able to annotate data flow paths.
The code below - copied from MSDN - establishes a path between two SSIS data flow components. By adding
    path.Name = "My name";
    new Application().SaveToSqlServer(package, null, "localhost", "myUser", "myPassword");

I can set the name of the path to whatever I like and then save the package in my local SQL Server. When I open the package in Visual Studio 2008, however, the name of the path can only be seen under path properties.
In Visual Studio, there is another path property, PathAnnotation, with the value AsNeeded and additional possibilities SourceName, PathName, Never. Changing the value to PathName gives me what I want: The path name appears next to the path in the data flow tab in Visual Studio.
My question is: Is it possible to set the value of the PathAnnotation property from code?
using System;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

namespace Microsoft.SqlServer.Dts.Samples
{
  class Program
  {
    static void Main(string[] args)
    {
      Package package = new Package();
      Executable e = package.Executables.Add("STOCK:PipelineTask");
      TaskHost thMainPipe = e as TaskHost;
      MainPipe dataFlowTask = thMainPipe.InnerObject as MainPipe;

      // Create the source component.
      IDTSComponentMetaData100 source =
        dataFlowTask.ComponentMetaDataCollection.New();
      source.ComponentClassID = "DTSAdapter.OleDbSource";
      CManagedComponentWrapper srcDesignTime = source.Instantiate();
      srcDesignTime.ProvideComponentProperties();

      // Create the destination component.
      IDTSComponentMetaData100 destination =
        dataFlowTask.ComponentMetaDataCollection.New();
      destination.ComponentClassID = "DTSAdapter.OleDbDestination";
      CManagedComponentWrapper destDesignTime = destination.Instantiate();
      destDesignTime.ProvideComponentProperties();

      // Create the path.
      IDTSPath100 path = dataFlowTask.PathCollection.New();
      path.AttachPathAndPropagateNotifications(source.OutputCollection[0],
        destination.InputCollection[0]);
    }
  }

A: I succeeded in getting an answer in a different forum. Please see
http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/23e6a43f-911f-44da-8e69-cd9e53d7e5ed


text:
Q: Creating a 'view' link in a grid listing that navigates to a detail route such as hero/:id in Angular In my template I am doing the following:

    {{ h.id}}
    {{ h.name}}
    {{ h.description}}
    View

How can I make it so View is a link that navigates to /heroes/:id? I have this setup in my route config. I verified that it works by going to http://localhost:4200/heroes/1
Am I better off using the (click) event and calling a function such as viewHero(id). If I did this I wouldn't be sure how to pass the id. Also, if it can be done directly inside of the html template within the href tag or routerLink I would like to know how to do that too. My main problem seems to be accessing h.id inside of a string such as href="".
Update: I got the following to work, but still not happy with it:
  View

  viewHero(hero) {
    this.router.navigate(['/heroes', hero.id]);
  }

There has to be a way to simply do this inside of the anchor tag directly. I am not getting a pointer finger when hovering the link.

A: Try this:

    {{ h.id}}
    {{ h.name}}
    {{ h.description}}
    View


text:
Q: Randomly select number and its index from an array in matlab I have one array c=[1 2 3 4 5]; with possibly number of  duplicate numbers.
I want to randomly choose an element from a array as well as its index.
Can anybody help me..

A: You could find
Code:
C = [1,2,3,4,5,4,4,5];  %// Example input. Change with your original array

no = C(randi(numel(C))) %// Your code to find a random number.
idx = find(C == no)    %// find all the indices matching the value of the number.

Output:
no =

 5

idx =

 5     8

A: First get the index:
idx = randi(numel(c));

Then get the element from the array
val = c(idx);


text:
Q: Undefined property: my_controller::$db Severity: Notice
Message: Undefined property: my_controller::$db
Filename: libraries/Session.php
Line Number: 88

A: use
$this->load->database();

before all database operation. or open application/config/autoload.php and search
$autoload['libraries'] = array(); replace that to
$autoload['libraries'] = array('database','session');


text:
Q: NativeScript Application breaks while moving position on google map I have added google maps in my mobile application using Nativescript google maps plugin. Here is my html
<MapView #mapView [latitude]="latitude" [longitude]="longitude" [zoom]="zoom" [minZoom]="minZoom" [maxZoom]="maxZoom" [bearing]="bearing" [tilt]="tilt" i-padding="50,50,50,50" [padding]="padding" (mapReady)="onMapReady($event)" (markerInfoWindowTapped)="onMarkerWindowTapped($event)" (cameraChanged)="onCameraChanged($event)" row="1" col="0" colspan="2"> </MapView>

I have a dropdown which has a dropdown showing multiple markers on the map. I wanted to change the camera position when i change the value in dropdown. Here is how i handle dropdown change event
onchange(args: SelectedIndexChangedEventData) {

let event = this.events.filter(event => event._id === this.itemSource.getValue(args.newIndex));

console.dir(event);
//this.latitude =  event[0].locationInfo.coordinates[0];
//this.longitude = event[0].locationInfo.coordinates[1];

}
This code executes successfully if i uncomment last 2 lines and camera position is getting changed. However after camera position is changed, i get below unknown exception which i am unable to debug
System.err: java.lang.reflect.InvocationTargetException System.err: at java.lang.reflect.Method.invoke(Native Method) System.err: at com.tns.NativeScriptUncaughtExceptionHandler.uncaughtException(NativeScriptUncaughtExceptionHandler.java:55) System.err: at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1068) System.err: at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1063) System.err: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.PendingIntent.send(android.content.Context, int, android.content.Intent)' on a null object reference System.err: at com.tns.ErrorReport.startPendingErrorActivity(ErrorReport.java:156) System.err: at com.tns.ErrorReport.startActivity(ErrorReport.java:133) System.err: ... 4 more System.err: java.lang.reflect.InvocationTargetException System.err: at java.lang.reflect.Method.invoke(Native Method) System.err: at com.tns.NativeScriptUncaughtExceptionHandler.uncaughtException(NativeScriptUncaughtExceptionHandler.java:55) System.err: at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1068) System.err: at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1063) System.err: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.PendingIntent.send(android.content.Context, int, android.content.Intent)' on a null object reference System.err: at com.tns.ErrorReport.startPendingErrorActivity(ErrorReport.java:156) System.err: at com.tns.ErrorReport.startActivity(ErrorReport.java:133) System.err: ... 4 more

Can someone at least provide me hint on what might be causing the same? Please note that if i comment the lines for changing lat/long when i change my dropdown, everything works perfectly fine.


text:
Q: spatial filtering by proximity in R I have occurrence points for a species, and I'd like to remove potential sampling bias (where some regions might have much greater density of points than others). One way to do this would be to maximize a subset of points that are no less than a certain distance X of each other. Essentially, I would prevent points from being too close to each other.
Are there any existing R functions to do this? I've searched through various spatial packages, but haven't found anything, and can't figure out exactly how to implement this myself.
An example occurrence point dataset can be downloaded here.
Thanks!

A: I've written a new version of this function that no longer really follows rMaternII.
The input can either be a SpatialPoints, SpatialPointsDataFrame or matrix object.
Seems to work well, but suggestions welcome!
filterByProximity <- function(xy, dist, mapUnits = F) {
    #xy can be either a SpatialPoints or SPDF object, or a matrix
    #dist is in km if mapUnits=F, in mapUnits otherwise
    if (!mapUnits) {
        d <- spDists(xy,longlat=T)
    }
    if (mapUnits) {
        d <- spDists(xy,longlat=F)
    }
    diag(d) <- NA
    close <- (d <= dist)
    diag(close) <- NA
    closePts <- which(close,arr.ind=T)
    discard <- matrix(nrow=2,ncol=2)
    if (nrow(closePts) > 0) {
            while (nrow(closePts) > 0) {
                if ((!paste(closePts[1,1],closePts[1,2],sep='_') %in% paste(discard[,1],discard[,2],sep='_')) & (!paste(closePts[1,2],closePts[1,1],sep='_') %in% paste(discard[,1],discard[,2],sep='_'))) {
                discard <- rbind(discard, closePts[1,])
                closePts <- closePts[-union(which(closePts[,1] == closePts[1,1]), which(closePts[,2] == closePts[1,1])),]
                }
            }
        discard <- discard[complete.cases(discard),]
        return(xy[-discard[,1],])
    }
    if (nrow(closePts) == 0) {
        return(xy)
    }
}

Let's test it:
require(rgeos)
require(sp)
pts <- readWKT("MULTIPOINT ((3.5 2), (1 1), (2 2), (4.5 3), (4.5 4.5), (5 5), (1 5))")

pts2 <- filterByProximity(pts,dist=2, mapUnits=T)

plot(pts)
axis(1)
axis(2)
apply(as.data.frame(pts),1,function(x) plot(gBuffer(SpatialPoints(coords=matrix(c(x[1],x[2]),nrow=1)),width=2),add=T))
plot(pts2,add=T,col='blue',pch=20,cex=2)

A: There is also an R package called spThin that performs spatial thinning on point data. It was developed for reducing the effects of sampling bias for species distribution models, and does multiple iterations for optimization. The function is quite easy to implement---the vignette can be found here. There is also a paper in Ecography with details about the technique.

A: Following Josh O'Brien's advice, I looked at spatstat's rMaternI function, and came up with the following. It seems to work pretty well.
The distance is in map units. It would be nice to incorporate one of R's distance functions that always returns distances in meters, rather than input units, but I couldn't figure that out...
require(spatstat)
require(maptools)
occ <- readShapeSpatial('occurrence_example.shp')

filterByProximity <- function(occ, dist) {
    pts <- as.ppp.SpatialPoints(occ)
    d <- nndist(pts)
    z <- which(d > dist)
    return(occ[z,])
}

occ2 <- filterByProximity(occ,dist=0.2)
plot(occ)
plot(occ2,add=T,col='blue',pch=20)

A: Rather than removing data points, you might consider spatial declustering. This involves giving points in clusters a lower weight than outlying points. The two simplest ways to do this involve a polygonal segmentation, like a Voronoi diagram, or some arbitrary grid. Both methods will weight points in each region according to the area of the region.
For example, if we take the points in your test (1,1),(2,2),(4.5,4.5),(5,5),(1,5) and apply a regular 2-by-2 mesh, where each cell is three units on a side, then the five points fall into three cells. The points ((1,1),(2,2)) falling into the cell [0,3]X[0,3] would each have weights 1/( no. of points in current cell TIMES tot. no. of occupied cells ) = 1 / ( 2 * 3 ). The same thing goes for the points ((4.5,4.5),(5,5)) in the cell (3,6]X(3,6]. The "outlier", (1,5) would have a weight 1 / ( 1 * 3 ). The nice thing about this technique is that it is a quick way to generate a density based weighting scheme.
A polygonal segmentation involves drawing a polygon around each point and using the area of that polygon to calculate the weight. Generally, the polygons completely cover the entire region, and the weights are calculated as the inverse of the area of each polygon. A Voronoi  diagram is usually used for this, but polygonal segmentations may be calculated using other techniques, or may be specified by hand.


text:
Q: How can I get snap applications to run in VNC session? I have a PC running Ubuntu 22.04 that I sometimes run headless and connect to through VNC (TigerVNC server, xfce4 desktop). Since upgrading from 20.04 to 22.04, some of my applications, such as Firefox and Inkscape have changed to Snap. Normally, when I use my PC with a monitor and keyboard and mouse, all still works fine, but when connected through VNC, I can no longer open these applications. In the GUI Applications menu, they've just disappeared, and when I try to start them from the command line, I get the following error:
/system.slice/system-vncserver.slice/vncserver@1.service is not a snap cgroup

Searching online, I found a possible solution here:
xhost +
env DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus firefox

but unfortunately I was unable to get this to work (the xhost + part seems to work as it should, but the command after that just gives me the same error about not being a snap cgroup). This may have to do with my $XDG_RUNTIME_DIR not being set, but I'm not sure how to solve that.
In another post, related to a similar issue, the answer (https://askubuntu.com/a/1419532/1646198) suggests to disable cgroups, citing this discussion, but this answer also mentions "many permission denied errors", so I'm not sure whether this would be the way to go.
Does anyone know how to fix this properly?
EDIT: When I substitute $XDG_RUNTIME_DIR in the above env command with /run/users/1000, Firefox starts, but with a ton of "permission denied" errors:
update.go:85: cannot change mount namespace according to change mount (/var/lib/snapd/hostfs/usr/share/gimp/2.0/help /usr/share/gimp/2.0/help none bind,ro 0 0): cannot open directory "/var/lib": permission denied
update.go:85: cannot change mount namespace according to change mount (/var/lib/snapd/hostfs/usr/share/xubuntu-docs /usr/share/xubuntu-docs none bind,ro 0 0): cannot open directory "/var/lib": permission denied
[Parent 122148, Main Thread] WARNING: Unable to connect to ibus: Could not connect: Connection refused: 'glib warning', file /build/firefox/parts/firefox/build/toolkit/xre/nsSigHandlers.cpp:167

(firefox:122148): IBUS-WARNING **: 16:13:46.960: Unable to connect to ibus: Could not connect: Connection refused

EDIT 2: Even with monitor, keyboard and mouse attached, things don't run as they used to: when I right-click an SVG-file and select 'Open with Inkscape', the Ubuntu spinner shows up for a while, and then... nothing happens. I can now only open SVG-files directly from Inkscape (i.e. first start Inkscape, then use File - Open..., or Ctrl-O).
Any ideas anyone?

A: Workaround: Use apt versions of those apps instead of snap version.
For Firefox, follow this answer. For Inkscape, run the commands
sudo snap remove inkscape
sudo apt install inkscape

EDIT: To get the most recent version of Inkscape through apt, the Inkscape ppa is helpful:
sudo add-apt-repository ppa:inkscape.dev/stable
sudo apt update
sudo apt install inkscape