text:
Q: Python Virtual Assistant not continuing after a block of code. while 1: I will provide the code for a portion. It doesn't continue after using commands within a while block. I think it is the code block text = get_audio().lower() that is giving me the error.
def process_text():
pass

if __name__ == "__main__":
assistant_speaks('''Hello, I am a Virtual Assistant.
                I am here to make your life easier. You can command me to perform
                various tasks such as calculating sums or opening applications.
                Please tell me who you are.''')
name = 'are'
name = get_audio()
assistant_speaks("Hello, " + name + '.')

while 1:

    assistant_speaks("What can i do for you?" + name + '.')
    text = get_audio().lower()

    if text == 0:
        continue

    if "exit" in str(text) or "bye" in str(text) or "sleep" in str(text):
        assistant_speaks("Ok bye, " + name + '.')
        break

    # calling process text to process the query
        process_text()

    def process_text():
        try:
            if 'search' in input or 'play' in input:
                # a basic web crawler using selenium
                search_web(input)
                return

            elif "who are you" in input or "define yourself" in input:
                speak = '''Hello, I am a virtual assistant.
                I am here to make your life easier. You can command me to perform
                various tasks such as calculating sums or opening applications.'''
                assistant_speaks(speak)
                return

Basically, it doesn't answer any questions when I ask the elifs. Past the try:
Does anyone have any ideas?

A: There are at least three mistakes you should correct in order to get the behavior you want from your program:

*

*Replace input with text inside the try block. In Python, input is a built-in function, not a string. You already assigned the user's answer to the variable text, so why not use that one? :)

*Define your process_text function before you call it. Practically, you should move the line where you call process_text() somewhere after the definition of that function.

*There are also a couple of indentation errors, and the most important happens when you call the process_text() function: you should un-indent that line back one level, otherwise it will be executed inside the if "exit" in ... block.

You should also define process_text before the while loop, because you just need to define it once.


text:
Q: Django: migrate with id field Using django 1.8
i removed primary_key=True arg from one of my model field, after makemigrations below migration file create with id field.
sample code from migration file :
migrations.AddField(
            model_name='transaction',
            name='id',
            field=models.AutoField(auto_created=True, primary_key=True, default=1, serialize=False, verbose_name='ID'),
            preserve_default=False,
        ),

when python manage.py migrate
Error: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "app_transaction"
And i don't have any data in that table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why $H_{V^* \cup W^*} > H_{V \cup W}$ if $H_V$ denotes entropy of language Let $W \subseteq X^*$ be an infinite language over a finite alphabet $X$, and define ($|w|$ denotes the length of $w \in W$)
$$
 H_W := \limsup_{n\to \infty} \frac{\log_{|X|} | \{ w \in w \in W, |w| = n \} |}{n}
$$
the entropy of the language. Then of course if $U \subseteq V$ for two languages we have $H_U \le H_V$ as $V$ has at least at many words as $U$ of each length. But if $H_{V^*} > H_V$ and $H_{W^*} > H_W$, why do we have
$$
 H_{V^* \cup W^*} > H_{V \cup W}
$$
where $V^*$ denotes the Kleen-star $V^* := \bigcup_{n=0}^{\infty} V^n$.


text:
Q: Finding all files with certain extension in Unix? I have a file /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
I am trying to find if I have the *.jdk anywhere else on my hard drive. So I do a search command:
find . -name "*.jdk"

But it doesn't find anything. Not even the one I know that I have. How come?

A: Probably your JDKs are uppercase and/or the version of find available on OS X doesn't default to -print if no action is specified; try:
find . -iname "*.jdk" -print

(-iname is like -name but performs a case-insensitive match; -print says to find to print out the results)
--- EDIT ---
As noted by @Jaypal, obviously find . ... looks only into the current directory (and subdirectories), if you want to search the whole drive you have to specify / as search path.

A: The '.' you are using is the current directory. If you're starting in your home dir, it will probably miss the JDK files.
Worst case search is to start from root
 find / -name '*.jdk' -o -name '*.JDK' -print

Otherwise replace '/' with some path you are certain should be parent to you JDK files.
I hope this helps.

A: If you are on Mac terminal, and also already in the directory where you want the search to be conducted at, then this may also work for you:
find *.pdf

At least it worked for me.

A: find / -type f -name "*.jdk" works on Mac also

A: find . only looks in your current directory. If you have permissions to look for files in other directories (root access) then you can use the following to find your file -
find / -type f -name "*.jdk"

If you are getting tons of permission denied messages then you can suppress that by doing
find / -type f -name "*.jdk" 2> /dev/null

A: a/
find . means, "find (starting in the current directory)." If you want to search the whole system, use find /; to search under /System/Library, use find /System/Library, etc.
b/
It's safer to use single quotes around wildcards. If there are no files named *.jdk in the working directory when you run this, then find will get a command-line of:
    find . -name *.jdk

If, however, you happen to have files junk.jdk and foo.jdk in the current directory when you run it, find will instead be started with:
    find . -name junk.jdk foo.jdk

… which will (since there are two) confuse it, and cause it to error out. If you then delete foo.jdk and do the exact same thing again, you'd have
    find . -name junk.jdk

…which would never find a file named (e.g.) 1.6.0.jdk.
What you probably want in this context, is
    find /System -name '*.jdk'

…or, you can "escape" the * as:
    find /System -name \*.jdk

A: This works for me on macOS.
find . -type f -iname '*.jdk'

A: ls *.jpg | cut -f 1 -d "."
sub out the '.jpg' to whatever extension you want to list


text:
Q: Storing token frequencies in elasticsearch, instead of storing text From my understanding from reading the documents, how elasticsearch works is that it counts term frequency * indiverse term frequency. It converts text to some sort of term frequency dictionary that also includes the indices of locations where these terms are most frequent.
What I'm trying to do is not store text, but term frequencies for each row of data. The search works fine when I simply upload the full text, but it will not work well in a full scale solution with 10+mil pages of text. Would it not be more effective to only store term frequencies if the text content otherwise is irrelevant?
edit: the anonymity of the data is also relevant and therefore I would not want full sentences and paragraphs stored externally.

A: For your purposes, you could implement a termvector in the text field for the term frequencies. Please read the documentation here.
Then you could use the bulk query for termvector that is mtermvector- doc here, and python api doc.  It works with a list of ids. For example, If you have a list of all the ids of your documents that match "sky" you could proceed in that way:
from elasticsearch import Elasticsearch

es = Elasticsearch()

index = "abc"
my_doc_type ="your_doc_type"
ids = []

result = es.search(index="abc", doc_type= my_doc_type body={"query": {"term": {"my_field":  "sky"}}})

for res in in result['hits']['hits']:
    ids.append(res['ids'])

for doc in es.mtermvectors(index=index,doc_type=doc_type,body=dict(ids=ids,parameters=dict(term_statistics=True,field_statistics=True,fields=fields)))['docs']:
    fields = doc['term_vectors']
    terms = field['terms']
    tf = vec["term_freq"]
    df =  vec["doc_freq"]


text:
Q: How to get html string of a child tag and parent tag using jquery? For example if I have HTML ul list like

If I use jQuery like this
var htmlStr = $("#li2").html();

The result will be only string that contains label tag
 I need to get Html string that contains this

