text:
Q: Chapter colorized in different colors Is it possible to give to each chapter a different color coming from something like a color array?
I basically know how to colorize text, but for that purpose the color value is fixed. What I want to do is build up something like an array of colors and then use the color specified in cell 1 for chapter 1, second chapter color in cell 2, etc.
Is something like that doable in Latex?

A: Random colors:
\documentclass{scrbook}
\usepackage{pgffor, xcolor}
\usepackage{pgfmath}

\pgfmathdeclarerandomlist{color}{{red!20!yellow}{blue}{yellow}{green!20}{red}{black!20}{orange}}% declare random list
\setkomafont{sectioning}{\pgfmathrandomitem{\randcolor}{color}\color{\randcolor}}% use random list

\begin{document}
%Showcase only!
\let\cleardoublepage\relax
\foreach \x in {A,...,H}{
\chapter{\x}}
\newpage

\end{document}

Cycle thru list
\documentclass{scrbook}
\usepackage{pgffor, xcolor}
\usepackage{pgfmath}
%The following list must be very long to make sure that pgfmath
%does not try to read a non existing element
% pgfarrys start form index 0 but chapters start form 1 so "dummy" is needed
% in order to have it started form the desired (first) color
% this could be any element cause it't not read anyway
\def\mytemparray{{"dummy" ,"blue!20!green","yellow","green!20","red","black!20","orange","red!20!yellow" ,"blue","yellow","green!20","red","black!20","orange"}}%
\setkomafont{sectioning}{\pgfmathparse{\mytemparray[\thechapter]}\color{\pgfmathresult} }

\begin{document}
%Showcase only!
\let\cleardoublepage\relax
\foreach \x in {A,...,H}{
\chapter{\x}}
\newpage

\end{document}

I used KOMAScript to alter the appearance of the chapters, just to make thing easy for me. Nevertheless the shown techniques should work with any approach to alter the sectioning.

A: You could use
\csname colorchap\Roman{chapter}\endcsname

as your color command in your chapter heading code and then you need
\newcommand\colorchapA{\color{red}}
\newcommand\colorchapB{\color{blue}}
\newcommand\colorchapC{\color{green}}

to set up as many colors as you need.


text:
Q: Map of Iterables - a generic way to add values to an iterable under the given key I can write the following for Vectors:
def add[K,V](map: Map[K,Vector[V]], key: K, values: Vector[V]): Map[K,Vector[V]] = {
  map + (key -> (map.getOrElse(key, Vector.empty) ++ values))
}

Usage:
scala> add(Map(1 -> Vector(1,2,3)), 1, Vector(4,5,6))
res1: Map[Int,Vector[Int]] = Map(1 -> Vector(1, 2, 3, 4, 5, 6))

The code for Sets is almost identical:
def add[K,V](map: Map[K,Set[V]], key: K, values: Set[V]): Map[K,Set[V]] = {
  map + (key -> (map.getOrElse(key, Set.empty) ++ values))
}

How to make a single function that works for all Iterables? I tried to write it like this:
def add[K,V](map: Map[K,Iterable[V]], key: K, values: Iterable[V]): Map[K,Iterable[V]] = {
  map + (key -> (map.getOrElse(key, Iterable.empty) ++ values))
}

But in this case I lost type info:
scala> add(Map(1 -> Set(1,2,3)), 1, Set(4,5,6))
res4: Map[Int,Iterable[Int]] = Map(1 -> Set(5, 1, 6, 2, 3, 4))

I tried the following:
def add[K,V,I[_] <: Iterable[_]](map: Map[K,I[V]], key: K, values: I[V]): Map[K,I[V]] = {
  map + (key -> (map.get(key).map(_ ++ values).getOrElse(values)))
}

But it didn't compile:

Cannot construct a collection of type That with elements of type Any based on a collection of type Repr.
  [error]     map + (key -> (map.get(key).map(_ ++ values).getOrElse(values)))

A: You need to use CanBuildFrom to channel the type info about the used collection through the ++ call. See the overloads of ++ on TraversableLike for this.
The following works (not caring about details, like undefined keys).
def add[K,V,It <: TraversableLike[V,It]]
  (map: Map[K,It],k: K, vs: Traversable[V])
  (implicit bf: CanBuildFrom[It,V,It])
  :Map[K,It] =
    map + (k -> (map(k) ++ vs))

A: Ugly instanceof but works :)
def add[K,V,I[V] <: Iterable[V]](map: Map[K,I[V]], key: K, values: I[V]): Map[K,I[V]] = {
       val m: Map[K, Iterable[Any]] =  map + (key -> (map.get(key).map(_ ++ values.asInstanceOf[Iterable[V]]).getOrElse(values)))
       m.asInstanceOf[Map[K, I[V]]]
}

Results from scala console:
scala> def add[K,V,I[V] <: Iterable[V]](map: Map[K,I[V]], key: K, values: I[V]): Map[K,I[V]] = {
     |        val m: Map[K, Iterable[Any]] =  map + (key -> (map.get(key).map(_ ++ values.asInstanceOf[Iterable[V]]).getOrElse(values)))
     |        m.asInstanceOf[Map[K, I[V]]]
     | }
warning: there were 1 feature warning(s); re-run with -feature for details
add: [K, V, I[V] <: Iterable[V]](map: Map[K,I[V]], key: K, values: I[V])Map[K,I[V]]

scala> add(Map(1 -> Vector(1,2,3)), 1, Vector(4,5,6))
res0: Map[Int,scala.collection.immutable.Vector[Int]] = Map(1 -> Vector(1, 2, 3, 4, 5, 6))

scala> add(Map(1 -> Set(1,2,3)), 1, Set(4,5,6))
res1: Map[Int,scala.collection.immutable.Set[Int]] = Map(1 -> Set(5, 1, 6, 2, 3, 4))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create polygon from outermost point spatial coordinates I have a large dataframe of point coordinates and I am trying to make a polygon out of the edge of the coordinates. Some of the points fall near the middle, so I do not want those points to shape the boundary of the polygon created. These are spatial data and I do convert them into sf or terra objects, but in the simplest form they are just (x,y) coordinates.
I've looked and I can't find any already developed function for this task.
Here's a basic set of coordinates that replicate the problem:
lat <- c(-34.8861,-34.9845,-34.9839,-34.4555,-34.3272,-34.922,-34.7)
lon <- c(118,117.721,117.118,116.789,115.785,115.843,116.5)

plot(lon,lat)

Any ideas for creating a polygon out of the outermost points of these coordinates?

A: something like this:
library(sf)
df <- data.frame(x = lon, y = lat)
pts1 <- st_as_sf(x = df, coords = c('x', 'y'))
my_hull <- st_convex_hull(st_union(pts1))
plot(my_hull)

A: With 'terra' it goes like this:
lat <- c(-34.8861,-34.9845,-34.9839,-34.4555,-34.3272,-34.922,-34.7)
lon <- c(118,117.721,117.118,116.789,115.785,115.843,116.5)

library(terra)
v <- vect(cbind(lon, lat), crs="+proj=longlat")
x <- convHull(v)

plot(x, col="red")
points(v, cex=2, col="blue")


text:
Q: Creating a new distribution certificate without revoking old ones Im very new to this.I want to submit  update of an app.My client forgot the password for the private key.so im going to generate a new distribution certificate and submitting to appstore.so will this create any issue?Also is it possible to create a new distribution certificate without revoking old ones.Can any one help me on this.Thanks in advance.Any help is appreciated.

A: You can't create new distribution certificate without revoking old one.
Solution : Create new distribution certificate and then create new provisioning profile for same app identifier.Create build and upload to app store.Good Luck!!


text:
Q: AngularJS - Can I use data binding value depending on ternary operator I have an ng-repeat li elements and I want to set a specific value for that li depending on whether a function returns true or false and I don't want to do it in the controller because I have dependency issues where it makes it Minimize or Maximize for ALL li elements but I want it to be for each individual li element. I tried using several things including the following without any luck. I am not sure what I am doing wrong but I would appreciate any input or any other way of doing this.
object1 is from an ng-repeat that includes this li element.

{isItHidden(object1) ? 'Minimize' : 'Maximize'}

SOLUTION (thanks to jdp)

{{isItHidden(object1)}}

$scope.isItHidden = function(object){
    return object.hidden ? 'Maximize' : 'Minimize';
}

A: With the release of angular 1.2, you can now use the more intuitive ternary operator inside ng-bind

or inside brackets
{{ object1.hidden ? 'Maximize' : 'Minimize' }}

A: You can do this
{{ object1.hidden && 'Minimize' || 'Maximize' }}

In angular 1.2 a real ternary operator will be added.


text:
Q: Fixed element gets pushed down This is a part of the application I'm building. There are two columns. First column contains a song lyrics, and the second column contains some buttons that control some of the properties of lyrics column.
Fiddle: default

Kryptonite - 3 Doors Down

[Verse 1]

I took a walk around the world to ease my troubled mind

                ▲
                15px
                ▼

I decided not to post CSS and JS here, because it'll just spam the question, make it longer and scare you. That's why I isolated the code and created fiddles with different states. If anyone were to suggest that I should also include them, I will.
Since the second column is shorter than the first column, it'll disappear if I scroll down. I don't want that. So, I change the position of the second column to fixed. That solves the problem, but causes another one.
If I change text-align or font-size of lyrics (first) column through control buttons, the second columns gets pushed down.
Fiddle: gets pushed down
To fix the problem, I added another line of code to the control buttons:
controls.style.position = "fixed";

So, after changing text-align or font-size properties of the first column, I set the position of the second column to fixed, though it's already set to fixed with CSS.
Unchecking and checking the position property of the second column in Developers Tools also solves the problem. That gave me the idea of adding controls.style.position = "fixed"; to the end of the control button functions.
Fiddle: js fix
Even though I managed to find a way to make it work, I want to know what causes the problem. Why the second column gets pushed down? And why unchecking and checking it's position property back fixes it?

A: I agree with @CBroe's comment. Such behavior (fixed position without top, left, right or bottom) is undefined by the spec so there's no telling why it's doing that.  If I go into dev tools and remove and add again the fixed positioning, it goes back to where it should be, so I don't think it's intentional (webkit bug perhaps), but in any case, you should be assigning direction attributes along with the fixed positioning.  It gets a bit hairy here because it's hard to place it in that exact spot, but considering your first column is more or less a fixed width, you can add a right or left attribute of 50% and adjust is with a negative margin.  For example:
position: fixed;
top: 48px;
right: 50%;
margin-right: -388px; /* about half of the left
                         columns ultimate width
                         including padding, margin,
                         etc. */

If your code needs to be more dynamic (is responsive or the code must be reusable with containers of other sizes) you will need to add different classes, use media queries, use javascript to calculate it, or use a combination of these methods.
Demo: fork of your fiddle demonstrating the above CSS