A: The second OuterHTML technique Andres mentions (from the Web Architects' Blog) works on all browsers, so it's probably a better choice. The basic idea is that you can get an element's outer HTML by making it another element's innerHTML:
var outerHtml = $("
").append($("#li2").clone()).html();

There's only one slightly tricky bit - make sure to clone your original element, so you don't remove it from the DOM.
If you do this often or want to do this to arrays of elements, it's probably worth following the linked example and make a little plugin to do this.

A: You can also write a small jQuery plugin with proposed method from Jeff Sternal:
// jQuery plugin 'htmlWithParent'

jQuery(function($) {

  $.fn.htmlWithParent = function() { return $j("
").append($j(this).clone()).html(); };

});
and use this small cutom plugin, for example:
var htmlCode = $("
Helo world!
");

// Return only child nodes: Helo world!
var output1 = $(htmlCode).html();

// Return whole HTML code (childs + parent):
Helo world!

var output2 = $(htmlCode).htmlWithParent();
Very useful method. ;)

A: jQuery OuterHTML , OuterHTML II


text:
Q: What does it mean when question is tagged as code golf question?
Possible Duplicate:
What is "code golf" on stack overflow?

Hi,
I am been using Stackoverflow for quite few time now and recently my question was given comment as code golf questions ? and I was not quite sure of what actually it is and so I wanted to know what does it mean when question is been marked as code golf question ?

A: Look here. Also, you should try to search (Meta) Stack Overflow before asking a question - it might have already been asked (like this case).


text:
Q: when I print @property value it return this  I am working on Django serve, my question is How I can print a actual value of this
file modles.bookings.py
    @property
    def grand_total_amount_display(self) -> str:
        return format_currency_amount(self.grand_total_amount, self.currency)
    grand_total_amount_display.fget.short_description = 'Grand Total'

util.spaces file
def get_booking():
    from sook_booking.models.bookings import Booking # circulation-import issue
    print('Booking.grand_total_amount',Booking.grand_total_amount_display)
    return str(Booking.grand_total_amount_display)

and i am getting this value when I print
Booking.grand_total_amount <property object at 0xffff906b2048>


text:
Q: How to separate into diff projects docker-compose architecture and individual projects? I am new to docker-compose and I am trying to create an architecture that can be utilized by multiple projects. Imagine my 2 services are airflow and postgres. I would like to be able to version control my architecture separated from my projects.
For instance, currently I have projects: project_architecture and project_individual.

*

*project_architecture includes all my docker information, like docker-compose.yml

*project_individual is a python project where I have functions to get data and transform it

The reason I want to be able to separate these projects is that I can have diff repos and version control for each one independently instead of having coupled with each other. Moreover, if I am successful, I could create new "individual" projects and reuse the architecture.
project_architecture:
── README.md
├── config
│   ├── airflow_container.env
│   ├── postgres.env
├── docker-compose.yml
├── services
│   └── postgres
│       ├── 00_create_user.sh
└── shared
    ├── airflow_requirements.txt
    ├── dags
    │   ├── example_dag.py

project_individual:
├── __init__.py
├── data
│   ├── __init__.py
│   ├── data.py
├── docker
│   ├── create_main_tables.sql
│   └── my_specific_dag.py
├── func
│   ├── __init__.py
|   └── functions.py

If you see closer, I have a docker folder on my individual_project where I was planning to develop its own DAGs and database scripts that will be used on the project_architecture Airflow and Postgres respectively. Moreover, I would want to call specific functions, methods, classes from my project like that on data/data.py.
Currently, on my docker-compose.yml file, I am trying to mount an external DAG like this (this does not work):
    volumes:
      - ${PWD}/../project_individual/docker/my_specific_dag.py:/usr/local/airflow/dags/my_specific_dag.py

I have to think the problem I am describing has been solved by companies using container solutions with airflow. I can imagine that there would be a team managing a central airflow while developers generate their projects on their own squad decouple from the architecture. I am happy to take any advice or recommendation. My end goal is to make sure my 2 projects are not coupled and I can expand the projects that can reuse the same architecture (described on project_architecture)

A: You can probably add more services for each of your individual projects to your docker compose, but if you want to separate deployment, the easiest way would be to create multiple docker-compose files.
This way, you could have a docker-compose.common.yml file detailing your common services, then use the extends step of docker-compose to customize your configurations.
You can even call multiple docker-compose files at once during a docker-compose up using the -f option :
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d


text:
Q: How can I define a map whose values contain a fixed length array of type String? I'm attempting to represent the basic strategy of a blackjack game as a map with integer keys whose values are a fixed length array of strings.
The keys represent the value of the player's hand, the array index represents the value of the dealers up card (hence the fixed length array of size 10 corresponding to card values 2-11).  The string value in the array at the position corresponding to the dealer's up card contains the ideal play (stay, hit, split, double).
IE) player hand value is a hard 8, dealer up card is a 2.  Basic strategy says the player should hit.  To determine this using my map, I would get the array whose key is 8(player hand value = 8) and then looking at the string in array index 0 (Dealer up card = 2).
I've attempted to define it this way:
val hardHandBasicStrategy = collection.mutable.Map[Int,Array[String](10)]

but Scala doesn't seem to like this...
Please help me understand what I've done wrong, and/or suggest a way to make it work.

A: Scala doesn't have a type that represents arrays of a fixed size.  You can either simply use arrays of size ten--this is what is normally done--or, if you want stronger guarantees that it really is size ten, you can construct a ten-long-array-class yourself:
class ArrayTen[T: ClassManifest](zero: T) {
  protected val data = Array.fill(10)(zero)
  def apply(i: Int) = data(i)
  def update(i: Int, t: T) { data(i) = t }
  protected def set(ts: Array[T]) { for (i <- data.indices) data(i) = ts(i) }
  def map[U: ClassManifest](f: T => U) = {
    val at = new ArrayTen(null.asInstanceOf[U])
    at.set(data.map(f))
    at
  }
  def foreach(f: T => Unit) { data.map(f) }
  override def toString = data.mkString("#10[",",","]")
  override def hashCode = scala.util.MurmurHash.arrayHash(data)
  override def equals(a: Any) = a match {
    case a: ArrayTen[_] => (data,a.data).zipped.forall(_ == _)
    case _ => false
  }
  // Add other methods here if you really need them
}

Example:
scala> new ArrayTen("(nothing)")
res1: ArrayTen[java.lang.String] =
  #10[(nothing),(nothing),(nothing),(nothing),(nothing),
  (nothing),(nothing),(nothing),(nothing),(nothing)]

scala> res1(3) = "something!!!"

scala> res1
res3: ArrayTen[java.lang.String] =
  #10[(nothing),(nothing),(nothing),something!!!,(nothing),
  (nothing),(nothing),(nothing),(nothing),(nothing)]

If you need the the fixed-length array to take a parameter that determines the length, then you should
trait Size { size: Int }
class ArraySize[S <: Size, T: ClassManifest](zero: T, s: Size) {
  protected val data = Array.fill(s.size)(zero)
  ...
}

You won't have all the collections goodies unless you reimplement them, but then again you don't want most of the goodies, since most of them can change the length of the array.


text:
Q: Brackets.io < data-bracket-id=" " >issue. How to remove out when using Chrome Dev Tools I'm using Brackets to write HTML/CSS but when I do Live Previews and open Chrome Dev tools(Ctr+Shift+i). It's always have data-bracket-id=" " insert into every tag. It make confuse when reading on there. But when I try using Sublime Text then open Chrome Dev Tools, it's ok, and also same with Editor. Please advise I prefer to using Brackets than Sublime Text. Please see issue below.

Box Model

Lorem ipsum dolor sit amet, consectetur adipisicing elit.


text:
Q: How to draw a line with an arrow head? I need to draw a line with an arrow head. How can i do this using Core graphics.
Any help!!!

A: *

*Draw a line.

*Draw a triangle at the end of it.

Yes, that is, in fact, the only way. (Well, unless somebody has released some source code that does that for you. If not, maybe you'll be the one to do so? ☺)


text:
Q: My codes using 'pandas.dataframe.nlargest()' returns a memory error I'm trying to find top n values from my pandas dataframe.
(raw data is around 2000*2000 idx*column size)
It is returning Memory Error.
Not even sure what exactly my error means.
Tried to google it but couldn't find same issue so far
X = int(input())
TopX = CorrVal.stack().nlargest(X)

(CorrVal data is correlation value between item sales amount)
So I want to have top n largest values of correlation
item01 item02 0.744
item05 item04 0.689
item04 item03 0.554
...    ...    ...

Error Codes below
TopX = CorrVal.stack().nlargest(X)

File
  "C:\Users\2F4\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\series.py",
  line 3120, in nlargest
      return algorithms.SelectNSeries(self, n=n, keep=keep).nlargest()   File
  "C:\Users\2F4\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\algorithms.py",
  line 1058, in nlargest
      return self.compute('nlargest')   File "C:\Users\2F4\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\algorithms.py",
  line 1124, in compute
      kth_val = algos.kth_smallest(arr.copy(), n - 1) MemoryError

What kind of functions or tools can i use solve this problem?


text:
Q: Why not the big crunch? Entropy
As per the second law of thermodynamics
"Order tends to disorder"
And recently I watched a video series by minute physics
3:25
The Big Picture: Entropy & Time (feat. Sean Carroll)S1 • E1
Why Doesn't Time Flow Backwards? (Big Picture Ep. 1/5)
minutephysics
CC

As per that with increasing time there will be increasing entropy.
And therefore it is said:-
As time progresses we will be left with just empty space,
Thus based on the above information I would like to ask
1)thus the big crunch of the ending of the universe cannot take place!
2)how did the big bang infinitely small point come into play! ???

A: The entropic description of fate of universe does not make much sense. The disorder, or unavailability of energy to perform mechanical work is very different phenomena from gravity.
If left alone, gravity does not reduce availability of energy to perform work. On the contrary, it maintains the availability of energy. Examples - 1. Something put into the orbit, gravity maintains the availability of energy. 2. Make a hole through center of a planet, drop something in it. If no resistance, the mechanical energy does not disappear ever.
It is other processes like resistance, friction, impact of falling, energy escaping as radiation... so on that cause the entropy to go up. Gravity by itself does not increase entropy. Gravity can catch up and bring back the entropy to lower levels at universe scale. Therefore big crunch can not be ruled out.


text:
Q: How to check bluetooth state in Ionic 4 I am new with Ionic 4, I am trying to check the bluetooth state with @ionic-native/diagnostic, here is my code
app.module.ts
@NgModule({
  declarations: [
    MyApp,
    HomePage,
    CheckRegInfo
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      }
    }),
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    CheckRegInfo
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Diagnostic,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

The checking function:
import { Component } from '@angular/core';
import {AlertController, NavController} from 'ionic-angular';
import {Diagnostic} from "@ionic-native/diagnostic/ngx";

@Component({
  selector: 'page-check',
  templateUrl: 'check.html'
})
export class CheckRegInfo {
  logowhitesrc:string = "assets/imgs/logowhite.png";
  constructor(public navCtrl: NavController, private alertController:AlertController, private diagnostic: Diagnostic) {

  }
  checkBluetoothState(){
    let titleStr: string;
    this.diagnostic.getBluetoothState()
      .then((state) => {
        if (state == this.diagnostic.bluetoothState.POWERED_ON){
          titleStr = "Okay"
        } else {
          titleStr = "Not Okay"
        }
      }).catch(e => console.error(e));
    let addAlert = this.alertController.create({
      title:"Bluetooth state",
      message:titleStr
    });
    addAlert.present();
  }

}

But when I try this on the device, there is no response ? I try on the ionic serve -> it going to the error Object(...) is not a function

A: Try the following:
declare let cordova: any;

@Component({
 selector: 'page-check',
 templateUrl: 'check.html'
})

export class CheckRegInfo {
  logowhitesrc : string = "assets/imgs/logowhite.png";

  constructor(public navCtrl          : NavController,
              private alertController : AlertController,
              private diagnostic      : Diagnostic) {}

checkBluetoothState(){
   let titleStr: string;
   cordova.plugins.diagnostic.getBluetoothState().then((state) => {
    if (state == cordova.plugins.diagnostic.bluetoothState.POWERED_ON){
      titleStr = "Okay";
      showAlert(titleStr);
    } else {
      titleStr = "Not Okay";
      showAlert(titleStr);
    }
  }).catch(e => console.error(e));
}

showAlert(title){
  let addAlert = this.alertController.create({
    title  :"Bluetooth state",
    message:titleStr
 });
 addAlert.present();
}

According to the docs, you need to call it using cordova.plugins.diagnostic:

The core plugin module is exposed via the global cordova.plugins.diagnostic object and it aliases all functions and properties of the other optional modules.

Also, since then() is used for asynchronous operation, therefore you need to call the method showAlert(titleStr) inside of .then().


text:
Q: Appending to string each time a substring is found I have a string that is made of html srcset. I extracted the value of srcset using DOMDocument, it's something like:
$srcset = "/wp-content/uploads/2016/05/something-970x647-c-300x190.jpg 300w,
/wp-content/uploads/2016/05/something-970x647-c-120x76.jpg 120w,
/wp-content/uploads/2016/05/something-970x647-c-265x168.jpg 265w";

As you can see, urls are relative. I want to change them into absolute form with the host being something like http://example.com
For that I was thinking of looping through occurrences of /wp-content in the string and append the host url to its beginning.
How do I do that?

A: $srcset = str_replace('/wp-content/', 'http://example.com/wp-content/', $srcset);


text:
Q: How to clean Lib and Dll folder I'm making a .dll for an .exe program and embedding python in it. For it to work I need to include the .py programs and the Dll and Lib folders in the .exe folder like it says in here. It works fine on my computer but i want to use the .dll in other computers.
So what I want is to erase everything that isn't necessary from the Lib and Dlls folders (right now the two folders have 210Mb)
I already looked into ModuleFinder(like it says here) and managed to erase some modules. But that's not what I want. ModuleFinder tells me the unused modules but how do I clean them and all the other unneeded files from Lib and Dll when there are thousands of files there?
Anyone knows any good way of doing this?

A: "Dependency Walker" is a tool which can show you which DLLs are needed. That includes both a static mode (which are needed just to load the EXE?) and a dynamic mode (which are needed at runtime?)


text:
Q: Cancelling (prime) roots of unity I have to show that the fraction
$$\frac{u^{pq}-1}{(u^p-1)(u^q-1)}$$
is of the from
$$\frac{f_{p,q}(u)}{u-1}.$$
I'm searching for a short proof.
If we factorize, the p'th and q'th roots of unity cancel, except for 1, which canceles only once. Is there a nicer way to explain this?

A: Consider the expressions as polynomials in $u$.
Then $u^{pq}-1$ is a multiple of both $u^p-1$ and $u^q-1$ and so is a multiple of their lcm:
$$
u^{pq}-1
=f(u)\operatorname{lcm}(u^p-1,u^q-1)
$$
Since $\gcd(u^p-1,u^q-1)=u-1$, we get
$$
\operatorname{lcm}(u^p-1,u^q-1)=\frac{(u^p-1)(u^q-1)}{u-1}
$$
and so
$$
u^{pq}-1
=f(u)\operatorname{lcm}(u^p-1,u^q-1)
=\frac{f(u)(u^p-1)(u^q-1)}{u-1}
$$
This argument only needs that $\gcd(p,q)=1$, not that $p,q$ are primes.
More generally, if $m=\operatorname{lcm}(p,q)$ and $d=\gcd(p,q)$, then
$$
\frac{u^m-1}{(u^p-1)(u^q-1)} = \frac{f(u)}{u^d-1}
$$
since $\gcd(u^p-1,u^q-1)=u^d-1$.


text:
Q: Flot Graph not plotting data I a trying to plot some information using a flot graph but I can not get the values to appear on the graph.  This code was part of a demo file included in a template and so i have modified it to plot the data rather than using a randomise for the values, i am getting no errors but the chart isn't working and was hoping somebody could point me in the right direction.
My code is here:
 init: function()
    {
        // apply styling
        charts.utility.applyStyle(this);

        this.plot = $.plot(
            $("#chart_simple"),
            [{
                label: "Jobs",
                data: this.data.d1,
                lines: {fillColor: "#dd3333"},
                points: {fillColor: "#dd3333"}
            },
            {
                label: "Resumes",
                data: this.data.d2,
                lines: {fillColor: "#282b30"},
                points: {fillColor: "#282b30"}
            }], this.options);
    }
},

// lines chart with fill & without points
chart_lines_fill_nopoints:
{

    // chart data
    data:
    {
        d1: [[1,100], [2,150], [3,100]],
        d2: [[1,100], [2,150], [3,100]]
    },

    // will hold the chart object
    plot: null,

    // chart options
    options:
    {
        grid: {
            show: true,
            aboveData: true,
            color: "#3f3f3f",
            labelMargin: 5,
            axisMargin: 0,
            borderWidth: 0,
            borderColor:null,
            minBorderMargin: 5 ,
            clickable: true,
            hoverable: true,
            autoHighlight: true,
            mouseActiveRadius: 20,
            backgroundColor : { }
        },
        series: {
            grow: {active:false},
            lines: {
                show: true,
                fill: true,
                lineWidth: 2,
                steps: false
            },
            points: {show:false}
        },
        legend: { position: "nw" },
        yaxis: { min: 0 },
        xaxis: {ticks:11, tickDecimals: 0},
        colors: [],
        shadowSize:1,
        tooltip: true,
        tooltipOpts: {
            content: "%s : %y.0",
            shifts: {
                x: -30,
                y: -50
            },
            defaultTheme: false
        }
    },

A: So, digging a bit, I see you are using javascript from here.  Looking at a working example here, you've broken their code in the following ways:
1.)  You no longer seem to have a parent charts object, so
charts.utility.applyStyle(this);
isn't going to work.
2.) The init function is part of the chart_lines_fill_nopoints object, in your cut/paste code it isn't anymore.
3.) In your sample code you never actually call the init function to draw the plot.
4.) In the options backgroundColor : { } is invalid for flot (maybe this is part of the missing charts.utility.applyStyle).
Taking all this into account here's a fiddle which makes this code work.
Generating flot plots with the above code feels unnecessarily convoluted.  Perhaps it makes sense when using these templates, but if you just using this as an example of how to call flot it's not very straightforward.
Also, please next time you post a question, include all relevant information (like where you found this code and how you changed it).  Taken out of context this code makes little sense.

A: This code is working
//Defining data for the chart

var data=
{
    d1: [[1,100], [2,150], [3,100]],
    d2: [[1,100], [2,150], [3,100]]
};

//Defining options for the chart
var options=
{
    grid: {
        show: true,
        aboveData: true,
        color: "#3f3f3f",
        labelMargin: 5,
        axisMargin: 0,
        borderWidth: 0,
        borderColor:null,
        minBorderMargin: 5 ,
        clickable: true,
        hoverable: true,
        autoHighlight: true,
        mouseActiveRadius: 20,
        backgroundColor : { }
    },
    series: {
        grow: {active:false},
        lines: {
            show: true,
            fill: true,
            lineWidth: 2,
            steps: false
        },
        points: {show:false}
    },
    legend: { position: "nw" },
    yaxis: { min: 0 },
    xaxis: {ticks:11, tickDecimals: 0},
    colors: [],
    shadowSize:1,
    tooltip: true,
    tooltipOpts: {
        content: "%s : %y.0",
        shifts: {
            x: -30,
            y: -50
        },
        defaultTheme: false
    }};

// shorthand for document.ready
$(function(){

    this.plot = $.plot(
        $("#chart_simple"),
        [{
            label: "Jobs",
            data: data.d1,
            lines: {fillColor: "#dd3333"},
            points: {fillColor: "#dd3333"}
        },
        {
            label: "Resumes",
            data: data.d2,
            lines: {fillColor: "#282b30"},
            points: {fillColor: "#282b30"}
        }], this.options);
});

Check out the working example here on jsfiddle.


text:
Q: Getting connection timeout error while calling get access token Microsoft Graph API through REST POST call I am trying to get access token from https://login.microsoftonline.com/{tenentname}/oauth2/v2.0/token endpoints though HttpClient post request. Applied required 4 parameters/headers with the same.
But I am getting connection timed out. Connection will be retried using another IP address (after trying with 7 different IP address) getting Shutdown connection error. Connection discarded.
Please find below code snippet.
HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
HttpPost post = new HttpPost("https://login.microsoftonline.com/{tenentname}/oauth2/v2.0/token");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
urlParameters.add(new BasicNameValuePair("client_id", {id_value}));
urlParameters.add(new BasicNameValuePair("client_secret", {secret_value}));
urlParameters.add(new BasicNameValuePair("scope", "https://graph.microsoft.com/.default"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));
post.setHeader("Content-type", "application/x-www-form-urlencoded");

ClosableHttpClinet httpClient = HttpClients.custom().setConnectionManager(poolingConnManager).build();
ClosableHttpResponse response = httpClinet.execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));

Same its worked with Postman without any proxy setting, I am getting proper response in Postman.
Please assist on the same.

A: Instead of using HTTPClient, i tried with Microsoft Graph Client (you can download from NuGet) and it worked for me. So i would suggest you to follow the steps.

*

*Install the SDK

*Configure the GraphClient

*Make the call.

Also with specific to ivy dependency, here's the related thread.


text:
Q: Extract one triangle of a correlation matrix with attributes I have a dataframe/matrix of equal rows and columns. I want to extract only the upper or lower triangle.
x<-data.frame(matrix(1:25,nrow=5))
colnames(x)<-LETTERS[1:5]
rownames(x)<-LETTERS[1:5]

x[upper.tri(x,diag=F)]

From this result, it is not possible to say what combination of column and row the value came from. So, I would like to have the row and column attributes in the results. Something like this:
Col Row Val
B   A   6
C   A   11
C   B   12
...

I need to do this for a large correlation matrix.
Thanks.

A: I'd just use which with arr.ind = TRUE like this:
ind <- which( upper.tri(x,diag=F) , arr.ind = TRUE )

data.frame( col = dimnames(x)[[2]][ind[,2]] ,
            row = dimnames(x)[[1]][ind[,1]] ,
            val = x[ ind ] )

   col row val
1    B   A   6
2    C   A  11
3    C   B  12
4    D   A  16
5    D   B  17
6    D   C  18
7    E   A  21
8    E   B  22
9    E   C  23
10   E   D  24

A: First, to make things unambiguous, I change
colnames(x) <- LETTERS[6:10]

Use expand.grid to get the row and column names like this
rowCol <- expand.grid(rownames(x), colnames(x))

To get the correct rows from this data frame, take
labs <- rowCol[as.vector(upper.tri(x,diag=F)),]
df <- cbind(labs, x[upper.tri(x,diag=F)])
colnames(df) <- c("Row","Col","Val")
df[,c(2,1,3)]
##    Col Row Val
## 6    G   A   6
## 11   H   A  11
## ...

A: ... this might be a solution
nam <-apply(ind, 2, function(y, x) rownames(x)[c(y)], x=x)
cbind(nam, x[upper.tri(x,diag=F)])

hth

A: The lower triangle is defined with the expression "column index is not greater than the row index".
This code gives the lower triangle (or upper by switching the > operator) a value of 0.  Use "" in place of 0 to keep the triangle.
x[!(col(x) > index(x))] <- 0

To produce a data set as in the original post, I would use reshape2::melt and dplyr::(filter, select) functions.
First create an id variable to melt on.
x$id <- rownames(x)

Then,
melt(x, id = "id") %>%
 filter(value > 0 ) %>%
   select(Col = variable, Row = id, Val = value)

   Col Row Val
1    B   A   6
2    C   A  11
3    C   B  12
4    D   A  16
5    D   B  17
6    D   C  18
7    E   A  21
8    E   B  22
9    E   C  23
10   E   D  24