text:
Q: How to add spaces before & after a set of expressions using re.sub() in Python? How to add spaces before & after a set of expressions showing below:
"-", "_", "abc", "%dKK" (%d means an integer here)
For example, "abc3KK-_" will be split as " abc 3KK - _ ".
Thanks.

A: ' '.join(re.findall('-|_|abc|\d+KK', 'abc3KK-_')) would work for your example.
It does not use re.sub but still uses a regex.
Since there is not much information about the kind of strings you want to handle, I don't know if it fits your needs.


text:
Q: Access-Control-Allow-Origin Request blocked from Localhost:3000 on firebase I am getting an error on post method of axios for the code:
ERROR :
Access to XMLHttpRequest at 'https://identitytoolkit.googleapis.com/v1/signupNewUser?key=AIzaSyAHO' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CODE:
 const authData = {
            email: email,
            password: password,
            returnSecureToken:true
        }
 axios.post('https://identitytoolkit.googleapis.com/v1/signupNewUser?key=AIzaSyAHOBs', authData)
                .then( response => {
                    console.log(response);
                    dispatch(authSuccess(response.data));
                })
                .catch(err => {
                    console.log(err);
                    dispatch(authFail(err));
                });

A: I was using different URL for post method, ie
https://identitytoolkit.googleapis.com/v1/signupNewUser?key=[API_KEY]

But the correct URL is same you posted and it even works without modification of headers :
https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]

code snippets :
export const auth = (email, password) => {
    return (dispatch) => {
      dispatch(authStart());
      const authData = {
        email: email,
        password: password,
        returnSecureToken: true,
      };
      const config = {
        headers: {
          "Content-Type": "application/json",
        },
      };
      axios.post(
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAHOBsv31rdWYhCr15gRS727QuCnajk2CU",
        authData,
        config
      )
        .then((response) => {
          console.log(response.data);
          dispatch(authSuccess(response.data));
        })
        .catch((err) => {
          console.log(err);
          dispatch(authFail(err));
        });
    };
  };

thank you so much
Happy coding :)

A: I am doing the same course and facing the same error.
after a long time, I found that the problem was where we call the function (Auth.js file).
while we handle the onSubmit method we call the onAuth method from mapDispatchToProps like this
const mapDispatchToProps = dispatch =>{
    return {
        onAuth: (email, pass) => dispatch(actions.auth(email,pass))
    }
}

on the course video, the submit handler was like this. that was not correct and indicating an object instead of a string value.
submitHandler = (event) => {
        event.preventDefault();
        this.props.onAuth(this.state.controls.email, this.state.controls.password);
    }

the correct handler would be like this ...
submitHandler = (event) => {
        event.preventDefault();
        this.props.onAuth(this.state.controls.email.value, this.state.controls.password.value);
    }


text:
Q: Content-Security-Policy Spring Security assuming a working hello world example of spring security and spring mvc.
when i take a trace with wireshark i see the following flags on the http request
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; Path=/; Secure; HttpOnly

i would like to add this to my headers:
Content-Security-Policy: script-src 'self'

I know that the X-Frame-Options is doing almost the same job, but still it makes me sleep better.
Now i guess that i would need to do it under the configure function of my spring security configuration however i do not know how exactly, i.e. i suppose
.headers().something.something(self)
 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
//          .csrf().disable()
//          .headers().disable()
            .authorizeRequests()
                .antMatchers(   "/register",
                                "/static/**",
                                "/h2/**",
                                "/resources/**",
                            "/resources/static/css/**",
                                "/resources/static/img/**" ,
                                "/resources/static/js/**",
                                "/resources/static/pdf/**"
                                ).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

A: As documented in Spring security documentation:
https://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    // ...
    .headers()
        .contentSecurityPolicy("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
        .reportOnly();
}
}

A: While the approach with StaticHeadersWriter works, in the newest versions of Spring Security it's possible to use a special method:
headers()
    .contentSecurityPolicy("script-src 'self'");

See documentation for details: https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/headers.html#headers-csp-configure

A: Simply use the addHeaderWriter method like this:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
      // ...
  }
}

Note that as soon as you specify any headers that should be included, then only those headers will be include.
To include the default headers you can do:
http
  .headers()
    .contentTypeOptions()
    .xssProtection()
    .cacheControl()
    .httpStrictTransportSecurity()
    .frameOptions()
    .addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
    // ...

You can refer to the spring security documentation.


text:
Q: Should I merge database migrations together before release? During the development process many migrations may appear. Is there any point to keep them instead of merging them all together?
Let's take a look into a simple example.
During development we introduce a new model Person:
public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
}

Migration #1 creates a new table Persons with two fields in the database.
Later we decided we need another field - Surname. Migration #2 alters table by adding a new field.
Later we decided to introduce a new related model, so Migration #3 creates new table and alters Persons by adding foreign key.
Later we decided to remove Surname. Migration #4 alters table by removing column.
Later we decided to rename plural form of Persons to Person. Migration #5 removes all foreign keys, laters table by renaming it, creates new foreign keys.
In the end we have a bunch of migrations doing back'n'forth work of creating and removing some fields that we don't need in the final release. Those fields among with some other possible migrations actions are just a part of the history of development, but we don't really need them.
So I was thinking what if I roll back the database to the very first state, remove all migrations and then generate a new one, which will do only nessesary actions to bring a database to it's final state, reducing a possibly huge number of migrations and exessive actions to just one straight forward migration.
Is it a good idea or it is considered an anti-pattern?

A: The migrations will be applied automatically when your system deploys. It is very unlikely that DDL commands in SQL dominate the time an installation takes, so the appropriate thing to do is not to worry about this low-level detail of the system. Consolidating them all would require work and contribute virtually nothing to the outcome, so it's the kind of lowest-priority task that you should leave until there's absolutely nothing more urgent to do in the project.

A: This is ok as long as you are 100% sure the merged migrations will never hit a database which is in an intermediate state (so, for example, the Surname column is there, though it should not).
This depends on how well you control your deployment process (especially the deplyoment of the migrations). Note this is not necessarily restricted to production releases - you also need to know which intermediate states you may have in your test environment, and if you have a larger dev team where each dev has his own db for local testing purposes, this might also be affected by the potential state of the different dev environments.

A: I've see migrations rolled up for deployment in large companies. I would not call it an anti pattern.
EF is a bit of an odd case, but in general you want to be very careful with your DB Migrations. The most common approach I have seen is to regenerate and then hand craft them.
This allows you to Test them against DBs with similar volumes of data to production to ensure that they will function correctly and will not cause any performance issues. Also, you will want to ensure that you have working rollback scripts which can be applied etc
Indeed after you merge them all together you may want to split them again to allow for a phased rollout with backwards compatibility or other requirements.
It's a brave developer who just updates his objects and lets EF figure out what to do with the Production DB. (although tbf MS does a pretty good job of it)


text:
Q: Responsive images I'm not looking for a inventive solution on the images, I've read plenty of content about loading images etc.
I'm just doing some basic responsive design and want to load a large image and just squash it down as the window gets smaller.
I've written the following CSS:
@media (max-width:420px){
     #header #logo{
        width:60%;
        float:left;
        background:red;
    }

    #header #logo #image{
        margin:5%;
        width:20%;
        float:left;
        background:green;
    }

    #header #nav{
        width:40%;
        float:left;
        background:purple;
    }

    #header #nav #search{
        max-width:33%;
        float:left;
    }

    #header #nav #account{
        max-width:33%;
        float:left;
    }

    #header #nav #menu{
        max-width:33%;
        float:left;
    }
 }

And the HTML to go with it:

            s

The images aren't resizing as I'm resizing the window.
What is the correct CSS syntax to achieve this?
Thanks :)

A: Apply max-width to your images.
img {
    max-width: 100%;
}

http://jsfiddle.net/VBHhD/
I would also use an unordered list for navigation, but that's just me.

A: In your CSS You are using media query for a max-width of 420px which is a mobile view. Have you tried to resize your browser at a very low level?    @media (max-width: 420px){
     #header #nav #search img,#header #nav #account img,#header #nav #menu img {
  width:50%;
} http://codepen.io/anon/pen/kchqg


text:
Q: Group_by or similar in Haystack-django-solr I have indexed 1 million comments at solr with haystack in the 'text' field. Othewise, I have a restaurantId at the same Index, which belongs to the restaurant, the one that has been made the comment. And I'd like to look for comments group by restaurantId. Is something like group_by in haystack?
I have this query to look for comments with some words:
query_set = SearchQuerySet().using('comments').raw_search('text:nice\ fast\ clean')

If there is something like:
query_set = SearchQuerySet().using('comments').group_by('restaurantId').raw_search('text:nice\ fast\ clean')

Cheers! And thanks in advance!
Update 1
Now I want to add this experimental code: https://gist.github.com/acdha/3750774#file-solr_grouping_backend-py to my project.
How could I do it? Where I have to paste that code?


text:
Q: Form field dependency on one another in django I have the below form field :
forms.py
class BuildForm(forms.Form):

   site_num  = forms.IntegerField(label=("No of Sites"))
   site_name = forms.CharField(label=("Site Name"))

I want that the field "site_name" should be displayed as per the integer value entered in the "site_num" field.
e.g: If the user enters 2 in "No of Sites" then two "site_name" fields should be displayed to enter two site names.
If I use a form wizard then the site_name field will be in another form and in that case how can i get the previous form data and process accordingly to show field as per the integer value.
Can anyone let me know, how can this be achieved ??

A: SOLVED :
I have overridden the get_form_kwargs method of my form wizard in views
view.py
class FormWizard(SessionWizardView):

    def get_form_kwargs(self, step=None):
        kwargs = {}
        if step == '2':
            site_num = self.get_cleaned_data_for_step('1')['site_num']
            kwargs.update({'site_num': site_num,})
        return kwargs

and also the init function of my form with the site_name field.
forms.py
class MyForm(forms.Form):
    #some fields

class MyForm1(forms.Form):
    site_num = forms.IntegerField()

class MyForm2(forms.Form):
    def __init__(self, *args, **kwargs):
        extra = kwargs.pop('site_num')
        super(MyForm2, self).__init__(*args, **kwargs)

        for i in range(extra):
            self.fields['site_name_%s' % i] = forms.CharField()


text:
Q: VBA: Excel Scatter Graph Animation with Method 'Range' of object'_Global' failed error I have a personal investment tracking workbook where I have scatter graphs of my accounts comparing their performance to different indices over time.  I wanted to animate plotting of the points showing the comparative performance over time.  I borrowed a macro subroutine to do this from another users group site and am trying to implement it.
I have one COMPARISON worksheet (Sheet3) with the charts on it, with account and index data on other worksheets (Sheet2, Sheet4, ...).  I would later attach this to a button next to the chart to launch it.  This subroutine will work (without the "Sheet2!" in the Range statements) on the chart when it is on the same worksheet as the data but when I move it to the COMPARISON worksheet it will not work.  I keep getting the