text:
Q: Proper way to use latest babel and Jest in a Vue or Quasar CLI project Need to use Babel 7 and Jest together with the Vue/Quasar CLI.
I've been told in the quasar discord chat that Jest needs Babel 7 beta 54.  Jest documentation is lacking and confusing surrounding babel 7 support, so I went with the recommendation in discord and got it working perfectly, but I get lots of warnings during "npm install" now.
When I google for these warnings all I can find is people who created github issues asking for help in the Jest and Babel and Quasar and Vue CLI repos, and people telling them "they're just warnings, not errors" and the issues being closed: Nobody solves or explains the issue.
Can someone please explain how to get Babel 7 and Jest to work with the Quasar/Vue CLI without warnings, or explain why the warning messages are showing?
NOTE: The warning message texts are actually incorrect.  I have the versions being asked for installed.
NOTE: I have tried installing 7.0.0-beta.50 and every version in between, both in devDependencies and dependencies to no avail of the warnings.
If it helps, I'm using Windows 10, although fellow devs have said they get the same warnings on Macs and Linux.
Warning messages that appear when you type "npm install" with the below package.json:
npm WARN @babel/plugin-proposal-class-properties@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-syntax-class-properties@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-syntax-import-meta@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/preset-stage-3@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-proposal-async-generator-functions@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-proposal-json-strings@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-proposal-object-rest-spread@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-proposal-optional-catch-binding@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-proposal-unicode-property-regex@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-syntax-async-generators@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-syntax-dynamic-import@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-syntax-json-strings@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-syntax-object-rest-spread@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-syntax-optional-catch-binding@7.0.0-beta.54 requires a peer of @babel/core@>=7.0.0-beta.50 <7.0.0-rc.0 but none is installed. You must install peer dependencies yourself.

package.json:
{
  "name": "test",
  "version": "1.0.0",
  "dependencies": {
    "@babel/core": "^7.1.2",
    "@babel/runtime": "^7.1.2",
    "debug": "^4.1.0",
    "es6-iterator": "^2.0.3",
    "gsap": "^2.0.2",
    "lodash.get": "^4.4.2",
    "socket.io-client": "^2.1.1",
    "vue-i18n": "^7.3.3",
    "vue-json-pretty": "^1.4.1",
    "perfect-scrollbar-vue2": "^1.2.0",
    "vuelidate": "^0.7.4",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@babel/plugin-proposal-decorators": "7.1.2",
    "@babel/plugin-proposal-export-namespace-from": "7.0.0",
    "@babel/plugin-proposal-function-sent": "7.1.0",
    "@babel/plugin-proposal-numeric-separator": "7.0.0",
    "@babel/plugin-proposal-object-rest-spread": "7.0.0",
    "@babel/plugin-proposal-throw-expressions": "7.0.0",
    "@babel/plugin-syntax-dynamic-import": "7.0.0",
    "@babel/plugin-transform-runtime": "7.1.0",
    "@babel/preset-env": "7.1.0",
    "@babel/preset-stage-2": "7.0.0",
    "@babel/types": "7.1.3",
    "@storybook/addon-actions": "^4.0.9",
    "@storybook/addon-links": "^4.0.9",
    "@storybook/addons": "^4.0.9",
    "@storybook/vue": "^4.0.9",
    "@vue/cli-plugin-unit-jest": "^3.0.5",
    "@vue/test-utils": "^1.0.0-beta.26",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "^8.2.1",
    "babel-jest": "^23.6.0",
    "babel-loader": "^8.0.4",
    "babel-preset-vue": "^2.0.2",
    "eslint": "^4.18.2",
    "eslint-config-standard": "^11.0.0",
    "eslint-friendly-formatter": "^4.0.1",
    "eslint-loader": "^2.0.0",
    "eslint-plugin-import": "^2.9.0",
    "eslint-plugin-node": "^6.0.1",
    "eslint-plugin-promise": "^3.7.0",
    "eslint-plugin-standard": "^3.0.1",
    "eslint-plugin-vue": "^4.3.0",
    "eslint-plugin-vue-a11y": "0.0.28",
    "fse": "^4.0.1",
    "jest": "^23.6.0",
    "lighthouse": "^3.0.3",
    "mocha": "^5.2.0",
    "node-fetch": "^2.2.0",
    "pug": "^2.0.3",
    "pug-plain-loader": "^1.0.0",
    "quasar-cli": "^0.17.22",
    "request-promise": "^4.2.2",
    "socket.io-mock": "^1.2.3",
    "strip-ansi": "=3.0.1",
    "vue-jest": "^3.0.1",
    "wallaby-vue-compiler": "^1.0.3"
  },
  "engines": {
    "node": ">= 8.9.0",
    "npm": ">= 5.6.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 10"
  ]
}


text:
Q: how to fix not generated css file from less while run static deploy command in magento 2? Magento Version 2.1.9
Current Mode: production
After switched from developer to production mode, I ran the static deploy command but in that, I got the following error on CLI
$ php bin/magento setup:static-content:deploy
Requested languages: en_US
Requested areas: frontend, adminhtml
Requested themes: Magento/blank, Magento/luma, Sm/market, Magento/backend
=== frontend -> Magento/blank -> en_US ===
=== frontend -> Magento/luma -> en_US ===
=== frontend -> Sm/market -> en_US ===
=== adminhtml -> Magento/backend -> en_US ===

Compilation from source: /home/<yoursite.com>/public_html/vendor/magento/theme-frontend-blank/web/css/email.less
Compilation from source:
frontend/Sm/market/en_US/css/email.less
Unable to get content for 'frontend/Sm/market/en_US/Magento_Bundle/css/source/_email.less'

Compilation from source: /home/<yoursite.com>/public_html/vendor/magento/theme-frontend-blank/web/css/email-inline.less
Compilation from source:
frontend/Sm/market/en_US/css/email-inline.less
Unable to get content for 'frontend/Sm/market/en_US/Magento_Bundle/css/source/_email.less'

and due to this, above mention files are not generated on the pub/static folder so please suggest to me how to fix it in production mode?

A: Not enough info to detect the problem.
Please answer some questions to debug your problems.

*

*Show more theme structure

*theme.js

*did you have any email.less file on your theme??

*Did you have any file.less include _email.less in Magento_Bundle module?

*If you have file source.less or _module.less have included _email.less please remove that line, because default magento auto load emaill.less >> Style Email Template In Magento 2

*Please check any empty .less files then remove them.


text:
Q: URL Rewrite 2.0 Wildcards - IIS 7.5 <rule name="WomensSilverBangles" patternSyntax="ExactMatch">
    <match url="/Bangles/Silver/Womens.aspx" />
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
    <action type="Rewrite" url="Collections/jewellery.aspx?AXSW_CategoryID=Bangles&AXSWFinenessId=Silver&AXSW_GenderID=Womens&MenuName=Jewellery&SiteMapNode=Silver Bangles&depth=2" />
</rule>

Can this be written using wildcards?
As you can see, the three variables in the match URL are used in the rewritten URL string.

A: I know it's been a while since this question was posted, but there is an excellent article on rewriting here and based on that, you could try experimenting with something like this(not tested):
    <rule name="3levelcatchall" patternSyntax="Wildcard">
      <match url="/*/*/*.aspx"/>
      <action type="Rewrite" url="Collections/jewellery.aspx?AXSW_CategoryID={R:1}&AXSWFinenessId={R:2}&AXSW_GenderID={R:3}&MenuName=Jewellery&SiteMapNode={R:2} {R:1}&depth=2" appendQueryString="false"/>
    </rule>


text:
Q: Call SQL Server Stored Procedure With a Return Value From Spring Data JPA I need to call a SQL Server Stored Procedure that returns a boolean value, not by output parameter, like this:
exec ? = sp_adm_verificapermissao ?,?,?,?

I am using Spring Data.


text:
Q: Can't select row of TableView in QML I have created a TableView in QML, connected to a SoftFilterProxyModel.  The data displays fine, and when I click on a row my "selectRow" function runs, and receives the correct row number.  However, nothing shows as selected.  I based my design on this SO question
The relevant code is:
ItemSelectionModel {
    id: companyTableISM
    model: companySFPM
}

function selectRow(row) {
    console.log("In selectRow row "+row);
    companyTableISM.select(companySFPM.index(row, 0), ItemSelectionModel.select | ItemSelectionModel.current );
    console.log(companyTableISM.selectedIndexes);
    console.log(companyTableISM.hasSelection);
}

So when I click a row it outputs:
qml: In selectRow row 3
qml: []
qml: false

Since my selectRow function is receiving the correct row number, the model (companySFPM) matches the one used by the TableView, why do my 2 log statements showing nothing selected and false (hasSelection)?

A: I believe you have two typos in the line:
ItemSelectionModel.select | ItemSelectionModel.current

Notice the capitalization of the enumerated types?  It should be:
ItemSelectionModel.Select | ItemSelectionModel.Current

A: Current and Select are selection flags enum of select(). For more selection flags you can read this .
Replace s and c of select and current with capital letter.
companyTableISM.select(companySFPM.index(row, 0), ItemSelectionModel.Select | ItemSelectionModel.Current);


text:
Q: Linux - openssl sha256 using key from file I have a 32 byte key stored in a file called test_key.key
I wish to use openssl to create hash of a different file called mytext.txt. I need to create the hash using HMAC-SHA-256 & the key in test_key.key
I thought I had it working with the following command:
openssl dgst -sha256 -hmac $test_key.key mytext.txt

However, on closer examination I noticed it was using the string "test_key.key", not the actual file contents. I have tried a few different variations of this for the key file such as:
"$test_key.key"
'$test_key.key'
/test_key.key

Sadly, they all seem to have the same problem.
Can anyone advise me on this? I wish to keep this as a one line command if possible.

A: openssl dgst -sha256 -hmac $(<test_key.key) mytext.txt

(credit to user David C. Rankin)


text:
Q: why numpy multiply won't multiply (5,5) and (5,23) array The following code is crashing with the following error:
ValueError: operands could not be broadcast together with shapes (5,5) (5,23)
I know that these two matrices can be multiplied together, so what is going on?
def recon_temp(recon_pc_matrix, ew, eof, n, p):
    new_temps = np.zeros((p, p))
    for i in range(0,p-1):
        a = np.array([ew[i]*(recon_pc_matrix[i,0:p])]).T
        b = np.array([eof[i, 0:n]])
        new_temps = np.add(new_temps, np.multiply(a, b))
    return new_temps

a = np.array([[-0.1712077   0.30916178  0.3639138   0.86173197  0.00957432]
 [ 0.09886268 -0.56593983  0.75287704 -0.09865605  0.30558374]
 [-0.23426853  0.07244316  0.4005179  -0.23221139 -0.85178256]
 [ 0.1941591  -0.70654452 -0.339463    0.4397842  -0.39300358]
 [-0.93184473 -0.28227279 -0.15840833 -0.01878062  0.16291583]])