"Run-time error '1004': Method 'Range' of object'_Global' failed"

error no matter how I construct the range syntax string.
Here is the non-working code:
Public Sub AnimateChart1()
  Dim rX As Range
  Dim rY As Range
  Dim x As Long
  Dim chtObj As ChartObject
  Dim dWait As Double

  'change as desired
  Set chtObj = ActiveSheet.ChartObjects("Chart1") 'chartname
  Set rX = Range("Sheet2!J116:J340") 'X-range
  Set rY = Range("Sheet2!G116:G340") 'Y-range
  dWait = TimeValue("0:00:01") '1 sec wait

  For x = 1 To rX.Rows.Count
    With chtObj.Chart.SeriesCollection(1)
      .XValues = rX.Resize(x)
      .Values = rY.Resize(x)
      Application.Wait (Now + dWait)
    End With
  Next
End Sub

The "Run-time error '1004'" occurs on Code Line 9 with the "Set rX = ..." and I am sure it would not work on Code Line 10 with the "Set rY = ...".  I have tried all permutations of a valid excel link string with many producing compile time errors in Excel debugger.  It looks like the Range object/function/statement is being used to convert the worksheet range string to an actual range and I have not found this usage of Range around much.
I would like to keep this Range syntax as a string because I would later generalized the subroutine for multiple charts with arguments passed as strings for efficiently using it.  Thanks for any help in resolving this problem I am having.

A: Try
Set rX = Sheet2.Range("J116:J340")
Set rY = Sheet2.Range("G116:G340")


text:
Q: Подскажите, в чем может быть проблема с int(sys.argv[1])? Возникает ошибка с int(sys.argv[1]):
IndexError: list index out of range

A: sys.argv - это список параметров скрипта. В этом списке всегда есть хотя бы один элемент - имя скрипта или пустая строка, если к sys.argv обращаются из интерактивной оболочки (запустить python, и в нем вывести содержимое sys.argv).
Далее, если в скрипт передаются какие-то параметры, то они появляются в sys.argv. Например, скрипт:
import sys

print(sys.argv)

Запускаем так:
python test.py 1 abc def

Получаем:
['test.py', '1', 'abc', 'def']

Если не передать никаких парметров:
python test.py

Получим только имя скрипта:
['test.py']

Длина этого списка 1, первый элемент имеет индекс 0. Если обратиться к элементу с индексом 1, этот индекс будет уже за пределами списка, в итоге получим ошибку:
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print(sys.argv[1])
IndexError: list index out of range

Как эту проблему решить:

*

*во-первых, в скрипт нужно передать параметр, если вы это собирались сделать, но не сделали.

*во-вторых, нужно проверять длину sys.argv, и если передано меньше параметров, чем ожидалось, то как-то сообщить о проблеме пользователю.

*если у вас ожидается числовой параметр, а пользователь передал в скрипт не число (пользователи бывают очень изобретательны), то скрипт прервется с ошибкой ValueError: invalid literal for int() with base 10. Подобные проблемы также нужно уметь обрабатывать. В данном случае можно обернуть преобразование параметра к целому числу в блок try-except с обработкой исключения ValueError. Небольшое руководство по обработке исключений.

Пример кода с обработкой возможных ситуаций:
import sys

if len(sys.argv) <= 1:
    print('Недостаточно параметров')
else:
    try:
        print(int(sys.argv[1]))
    except ValueError:
        print('Параметром скрипта должно быть число')


text:
Q: Add property in azure table storage using Microsoft Bot Services I'm programming a chatbot, in the beginning, it's showing a menu and it is up to the user to choose the right information, what I try to do once the user chooses a piece of information the bot store it in a table using Azure Table Storage.
I use a c# as a programming language and SDK Bot Builder V4
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
   CloudConfigurationManager.GetSetting("StorageConnectionString"));
await turnContext.SendActivityAsync("bababa1");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("UserChoice");
table.CreateIfNotExists();

MenuChoiceDao choiceUser = new MenuChoiceDao(
     ChooseInf,
     turnContext.Activity.Id.ToString());
choiceUser.count = "1";

TableOperation insertOperation = TableOperation.InsertOrReplace(choiceUser);
table.Execute(insertOperation);

And i add the following variable in web.config :
<appSettings>
      <add key="StorageConnectionString" value="......" />
</appSettings>

When I execute the bot, it doesn't work and the value 'storageAccount' returns Null, also when I do the same code in a new project console App it works
Does anyone have an idea about this issue?

A: In .NET Core, they have moved away from web.config and using JSON configuration files. Please see more information here. Just a warning; you may come across these issues as well:
https://github.com/Azure/azure-sdk-for-net/issues/4010
https://github.com/Azure/azure-sdk-for-net/issues/4047
Make sure using Microsoft.Azure.ConfigurationManager 4.0.0 not Microsoft.WindowsAzure.ConfigurationManager 3.2.3


text:
Q: Clarification about Hasse's Theorem for Elliptic Curve over Finite Fields In the proof of Hasse's Theorem over finite fields, one considers the Frobenous endomorphism $\phi(x,y) \rightarrow (x^q,y^q) \in E(\bar{F_q})$ and then notes that this endomorphism fixes the elements of $F_q\times F_q$ but permutes the rest of the element of ($\bar{F_q}\times \bar{F_q})\setminus (F_q\times F_q)$. Therefore, $$\#E(F_q) = \#ker(\phi - 1) = deg(\phi - 1)$$
In both Silverman's book as well as Washington's book, they go to extreme lengths (requiring Weil's pairing) in calculating the degree of this endomorphism. My question is, why can't we directly calculate the degree of this endomorphism? In other words, what's wrong with the following argument?
Let's pick a point $(\bar{x},\bar{y}) \in E(\bar{F_q})\setminus E(F_q)$ which will not be fixed by Frobenous. Then $(\bar{x}^q,\bar{y}^q)$ and $(\bar{x},\bar{y})$ cannot be equal. Therefore the explicit formula for the X-coordinate of $(\phi - 1)(\bar{x},\bar{y}) = (\bar{x}^q,\bar{y}^q) \oplus (\bar{x},-\bar{y})$ can be calculated using explicit point addition formula as $$\left(\frac{\bar{y}^q + \bar{y}}{\bar{x}^q - \bar{x}}\right)^2-\bar{x}^q - \bar{x} = \beta$$ for some $\beta \in \bar{F_q}\setminus F_q$ which is the the x-coordiate of some point. The degree of this equation can be easily calculated using high-school algebra, and that should tell us the number of points on the curve.
There is something wrong with my argument or Hasse's theorem won't be a bound. Can someone please point me what's wrong?

A: I actually found the answer. Basically in the expression $$\frac{(y^q + y)^2}{(x^q -x)^2} - (x^q + x) = \beta $$ one needs to discard all the roots of $x \in F_q$ since for those values of $x$, $(x^q -x)^2$ in the denominator will end up being zero. (Note that we are not guaranteed that simplifying the above equation will only have roots in $\bar{F}_q \setminus F_q $. This was the main flaw in my original argument.) Therefore, we have to manually discard roots that are in $F_q$.
After discarding those roots, the degree of numerator (or equivalently, the degree of the denominator + 1; +1 for point at infinity) is equal to size of the kernel.
Doing this exercise has helped me understand the motivation for SEA algorithm so much better. Thanks everyone for taking the time to reply to my question.

A: Here is a partial answer. The fraction$$(y^q + y)^2/(x^q - x)^2 - x^q - x$$is a rational function in $x$, but of much lower degree than $3q$.
When I tried it for the elliptic curve $y^2 = x^3 - x$ mod $7$, as in the example above, it reduced to an degree $8$ polynomial divided by a degree $7$ polynomial. That exactly agrees with the degree of $\phi - 1$ being $8$.
In general, the degree should tell us how many rational points are on the curve, but I do not see how to obtain this from the rational function. Any $x_0$ in the finite field with $q$ elements for which the corresponding $y$ satisfies $y = 0$ or $y^{q - 1} = -1$ cancels $x - x_0$ from the numerator and denominator and thereby lowers the degree.
But I have not yet been able to turn this into a count of rational points on the curve. I am sure it is possible with the correct insight.


text:
Q: DB2 SQL Query not considering spaces in field's data The database in my application saves data in table's field with spaces. But when I query the data it's not considering spaces in field's data And gives the all result irrespective the spaces
VAT_TABLE.VAR_DATA
------------------
I                   --- 1 space after I
I                   --- 2 space after I
I                   --- 0 space after I
I                   --- 1 space after I
I                   --- 3 space after I
I                   --- 4 space after I

When I run this query >>>  SELECT * FROM VAT_TABLE WHERE VAR_DATA = 'I '
The result gives all 6 rows irrespective the spaces after 'I'
Any Idea??

A: DB2 specifically ignores trailing spaces when comparing two strings.
So "I" == "I " == "I         "
If you want to differentiate between "I" and "I  " you need :-
WHERE VAR_DATA = 'I' AND LENGTH(VAR_DATA) = 2

This behavior reflects the comparison logic of COBOL, MVS Assembler and PL/1 which were the dominant languages on the target platforms when DB2 was originally developed.


text:
Q: Manifest Merger error when adding dependencies for CardView. Whenever I try to add dependencies for CardView, Android Studio is showing the following error:
[> Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.1) from
    [com.android.support:design:25.3.1] AndroidManifest.xml:27:9-31     is
    also present at [com.android.support:cardview-v7:26.0.0-alpha1]
    AndroidManifest.xml:24:9-38 value=(26.0.0-alpha1).    Suggestion: add
    'tools:replace="android:value"' to  element at
    AndroidManifest.xml:25:5-27:34 to override.]1

A: This is because you might have set compile-sdk and target-sdk to 25. Change dependency to compile 'com.android.support:design:25.3.1'.


text:
Q: Big O for code snippet Hello it has been some time sins i have used Big O notation, so i'm a bit rusty.
I know that having 1 loop, that loops n times is O(n), and having 1 loop that loops n time within another loop that loops n times is O(n^2).
But in the following code snippet do i have a loop that loops n times, and within that a loop that loops n-i times.
What will the Worst and Best O notation be for this code?
The worst is where it runs without finding a collision, and the best will be when there are a collission between the 2 first rectangles.
class TestClass
{
    bool Run(List<Rectangle> R)
    {
        var b = false;
        var i = 0;
        var n = R.Count;
        var j = 0;
        while ((i < n-1 ) && !b )
        {
            j = i + 1;
            while (j<n && !b)
            {
                if ((R[i].x >= R[j].x - R[i].w) && (R[i].x <= R[j].x + R[j].w))
                    if ((R[i].y <= R[j].y + R[i].h) && (R[i].y >= R[j].y - R[j].h))
                        b = true;
                j++;
            }
            i++;
        }

        return b;
    }
}