b = np.array([[-0.89934942  1.51224286  1.17335825 -0.08218979  0.98625991  1.13124679
   0.12082299 -1.45882345 -1.6897246   0.70884387 -1.21370037 -0.03640097
   0.25423117 -0.34026433 -0.94905651 -0.48517389  0.05775344  0.71212526
   1.11442191  0.31825772 -1.41012823 -0.59093546  1.06618286]
 [ 0.85264281  1.63168765  0.80196132  0.04534459  0.48561984 -0.11086797
   1.11591161 -0.24153581  0.65829793 -0.07172239  1.12920778 -0.52778775
  -2.2780791   0.90289084 -0.20018346 -0.20287233 -0.31416035 -0.83016084
  -0.8077091  -0.29606383 -1.19852534 -0.0768147  -0.46708139]
 [ 0.67870887 -0.01875505  0.26984334 -0.6223331   0.32559298 -0.94280004
  -0.81414199 -0.19893921  0.84574502  1.09421435 -0.15831082  1.81599507
   0.00648578 -1.21146774 -0.3179769   1.04116227 -0.11486882 -0.31177898
  -0.19821291  0.10022766 -1.09882425 -0.1149134  -0.05465211]
 [-0.03707971  0.53168148  0.41874141  0.03673735 -1.33893753  0.12464263
  -0.1343872   0.46679816 -0.75343034 -0.23104592 -0.22133639  0.28104257
  -0.37346672 -0.65672427  0.54146026 -0.13421286 -0.18973127 -1.0554372
  -0.44792916  0.85063804 -0.02023537  1.22571478  1.11649726]
 [ 0.31681713 -0.12923957 -0.04577132  0.2485488  -0.03239199 -0.07354265
   0.35762585 -0.97073981 -0.59382981  0.00892815  0.74089591 -0.04775075
   0.30722372 -0.51731235  0.43637896  0.21612401  0.83204179 -0.29326734
  -0.59640106  0.22724823  0.21728589 -0.64666786  0.03779609]])
c = np.array([ 0.92504802  0.7660462   0.540457    0.40724992  0.20059767])

temp = recon_temp(a, c, b, 23, 5)

It crashes when multiplying a and b

A: np.multiply does elementwise multiplication. Two arrays with shapes (5, 5) and (5, 23) cannot be elementwise multiplied, hence the error. If you want to perform matrix multiplication, use np.dot:
>>> a = np.random.rand(5, 5)
>>> b = np.random.rand(5, 23)
>>> np.multiply(a, b) <-- This gives a broadcasting error
>>> np.dot(a, b) <-- This gives the matrix multiplicaitn of a and b


text:
Q: Optimize R chains (magrittr) I would like to pipe (chain) magrittr object into loop. How can I do this?
I will use dummy operations/data as an example:
library(data.table)
library(magrittr)

# Dummy data modification
d <- mtcars %>%
    setDT() %>%
    .[, cylSQ := sqrt(cyl)] %>%
    .[, carb3 := carb^3]
# Dummy loop
res <- list()
for(i in unique(d$gear)) {
    res[[i]] <- d[gear == i] %>%
        .[, lm(cylSQ ~ mpg + carb3 * wt)] %>%
        .$fitted.values
}

Is it possible not to create object d and to pipe it directly to loop? For example:
for(i in unique(.$gear)) {
    res[[i]] <- .[gear == i] %>%
    ...
}

Edit: I don't want to replace loop with data.table or dplyr, just curious about piping.

A: Don't you mind using dplyr instead of data.table here? If not, try this:
library(dplyr)
d <- mtcars %>%
    mutate(cylSQ = sqrt(cyl), carb3 = carb^3) %>%
    group_by(gear) %>%
    do(fitted.values = lm(cylSQ ~ mpg + carb3 * wt, data = .)[["fitted.values"]])

A: This is a bit of sketchy work around, but you can use the exposition operator in the magrittr package %$%.
I.e.:
mtcars %>%
  filter(hp > 1) %$%
  for(i in 1:ncol(.)) {
    print(.[1,i])
  }

[1] 21
[1] 6
[1] 160
[1] 110
[1] 3.9
[1] 2.62
[1] 16.46
[1] 0
[1] 1
[1] 4
[1] 4

A: I'm not magrittr practitioner so it could probably be improved, but at least works, and should be efficient.

as.data.table(mtcars
              )[, cylSQ := sqrt(cyl)
                ][, carb3 := carb^3
                  ][, lm(cylSQ ~ mpg + carb3 * wt)$fitted.values, by=gear
                    ] %>%
    split(by = "gear", keep.by = FALSE) %>%
    lapply(unlist) %>%
    lapply(unname) -> res

Due to new split.data.table it requires data.table in 1.9.7, see installation wiki for details how to install on various platforms.


text:
Q: Why reading a std::string from file input returns blanks? I am looking to return a string from a class.
I have an object like:
.....
using namespace std;
class inputFile{
private:

fstream  _file;
bool  _exists;
std::string _inFileName;  // the filename
std::string _fileContents;

protected:

public:
inputFile(std::string*);
std::string getFileContents();
};

constructor:
inputFile::inputFile(std::string *in)
{
   _inFileName=*in;

   _file.open(_inFileName.c_str(),ios_base::in);
   while(_file.good()){
      getline(_file,_fileContents);

   cout << _fileContents << endl;
}

if(_file.is_open())
   _exists=true;
else
  _exists=false;
}

My method to return _fileContents always returns null instead of the file's contents i am reading in.  why is this?
std::string inputFile::getFileContents(){
    return _fileContents;
}

driver.cpp:
meshfile=new inputFile("test.txt")
std::cout << meshFile->getFileContents() << std::endl;

returns blanks

A: You don't save lines in _fileContents. You overwrite it every time. You have to append every line using _fileContents.append or operator +=.
class inputFile{
private:
    fstream  _file;
    bool  _exists;
    std::string _inFileName;  // the filename
    std::string _fileContents;

protected:

public:
    inputFile(std::string* in) {
        _inFileName = *in;

        _file.open(_inFileName.c_str(), ios_base::in);
        while (_file.good()) {
            std::string line;
            getline(_file, line);
            _fileContents += line;
        }

        cout << _fileContents << endl;
    }
    std::string getFileContents();
};


text:
Q: is it possible to create new worksheet in Excel 2013 using Office.js in Office Apps ?? I am developing task pane Office Apps in excel 2013. As part it , I have to create a new worksheet in Excel 2013 using Office.js .
Do we have any new sheet creating utility/function in Office.JS for Excel 2013 ????  or any alternate solution readily available for this ??
Please respond to my post asap as this impacts our current development.
Regards,
Ram

A: As far as I know, there are no such kind of feature in current Office JavaScript API. But you should be able to post a feature request to Office Development Platform User voice.
http://officespdev.uservoice.com

A: No, I've not found a way of doing this, but my work around has been to start with a template Excel file with plenty of sheets already in it.

A: In Excel 2016 you can use the add method in the WorksheetCollection object.
Excel.run(function (ctx) {
    var wSheetName = 'Sample Name';
    var worksheet = ctx.workbook.worksheets.add(wSheetName);
    worksheet.load('name');
    return ctx.sync().then(function() {
        console.log(worksheet.name);
    });
}).catch(function(error) {
        console.log("Error: " + error);
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
});

Source: https://dev.office.com/reference/add-ins/excel/worksheetcollection


text:
Q: Rails Application expecting me to restart my webrick server for any change in my controller I am working on an existing Rails 2.3.x application, So I was working on it and it was a messy code with great difficulty I was able to run the application. But now for every small change in one of my controller it is expecting me to restart my serer otherwise the changes are not reflecting back, Let's take an example scenario here, Let's just say in one of the before_filter method I just added a puts statement on top of the method and it was not printing in the log, after I restart the server it is printing, Can some one please let me know if I am missing something here.

A: What environment are you using?
The default environment is 'development', where the code is reloaded on each request. However, this behaviour can be overwritten in the config file.
To be sure that the code is reloaded, add this into your config/development.rb file:
  # In the development environment your application's code is reloaded on
  # every request.  This slows down response time but is perfect for development
  # since you don't have to restart the webserver when you make code changes.
  config.cache_classes = false

A: If you are using config.threadsafe! It needs to be present before config.cache_classes=false as threadsafe makes cache_classes true again,  following link would make it more clear. here

A: Maybe you have don't flush. The log system in Rails use a BufferedLogger. So need a flush to be print. Try a default logger.


text:
Q: Win8 Delete Files on Device when Importing Win8 has the native "Import Photos and Videos" app but also has a similar functionality in the WinRT environment in the Photos application.
The native application has an option to delete files on device after import.  This is a very handy feature which can help prevent importing the same files again leaving duplicate mess in the Photos file library.  No such setting that I can find exists on the WinRT "Photos" app.
I have configured my Win8 machine to open the "Import Photos and Videos" application when the camera is connected.  However, when connecting it the WinRT "Photos" app opens and not the native "Import Photos and Videos" app.
I either want to find a way for the WinRT "Photos" app to delete files after import OR have the native "Import Photos and Videos" application open upon connecting it to the computer.
Any ideas?
Thanks for reading.


text:
Q: CSS Animation isn't working, maybe keyframes is the issue? im trying to do an animation with CSS that makes text change color when you hover over it. Here is my code, im really not sure what my issue is here. Doesen't work in firefox or in chrome.
@keyframes swap {
from {background-color: black;}
to {background-color: purple;}
}

text.normText:hover {
animation-name: swap;
animation-duration: 2.5s;
}

The keyframes part doesen't highlight as a special word in Netbeans so maybe thats the issue?

A: If it's for text color you need to use the color property instead of background-color. I also wouldn't even worry about using keyframes for something this simple.  I would do it like this.

.text.normText {
  color: black;
  transition: color 2.5s;
}

.text.normText:hover {
  color: purple;
}


text:
Q: What does "Everything's a copy of a copy of a copy" mean? In Fight Club (1999), Narrator speaks about his health problem:

Narrator: For six months, I couldn't sleep. I couldn't sleep...with
insomnia,  nothing's real. Everything's far away. Everything's a
copy of a copy of a copy.

What does "Everything's a copy of a copy of a copy" mean?

A: People used to make copies of documents with something called a photocopier, instead of scanning and printing. They made poor quality copies. The narrator feels confused; tired. The world looks dull; faint; blurry.


text:
Q: Extending UITextField Control in iOS Development I am creating a custom UITextField which is responsible for ensuring that the user only enters numeric data into the TextField. I want to capture the following event inside the custom textbox.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

How can I do that?
UPDATE 1:
// the below code sets the delegate but the delegate methods never gets called
-(id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        self.delegate = self;
    }

    return self;
}

A: on your MyTextBox.h add the UITextFieldDelegate protocol
on your MyTextBox initialization code, add:
self.delegate = self;


text:
Q: GoDaddy A record and SSL Handshake error I have pointed A record to my server IP  in GOoDaddty as ns1.example.com and it is working.But I am confused with SSL error. I have generated SSL certificate with CN as ns1.example.com. When I try to connect to the server I get an error SSL handshake error. Is it like I need to setup DNS server on my server or it is ok with above setting. I generated certificates correctly. Is it like localhost in server != ns1.example.com thats why ssl is failing? how to resolve it?

A: It should be ok with above setting. Just make sure that you are reaching the correct IP (DNS being correctly propagated) and check with a DNS checker or openssl client the reason of the SSL hanshake error


text:
Q: Can i fill function named parameters from seq in scala? If I have Seq('a -> 1, 'b -> "some text"), how can I call a function f(a: Int, b: String), filled with parameters from Seq, bound by name (a, b)?

A: You should be able to do it using scala-reflect, I believe. Something like this (untested):
def applyWithNamedParameters[T: ClassTag](obj: T, m: MethodSymbol, params: Map[String, Any]) {
  val methodMirror = scala.universe.runtime.currentMirror.reflect(obj).reflectMethod(m)
  val paramNames = m.paramss.flatten.map(_.name.toString)
  val paramValues = paramNames.map(params)

  methodMirror.apply(paramValues)
}

params are given as a map instead of Seq to simplify code a bit.


text:
Q: CGPathRef intersection Is there a way to find out whether two CGPathRefs are intersected or not. In my case all the CGPaths are having closePath.
For example, I am having two paths. One path is the rectangle which is rotated with some angle and the other path is curved path. Two paths origin will be changing frequently. At some point they may intersect. I want to know when they are intersected. Please let me know if you have any solution.
Thanks in advance

A: Make one path the clipping path, draw the other path, then search for pixels that survived the clipping process:
// initialise and erase context
CGContextAddPath(context, path1);
CGContextClip(context);

// set fill colour to intersection colour
CGContextAddPath(context, path2);
CGContextFillPath(context);

// search for pixels that match intersection colour

This works because clipping = intersecting.
Don't forget that intersection depends on the definition of interiority, of which there are several. This code uses the winding-number fill rule, you might want the even odd rule or something else again. If interiority doesn't keep you up at night, then this code should be fine.
My previous answer involved drawing transparent curves to an RGBA context. This solution is superior to the old one because it is

*

*simpler

*uses a quarter of the memory as an 8bit greyscale context suffices

*obviates the need for hairy, difficult-to-debug transparency code

Who could ask for more?
I guess you could ask for a complete implementation, ready to cut'n'paste, but that would spoil the fun and obfuscate an otherwise simple answer.
OLDER, HARDER TO UNDERSTAND AND LESS EFFICIENT ANSWER
Draw both CGPathRefs separately at 50% transparency into a zeroed, CGBitmapContextCreate-ed RGBA memory buffer and check for any pixel values > 128. This works on any platform that supports CoreGraphics (i.e. iOS and OSX).
In pseudocode
// zero memory

CGContextRef context;
context = CGBitmapContextCreate(memory, wide, high, 8, wide*4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);
CGContextSetRGBFillColor(context, 1, 1, 1, 0.5);  // now everything you draw will be at 50%

// draw your path 1 to context

// draw your path 2 to context

// for each pixel in memory buffer
if(*p > 128) return true; // curves intersect
else p+= 4; // keep looking

Let the resolution of the rasterised versions be your precision and choose the precision to suit your performance needs.

A: 1) There isn't any CGPath API to do this. But, you can do the math to figure it out. Take a look at this wikipedia article on Bezier curves to see how the curves in CGPath are implemented.
2) This is going to be slow on the iPhone I would expect but you could fill both paths into a buffer in difference colors (say, red and blue, with alpha=0.5) and then iterate through the buffer to find any pixels that occur at intersections. This will be extremely slow.

A: For iOS, the alpha blend seems to be ignored.
Instead, you can do a color blend, which will achieve the same effect, but doesn't need alpha:
CGContextSetBlendMode(context, kCGBlendModeColorDodge);
CGFloat semiTransparent[] = { .5,.5,.5,1};

Pixels in output Image will be:

*

*RGB = 0,0,0  = (0.0f) ... no path

*RGB = 64,64,64 = (0.25f) ... one path, no intersection

*RGB = 128,128,128 = (0.5f) ... two paths, intersection found

Complete code for drawing:
-(void) drawFirst:(CGPathRef) first second:(CGPathRef) second into:(CGContextRef)context
{
    /** setup the context for DODGE (everything gets lighter if it overlaps) */
    CGContextSetBlendMode(context, kCGBlendModeColorDodge);

    CGFloat semiTransparent[] = { .5,.5,.5,1};

    CGContextSetStrokeColor(context, semiTransparent);
    CGContextSetFillColor(context, semiTransparent);

    CGContextAddPath(context, first);
    CGContextFillPath(context);
    CGContextStrokePath(context);

    CGContextAddPath(context, second);
    CGContextFillPath(context);
    CGContextStrokePath(context);
}

Complete code for checking output:
[self drawFirst:YOUR_FIRST_PATH second:YOUR_SECOND_PATH into:context];

// Now we can get a pointer to the image data associated with the bitmap
// context.
BOOL result = FALSE;
unsigned char* data = CGBitmapContextGetData (context);
if (data != NULL) {

    for( int i=0; i<width; i++ )
        for( int k=0; k<width; k++ )
        {
    //offset locates the pixel in the data from x,y.
    //4 for 4 bytes of data per pixel, w is width of one row of data.
    int offset = 4*((width*round(k))+round(i));
    int alpha =  data[offset];
    int red = data[offset+1];
    int green = data[offset+2];
    int blue = data[offset+3];

            if( red > 254 )
            {
                result = TRUE;
                break;
            }
        }

And, finally, here's a slightly modified code from another SO answer ... complete code for creating an RGB space on iOS 4, iOS 5, that will support the above functions:
- (CGContextRef) createARGBBitmapContextWithFrame:(CGRect) frame
{
   /** NB: this requires iOS 4 or above - it uses the auto-allocating behaviour of Apple's method, to reduce a potential memory leak in the original StackOverflow version */
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    void *          bitmapData;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;

    // Get image width, height. We'll use the entire image.
    size_t pixelsWide = frame.size.width;
    size_t pixelsHigh = frame.size.height;

    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and
    // alpha.
    bitmapBytesPerRow   = (pixelsWide * 4);
    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);

    // Use the generic RGB color space.
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color space\n");
        return NULL;
    }

    // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
    // per component. Regardless of what the source image format is
    // (CMYK, Grayscale, and so on) it will be converted over to the format
    // specified here by CGBitmapContextCreate.
    context = CGBitmapContextCreate (NULL,
                                     pixelsWide,
                                     pixelsHigh,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedFirst
                                     //kCGImageAlphaFirst
                                     );
    if (context == NULL)
    {
        fprintf (stderr, "Context not created!");
    }

    // Make sure and release colorspace before returning
    CGColorSpaceRelease( colorSpace );

    return context;
}


text:
Q: How to persist data in H2 database My application has 3 components,
1) A user facing component that receives requests and stores into the DB
2) A backend component that reads data form the DB, processes it and sends it on to an external system.
3) A DB that stores user input

I am currently testing using H2 in memory database (NOT file based) from eclipse.
I want to test end to end, but the problem is I have stop the user facing component and start the backend component.
So, the DB gets created from scratch each time I start the backend component.
How do I test so that the flow is like this: user enters data -> data persisted into DB -> Baackend connects to the same persisted data -> processes data + passes to external system?
NOTE: I tried using ddl-auto: update, but it doesn't work.

A: In addition to spring.jpa.hibernate.ddl-auto=update, set auto_reconnect as true.
Example:
spring.datasource.url=jdbc:h2:file:~/test2;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
spring.datasource.driver-class-name=org.h2.Driver


text:
Q: Different values of Initial weight of linear regression is converging to different minimized cost value I have implemented a univariate linear regression in python. The code is given below:
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1,2,4,3,5,7,9,11])
y = np.array([3,5,9,7,11,15,19,23])

def hypothesis(w0,w1,x):
  return w0 + w1*x

def cost_cal(y,w0,w1,x,m):
  diff = hypothesis(w0,w1,x)-y
  diff_sqr = np.square(diff)
  total_cost = np.sum(diff)
  total_cost_sqr = (1/(2*m)) * np.sum(diff_sqr)
  return total_cost, total_cost_sqr

def gradient_descent(w0,w1,alpha,x,m,y):
  cost, cost_sqr = cost_cal(y,w0,w1,x,m)
  temp0 = (alpha/m) * cost
  temp1 = (alpha/m) * np.sum(cost*x)
  w0 = w0 - temp0
  w1 = w1 - temp1
  return w0,w1

These are my hypothesis, cost, and gradient_descent functions implemented in python. When I use the initial weight w0 = 0 and w1 = 0, my minimized cost is 0.12589726000013188. But, if I initialize the w0 = -1 and w1 = -2, the minimized cost is 0.5035890400005265. What is the reason behind the different minimum costs using different initial weight values? As the error function MSE, is a convex function, shouldn't it reach the global minimum? Am I doing something wrong?
w0=0
w1=0
alpha =0.0001
m = 8
z = 5000
c = np.zeros(z)
cs = np.zeros(z)
w0_arr=np.zeros(z)
w1_arr=np.zeros(z)
index = np.zeros(z)
i = 0

while (i<z):
  index[i] = i
  c[i],cs[i] = cost_cal(y,w0,w1,x,m)
  #print(i, c[i], cs[i])
  w0, w1 = gradient_descent(w0,w1,alpha,x,m,y)
  w0_arr[i],w1_arr[i] = w0,w1
  i=i+1

inc = np.argmin(cs)
print(inc)
print(cs[inc])

A: The answer might vary based on your initial vector u choose in weight space. Apart from fact that the cost function is convex the curve has many critical points so it completely depends on the initial point or weights where we end up whether in local or global minima.
image link
https://1.bp.blogspot.com/-ltxplazySpc/XQG4aprY2iI/AAAAAAAABVo/xAqLIln9OWkig5rq4AU2sBFuPBuxW5CFQCLcBGAs/w1200-h630-p-k-no-nu/local_vs_global_minima.PNG
as per the image in the given link if u start from an initial point which is at the left corner we end up landing in global minima if we start from the right end we end up landing in local minima. Cost may vary by a huge difference but in most cases, the difference is not very large in case of local or global minima so if the cost is varying by big difference u need to cross-check once. Picking initial weights randomly is a good practice they should not be set manually.
in gradient_descent function, temp0 is assigned an array instead of the value, the sum of that array must be done before adding.