public class Rectangle
{
    public int x;
    public int y;
    public int w;
    public int h;
}

A: As a commenter pointed out, Big-O is always about the worst case scenario, so if increasing the value of R.Count would tend to make your worst-case scenarios increase at a rate greater than n*log(n), you're getting into the realm of n².
Since you have a double-nested while loop, and no additional method calls, at a glance I'd have said it's O(n²).
However, in this case, since i and j never increment, and n never decrements, and your loops are both based on i or j being less than n, this function will either exit right away (based on your if statements), or it never will.
O(infinity)?

Edit
Okay, now that you increment them, the n*(n-i) bit basically averages out to n*(n/2) each time you run it (not an average of all runs, but rather an average for each run). This is because you'll be doing (n, n-1, n-2, ..., 3, 2, 1) inner loops as you move through the outer loop. If you fold this set in on itself, you can easily sum up the number of loops:
n + 1 == n + 1
(n-1) + 2 == n + 1
(n-2) + 3 == n + 1
...

So you end up with n/2 instances of n + 1, which comes out to (n² + n)/2. From a big-O standpoint, this is the same as n².

A: Your actual worst case running time is  n X n/2 = n²/2.  Throw away the constants, and it's O(n²)


text:
Q: Laravel eloquent make visible only given attribute in one instance of model i have instance model from
$model = Model::find(1);

for example this instance always return these attribute (some is from $append):
-id
-name
-countRelation
-description
-created_at
-updated_at

what i want is to only retrive name and description from this instance;
makeVisible only work to show hidden attribute; i don't want use makeHidden because the result of find may change if on model i add new append attribute;

A: Since you are appending accessors limiting the SELECT statement won't stop those from being appended to the serializied output. You can use setVisible to do this though:
$model->setVisible(['name', 'description']);

Setting what is visible this way will limit the attributes, appends and relationships that are returned in the serialized output of the Model.

A: You can use select to only retrieve some column in your database, it will not affect append, see the doc for more info Eloquent
$model = Model::find(1);
// to this
$model = Model::select('name', 'description')->find(1);

See Query Builder for more insight about grabbing data from database.

A: if you retrieve name and description only, then you may use
$model = Model::select(['name', 'description'])->find(1);

A: You can use select() to select only certain columns in your query.
$model = Model::select('name', 'description')->find(1);

https://laravel.com/docs/8.x/queries#specifying-a-select-clause
You can also get the Model and use functions on the model. If you have a single Model you can use get().
$model = Model::find(1)->get('name', 'description');

If you have a collection you can use ->map->only(). This maps the only function as a callback for each Model in your Collection.
$models = $models->map->only(['name', 'description']);


text:
Q: How to Ensure the Correct Sorting on the Base of Date and Time in MySQL I am in a great confusion now. I have a comments table in mysql database. in comments table there is a field comment_posted_time (type DATETIME), I sort all the comments like this
$query = "SELECT * FROM comments ORDER BY comment_posted_time DESC";

Now, This can produce wrong results. I give you an example. Suppose there are two users sitting in front of computer, one in India and the other in America. Suppose India's Time is 10 hours forward from America. first the user from India posts a comment and its current local time is stored in comment_posted_time (type DATETIME). After 1 hour the user from America posts a comment and its current local time is stored in comment_posted_time (type DATETIME) as well. Now, in database the later posted comment from American User will not be counted the most current comment and sorting will not be correct.
How to handle this situation?

A: There is no difference where are your users, your php and mysql are in one server, so you must not have a problem with times, You can show times for each user by his timezone converting it by php, but don't change mysql default timezone for each user. Design your comments table and set on comment_posted_time default value NOW(), and don't use this field in your insert queries. So all records in that field will saved in same timezone.

A: How are getting the date for comment_posted_time?  Typically this would be the current date on the MySQL server.  If you're getting the datetime from the client machine (which I would NOT recommend), you could get the UTC date/time and then convert it back to the local time when you display it.
To store the current time from the MySQL server, you can do something like:
update comments set comment_posted_time = NOW() where id=...

This will not differ based on the client...

A: You can convert the date to its UNIX_TIMESTAMP and then sort by that.
$query = "SELECT * FROM comments ORDER BY UNIX_TIMESTAMP(comment_posted_time) DESC";

You can read more about UNIX_TIMESTAMP() documentation.
Edit:
You should not be storing the comment_posted_time relative to different timezones. All of the times should be relative to one timezone, like GMT, or the machine running php.

A: So if you're facing the problem, that your users are in different timezones you should ALWAYS calculate timepoints to one given timezone bofore persisting it (usually you take the main servers timezone, or UTC per default). With this approach you can do both: order by timepoint and show users the timepoint calculated to their timezone.


text:
Q: qt - qstandarditemmodel::itemchanged gives an invalid qvariant with a valid index I have the following connection in my TypeABC
connect(model, &QStandardItemModel::itemChanged, this, &TypeABC::update);

void TypeABC::update(QStandardItem *item) {
    auto data = item->data();
    auto idx = item->index();
}

after editing when I display data and index from item in TypeABC::updateOffers I get :

QVariant(Invalid)
QModelIndex(1,1,0x557a76315220,QStandardItemModel(0x557a763d89e0))

on console...
Why I am getting an invalid qvariant here yet the index is alright? I am feeding the model by using QStandardItemModel::setData like :
model->setData(model->index(rowNumber, Columns::Name), name);  //name is a QString

and the tableview seems good too


text:
Q: nicely display file rename history in git log The git command
git log --format='%H' --follow -- foo.txt

will give you the series of commits that touch foo.txt, following it across renames.
I'm wondering if there's a git log command that will also print the corresponding historical file name beside each commit.
It would be something like this, where we can interpret '%F' to be the (actually non-existent) placeholder for filename.
git log --format='%H %F' --follow -- foo.txt

I know this could be accomplished with
git log --format='%H' --follow --numstat -- foo.txt

but the output is not ideal since it requires some non-trivial parsing; each commit is strewn across multiple lines, and you'll still need to parse the file rename syntax ("bar.txt => foo.txt") to find what you're looking for.

A: You can simplify it a little bit like this:
git log --format='%H' --name-only --follow -- README.md

which will give you output kind of like this
621175c4998dfda8da

README.md
d0d6ef0a3d22269b96

README.md

which should be a little easier to parse.  For instance you can use a sentinel and sed out the newlines like this:
git log --format='%H%%' --name-only --follow -- README.md | sed ':a;N;$!ba;s/%\n\n/ /g'

which should give you the hash and the filename on the same line:
621175c4998dfda8da README.md
d0d6ef0a3d22269b96 README.md

For info on the sed invocation, see How can I replace a newline (\n) using sed? which has the answer I based that bit on.

A: --name-status should work for you:
git log --follow --name-status --format='%H' -- foo.txt

Result will look like this and can be easily parsed by Perl or Python:
'4da4d5e3e9c24251e14d20004a853b72bd096cce'

R100    b.txt   c.txt
'4966238c97198d096f0424a0a23ec550297d8086'

M       b.txt
'c0e41c11f0f7c5a7650cedfbad138c8941444023'

R100    a.txt   b.txt
'4b2318c0fbabd836d50cabd70bf19013d3964856'

A       a.txt

If you insist to get it in one line, this Perl one-liner does the trick (it works on Windows as is. On Linux, use single quotes or escape $ as \$):
git log --follow --name-status --format='%H' -- c.txt | perl -e "while(<>){chomp;print;<>;$_=<>;print q/ /,((split/\t/)[-1]);}"

which prints:
'4da4d5e3e9c24251e14d20004a853b72bd096cce' c.txt
'4966238c97198d096f0424a0a23ec550297d8086' b.txt
'c0e41c11f0f7c5a7650cedfbad138c8941444023' b.txt
'4b2318c0fbabd836d50cabd70bf19013d3964856' a.txt

A: This works in OSX terminal:
git log --format='%%%h' --name-only --follow -- README.md | xargs echo | perl -pe 's/\%/\n/g'