text:
Q: Export Users with group membership Is there a SOQL query or a method to extract all users, their profiles and group membership from Salesforce?

A: There is no straight forward way to export all the info in one go. You can export Users, and their profile info in one query and users/group membership in another query, then join the info based on the User id.
This gives users and profile info:
select
    Id,
    Email,
    Name,
    Profile.Name
from User

This gives UserIds, and their Groups List:
 select
    UserOrGroupId,
    Group.Name
 from GroupMember
 where UserOrGroupId in (select id from user)

Now you need to combine these two datasets based on the Id.


text:
Q: Removing Linux Partition from Secondary drive I have been tinkering with Ubuntu for a while in VMs and what not.  I recently decided to try a dual boot, but I wanted to keep my partition on my secondary drive.  I also put the GRUB bootloader on that drive as well.  Since I have don this dual boot I have been experiencing many problems with my primary drive which is running windows 10.  Essentially my windows 10 will freeze.  Windows won't close, I won't be able to access the start menu, the task bar freezes, and I can't access the task manager when this happens so I have decided it may be best to just go ahead and remove the linux partition and boot loader from that secondary drive since that is when the problems started.  Trouble is I'm not sure how to remove GRUB from that secondary drive.  Can anyone help me?
Thanks in advance


text:
Q: Image doesn't show after onChange function in IE Basically, I have made a function that selects a certain image to display depending on which option the user selects from the drop down menu which works great on Chrome and Firefox! But unfortunately not IE. I have no idea why and would appreciate anyone's wisdom on this matter.
CSS:
    #texture img {
        width: 395px;
        height: 288px;
        border: 1px solid #3d3d3d;
    }

JavaScript:
    function newTexture() {
            var textureName = '';
            document.getElementById("texture").innerHTML = textureName;
    }

HTML:
<form name="worktopForm">
    <select name="worktopColour" onChange="newTexture();">
        <option value="none" selected></option>
        <option value="starGalaxy">Star Galaxy(Band One)</option>
        <option value="seravalle">Seravalle(Band Two)</option>
        <option value="balmoralFineGrain">Balmoral Fine Grain(Band Three)</option>
        <option value="nutYellow">Nut Yellow(Band Four)</option>
       </select>

</form>

A: IE only fires the onchange event when the element loses focus, which isn't until you click the button, tab out or click somewhere on the screen...
i prefer u to use jquery or some other library for  event handling...
try this ....
give selectbox an id....say "worktopColour" ....


text:
Q: How to optimizing a function that takes two different forms in two different regions
a,b,and P are non-negative constants. And $\theta$ is a random variable with distribution function $F(\theta)$ and density function $f(\theta)$. Denote $H(\theta)= {F(\theta)\over f(\theta)}$. No constraints.
My method is letting the first-order derivative equals to zero, and get the optimal $z(\theta)$, but there is a problem that ${(P-z(\theta))}^+$ is a non-differentiable function, so can't use first-order derivative.