text:
Q: Color gradient not working in Firefox Ok my problem is that in firefox my hover gradient is showing up as black to white. Black being the top color and white as the bottom. Here is the css hover code I'm using. It doesn't make sense to me because I'm not even using the color codes for black or white. Any help would be greatly appreciated!
nav a {
color: #fff;
background: #b9b9b9; /* Old browsers */
background: -moz-linear-gradient(top,  #b9b9b9 0%, #616161 99%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#b9b9b9), color-stop(99%,#616161)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #b9b9b9 0%,#616161 99%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #b9b9b9 0%,#616161 99%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #b9b9b9 0%,#616161 99%); /* IE10+ */

nav a:hover, nav a:active {
background: #b9b9b9; /* Old browsers */
background: -moz-linear-gradient(bottom, #4f4f4f, #b9b9b9 ); /* FF3.6+ */
background: -webkit-linear-gradient(top,  #b9b9b9 0%,#4f4f4f 99%); /*
background: -o-linear-gradient(top,  #b9b9b9 0%,#4f4f4f 99%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #b9b9b9 0%,#4f4f4f 99%); /* IE10+ */
background: linear-gradient(to bottom,  #b9b9b9 0%,#4f4f4f 99%); /* W3C */

A: You are missing your closing braces.
Your code works otherwise: http://jsfiddle.net/66QQV/
nav a
{
    color: #fff;
    background: #b9b9b9; /* Old browsers */
    background: -moz-linear-gradient(top,  #b9b9b9 0%, #616161 99%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#b9b9b9), color-stop(99%,#616161)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  #b9b9b9 0%,#616161 99%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  #b9b9b9 0%,#616161 99%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  #b9b9b9 0%,#616161 99%); /* IE10+ */
}

nav a:hover, nav a:active
{
    background: #b9b9b9; /* Old browsers */
    background: -moz-linear-gradient(bottom, #4f4f4f, #b9b9b9 ); /* FF3.6+ */
    background: -webkit-linear-gradient(top,  #b9b9b9 0%,#4f4f4f 99%); /*
    background: -o-linear-gradient(top,  #b9b9b9 0%,#4f4f4f 99%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  #b9b9b9 0%,#4f4f4f 99%); /* IE10+ */
    background: linear-gradient(to bottom,  #b9b9b9 0%,#4f4f4f 99%); /* W3C */
}

This is assuming that you intend to put an  element inside of a  element ... if you meant for this to be a class or an ID (such as  or
), you need to use .nav or #nav instead, respectively.


text:
Q: Mongoengine creation_time attribute in Document I am trying to add a creation_time attribute to my documents. The following would be an example:
import datetime

class MyModel(mongoengine.Document):
    creation_date = mongo.DateTimeField()
    modified_date = mongo.DateTimeField(default=datetime.datetime.now)

Django models have built in parameter for their DateTimeField objects like add_now, etc.,
but MongoEngine does not support this.
I am wondering if best way to do this is the following:
m,created = MyModel.objects.get_or_create()
if created:
    m.creation_date = datetime.datetime.now()

or if there is a better, nicer way.

A: You could override the save method.
class MyModel(mongoengine.Document):
    creation_date = mongo.DateTimeField()
    modified_date = mongo.DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        if not self.creation_date:
            self.creation_date = datetime.datetime.now()
        self.modified_date = datetime.datetime.now()
        return super(MyModel, self).save(*args, **kwargs)

A: One nice solution is reusing a single signal handler for multiple documents.
class User(Document):
    # other fields...
    created_at = DateTimeField(required=True, default=datetime.utcnow)
    updated_at = DateTimeField(required=True)

class Post(Document):
    # other fields...
    created_at = DateTimeField(required=True, default=datetime.utcnow)
    updated_at = DateTimeField(required=True)

def update_timestamp(sender, document, **kwargs):
    document.updated_at = datetime.utcnow()

signals.pre_save.connect(update_timestamp, sender=User)
signals.pre_save.connect(update_timestamp, sender=Post)

Be careful to assign a callable and not a fixed-value as the default, for example  default=datetime.utcnow without (). Some of the other answers on this page are incorrect and would cause created_at for new documents to always be set to the time your app was first loaded.
It's also always better to store UTC dates (datetime.utcnow instead of datetime.now) in your database.

A: # -*- coding: utf-8 -*-
from mongoengine import *
from mongoengine import signals
from datetime import datetime

class User(Document):
    email = StringField(required=True, unique=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)
    # audit fields
    created_on = DateTimeField(default=datetime.now())
    updated_on = DateTimeField(default=datetime.now())

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        document.updated_on = datetime.now()

signals.pre_save.connect(User.pre_save, sender=User)

A: If you are using the timestamp field in a bunch of Documents you can keep your code DRY by creating an abstract Document instead.
from datetime import datetime
from mongoengine import Document

class CreateUpdateDocument(Document):
    meta = {
        'abstract': True
    }

    # last updated timestamp
    updated_at = DateTimeField(default=datetime.now)

    # timestamp of when entry was created
    created_at = DateTimeField(default=datetime.now)

    def save(self, *args, **kwargs):
        if not self.created_at:
            self.created_at = datetime.now()
        self.updated_at = datetime.now()
        return super(CreateUpdateDocument, self).save(*args, **kwargs)

A: My preferred solution is to use the @property decorator to return the creation datetime as extracted from the ObjectId:
@property
def creation_stamp(self):
    return self.id.generation_time

A: As an aside, the creation time is stamped into the _id attribute - if you do:
YourObject.id.generation_time

Will give you a datetime stamp.

A: Try use lambda value:
import datetime
from mongoengine import Document

class MyModel(Document):
    creation_date = mongo.DateTimeField()
    modified_date = mongo.DateTimeField(default=lambda : datetime.datetime.now())

A: Traditionally, I've set the creation_date default to datetime.now() and then have hidden the field on the admin form so you remove the possibility of a user overwriting the correct value. That requires almost no code.
Overriding the save method as suggested by Willian is also effective since you can programmtically block any updates to the creation_date and update the modfied_date at the same time.

A: You could use auto_now_add parameter as per documentation:
class MyModel(mongoengine.Document):
    creation_date = mongo.DateTimeField(auto_now_add = True)
    modified_date = mongo.DateTimeField(auto_now = True)


text:
Q: Textarea value change when summernote div is changed I have setup a div for the summernote to alter text pulled from a database.

<?php echo $laws['content']; ?>

$(document).ready(function() {
   $('#summernote').summernote({
     height: 300,
   });
});

directly following the div I have a text area with an ID.
<textarea id="lawsContent"></textarea>

I want the content of the textarea to change as I type in the summernote div. Just like what is happening while I am typing this question.

A: Inspired by @user3367639, this is a more generic way to do it
$('.summernote').each(function () {
    var $textArea = $(this);

    $textArea.summernote({
        onKeyup: function (e) {
            $textArea.val($(this).code());
            $textArea.change(); //To update any action binded on the control
        }
    });
});

And with this method :
String.prototype.strip = function()
{
   var tmpDiv = document.createElement("div");
   tmpDiv.innerHTML = this;
   return tmpDiv.textContent || tmpDiv.innerText || "";
}

You could do in your JS controller something like this to get the text value of your textarea
$myTextArea.val().strip(); //Where val() returns the html and strip() returns the text

Hope this will help

A: Use This Example:
<form id="form_id" action="/summernote.php" onsubmit="return postForm()">
    <textarea id="summernote" rows="6" name="textarea_name" ></textarea>
</form>

A: Using the summernote API
I came up with this solution:
$(document).ready(function() {
    $('#summernote').summernote({
      onKeyup: function(e) {
        $("#lawsContent").val($("#summernote").code());
      },
      height: 300,
    });
});

A: I think it is better to handle the onChange event.
v0.7.0
$('#summernote').summernote({
  callbacks: {
    onChange: function(contents, $editable) {
      console.log('onChange:', contents, $editable);
    }
  }
});

$(document).ready(function(){

    $("#summernote").summernote(
        {
            height: "10em",
            callbacks: {
              onChange: function (contents, $editable) {
                var code = $(this).summernote("code");
                $("#lawsContent").val(code);
              }
            }
        }
    );

});
#lawsContent
{
    width: 100%;
    height: 10em;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.7.0/summernote.min.css" rel="stylesheet"/>

Editor:

Output:
<textarea id="lawsContent" class="form-control"></textarea>

v0.6.5
As of this version, callback only works with camel case string.
$('#summernote').summernote({
  onChange: function(contents, $editable) {
    console.log('onChange:', contents, $editable);
  }
});

$(document).ready(function(){

    $("#summernote").summernote(
        {
            height: "10em",
            onChange: function (contents, $editable) {
                $("#lawsContent").val(contents);
            }
        }
    );

});
#lawsContent
{
    width: 100%;
    height: 10em;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.6.7/summernote.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

Editor:

Output:
<textarea id="lawsContent" class="form-control"></textarea>

A:
$('textarea').summernote({
  callbacks: {
    onChange: function(contents, $editable) {
      console.log('onChange:', contents, $editable);
    }
  }
})

<form>
<textarea name="content" onChange></textarea>
</form>

A:

        First impressions are everything.

    Features:

<textarea id="product_desc_long" name="product_desc_long"  class="summernote form-control" rows="10" placeholder="Enter the product long description..."></textarea>

$(document).ready(function() {
      $('.summernote').summernote({
        height: 300,
        onKeyup: function(e) {
           $("#product_desc_l").html($(this).code());
        }
      });
});

This worked for me


text:
Q: Why Mapbox eachLayer function doesn't fire every time page is loaded? This piece of code gives me some head aches:
regions = L.mapbox.featureLayer().loadURL('somefile.geojson');
layer.on('ready', function(e) {
     var regionBounds;
     console.log(regions);
     regions.eachLayer(function(lr) { //This function fires about one of two site loads.
         if(lr.feature.properties.title == '{{ $region->name }}') {
             regionBounds = lr.getBounds();
         }
     });

     layer.eachLayer(function(lr) {
         if(lr.feature.geometry.type == 'Point') {
              lr.setIcon(L.divIcon(icon));
         }
     });

     map.fitBounds(regionBounds);
}

When eachLayer() fails, regions _request property is set to XMLHttpRequest, and null when map is loaded properly, but I'm not sure what does it mean. I'd appreciate if someone could help me figure this out, and make this function work on each site load, obviously.

A: Your on.('ready', ...) function isn't connected to regions, it's connected to layer (which I'm guessing is defined elsewhere). If you change it to regions.on('ready', ...) the function won't execute until somefile.geojson is loaded and should execute on every page load.


text:
Q: Calculate "Working hours " based on IN and OUT time Employee Attendance Power bi I am using Power bi and I would like to calculate the working hours of my employees based on the time they entered and left the company.
Here is a sample of data
the supposed total hours should be 7 hours and 8 minutes.
SO, the time where the employee was out and do nothing. In my case, I should exclude the time starting from  OUT 2:04:20 to IN 3:09:46    about 1 hour.

A: You can calculate the next out for each in and take the difference:
select t.employee_id,
       sum(datediff(second, local_time, next_local_time)) as diff_seconds
from (select t.*,
             lead(local_time) over (partition by employee_id order by local_time) as next_local_time
     from t
    ) t
where action = 'IN'
group by t.employee_id;

Note:  This assumes that INs and OUTs are interleaved, so there are no rows with the same action in a row.
This also gives the result in seconds -- which can be converted to decimal hours or any other particular format you want.

A: In Power BI/Power Query, assuming your table is the same structure as your post you can create a new table with the following script. In this script yourSource is reference to your table.
let
    #"Sorted Rows" = Table.Sort(yourSource,{{"EmployeeID", Order.Ascending}, {"LOCAL_TIME", Order.Ascending}}),
    #"Added Index" = Table.AddIndexColumn(#"Sorted Rows", "Index", 1, 1, Int64.Type),
    #"Added Custom1" = Table.AddColumn(#"Added Index", "Employee_In_Out_Index", each if [Action] = "IN" then [Index] else null),
    #"Filled Down" = Table.FillDown(#"Added Custom1",{"Employee_In_Out_Index"}),
    #"Removed Columns" = Table.RemoveColumns(#"Filled Down",{"Index"}),
    #"Reordered Columns" = Table.ReorderColumns(#"Removed Columns",{"Employee_In_Out_Index", "EmployeeID", "Action", "LOCAL_TIME"}),
    #"Pivoted Column" = Table.Pivot(#"Reordered Columns", List.Distinct(#"Reordered Columns"[Action]), "Action", "LOCAL_TIME"),
    #"Added Custom" = Table.AddColumn(#"Pivoted Column", "Time Difference", each [OUT] - [IN])
in
    #"Added Custom"

In the new table, each record is for one in-out. There is a Time Difference column here which you can use in your calculations.


text:
Q: Prestashop autocomplete input type I am developing a prestashop module , i have created some custom fields ate product page .
i have a field that get values by autocomplete  from a json
Here is the module tpl Field :

        Post 6:

            {*<input type="text" name="principi_name" value="{$principi_name}">*}

            {include

                file="controllers/products/textarea_lang.tpl"

                languages=$languages

                input_name='principi_name'

                class="textarea testingautocolplete"

                input_value=$principi_name}

Here is the jquery :
 $(document).ready(function() {

    product_tabs['product_type'] = new function(){
         $('.testingautocolplete').autocomplete('http://www.domain.com/dbsearch.php', {
            width: 320,
            max: 4,
            highlight: false,
            multiple: true,
            multipleSeparator: " ",
            scroll: true,
            scrollHeight: 300,
        })

    }

});

The result on field is the all json :
I think I did a mistake but i cant find what:

Thank you .

A: We are not aware of the way you are using the autocomplete field but we have used it several times by using the following steps:
Add the following code to your JS code on the page (in document.ready javascript function)
$('YOUR_FIELD_ID').autocomplete(path_fold+"/FILE_PATH_TO_HANDLE_AJAX.php",{
     delay: 100,
     minChars: 1,
     autoFill: true,
     max: 20,
     matchContains: true,
     mustMatch: true,
     scroll: false,
     cacheLength: 0,
     multipleSeparator: '||',
     formatItem: function(item) {
         return item[0];
     },
     extraParams: {
         customerFilter: 1,
     }
 }).result(function(event, item) {
 //Code to use the result
 });

The php file that will be handling the ajax request will simply prepare and send data in the desired format.


text:
Q: Show that $\det(A)=(\lambda_1)^{m_1}(\lambda_2)^{m_2}…(\lambda_k)^{m_k}=\prod_{j=1}^k(\lambda_i)^{m_j}$ This is the problem... I got part a and part b... but I'm lost for part c.
Anyone have a hint of something I can try?

A: Since $\;A\;$ is diagonalizable there exists invertible $\;P\;$ such that
$$A=P^{-1}\begin{pmatrix}\lambda_1&0&\ldots&\ldots&0\\\ldots&\ldots&\ldots&\ldots&\ldots\\
0&\ldots&\lambda_1&\ldots&0\\
\ldots&\ldots&\ldots&\ldots&\ldots\\
0&\ldots&0&\lambda_k\ldots&0\\
\ldots&\ldots&\ldots&\ldots&\lambda_k\end{pmatrix}P\implies$$
$$ \det A=\det\begin{pmatrix}\lambda_1&0&\ldots&\ldots&0\\\ldots&\ldots&\ldots&\ldots&\ldots\\
0&\ldots&\lambda_1&\ldots&0\\
\ldots&\ldots&\ldots&\ldots&\ldots\\
0&\ldots&0&\lambda_k\ldots&0\\
\ldots&\ldots&\ldots&\ldots&\lambda_k\end{pmatrix}=\prod_{j=1}^k\lambda_j^{m_j}$$

A: By assumption there exists an invertible matrix $S$ such that $SAS^{-1}=D$ is a diagonal matrix, i.e., $D=\rm {diag}(\lambda_1^{m_1},\cdots ,\lambda_k^{m_k})$. Then the claim is obvious, since
$$
\det(D)=\det(SAS^{-1})=\det(S)\det(A)\det(S^{-1})=\det(A).
$$


text:
Q: How to copy this portion of the array to a new array in php? I have this php array X.
X= array(
    'Parent' => array(
        'title' => '123',
    )
)

I have this php array Y.
Y = array(
    'Parent' => array(
        'id' => '16',
        'title' => 'T1',
    ),
    'Children' => array(
        (int) 0 => array(
            'id' => '8',
            'serial_no' => '1',
        ),
        (int) 1 => array(
            'id' => '9',
            'serial_no' => '2',
        ),
        (int) 2 => array(
            'id' => '14',
            'serial_no' => '6',
        )
    )
)

I want to copy the Children of array Y to the parent of array X to form array Z such that it looks like this;
Z= array(
        'Parent' => array(
            'title' => '123',
        )
        'Children' => array(
            (int) 0 => array(
                'serial_no' => '1'
            ),
            (int) 1 => array(
                'serial_no' => '2'
            ),
            (int) 2 => array(
                'serial_no' => '6'
            )
        )
    )

Please note that the id key-value pair was removed from the Children of array Y.
I wrote some code of my own.
            $Z = array();
            $i=0;
            foreach($Y as $temp)
            {
                $Z['Children'][$i] = $temp['Children'][$i];
                unset($Z['Children'][$i]['id'];
                $i++;
            }
            $Z['Parent']=$temp['Parent'];

Unfortunately, there is an undefined index error. How can this be done in php? Forget about my code if there are better approaches.

A: You can do like.
   $Z = array();
   foreach($Y['Children'] as $temp)
   {
      $Z['Children'][] = array('serial_no' => $temp['serial_no']);
   }
   $Z['Parent']=$X['Parent'];

A: Actually your approach works too, but you need to iterate over sub-array:
$Z = array();
$i=0;
foreach($Y['Children'] as $temp)
{
    $Z['Children'][$i] = $temp;
    unset($Z['Children'][$i]['id'];
    $i++;
}

or what I may do:
$Z = $X;
$Z['Children'] = array();
foreach ( $Y['Children'] as $child ) {
    $Z['Children'][] = array(
        'serial_no' => $child['serial_no'],
    );
}


text:
Q: Setting a cookie in js and trying to read it from asp.net code behind breaks in some browsers unless I do it twice/refresh I'm having problems reading the cookie set in js in code behind due to the cookie is not set in some browsers. That is unless I refresh. I'm using an updatepanel on the page so no real refreshes will be done on the page.
Some browsers don't have the values in the cookie and some do which makes it a lot harder to debug this. Is there any way to refresh the cookievalues in asp.net or get new values for the cookies in request.cookies?


text:
Q: Heavily polymorphed table I have a table events. Each event can be 'initiated' and/or 'received' by a User, Visitor or a Team and I want to model these associations.
I am thinking something like
Event
type
user_actor_id
user_subject_id
visitor_actor_id
visitor_subject_id
team_actor_id
team_subject_id

Where the actor/subject refers to who initiated/received the event
Is this the correct approach? Seems like I store a lot of redundant data and I'd have to do a lot of conditional joins as it would like to query the table and get a result like
actor_id:
actor_type (either user, visitor or team)

UPDATE:
Then i'd do a select query like this
    select
  coalesce(ua.id, va.id, ta.id) as actor_id,
  (CASE WHEN ua.id IS NOT NULL THEN 'user' WHEN va.id IS NOT NULL THEN 'visitor' ELSE 'team' END) as author_type,
  (CASE WHEN ua.id IS NOT NULL THEN ua.display_name WHEN va.id IS NOT NULL THEN va.name ELSE ta.name END) as author_name,
  (CASE WHEN ua.id IS NOT NULL THEN ua.avatar WHEN va.id IS NOT NULL THEN va.avatar ELSE ta.icon END) as author_name
from events e
  left join users ua on ua.id = e.user_actor_id
  left join users us on us.id = e.user_sibject_id
  left join visitors va on va.id = e.visitor_actor_id
  left join visitors vs on vs.id = e.visitor_sibject_id
  left join teams ta on ta.id = e.team_actor_id
left join teams ts on ts.id = e.team_sibject_id

A: I would do the following:
create table tPeople ( -- contains as many rows as there are people
   int ID,
   nvarchar(max) Name
)

create table tRole ( -- contains three rows: Visitor, Team, User
   int ID,
   nvarchar(max) Name
)

create table tPeopleRole ( -- associates people with roles
   int People_ID, -- FK to tPeople.ID
   int Role_ID -- FK to tRole.ID
)

create table tEvent (
   int ID,
   int Type_ID,
   int InitiatedPeople_ID, -- FK to tPeople.ID
   int ReceivedPeople_ID -- FK to tPeople.ID
)

Then you can query tEvent and join on tPeople / tPeopleRole to get the initiator and receiver's names and/or roles.


text:
Q: Cloud Function - Getting file contents more than 10 MB The Google Cloud Function's quota page: https://cloud.google.com/functions/quotas says that the Maximum amount of Data sent by HTTP Function in an HTTP Response is 10 MB. I have files of 100 MB in Google Storage Bucket which I want to stream from the Cloud Function to my application. Due to security aspects of our architecture, my application cannot read directly from the Storage Bucket.
A Sample Go Code in the Cloud Function is:
func MyFn(w http.ResponseWriter, r *http.Request) {

    var appendedBytes []byte
    for {
        decryptedFileBuffer, err := fh.GetNextDecryptedPage()
        if err != nil {
            break
        }
        appendedBytes = append(appendedBytes, decryptedFileBuffer...)
    }
    w.Write(appendedBytes)
}

If I try to get files more than 10 MB using Cloud Function, I get following errors:

Error: incorrect function response. Function invocation was
  interrupted.
Error: could not handle the request

How can I get files from than 10 MB from the Cloud Function?

A: When we look at the quota page, we see a no against whether or not the quota can be increased.   A new player in town is Google Cloud Run ... see here.   This provides very similar capabilities to Cloud Functions but uses Kubernetes as the function hosting environment.   It's quota allowance is 32MB ... but this too is less than what you need and is also flagged as no for increase.
An immediate thought that occurs to me is to trade convenience (a simple cloud function) for flexibility and run your own compute resources on GCP.  For example, running up Compute Engines, App Engines or a Kubernetes cluster where the contained application serves responses through a Web Server is a perfectly fine proposition and not constrained in throughtput.  You will have to do the math on billing to determine the cost differentials as the metrics will be different but from a technical perspective, the game changes dramatically.  The cloud functions/cloud run capabilities are there primarily to support very short natured microservices and I am guessing that the transmission of 100MB directly is not considered a microservice.  It also may not be as cost effective as one may think.  It is my understanding that Cloud Functions bills per unit of time utilized.  Transmitting 100MBs is likely to be slow latency proposition and may not be as cost effective compared to always running compute as we may think.


text:
Q: Isn't Firebase phont auth very dangerous? I realized this while implementing user re-sign in my app.
Since phone authentication is received from the client rather than from the server side, there is a phenomenon in which a hacker receives a firebase auth user with his mobile phone number and signs in by writing down someone else's mobile phone number to log in.
Every time you re-login, you need to write a new access token.
If he authenticates with his cell phone number and writes a new token with someone else's ID, it is very fatal. am I getting it wrong?
So I try to use identity platforms, but the documentation is not managed, and the rest API also has v1 and v3, and both do not work well.

A: tl;dr: the scenario you describe is not possible with Firebase Authentication.
The UID of an account in Firebase Authentication is determined by the provider, not by the user themselves. The relationship between a UID and its credentials is determined when the account is first created, i.e. when you call one of the createUser... or when you call verifyPhoneNumber for the first time for a given number. There is no risk here, as this will be a new account owned by whatever credentials the user chose to enter.
After that account creation, the only way to associate more credentials with the account from the client-side SDKs is with the linkWith... methods, which can only be called after signing in with the credentials that were already associated with the account.


text: Q: Can Testing A Decision Tree Lead To No Prediction? I am training an ID3 (classification) and regression tree. When testing against my testing set, I come across instances where there are no branches that meet the criteria in my training set. This leads to an inability of my tree to make a prediction. Is there something I am not accounting for in my code to prevent this from happening?


text:
Q: Speeding up RandomVariate with custom probability distribution I have the defined a custom distribution, which is a Gaussian where the exponent can be any real n greater than 0 (set to actually be >0.5 in use), i.e.
ProbabilityDistribution[
  (2^(-((2^n*(Abs[x])^n)/FWHM^n))), {x, -Infinity, Infinity},
  Method -> "Normalize"
]

Under this normalisation, the part of the Piecewise function I need simplifies down to (when FullSimplify is used):
CustomFunction[FWHM_, n_] =
  ProbabilityDistribution[
    (2^(-1 - 2^n FWHM^-n Abs[x]^n) (2^n FWHM^-n)^(1/n) Log[2]^(1/n))/Gamma[1 + 1/n](*Re[n]>0*),
    {x, -Infinity, Infinity}
  ]

I wish to generate N values from this distribution, which I normally would do using RandomVariate:
RandomVariate[CustomFunction[FWHM, n] /. {FWHM -> 100, n -> 0.5}, 100(*N*)]

However I have noticed that for some values for FWHM and n this is very slow. For example:
RandomVariate[
  CustomFunction[FWHM, n] /. {FWHM -> 5235.315151`, n -> 0.534124`},
  1000
]; // AbsoluteTiming

takes >70s to run on my PC, whereas other numbers take less than 1s.
Is there any reason for this, or a way to speed up the RandomVariate?

A: $Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global`*"]

dist[FWHM_, n_] =
  ProbabilityDistribution[
   (2^(-((2^n*(Abs[x])^n)/FWHM^n))),
   {x, -Infinity, Infinity},
   Method -> "Normalize",
   Assumptions -> {n > 0, FWHM > 0}];

PDF[dist[FWHM, n], x]

(* (2^(-2^n FWHM^-n Abs[x]^n) Log[2]^(1/n))/(FWHM Gamma[1 + 1/n]) *)

CustomFunction[FWHM_?Positive, n_?Positive] :=
    Evaluate@ProbabilityDistribution[
       PDF[dist[FWHM, n], x],
       {x, -Infinity, Infinity}];

SeedRandom[1234];

(data1 = RandomVariate[CustomFunction[FWHM, n] /.
      {FWHM -> 100, n -> 0.5}, 1000]); //
 AbsoluteTiming

(* {0.060385, Null} *)

Show[Histogram[data1, Automatic, "PDF"],
 Plot[PDF[CustomFunction[FWHM, n] /.
    {FWHM -> 100, n -> 0.5}, x],
  {x, Min@data1, Max@data1},
  PlotRange -> All]]

Sometimes the data range can be excessive (although the timing is comparable).
SeedRandom[1234];

(data2 = RandomVariate[CustomFunction[FWHM, n] /.
      {FWHM -> 5235.315151`, n -> 0.534124`}, 1000]); //
 AbsoluteTiming

(* {0.063217, Null} *)

MinMax@data2

(* {-271327., 4.15334*10^8} *)

Using a different seed
SeedRandom[123];

(data3 = RandomVariate[CustomFunction[FWHM, n] /.
      {FWHM -> 5235.315151`, n -> 0.534124`}, 1000]); //
 AbsoluteTiming

(* {0.061821, Null} *)

MinMax@data3

(* {-245766., 356148.} *)

Show[Histogram[data3, Automatic, "PDF"],
 Plot[PDF[CustomFunction[FWHM, n] /.
    {FWHM -> 5235.315151`, n -> 0.534124`}, x],
  {x, Min@data3, Max@data3},
  PlotRange -> All]]


text:
Q: How to package Web application separating web services and HTML/JS We're trying to split our web application which is currently packaged as a single WAR file. We'd like to package the web services (RESTful) part, which relies on Spring Boot, into a single WAR. Separately we would like to be able to deploy the front-end part, containing all the HTML/JS components.
We're using Tomcat 8 as the application container.
We already have separated the code and have generated the .WAR for the web services, which is okay. We're wondering how to do it for the HTML/JS part. How to package it, using Maven? How to deploy and start it with Tomcat? And then how to configure Tomcat so that both parts of the application share the same endpoint:

*

*localhost:8080:application/ for the HTML/JS part

*localhost:8080:application/rest/ for the web services running under SpringBoot.

All we have for now is a manual copy of the HTML/JS files into the webapps folder of tomcat, but this is not satisfying for easy deployment. Plus we didn't manage to configure the endpoint in Tomcat.
Any help is welcome!

A: There are several ways and tools to achieve what you are trying to achieve.
I'm going to suggest a way to do it with a few tools I've picked up in a similar project. While this answer may seem opinion oriented, it may give you a few ideas to start with and make your own choices.
If any of the steps described below needs more detail, let me know and I'll update them.
How to package it, using Maven?
The first thing you'll need to do is split your project into at least two modules :

*

*a war module with your REST services

*a client module with the static files.

To build the client module, you could use Gulp. It will help you manage simple tasks on your static JS/HTML/CSS files.
You can launch gulp tasks with the frontend-maven-plugin by com.github.eirslett :
<plugin>
   <groupId>com.github.eirslett</groupId>
   <artifactId>frontend-maven-plugin</artifactId>
   <version>1.0</version>
   <executions>
      <execution>
         <id>install node and npm</id>
         <goals>
            <goal>install-node-and-npm</goal>
         </goals>
         <configuration>
            <nodeVersion>v6.9.1</nodeVersion>
            <npmVersion>3.10.9</npmVersion>
         </configuration>
      </execution>
      <execution>
         <id>npm install</id>
         <goals>
            <goal>npm</goal>
         </goals>
         <configuration>
            <arguments>install</arguments>
         </configuration>
      </execution>
      <execution>
         <id>npm rebuild node-sass</id>
         <goals>
            <goal>npm</goal>
         </goals>
         <configuration>
            <arguments>rebuild node-sass</arguments>
         </configuration>
      </execution>
      <execution>
         <id>gulp build</id>
         <goals>
            <goal>gulp</goal>
         </goals>
         <configuration>
            <arguments>build --no-notification</arguments>
         </configuration>
      </execution>
      <execution>
         <id>gulp test</id>
         <phase>test</phase>
         <goals>
            <goal>gulp</goal>
         </goals>
         <configuration>
            <arguments>test - - no-notification</arguments>
         </configuration>
      </execution>
   </executions>
</plugin>

In this example, the plugin launches the required steps :

*

*npm install -> needed for gulp

*gulp build -> your client side module build

*gulp test -> your client side unit tests

Then you'll need a gulpfile at the root of your module.
The least thing gulp needs to do now, is give the rest services backend's URL to your clent application. You're using angular, so I advise you to use gulp-ng-constant to modifiy angular constants on the fly during the build phase :
const ngConstant = require('gulp-ng-constant');

gulp.task('build', gulp.series('ngconstant:prod', gulp.parallel('other', 'webpack:dist')));

    gulp.task('ngconstant:prod', function () {
      return ngConstant({
          name: 'yourApp',
          constants: {
              BASE_URL : 'http://www.exemple.com:8080'
          },
          template: conf.constantTemplate,
          stream: true
      })
      .pipe(rename('app.constants.js'))
      .pipe(gulp.dest(conf.app + 'app/'));
    });

In the above gulpfile, webpack is used to do the actual build.
How to deploy and start it with Tomcat?

*

*localhost:8080:application/ for the HTML/JS part

*localhost:8080:application/rest/ for the web services running under
  SpringBoot.

I wouldn't do it this way. It seems complicated to have your webapp and client application on the same context root in Tomcat.
Instead, I advise you to deploy your static files to a different context root or to a different Http Server, like an Apache http server. Technically, your client application doesn't need an application server. And deploying it to a regular, lighter and faster http server like Apache would allow it to still be up when you're restarting your Tomcat server.
Then you'll end up with :

*

*http://www.exemple.com/ for your client application

*http://www.exemple.com:8080/services/ for your services webapp

Now your client application is on a different host than your services webapp. And it will cause Cross-origin errors. So you're going to have to configure CORS to allow your client application to send requests to your services webapp.
Another solution could be to set your Apache as a proxy for your tomcat. You could use define a VirtualHost that would forward all requests from port 8080 to the tomcat server.


text:
Q: How do I use data from sqlite to load a UITableView? How do I get all the values from my sqlite db to be displayed in a UITableView? My solution is only displaying one value. This is what I've tried:
- (NSMutableArray *)loadData {
    NSLog(@"display");
    sqlite3_stmt    *statement;
    const char *dbpath = [_databasePath UTF8String];
    arrayOfperson = [[NSMutableArray alloc]init];

    if (sqlite3_open(dbpath, &_DB) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat:@"SELECT * FROM iApp"];
        sqlite3_stmt *statement;
        const char *query_stmt = [querySQL UTF8String];
        NSMutableArray *resultArray = [[NSMutableArray alloc]init];

        if (sqlite3_prepare_v2(_DB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) == SQLITE_ROW)
            {
             /*

             NSLog(@"%@", aname);

               Results * aRv= [[Results alloc] init];
              [aRv setName:aname];

               NSLog(@"%@", aname);

            [arrayOfperson addObject:aRv];
              NSLog(@"%@ values of array",arrayOfperson );
               return resultArray;
            }
            else{
                NSLog(@"Not found");
                // return nil;
            }
            sqlite3_reset(statement);
        }
    }
  return arrayOfperson;
    //[self.arrayOfperson reloadData];
}

A: You need to have a good read of the SQLite C Documentation which sets out all the basic functions that you need to use to extract and insert data into an SQLite database.
It seems in your code that you are missing calls to sqlite_column_x() which is the function you use to extract data from a sqlite statement.
E.g.
while (sqlite_step(statement) != SQLITE_DONE) { // Could have while(sqlite_step(statement) == SQLITE_ROW) here...
    int myInt = sqlite_column_int(statement, 0); // Get int from column 1
    char *myText = sqlite_column_text(statement, 1); // Get text from column 2

    MyObj *obj = [MyObj objWithNum:myInt, text:[[NSString alloc] initWitCString:myText]];
    [myArray addObject:obj];
}

Also once you've finished with the statement you need to call sqlite_finalize(statement). Likewise once you've finished with the database reference you need to call sqlite_close(db);

A: Okay, lets make this long but simple.
First, you'll have to get FMDatabase which is pretty much mandatory if you don't want to put a bullet in your head.
Once you've got that set up (which should take you about 1 or 2 hours if you're a beginner and it's your first time), you will create a class that deals with your database.
In that class, you'll have different loading/setting methods, one being the one you need now which will return an NSMutableArray of those objects you need.
NSMutableArray *myObjects = [[NSMutableArray alloc]init];
FMResultSet *result = [db executeQuery:@"SELECT * FROM myTable"];
while ([result next]) {

    MyObj *obj      = [[MyObj alloc]init];
    obj.intNum      = [[results intForColumn:@"theNumColumn"]intValue];
    obj.nsnumberNum = [results intForColumn:@"theNSNumberColumn"];
    obj.theString   = [results stringForColumn:@"myString"];

    [myObjects addObject:obj];

}

return myObjects;

This will give you a reliable array of your custom object, which you can send to your tableview.
That array has to be given to the different delegate and datasource methods of your tableview, so it can know what to display, how to display it, and how much of it it should display.
From there on out it's cake. But I really strongly strongly suggest to use FMDB, it's a really good library that will make your life a hundred times easier than sqlite3.
(if you want your life to be a hundred times even more easier, I suggest you switch to core data)
But either way yeah :

*

*Class to manage database

*Method to return your array of custom obj

*Return that array into your display controller

*Eat Cookies.


text:
Q: colordialog conversion to number rather than string colordialog1.color will yield   "Color [A=255, R=95, G=33, B=222]", but i would like to return an integer like 2349821 instead. how is this possible?

A: Use
colorDialog1.Color.ToArgb()

A: Adding on to BlueMonkMN's answer
If you need the Alpha byte:
colorDialog1.Color.ToArgb()

If you don't want the Alpha byte:
colorDialog1.Color.ToArgb() And &H00ffffff


text:
Q: Invoke a web service form JQuery: doesn't work in IE (JQMIGRATE: jQuery.browser is deprecated ??) I'm a newbie in Ajax and JQuery but I need to invoke a web service in my little web application HTML/Javascript based.
All works fine using Firefox or Chrome  but nothing happens using IE (I'm using IE 9 now ...).
Here you are the code
if ($.browser.msie && window.XDomainRequest) {
            if (window.XDomainRequest) {
                var query = 'http://wms.pcn.minambiente.it/ogc?map=/ms_ogc/wfs/Numeri_Civici_2012.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=IN.NUMERICIVICI.2012&SRSNAME=EPSG:4326&bbox=7.70,44.80,7.75,44.85&outputFormat=GML2';
                var xdr = new XDomainRequest();
                if (xdr) {
                    xdr.onload = function () {
                        alert("OK");
                    }
                    xdr.onerror = function () {
                        alert("KO");
                    }
                    xdr.open('GET', query);
                    xdr.send();
                }
            }
        }
        else {
            var query = 'http://wms.pcn.minambiente.it/ogc?map=/ms_ogc/wfs/Numeri_Civici_2012.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=IN.NUMERICIVICI.2012&SRSNAME=EPSG:4326&bbox=7.70,44.80,7.75,44.85&outputFormat=GML2';
            $.ajax({
                type: "GET",
                url: query,
                dataType: "text",
                crossDomain: true,
                success: function (data1) {
                      alert("OK");
                      alert(data1)
                },
                error: function (response, textStatus, errorThrown) {
                    alert("KO");
                    alert(errorThrown);
                }
            });
        }

I tried to synthesize in a jsfiddle so you can try if you want.
When I try to execute in IE the browser console tell me that ...
JQMIGRATE: jQuery.browser is deprecated
How can I modify my code?
Thank you all in advance, any suggestion or wokaround will be appreciated!!!
Cesare

A: The $.browser function is, indeed, deprecated. If you want to detect IE, use this instead:
var browser = navigator.userAgent.toLowerCase(),
isIE = (browser.indexOf("msie")>-1 || browser.indexOf("trident")>-1);
if (isIE && window.XDomainRequest) {
  //the rest of your code
}


text:
Q: How we can show a custom popup in table view controller in swift language How we can show a custom view popup in table view controller when we click a table cell in Swift programming language ios

A: You can use the didSelectRowAtIndexPath tableview delegate method just like in Objective-C
override func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) {

    var alertView = UIAlertController(title: "Sample Popup", message: "You clicked cell at index : \(indexPath!.row)", preferredStyle: UIAlertControllerStyle.Alert)
    alertView.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alertView, animated: true, completion: nil)

}

Make sure you have inherited the UITableViewDataSource and UITableViewDelegate at your class definition. I've given a sample snippet
class SampleTableViewController : UITableViewController, UITableViewDataSource, UITableViewDelegate{

// data source and delegate methods....

}

Use this...


text:
Q: .ipa can not update app on iTunes, app just appears grey I currently have an app on the app store and am trying to test to see if the update work. I've created an ad hoc archive and exported it to a .ipa.
So I currently have the app on my phone, when I use go to iTunes and click update app, the app copies to the phone and then goes grey. It does change from here.
If I uninstall the current version of the app from my phone and then use iTune to install the app, it works perfectly.
Anyone know whats wrong?

A: You need to build the updated app using the same developer account as the appstore one. If you can't do that, you're out of luck - you should be able to replace the app, but the keychain won't work...


text:
Q: How can you tell if bash is being accessed from a remote machine? I am trying to write out a dynamic bash profile for a few machines, and was wondering if there is a variable that allows .bashrc if it is being accessed remotely. I've seen a few examples using X variables, but that is irrelevant to both machines.

A: if [ "$SSH_CONNECTION" ]; then
  echo I am remote
else
  echo I am local
fi

A: When you connect via ssh, your bash process is a child of sshd ($PPID is a variable of bash's parent process - ssh that is, if you connect remotely). You can check for that:
if ps ax | grep ^$PPID'.*sshd' &> /dev/null; then
  # do your stuff
fi

Edit: I was bored and used time to get execution times and found out that this version apparently is a couple of milliseconds faster:
if grep ^sshd: /proc/$PPID/cmdline &> /dev/null; then
  # do your stuff
fi


text:
Q: Vaadin/compass: URL paths from imported theme scss not compiled correctly I'm trying to compile a modified version of the styles.scss from the Vaadin Dashboard theme with compass. Like most Vaadin themes, it imports the Vaadin Base theme:
@import "../base/base.scss";

In pre-compiled themes, URLs specified in base.scss have been updated to match the location of the Base theme relative to the theme importing with a prefix ../base/ . For example, a statement like
background: transparent url(tree/img/connector-collapse.png) no-repeat 2px -52px;

is updated to
background: transparent url(../base/tree/img/connector-collapse.png) no-repeat 2px -52px;

When compiling my modified Dashboard theme with compass, URLs specified in base.scss are not updated with the ../base prefix. I suspect this problem might be very common, but I've been searching for hours and my keywords have resulted mostly in other url-related problems.
Any suggestions would be most welcome :)

A: I've solved this by using the com.vaadin.sass.SassCompiler instead of compass.


text:
Q: Create External Table atop pre-partitioned data I have data that looks like this:
/user/me/output/
  key1/
    part_00000
    part_00001
  key2/
    part_00000
    part_00001
  key3/
    part_00000
    part_00001

The data is pre-partitioned by "key_", and the "part_*" files contains my data in the form "a,b,key_".  I create an external table:
CREATE EXTERNAL TABLE tester (
  a STRING,
  b INT
)
PARTITIONED BY (key STRING)
ROW FORMAT
DELIMITED FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION '/user/me/output/';

But a SELECT * gives no output.  How can I create an external table that will read in this partitioned data?

A: You will have to change your directory structure to make sure that hive reads the folders. It should be something like this.
/user/me/output/
  key=key1/
    part_00000
    part_00001
  key=key2/
    part_00000
    part_00001
  key=key3/
    part_00000
    part_00001

Once this is done you can create a table on top of this using the query you mentioned.
CREATE EXTERNAL TABLE tester (
  a STRING,
  b INT
)
PARTITIONED BY (key STRING)
ROW FORMAT
DELIMITED FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION '/user/me/output/';

You will also have to explicitly add the partitions or do a msck repair on the table to load the partitions with hive metadata. Any of these would do:
msck repair table tester;

OR
Alter table tester ADD PARTITION (key = 'key1');
Alter table tester ADD PARTITION (key = 'key2');
Alter table tester ADD PARTITION (key = 'key3');

Once you have done this, queries would return the output as present in your folders.


text:
Q: Thermalization of BEC dark matter In the context of BEC/superfluid dark matter, one of the important requirements is that - within galaxies - dark matter thermalizes [1]. Axions are appropriate in this regieme, as their self-interactions provide means to reach a state of larger entropy [2].
My question is why is it important that DM thermalize in galaxies. Does thermalization mean to reach a state of thermodynamic equilibrium? If so, is it the nature of the BEC that imposes this constraint or is it observations of DM?
[1]     10.1103/PhysRevD.92.103510
[2]     10.1103/PhysRevD.85.063520


text:
Q: How to programmatically go to line / column in VS editor? What are the best practices when developing Visual Studio extensions to programmatically:

*

*Set focus on some file in some editor window?

*Set cursor on a specific line / column?

I have been searching for VS SDK documentation but I could not find anything. Any help would be greatly appreciated. Thanks!

A: To activate a file:
dte.ItemOperations.OpenFile(path, null);

To set cursor on a line/column:
EnvDTE.TextSelection ts = dte.ActiveDocument.Selection as EnvDTE.TextSelection;
ts.MoveToLineAndOffset(line, column);


text:
Q: Perturbation Method in Mechanics: Average velocity of a small mass on a vibrating inclined plane I've stumbled across this delightful and difficult collection of problems, by Jaan Kalda. The following problem has stumped me. (It's probem 16 on the sheet, which I have provided as a link)
http://www.ioc.ee/~kalda/ipho/meh_ENG.pdf

A block is situated on a slope with angle $\alpha$, the coefficient of friction between them is $\mu > \tan \alpha$. The slope is rapidly driven back and forth in  away that it's velocity vector $\vec{u}$ is parallel to both the slope and the horizontal and has constant modulus $v$; the direction of $\vec{u}$ reverses abruptly after each time interval $\tau$. What will be the average velocity $w$ of the block's motion? Assume $g\tau \ll v.$

The author also enlists some relevant and helpful ideas, which I'm not listing here but one of them has to do with perturbation method. He also mentions that the last assumption means that the block's velocity doesn't change much in the time interval $\tau$, so the zeroth approximation is that of a block moving in a straight line with constant velocity.
He then says that we can calculate the average value of the frictional force based on the motion obtained in the zeroth case.
I don't understand how that can be done, so any hint or idea would be immensely helpful. I've been trying this problem for 2 months now and just to ensure that I am not missing some maths, I've gone and read perturbation theory, but it hasn't been of any help.
How do I proceed now?
The answer given, is $\frac{v}{\sqrt{\mu^2 \cot^2 \alpha -1}}$.

A: The idea is that, roughly speaking, the block moves down the gradient of the slope.
Because the slope changes its direction of motion, it pushes the block left and right in roughly equal measure, and because it has a short period, the block never moves with significant horizontal velocity relative to the fixed axes. Thus, the horizontal speed of the block relative to the plane is always approximately $v$ and the average horizontal velocity is zero.
The velocity in the direction of the gradient may vary a small amount, but let us simply work with the average, $w$. The component of friction pointing up the gradient must be $F_w = m g \sin\alpha$ to prevent the block from accelerating. The friction force points opposite the velocity, so $\frac{F_x}{F_w} = \frac{v}{w}$.
Meanwhile, the friction force is $F = \mu N = \mu m g \cos\alpha$. Using $F^2 = F_x^2 + F_w^2$ we can eliminate the forces algebraically to find the answer you quoted.