text:
Q: jquery two clicks instead of one to execute code I found this javascript code, and that's exactly what I'm looking for. This is a Show/Hide code with slide effect.
$(document).ready(function() {
if($('div.tab').length > 0) {
    $('div.tab').click(function() {
        if($(this).hasClass('open')) {
            $(this).removeClass('open');
            $(this).addClass('close');
            $(this).next().slideDown(300);
            return false;
        } else {
            $(this).removeClass('close');
            $(this).addClass('open');
            $(this).next().slideUp(300);
            return false;
        }
    })
}

Now, I wanted to add a code to show only one DIV at a time, closing opened DIV with slide effect. So, I add some code and it works how I want it to work. But the problem is, when one DIV is opened, and I click on another, new DIV, everything is working, but when I click on already visited DIV, I need two clicks, instead of one, to execute the code. I don't have a knowledge in js coding, so I'm asking here for your help.
Here is a code with my changes.
$(document).ready(function() {
if($('div.tab').length > 0) {
    $('div.tab').click(function() {
        if($(this).hasClass('open')) {
            $(this).removeClass('open');
                  $(this).addClass('close')**.siblings('div.container').slideUp(300)**;
            $(this).next().slideDown(300);
            return false;
        } else {
            $(this).removeClass('close');
            $(this).addClass('open');
            $(this).next().slideUp(300);
            return false;
        }
    })
}

A: I've got it works. I changed some code, and I've got exactly what I'm looking for. It show now one tab at a time, show/hide works when click on the same tab. Maybe it's not a proper coding way, because I don't have a knowledge in js, but it works for me perfectly.
$(document).ready(function() {

$('div.tab').click(function() {
    if($(this).hasClass('open')) {
        $(this).next().slideToggle(300).siblings('div.container').slideUp(300);

    } else {

        $(this).next().slideToggle(300);

    }
})

})
http://jsfiddle.net/9szef/1/


text:
Q: Odoo 10 : Secure access to custom module I tried to create custom user groups to my custom module to make it appear on the top menu by following this thread Odoo 10 : Custom module doesn't appear in top black menu after installation
Module name :simcard
model name : simcard.simcard
my csv file :
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
demo_admin, Model admin access,simcard.model_simcard_simcard,simcard.group_manager,1,1,1,1
demo_user, Model user access,simcard.model_simcard_simcard,simcard.group_user,0,0,0,0

my user_groups.xml :
<odoo>
  <data>
    <record model="ir.module.category" id="module_management">
      <field name="name">Simcard</field>
      <field name="description">User access level for this module</field>
      <field name="sequence">3</field>
    </record>

   <record id="group_user" model="res.groups">
     <field name="name">User</field>
     <field name="implied_ids" eval="[(4, ref('base.group_user'))]"/>
     <field name="users" eval="[(4, ref('base.user_root'))]"/>
     <field name="category_id" ref="simcard.module_management"/>
    </record>

    <record id="group_manager" model="res.groups">
      <field name="name">Manager</field>
      <field name="implied_ids" eval="[(4, ref('simcard.group_user'))]"/>
      <field name="category_id" ref="simcard.module_management"/>
    </record>
   </data>
</odoo>

when i start my odoo as ./odoo-bin -u simcard , i get below error which i dont understand :
    [12/Oct/2018 08:41:34] "POST /longpolling/poll HTTP/1.1" 500 -
2018-10-12 08:41:34,354 470 ERROR Dev-DB werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 180, in run_wsgi
    execute(self.server.app)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 168, in execute
    application_iter = app(environ, start_response)
  File "/odoo/odoo-server/odoo/service/server.py", line 244, in app
    return self.app(e, s)
  File "/odoo/odoo-server/odoo/service/wsgi_server.py", line 186, in application
    return application_unproxied(environ, start_response)
  File "/odoo/odoo-server/odoo/service/wsgi_server.py", line 172, in application_unproxied
    result = handler(environ, start_response)
  File "/odoo/odoo-server/odoo/http.py", line 1326, in __call__
    return self.dispatch(environ, start_response)
  File "/odoo/odoo-server/odoo/http.py", line 1300, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/lib/python2.7/dist-packages/werkzeug/wsgi.py", line 591, in __call__
    return self.app(environ, start_response)
  File "/odoo/odoo-server/odoo/http.py", line 1482, in dispatch
    odoo.registry(db).check_signaling()
  File "/odoo/odoo-server/odoo/__init__.py", line 52, in registry
    return modules.registry.Registry(database_name)
  File "/odoo/odoo-server/odoo/modules/registry.py", line 59, in __new__
    return cls.new(db_name)
  File "/odoo/odoo-server/odoo/modules/registry.py", line 83, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/odoo/odoo-server/odoo/modules/loading.py", line 373, in load_modules
    force, status, report, loaded_modules, update_module, models_to_check)
  File "/odoo/odoo-server/odoo/modules/loading.py", line 270, in load_marked_modules
    perform_checks=perform_checks, models_to_check=models_to_check
  File "/odoo/odoo-server/odoo/modules/loading.py", line 182, in load_module_graph
    _load_data(cr, module_name, idref, mode, kind='data')
  File "/odoo/odoo-server/odoo/modules/loading.py", line 96, in _load_data
    tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
  File "/odoo/odoo-server/odoo/tools/convert.py", line 845, in convert_file
    convert_xml_import(cr, module, fp, idref, mode, noupdate, report)
  File "/odoo/odoo-server/odoo/tools/convert.py", line 915, in convert_xml_import
    obj.parse(doc.getroot(), mode=mode)
  File "/odoo/odoo-server/odoo/tools/convert.py", line 796, in parse
    self.parse(rec, mode)
  File "/odoo/odoo-server/odoo/tools/convert.py", line 799, in parse
    self._tags[rec.tag](rec, de, mode=mode)
  File "/odoo/odoo-server/odoo/tools/convert.py", line 707, in _tag_record
    id = self.env(context=rec_context)['ir.model.data']._update(rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode)
  File "/odoo/odoo-server/odoo/addons/base/ir/ir_model.py", line 1197, in _update
    record.write(values)
  File "/odoo/odoo-server/odoo/addons/base/res/res_users.py", line 724, in write
    self._update_user_groups_view()
  File "/odoo/odoo-server/odoo/addons/base/res/res_users.py", line 786, in _update_user_groups_view
    view.with_context(lang=None).write({'arch': xml_content, 'arch_fs': False})
  File "/odoo/odoo-server/odoo/addons/base/ir/ir_ui_view.py", line 380, in write
    return super(View, self).write(self._compute_defaults(vals))
  File "/odoo/odoo-server/odoo/models.py", line 3586, in write
    field.determine_inverse(records)
  File "/odoo/odoo-server/odoo/fields.py", line 1046, in determine_inverse
    getattr(records, self.inverse)()
  File "/odoo/odoo-server/odoo/addons/base/ir/ir_ui_view.py", line 220, in _inverse_arch
    view.write(data)
  File "/odoo/odoo-server/odoo/addons/base/ir/ir_ui_view.py", line 380, in write
    return super(View, self).write(self._compute_defaults(vals))
  File "/odoo/odoo-server/odoo/models.py", line 3568, in write
    self._write(old_vals)
  File "/odoo/odoo-server/odoo/models.py", line 3732, in _write
    self._validate_fields(vals)
  File "/odoo/odoo-server/odoo/models.py", line 1081, in _validate_fields
    raise ValidationError("%s\n\n%s" % (_("Error while validating constraint"), tools.ustr(e)))
ParseError: "Error while validating constraint

Field `ignore_on_api` does not exist

Error context:
View `res.users.groups`
[view_id: 155, xml_id: base.user_groups_view, model: res.users, parent_id: 152]
None" while parsing /odoo/odoo-server/addons/simcard/security/user_groups.xml:37, near
<record id="group_simcard_user" model="res.groups">
        <field name="name">Officer2</field>
        <field name="category_id" ref="base.module_category_human_resources"/>
        <field name="implied_ids" eval="[(4, ref('base.group_user'))]"/>
        <field name="comment">the user will be able to approve document created by employees.</field>
    </record>

This ignore_on_api field exists in res.partner and user tables. I believe this is not the source of the error because when i remove users_groups.xml then this error is gone.
Info : Same module is installed on another odoo on another machine and it doesn't give any error.
Any idea what should i do  for this error?


text:
Q: E0349 no operator ">>" matches these operands I'm new to C++, so please forgive me if this is extremely simple.
Just trying to make my own independent projects, and then this error happens to me:

E0349 no operator ">>" matches these operands

// usd-to-aud.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <windows.h>
#include <iostream>

// MAIN
int main()
{
    std::cout << "Welcome to Currency conversion!\n";
    Sleep(1000);
    std::cout << "This application is used to convert USD to AUD\n";
    Sleep(1000);
    int num();
    std::cout << "Enter amount in USD: ";
    std::cin  >> num();
    std::cout << num() << " is " << num() * 1.68 << " in AUD.\n";

    return 0;
}

A: Assuming you're not intending to declare a function named num taking no arguments, and calling it repeatedly, simply removing the parentheses at every use of num (declaration included) should fix your problem. If it's not a callable of some sort, you don't want parens here.


text:
Q: ServerSocket and Multiple Clients from Same IP I understand from earlier SO posts, that you need multiple process (when each process has the same IP) to connect to a ServerSocket. Is this correct?
Then how does a webserver work when you open a website simultaneously in two different tabs of a browser? (Assuming the tabs are running in the same process)
To be exact, I was writing a MJPEG Streamer using ServerSocket, it works fine in one tab of a browser instance, if i open another tab to the same URL, the server never accepts the incoming connection.
How can it be achieved?

A: *

*No.

*Several reasons. Check your server code, debug it when the second client from the same IP is connected.

Does your server work properly, if you open two connections in parallel from different IP addresses? If yes, do you use the client's IP address for something special? If yes, you should consider using IP:PORT of clients as an identifier, not IP only.

A:
Then how does a webserver work when you open a website simultaneously in two different tabs of a browser? (Assuming the tabs are running in the same process)

server serves each request in separate thread.
The basic flow of logic in such a server is this:
while (true) {
    accept a connection ;
    create a thread to deal with the client ;
end while

Go Through Supporting Multiple Clients Section

A: No, a single process can open multiple sockets.  Most browsers can/will open multiple connections a web site to download resources such as CSS and graphics files.  There are several techniques which can be used to handle this.  Usually threading is used, but multiplexed I/O can also be used.
These have different ports on the browser end. The server differentiates connections by IP Addresses and port.  Servers usually use multiple threads, multiple processes, multiplexed I/O, or a combination of these.
The browser should be able to handle multiple tabs connecting to the same web site.  I frequently run multiple multimedia tabs to the same site in Firefox.


text:
Q: How to use fs in Jupyter Lab extension/typescript? I tried to use fs to read a file in an Jupyter lab extension and require() only looks for files under the /lib folder and cannot find it.
WARNING in ./lib/index.js 41:19-32
Module not found: Error: Can't resolve 'fs' in
'C:\Users\Username\Documents\github\jupyterlab_extension\lib'
 @ container entry ./extension[0] ./index[0]

If I use import, the following error occurs:
ModuleNotFoundError: Module not found: Error: Can't resolve 'fs' in 'C:\Users\Matt\Documents\github\py2hex\lib'
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\Compilation.js:2011:28
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\NormalModuleFactory.js:795:13
    at eval (eval at create (C:\Users\Matt\Documents\github\py2hex\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:10:1)
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\NormalModuleFactory.js:275:22
    at eval (eval at create (C:\Users\Matt\Documents\github\py2hex\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:9:1)
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\NormalModuleFactory.js:431:22
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\NormalModuleFactory.js:124:11
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\NormalModuleFactory.js:667:25
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\NormalModuleFactory.js:852:8
    at C:\Users\Matt\Documents\github\py2hex\node_modules\webpack\lib\NormalModuleFactory.js:972:5
resolve 'fs' in 'C:\Users\Matt\Documents\github\py2hex\lib'
  Parsed request is a module
  using description file: C:\Users\Matt\Documents\github\py2hex\package.json (relative path: ./lib)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      C:\Users\Matt\Documents\github\py2hex\lib\node_modules doesn't exist or is not a directory
      looking for modules in C:\Users\Matt\Documents\github\py2hex\node_modules
        single file module
          using description file: C:\Users\Matt\Documents\github\py2hex\package.json (relative path: ./node_modules/fs)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              C:\Users\Matt\Documents\github\py2hex\node_modules\fs doesn't exist
            .js

I've included node in tsconfig file:
"types": ["node"],
"typeRoots": ["node_modules/@types"]

and have installed @types/node using npm install --save @types/node.
Eslint doesn't seem to have a problem with it either after I included "node" in "types" in the tsconfig file, but the compiler just can't pick it up.

A: JavaScript extensions run in browser, not in Node - you cannot use node modules like fs in the browser as it fortunately does not have access to the local file system. You need to either use jupyter-server contents REST API to retrieve the file or create a jupyter-server extension and expose the file with a custom endpoint.


text:
Q: Chat not pinging when name is too short As seen HERE, pings aren't registered when they use less than 3 characters.
His name "C X" is 3 characters, but because of the space and the way spaces are removed for pings it doesn't seem possible to ping him unless it's a direct reply.


text:
Q: Как расчитать требуемый буфер для Unicode перед передачей в _snwprintf_s? Я подумал, что раз в си можно рассчитать требуемый буфер с помощью snprintf, то такой же вариант прокатит и с функцией _snwprintf_s, но как оказалось, при приведенном ниже кодом, данная функция всегда будет возвращать 0.
::size_t size_needed = ::_snwprintf_s(nullptr, 0u, 0u, L"me_window_class[%s]", application_name);
m_class_name_.resize(size_needed + 1u);
::_snwprintf_s(&m_class_name_.front(), m_class_name_.size(), _TRUNCATE, L"me_window_class[%s]", application_name);

Как это можно провернуть не прибегая к использованию std::stringstream?

A: Для этого есть функция _scwprintf


text:
Q: WINAPI: capture mouse click in a ListBox for adding new items I have a Windows application with a ListBox inside a Dialog.
What I want to do is to get a notification when the user clicks in an empty area of the listbox and then add an item that I would get from a new dialog.
How can this be done?
Thanks in advance for your help!
Update1: I added subclassing, and now I get the clicks in Listboxproc.
But I only wanted the clicks outside of existing items, in empty part of the Listbox. How can I check that?
Update2: I tried to call LBItemFromPt() to determine if the click was over an item, but the function always returns -1.
LRESULT CALLBACK ListboxProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam,
                         UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
switch (msg)
{
case WM_LBUTTONDOWN:
    // Listbox was clicked
    long x = LOWORD(lParam);
    long y = HIWORD(lParam);
    POINT p = { x, y };
    int pos = LBItemFromPt(hWnd, p, 0); // always -1 !!!!
    return TRUE;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);

}

LRESULT CALLBACK DlgProc (HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
case WM_INITDIALOG:
 {
     HWND hListBox = GetDlgItem(hDlg, IDC_LISTBOX);
     // Subclassing
     SetWindowSubclass(button, ListboxProc, 0, 0);

     SendMessage(hListBox, LB_RESETCONTENT, 0, 0);
     for(int i=0; i<nItems; i++)
     {
       int pos = (int)SendMessage(h, LB_ADDSTRING, 0, (LPARAM) buf[i]);
       SendMessage(hListBox, LB_SETITEMDATA, pos, (LPARAM) i); // item index
     }
 }
 case WM_COMMAND:
 {
     switch (LOWORD(wParam))
     {
           case IDC_LISTBOX:
            switch (HIWORD(wParam))
             {
                 case LBN_DBLCLK:
                 {
                     HWND hListBox = GetDlgItem(hDlg, LOWORD(wParam));
                     int pos = (int)SendMessage(hListBox, LB_GETCURSEL, 0, 0);
                     int i =(int)SendMessage(hListBox, LB_GETITEMDATA, pos, 0);
                     ... do something with buf[i]
                     SendMessage(h, LB_SETCURSEL, -1, 0);
                 }
                 break;
             }
      }
}
// but how to get clicks in the listbox which are not on an item?

A: You need to convert x, y to screen coordinates:
long x = LOWORD(lParam);
long y = HIWORD(lParam);
POINT p = { x, y };
ClientToScreen(hWnd, &p); //add this line
int pos = LBItemFromPt(hWnd, p, 0);


text:
Q: Every Lipschitz function is the primitive of a measurable function I was doing exercise 5 of this exercise sheet and I don't know how to conclude.
I need to prove that if $f \colon [0,1]\to \mathbb{R}$ is Lipshitz, $X$ is a uniform$(0,1)$ random variable and $$X_n=\frac{\lfloor 2^nX \rfloor }{2^n}$$
then $$f(X_n + 2^{-n})-f(X_n)=\int_{X_n}^{X_n+2^{-n}}g(u)du$$
implies that $$f(x)-f(0)=\int_0^xg(u)du$$
for every $x \in [0,1]$
Any help will be appriciated.

A: You have proved that the equality
$$f(X_n+2^{-n}) - f(X_n) = \int_{X_n}^{X_n+2^{-n}} g(u) \, du \tag{1}$$
holds for any random variable $X \sim U(0,1)$ where $X_n := 2^{-n} \lfloor 2^n X \rfloor$. Now consider the measurable space $([0,1],\mathcal{B}([0,1]))$ endowed with the Lebesgue measure and set
$$X(x) := x, \qquad x \in [0,1].$$
Obviously, $X \sim U(0,1)$ and $$X_n(x) = \frac{\lfloor 2^n x \rfloor}{2^n} \to x \qquad \text{as} \, n \to \infty. \tag{2}$$
Moreover, for any $x \in [k/2^n,(k+1)/2^n)$, we have
$$f(X_n(x)+2^{-n})-f(0) = f((k+1)/2^n)-f(0) = \sum_{j=0}^{k} f((j+1)/2^n)-f(j/2^n).$$
Therefore, it follows from $(1)$ by summation that
$$f(X_n(x)+2^{-n})-f(0)= \int_0^{X_n(x)+2^{-n}} g(u) \, du.$$
Finally, we conclude from $(2)$ and the dominated convergence theorem that
$$f(x) - f(0) = \int_0^x g(u) \, du.$$