text:
Q: How to get 10bit data of ADC using SPI protocol I am doing Single master multiple slave implementation.
Master - PIC18F4550
Slave - PIC18F4520
A potentiometer is connected to the Slave. Slave will convert the Potentiometer value to digital and communicate with the master using SPI protocol.
I am getting 8bit data (ADRESH -- Left justified)correctly from slave. But I have to get 10bit data (ADRESH - 8bit, ADRESL - 2bit).
How can I get 10bit data?
Master code
OpenSPI(SPI_FOSC_64, MODE_01, SMPMID);   //SPI configuration

SSPCON1bits.WCOL = 0;    //Clearing SSPBUF
LATDbits.LATD0 = 0;  //Slave select
WriteSPI(0xFF);  //writing 0xFF to slave
for(mdelay = 0; mdelay < 10; mdelay++);
var1 = SSPBUF;
LATDbits.LATD0 = 1;
highbyte = var1;
highbyte = highbyte << 8;    //deselecting SS
for(mdelay = 0; mdelay < 100; mdelay++);

SSPCON1bits.WCOL = 0;
LATDbits.LATD0 = 0;  //2nd time slave selct
WriteSPI(0xAA);
for(mdelay = 0; mdelay < 10; mdelay++);
var2 = SSPBUF;
LATDbits.LATD0 = 1;
lowbyte = var2;
for(mdelay = 0; mdelay < 100; mdelay++);

highbyte = highbyte | lowbyte;
result = highbyte;

Slave
int Count;
unsigned char ch1,ch2,data;

ADCON0 = 0x01;   // AD Control Register 1: Enable (turn on ADC)
ADCON2 = 0x3C;   // AD Control Register 2: 20 TAD (accuracy), FOSC 4 (freq/4)
ADCON2bits.ADFM = 0;     // ADC result left justified (D10 - D2 --> ADRESH, D1 - D0 --> ADRESL)

TRISCbits.TRISC3 = 1;    //SPI pins(PIC18F4520)
TRISCbits.TRISC4 = 1;
TRISCbits.TRISC5 = 0;
TRISAbits.TRISA5 = 1;

TRISDbits.TRISD0 = 0;    //Configuring PORTD as output
TRISDbits.TRISD1 = 0;
TRISDbits.TRISD2 = 0;
TRISDbits.TRISD3 = 0;
TRISDbits.TRISD4 = 0;
TRISDbits.TRISD5 = 0;
TRISDbits.TRISD6 = 0;
TRISDbits.TRISD7 = 0;

SSPSTATbits.SMP = 0;     //Configuration of SPI register
SSPSTATbits.CKE = 0;
SSPCON1bits.CKP = 0;
SSPCON1bits.SSPM3 = 0;
SSPCON1bits.SSPM2 = 1;
SSPCON1bits.SSPM1 = 0;
SSPCON1bits.SSPM0 = 0;
SSPCON1bits.SSPEN = 1;

while(1)
{

ADCON0bits.CHS0 = 1;     //Selecting AN0 as analog input
ADCON0bits.CHS1 = 0;
ADCON0bits.CHS2 = 0;
ADCON0bits.CHS3 = 0;
ADCON0bits.GO = 1;   //Start analog to digital conversion
while (ADCON0bits.NOT_DONE);
ch1 = ADRESL;
ch2 = ADRESH;

data = SSPBUF;   //loading the SSPBUF value to some dummy varible(Previous data in SSPBUF)

//First time slave select
SSPCON1bits.WCOL = 0;    //Clearing SSPBUF register
while(PORTAbits.RA5 == 1);  //wait for slave select
SSPBUF = ch1;    //Loading ADRESH value to SSPBUF
while(SSPSTATbits.BF == 0); //wait untill the buffer is full

for(Count=0;Count<10;Count++);  //delay

//Second time slave selct
SSPCON1bits.WCOL = 0;    //Clearing SSPBUF register
while(PORTAbits.RA5 == 1);  //wait for slave select
SSPBUF = ch2;    //Loading ADRESL value to SSPBUF
while(SSPSTATbits.BF == 0); //wait untill the buffer is full

for(Count=0;Count<10;Count++);  //delay
}

A: There are a few things that look suspicious to me. On the master side, I would introduce a small delay between setting the slave select signal and sending the dummy data (to start the transfer), though this may not be a problem. The other things that's suspicious is that in your slave code you first have ...
ch1 = ADRESL;
ch2 = ADRESH;

but then
SSPBUF = ch1;    //Loading ADRESH value to SSPBUF
...
SSPBUF = ch2;    //Loading ADRESL value to SSPBUF

So, according to your comments and to the code the master expects, you expect to get the high byte first, then the low byte, but the slave actually sends ADRESL first, then ADRESH.
Lastly, after the first byte transfer you introduce a long(er) delay (mdelay<100) before deselecting SS on the master. On the slave side, there is only a short delay, then you wait for the SS to be set again, which most likely is still set based on the long delay by the master. You then set the second data byte and wait for the BF bit to be set. I'm not familiar with the PIC18F4550, so I don't know if this is an issue, but since you never explicitly clear the BF bit, it might still be set from the first round, which would then cause your slave to restart the main loop (after another short delay).


text:
Q: Load data first before AuthGuard called in Angular I am currently implementing Auth guard in my routes. I want to load data first before auth guard being called. Currently I am doing this.
In my auth-guard.service.ts I have this.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if ( this.authService.isLoggedIn() ) {
      return true;
    } else {
      this.router.navigate(['login']);
      return false;
    }
  }

And in my auth.service.ts
 export class AuthService {

  constructor() { }

  isLoggedIn() {
    return this.getUser() !== null;
  }

  setSession(userId: string) {
    sessionStorage.setItem('userId', userId);
  }

  getUser() {
    return sessionStorage.getItem('userId');
  }

}

And in my routes I am calling Auth guard and DataResolver
const routes: Routes = [
  {
    path: '',
    component: UserComponent,
    canActivate: [AuthGuardService],
    resolve: {
      data: DataResolver
    },
    children: [
      {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full',
      },
      {
        path: 'dashboard',
        component: UserDashboardComponent,
        data: {
          breadcrumb: 'Dashboard',
        },
      }
    ]
  ]

DataResolver
@Injectable({
  providedIn: 'root'
})
export class DataResolver {

  constructor(private authService: AuthService,
              private activatedRoute: ActivatedRoute) { }

  resolve() {
    this.activatedRoute.queryParams.subscribe((data) => {
      const userId = data.userId;
      if (userId) {
        this.authService.setSession(userId);
      }
    });
  }
}

Why it is still calling the auth guard first. What I want to to call the DataResolver first before the auth guard.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solving cross product equation $a\times x =3/4x-1/4a$ To be honest I don't completely understand this problem, by definition - cross product is a vector and this vector is orthogonal to vectors involving in cross product, but here i see that vector of cross product is a linear combination of vectors $a$ and $x$, so it's means that this vector is coplanar to $a$ and $x$, am I wrong?
But okay, I did this following
Let $$a\times x=b$$ Then $$x =\alpha a +\beta[a\times b]$$ Where $\alpha$ and $\beta$ are projections, hence $$\alpha=(x\cdot a)/|a|^2$$
$$\beta=1/|a|^2$$ $$[a\times b]=[a\times(3/4x-1/4a)]$$ $$[a\times b]=3/4[a\times b]$$ $$x =\alpha a +   3/4\beta(1/4a-3/4x)$$ it's leaves us with $$x = (16\alpha+3\beta)/(16+9\beta)a$$ so I've got that this vectors are colinear, it's very confusing, $$x=(16(x\cdot a)+3)/(16|a|^2+9)a$$ no matter what I'm doing I'm still having this result, but you all see that in this case $x$ and $a$ are zero vectors, idk, where is my mistake?

A: You are right that normally the cross product of two vectors cannot be co-planar to those vectors, unless something turns out to be zero - either $a$, $b$, or $a\times b$.
If $a$ or $b$ is zero, so is $a\times b$, and the equation forces both $a$ and $b$ to be zero. If $a\times b$ is zero, then the equation becomes $$0=\frac{3}{4}x - \frac{1}{4}a$$
with the solution $$a=3x .$$
That is, the two vectors are parallel - another situation in which the cross product is zero.


text:
Q: How to install/enable php-exif in cpanel According to this link and this answer I have to configure PHP with --enable-exif and add extension, but the problem is I don't know how to configure PHP with --enable-exif and I cannot find the way to edit php.ini to add extension=exif.so
I don't have WHM credentials and cannot access EasyApache, I only have cpanel user login with limited access..
My php version
[user@server ~]$ /opt/cpanel/ea-php73/root/bin/php -v
PHP 7.3.18 (cli) (built: May 21 2020 03:33:34) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.18, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.18, Copyright (c) 1999-2018, by Zend Technologies

Is there a way to enable php-exif or should I ask my ISP/Administrator?

A: It seems you don't have full WHM access.
Php EXIF is generally enabled on most of the servers.
To check if you have EXIF enabled create a PHP file in your cPanel file manager and paste this code in that file:
<?php phpinfo(); ?>

then visit that page.
It will show all PHP information. Search for EXIF there.
If it is disabled then ask your server administrator to enable that for you.


text:
Q: Tikz pump symbol is there a symbol for pumps like the attached one?

Thank you!

A: Easy enough to make. One of many ways of doing so is a node style with a path picture.

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\tikzset{
  pump/.style={
    circle,
    draw,
    thick,
    minimum size=1cm,
    path picture={
      \draw [thick] (path picture bounding box.north) --
                    (path picture bounding box.east) --
                    (path picture bounding box.south);
      },
  node contents={}
  }
}
\begin{document}
\begin{tikzpicture}
 \node[pump];
\end{tikzpicture}
\end{document}

A: Another approach with TikZ.

\documentclass[12pt]{article}
\usepackage{pgf,tikz}

\newcommand{\cirtri}[1]{%
\begin{tikzpicture}[#1]
\draw [line width=.5pt] (0.,0.) circle (2.cm);
\draw [line width=.5pt] (0.,2.)-- (2.,0.);
\draw [line width=.5pt] (2.,0.)-- (0.,-2.);
\end{tikzpicture}%
}

\begin{document}
It is \cirtri{scale=.03mm} a new symbol.

\end{document}


text:
Q: connection between Android and windows 7 I want to do android application. using windows server and client is android. application send to message from android to server and server save that message to sql.in android i want to see message to which come to me.have you got any example for sending messege to server from android.

A: Your question is very broad. You did not specify with what language you want to program your server.
As a start you should create simple Android TCP Client and simple TCP server.
Look at this threads:
Android (Java) network programming resources,
http://www.anddev.org/socket_programming-t325.html to get basic information on topic.

A: You seem to have no Idea (yet) as how to make a connection. Forgive me if I'm wrong, but that might mean you are not a really experienced programmer, and your question here implies some sort of time-pressure or at least not the willingness to dive too deeply into the material.
Therefore I'd suggest you take the 'easy' route, that might not be the most efficient in all cases, but would be usefull enough for a number of things.

*

*use a webserver and some files (php?) that can add rows to the database when they are requested.

*call these pages in your application trough standard HTTP.

Both of these steps are easy to graps as a concept, and you can find the how and why a lot easier if you understand the method.
No real catches here.


text:
Q: Scala Spark : Creating variable that contains col names for partition I want to make several columns that will sum over other column partition by several columns. I want to make a variable that contains all the col names for the partition by, in that way my code will be cleaner. It goes like this
var myunit = $"reporttype_code", $"review_code", $"businessgroup_code",
           $"company_code", $"grade_code", $"terminationtype_code"

var semesterly = Window.partitionBy(myunit, $semester)
              .orderBy($year, $month)
              .rowsBetween(Window.unboundedPreceding, Window.currentRow)
var quarterly = Window.partitionBy(myunit, $quarter)
              .orderBy($year, $month)
              .rowsBetween(Window.unboundedPreceding, Window.currentRow)

test =  test.withColumn("turnover_over_semester", sum($"val1").over(semesterly))
            .withColumn("turnover_over_quarter", sum($"val1").over(quarterly))

I'm gonna make a lot of columns which includes parition by var unit. But the var raised error : expected ; but , found Is it possible to create the var other way?


text:
Q: C++11 decltype: How to declare the type that a pointer points to? I have the following code:
#include <memory>

int main()
{
    int* a = new int(2);

    std::unique_ptr<decltype(*a)> p(a);
}

which leads to these error message:
In file included from a.cpp:1:
In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/memory:81:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/bits/unique_ptr.h:138:14: error: '__test' declared as a pointer to a reference of type 'int &'
          static _Tp* __test(...);
                    ^
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/bits/unique_ptr.h:146:35: note: in instantiation of member class 'std::unique_ptr<int &,
      std::default_delete<int &> >::_Pointer' requested here
      typedef std::tuple<typename _Pointer::type, _Dp>  __tuple_type;
                                  ^
a.cpp:7:35: note: in instantiation of template class 'std::unique_ptr<int &, std::default_delete<int &> >' requested here
    std::unique_ptr<decltype(*a)> p(a);
                                  ^
In file included from a.cpp:1:
In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/memory:81:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.9.2/../../../../include/c++/4.9.2/bits/unique_ptr.h:227:33: error: 'type name' declared as a pointer to a reference of type 'int &'
               is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
                                       ^
a.cpp:7:35: note: in instantiation of template class 'std::unique_ptr<int &, std::default_delete<int &> >' requested here
    std::unique_ptr<decltype(*a)> p(a);
                                  ^
2 errors generated.

I understand the reason is that the unique_ptr template expects type int, but decltype(*a) gives int&. In the case that int is a very long and complicated type, how can I make this code work with decltype?

A: You can use a typedef inside a templated class and then use template specialisation, like this
template<typename T> struct unref {
  typedef T raw;
};
template<typename T> struct unref<T&> {
  typedef T raw;
};

int main() {
    int* a = new int(2);
    std::unique_ptr<unref<decltype(*a)>::raw> p(a);
}

A: Use std::decay_t. This is the conversion that is applied when you pass an argument to a function by value.


text:
Q: Mounting windows share to Rasbian Jessie I have read a lot of posts on this but nothing i try seems to work.
I have a windows 10 machine which has a share on it. The share does not require a username or password to access.
I can ping the machine from the pi fine. The share has permission "everyone" full access
i have tried cifs with no luck, but if i type this into a terminal window
sudo mount //192.168.1.153/Mybook /mnt/Media
It asks me for my password. I just hit enter with no password and it mounts.
I then umount /mnt/Media
I then try to add to fstab
//192.168.1.153/Mybook /mnt/Media cifs guest,uid=1000,gid=1000 0 0
I have tried writing the above many different ways this is just the last way i have tried.
I then exit and try to do
sudo mount -a and nothing happens it just hangs.
I do a reboot and then check df -h and its not there.
I am out of ideas on what to try. Please help.

A: I finally gave up and just added a windows password to my share.


text:
Q: How to center a div on multiple devices I have a div which contains some anchor tags which contains an image. Is there a way by which i can center the div in multiple devices no matter what the width of devices is?
Here is the code:

         sample text

         sample text

         sample text

Each anchor tag has a fixed width and height and depending on width of screen some times 2 anchor tags display in a row and sometimes 3.
Here is my css:
 @media(max-width:480){
  .jaffa a{
  width:200px;
  height:90px;
  padding:20px;
  }
  @media(min-width:481){
  .jaffa a{
  width:140px;
  height:90px;
  padding:20px;
  }

A: if position static (default) you have to use margin:0 auto; else use left:50%;  margin-left:-(half of the width of your div)

A: try this img {margin-left: auto; margin-right: auto;} This will center the image exactly in the middle of the container no matter the width is.
If you face any problems with the height you can also try:
margin-top:auto; margin-bottom: auto;


text:
Q: Put up at vs. put up in Consider the following examples:

*

*We put up at a hotel in the city centre.

*We put up in a hotel in the city centre.

To me, the first example sounds better than the second one. Can we use the preposition "in" after the phrasal verb "put up" here?

A: You can use either preposition. Neither is more 'natural' or 'better'.

Put up
  verb 6a
  INTRANSITIVE OLD-FASHIONED
  to stay for a short
  time in a place that is not your home
  put up at/in:
  We put up at a
  cheap hotel.

Put up (Macmillan Dictionary)


text:
Q: Error con git desde windows 10 Tengo el siguiente inconventiendo con git
Commit failed with error:

The Git process exited with the code -1.073.741.819

El siguiente error me sale al hacer commit y push
Al igual cuando intento hacer pull me da como respueta el mensaje que se mustra a continuación:
Fetch failed

fatal: UriFormatException encountered

Pregunto si es un problema de compatibilidad o algo parecido...
Cabe destacar que he clonado mis proyectos sin ningún tipo de inconvenientes..
Como también he realizado las configuraciones tanto del nombre de usuario como el email.
De antemano muchas gracias por la ayuda que me puedan aportar!

A: El problema era porque Tenia instalada la versión mas actual de git que era la 2.13.1 la desinstale e instale la versión 2.10 que era la versión que utilizaba anteriormente Y funciona correctamente. Al parecer es un problema con la versión 2.13. de git que generaba ese problema en windows.


text:
Q: How can I replace words in a string and add id in Javascript

var list = [{
    name: "koala",
    owner: "mark"
  },

  {
    name: "opossum",
    owner: "lala"
  },

  {
    name: "dog",
    owner: "lucia"
  }
];

var str = document.body.innerHTML;
var toChange = /fox|penguin|cat/ig;

for (let listItem of list) {
  str = str.replace(toChange, listItem.name);
  str.id = 'span';
  document.body.innerHTML = str;
  console.log(listItem.name);
}
span {
  text-decoration: underline;
  color: red;
}
The fox jumps over the bush, the penguin walks, the cat drinks.

What I basically want to do is to replace the animals in the HTML text with the animals in "list". Additionally I want these last changed animal names to change color as well. I managed to replace with the animal Koala, but I am not really sure why it only replaces with Koala, as if I console.log(listItem.name) I get all three animals. Is there a problem with the for loop?

A: I think this is what you want to do. As Heretic Monkey pointed out, using only one regex like that doesn't work. You can't set an id on a string. Also, ids must be unique, so you can't set the same id to various elements.

var list = [{
    name: "koala",
    owner: "mark"
  },

  {
    name: "opossum",
    owner: "lala"
  },

  {
    name: "dog",
    owner: "lucia"
  }
];

var str = document.body.innerHTML;
var toChange = [/fox/ig, /penguin/ig, /cat/ig];

for (let i = 0; i < list.length; i++) {
  str = str.replace(toChange[i], `<span>${list[i].name}</span>`);
  document.body.innerHTML = str;
  console.log(list[i].name);
}
span {
  text-decoration: underline;
  color: red;
}
The fox jumps over the bush, the penguin walks, the cat drinks.

A: Replace the corresponding portion of your code with this:
var toChange = [/fox/ig, /penguin/ig, /cat/ig];

for (let listItem of list) {
  str = str.replace(toChange[list.indexOf(listItem)], listItem.name);

Result:
The koala jumps over the bush, the opossum walks, the dog drinks.

A: You are just replacing the whole HTML content not appending so you need to create a new span element and add that element in body also you can use innetText in place of innerHtml as innerHtml will give inner element as well with the text.

var list = [{
    name: "koala",
    owner: "mark"
  },

  {
    name: "opossum",
    owner: "lala"
  },

  {
    name: "dog",
    owner: "lucia"
  }
];
var htmlText = document.body.innerText;
var toChange = /fox|penguin|cat/ig;
var spanComponent='';
for (let listItem of list) {
  var str =  htmlText.replace(toChange, listItem.name);
  console.log(str)
  var span = document.createElement('span')
  span.innerText = str;
  document.body.appendChild(span);
}
The fox jumps over the bush, the penguin walks, the cat drinks.

Please run the snippet.


text:
Q: Python code to generate an alternative python code Related:Seeing all the values of variables in python as it is run
I wanted to see the value of variables whenever the value of the variable change, so that I can easily spot where I wrongly coded.
I know if I add lines like
print('i=',i)

then I can see it, but it 1) makes whole code dirty, 2) takes long time to add these lines.
So if I have a something like print_adder.py  that automatically changes code.py and save it as code2.py, that will be great. Can it be possibly done?
code.py
i=0
for i in list:
    i=i+1

code2.py
i=0
print('i=', i)
for i in list:
    i=i+1
    print('i=', i)

And would it be also possible to show only small portion of the value if it the variable is too large like 10000 element list?


text:
Q: Create Entity-Relationship Diagram from MySQL Database I am trying to create an Entity-Relationship Diagram by reverse engineering a MySQL database using a .SQL file. The process has been successful, using MySQL WorkBench and Toad Data Modeler. However, the diagram that both tools generate does not show the relationships between entities. So the diagram is of little use.
Having asked the software's technical support team why this is so, the reply is that they have used ADODB as a database abstraction layer in order to support several DBMSs, and ADODB doesn't explicitly define foreign keys. My question is, is there a tool that can generate these relationships by making guesses related to column names etc.?
They also mention that they use an XML descriptor to view the database structure. So is it possible to generate a diagram from the XML document?
I would generally create the ERD myself, but the database contains 99 tables and would be an extremely tedious process.
Thanks a lot,
Amy

A: Another is ERWin by CA. Its fanatastic tool to reverse and forward engineer databases and can infer relationships from column names. Its very costly though, i have used the trial version.

A: I have found the answer to my question:
In Toad Data Modeler, there is a function that infers the relationships between tables based on field names etc. In the Menu, it is under Macros -> All -> Infer Relationship.
I haven't checked that the relationships are completely accurate, but it appears to have worked well.
Thanks,
Amy


text:
Q: How do I generate a diff or patch file only showing the differences of the files included in another patch file? I was banging my head into my wall looking for an easy way to do this but couldn't find anything online, so I figured I'd share the solution I came up with.
This is useful for when you need to break apart specific diff files.

A: So while working on a bigger company project that required the issue being broken into multiple tickets, I found myself needing to create separate diff/patch files for each ticket, even though I was working on the same branch with quite a few file changes. Each patch file needed to only contain the differences for specific files, which you can do with:
git diff master FILENAME_X FILENAME_Y FILENAME_Z (etc.)

but that was quite time consuming to do manually for each file every single time I needed to generate a patch, and it includes the possibility of me forgetting files every time.
The following command will create a diff/patch file of all files included in a different patch file:
`cat NAME_OF_INPUT_DIFF.diff | grep "+++" | awk -F "+++ b/" '{if (NR == 1)printf "git diff master " $2; else printf " " $2}'` > NAME_OF_OUTPUT_DIFF.diff

The cat NAME_OF_INPUT_DIFF.diff | grep "+++" breaks the previous diff into only the lines with the names of files that were added/modified, then awk -F "+++ b/" breaks that into just the parsed names of the files, stripping the preceding characters. The rest creates the lengthy git command to generate a diff of specific files, and wrapping it all in backticks makes it be evaluated on execution. Then > NAME_OF_OUTPUT_DIFF.diff outputs the resulting diff to a file.
Anyways, I hope this helps someone like it did me! Quite a timesaver.


text:
Q: jQuery myClass.click not working but html.click function is working for the life of me I can't figure this out. I've tried classes, IDs and regular element selectors. Below is a snippet I'm trying to run.
$(document).ready(function () {
    $(".myClass").click(function () {
        console.log("Hello!");
    });
});

The example above will NOT run. However when changing it to the example below it will run.
$(document).ready(function () {
    $("html").click(function () {
        console.log("Hello!");
    });
});

Example HTML below

Map Key

        Last Truck Location

        Delivered Load

        First Pick

        Additional Pick

        Check Call / Previous Location

        Additional Drop

        Final Drop

It seems as if anytime I try to tie my function to a class or ID it doesn't want to run. I have also tried the .on("click", function()) method as well with the same results.
Any help would be greatly appreciated! I've never ran into this before.
Thanks!

A: Your code runs, but cause is  element, it refresh all the page and as result you don't see the console.log. If you really want to add click event on , you should add the following line.
$(document).ready(function(){
    $(".myClass").click(function(e){
        e.preventDefault();
        console.log("clicked");
    });
});

The variable eand the function preventDefault() is the key here. As you can guess the preventDefault doesn't run the default code for  so it will not refresh your page.
I hope to help you a bit


text:
Q: ObjC Realm Threading issue I have a Realm object (LFEMemory) which has a publish method.
When I call the publish method, I have to upload an image to AWS and then update the object with the URL returned by Amazon.
The problem is that when the block returns from AWS, my self LFEMemory object is no longer thread-safe. (In fact, it usually is during the usual running of the app but never if I'm using an App Extension).
I could fix this by removing the publish method from the realm object, and handling it in a controller object, which can fetch a new realm object on the new thread.  But that means I need to create new realms everytime I call a block, which surely isn't a good practise.
How do most people handle this situation?
- (void)publishWithBlock:(ResultBlock)block {

    FileUploadManager *manager = [[FileUploadManager alloc] init];
    [manager uploadWithSuccess:^(NSString *filename) {

        //self is no longer thread-safe and will cause a crash
        self.media.path = filename;

    } failure:^(NSError *error) {
        block(NO, error);
    };
}

A: You have various options you can explore:
1) if your object has a primary key (string or a number) you can store the id as a constant inside the method and use it to fetch back the object from any thread by using [Realm objectOfType:forPrimaryKey:]. docs
Don't be afraid to get a new realm from the different thread if that's what you need to do - that does not create "another" Realm or duplicate your file.
2) if you don't have a primary key you can simply create self.media on the main thread and whenever the upload has finished, switch again to the main queue and modify your object there - modifying a property or two on a Realm object will not harm at all your performance on the main thread.
Further - if you have access to your object (as in self.media) it already gives you access to the original Realm used to create / read the object via its realm property docs
Still - I'd go with using the primary key of the object to re-fetch a reference to the object I need if in doubt.


text:
Q: Given the polynomial: x^2 +ax + b. Find the roots. QUESTION:
Let (a,b) in $R^2$ be an arbitrary point on the plane.
We need to color it RED, WHITE, OR BLUE according to the following scheme:

*

*(a,b)is RED if $x^2 + ax + b $ has two different real roots.

*(a,b) is WHITE if $x^2 + ax + b$ has no real roots.

*(a,b) is BLUE if $x^2 + ax + b$ has a real root which occurs twice.

Color this plane according to the scheme(use colors) and give justification for your coloring.

My attempt to do this problem:
But i cant graph the points.

A: You've basically done all of the hard work -- it's just a matter of interpreting your results.
You've shown that the equation $x^2 + ax + b = 0$ has one solution if $b = \left(\frac{a}{2}\right)^2$, has two solutions if $b < \left(\frac{a}{2}\right)^2$, and has no solutions if $b > \left(\frac{a}{2}\right)^2$.  So draw the curve $b = \left(\frac{a}{2}\right)^2$ in blue, color below it in red, and color above it in white.


text:
Q: Google Analytics and cookies My question is: I'm developing a website and I want to monitor analytics with Google Analytics, however I've been reading articles about cookies and I didn't realize if I need to program my website with some kind of cookies in order to use google tool, or if I simply don't need to do anything on my website.
Thanks

A: To do tracking you simply need to insert the code snippet that you can get from the GA admin interface.
However since you are in the EU you need to point out to your visitors that they are being tracked on your web page and that the site uses cookies to do so (and I think you need to provide an opt-out, although that might be a German thing). This is mandated by the European Privacy directive, which is sometimes referred to as "Cookie Law" (technically incorrect, since it is neither a law nor specifically about cookies), so maybe this gave you the idea that you need to do extra programming.


text:
Q: VBA/ACE OLEDB/SQL Run-Time error -2147217913 Data type mismatch in criteria expression I am running a SQL query from VBA using ACE OLEDB without connecting to Access. I do this so I can smash together quickly some Excel tables. I am not looking to transition this to another platform so would prefer to resolve the current issue.
VBA code works without issue for numerous queries but I am running into the mentioned error for the following query:
SELECT
    bcr.DialCode,
    bcr.Destination,
    (
        SELECT
            TOP 1 cc.CountryCode
        FROM
            table2 AS cc
        WHERE
            bcr.DialCode LIKE cc.CountryCode+'%'
        ORDER BY LEN(cc.CountryCode) DESC
    ) AS CountryCodes
FROM
    table1 AS bcr

Code adapted from: Longest prefix match in SQL Server 2000
The intention is to match dialed telephone numbers to the destination country by finding the most inclusive match. Reusing the quoted text sample of input and expected results (adapted to this exercise):
bcr.DialCode = '0841234567'

cc.CountryCode = {'084',
                 '0841',
                 '08412'}

Expected output = {'0841234567','Destination 1','08412'}

From searching online seems like maybe I'm using a reserved word in the query. But I have tested different parts of the query individually and don't get any errors. For example:
SELECT
    bcr.DialCode,
    bcr.Destination
FROM
    table1 AS bcr

Works as expected. Also:
SELECT
    TOP 1 cc.CountryCode
FROM
    table2 AS cc
WHERE
    cc.CountryCode LIKE '1'+'%'
ORDER BY LEN(cc.CountryCode) DESC

Has no errors and outputs the expected results.
The variable used to pass the query to the ADO connection is dimmed as String but I have tried setting as Variant with no change.
Is there perhaps a difference in the implementation of SQL through ACE for which the "Longest prefix match" query doesn't work? Any guidance will be greatly appreciated.

A: First of all, please read my comment to the question.
Secondly, please read these articles:
I get a message about data type mismatch
MS Access 2003: LIKE condition (using wildcards)
Finally, if you would like to compare one data to another which StartsWith("SomeString"), you can use something like this:
SELECT
    bcr.DialCode,
    bcr.Destination,
    cc.CountryCode
FROM table1 AS bcr
    INNER JOIN table2 AS cc
    ON cc.CountryCode = LEFT(bcr.DialCode, LEN(cc.CountryCode))
ORDER BY LEN(cc.CountryCode) DESC;

For further details, please see: MS Access: Left Function
Note: Do not forget to use [;] at the end of query. MS Access database likes it ;)


text:
Q: Why does this MVC4 Web API route not work compared to an ASP.NET website project? In a MVC4 Web API project has the "itemtypelist" route below
public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  );

  routes.MapRoute(
  name: "itemtypelist",
  url: "{controller}/list/{itemtype}/{searchtext}",
  defaults: new { controller = "home", action = "list", itemtype = (string)null, searchtext = (string)null }
  );

}

which is intended to map to the following controller action
[AcceptVerbs("GET", "POST")]
public IEnumerable<Repository.ViewModel.Brand> List(string itemType, string searchText)

and URL
/api/brand/list/mytype/mysearchtext

However, the URL returns a 404 message. This route and controller action work in a website project, but not in the Web API project. What is different in the MVC4 Web API project that would cause the action not to be found?

A:
What is different in the MVC4 Web API project that would cause the action not to be found?

Everything is different. Absolutely everything. Starting from the way you configure your API routes, going through the entire model binding, up until the base controllers. So basically you forget everything you know about ASP.NET MVC if you want to develop a Web API. Microsoft have duplicated every single thing. It's a new design, new assemblies, new namespaces, new API. Nothing to do with ASP.NET MVC.
So if you want to configure Web API routes you need to use the MapHttpRoute extension method and not the MapRoute which is only for standard MVC controllers. Do not confuse the base System.Web.Mvc.Controller (which you are accustomed in using in your MVC applications) with the System.Web.Http.ApiController (which is the base class for your API controllers). Those are two completely different beasts.
So here's how to configure a route for an ApiController:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "DefaultAPI",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Also notice that in a RESTful API you do not specify the action name in the route. It is assumed from the HTTP verb used to consume it. Here's a good article I recommend you reading about RESTful routing in the Web API.
By the way if you create a new ASP.NET MVC 4 project using either the internet or the empty template you will notice that Visual Studio will create 2 files for you:

*

*~/App_Start/RouteConfig.cs - where you put all your standard MVC routes

*~/App_Start/WebApiConfig.cs - where you put all your Web API configuration (including routes, custom formatters, ...)

You will also notice that they are using 2 completely different approaches. Do not forget that the Web API could be self hosted, for example in a Console Application. That's why Microsoft decided to implement everything from scratch. They didn't want any coupling with ASP.NET MVC.


text:
Q: How do I find out which dlls an executable will load? If I have a Windows executable, how can I find out which dlls it will load?
I'm just talking about which ones that will be loaded statically, not ones it might load dynamically with something like LoadLibrary.

A: dumpbin is a tool that comes with VC++.
To see what DLLs a program will import:

*

*Open Visual Studio

*Menu Item Tools | Visual Studio Command prompt

*cd to folder containing executable

*dumpbin /dependents whatever.exe

Dump of file whatever.exe

File Type: EXECUTABLE IMAGE

  Image has the following dependencies:

    AIOUSB.DLL
    sqlite3.dll
    wxmsw293u_core_vc_custom.dll
    wxbase293u_vc_custom.dll
    KERNEL32.dll
    ole32.dll
    OLEAUT32.dll
    MSVCP90.dll
    MSVCR90.dll

To see what functions (and DLLs) it will import, use
C:\> dumpbin /imports whatever.exe

A: There are utilities that will do this for you.
In the past I've used the MS tool (depends.exe) that came with (I think) VB.:
VS2010
VS2012
VS2013
VS2015
Current
and there's this as well:
http://dependencywalker.com/
and probably others as well.

A: Solution for Microsoft .Net:
foreach (AssemblyName a in Assembly.ReflectionOnlyLoadFrom("SAMPLE.EXE").GetReferencedAssemblies())
{
    MessageBox.Show(a.Name);
}

A: Open the command prompt and then type below command
tasklist /m /fi "imagename eq netbeans.exe"
Type instead netbeans.exe whatever name your exe file name.

A: There is a handy tool called NDepend that will give you all DLL dependencies.

A: Dependency Walker can help you determine which .dll will be loaded.

A: Just go to the command prompt and type tasklist /m, you will see the list of dll files used by specific program.

A: progfr is simple and useful:
[http://members.fortunecity.com/michaelmoser/tip11.htm]

A: Dependencies - An open-source modern Dependency Walker shows which DLLs a Windows executable will load and it works well in modern Windows 10.
It is a little less powerful than Dependency Walker, but the latter may or may not work in Windows 10 as it was last updated in 2006. (Newer versions of Dependency Walker were bundled with some versions of Windows Development Kit for Windows 10, but not any more.)

A: Process Explorer
Comes with SysInternals Suite
https://learn.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite
Benefits: allows to explore the process that is already running (I have not found a was to attach the dependency walker to the existing process)


text:
Q: Count specific character in string using SubString I'm teaching myself VB.net and I'm trying to complete challenges.
I'm stuck on this challenge.
I'm trying to figure out how to go about counting specific characters in a string using SubString.
I should not use string processing functions other than: Trim, ToUpper, ToLower, Indexof, SubString.
Add one button for each vowel of the alphabet. When clicked, the output is the count of that vowel in the text entered.Using SubString, the code under the button click event handler,displays how many times the corresponding character appears in the text.
This is what I have so far, but how should I incorporate SubString?
    Dim counter As Integer = 0
    For Each vowelA As Char In TextBox1.Text
        If vowelA = "a" Then
            counter += 1
        End If

        If vowelA = "A" Then
            counter += 1
        End If

    Next

A: Here I incorporated also .ToUpper so you don't need to compare "a" and "A"
Dim counter As Integer = 0
For i = 0 To TextBox1.Text.Length - 1
    If TextBox1.Text.ToUpper.Substring(i, 1) = "A" Then
        counter += 1
    End If
Next

A: Without using a substring() function,
 Function count_vowels(ByVal str As String, ByVal chr As String) As Integer
        str = str.ToUpper()
        chr = chr.ToUpper()
        count_vowels = str.Split(chr).Length - 1
        Return count_vowels
 End Function

Usage:
Dim counter As Integer = 0
counter = count_vowels(TextBox3.Text, "a")

or simply use
 counter = TextBox1.Text.ToUpper.Split("a".ToUpper).Length - 1

A: Try something like this:
    Dim pos As Integer = 0
    Dim letter as String
    While pos < TextBox1.Text.Length
        letter = TextBox1.Text.Substring(pos, 1)
        If letter = "A" Then
            counter += 1
        End If

        pos += 1
    End While


text:
Q: How best to reduce dimensionality of a dataset composed of events and trials? I'm trying to reduce dataset dimensionality. PCA is a good metric but that gives me new dataset. My goal is to determine from number of events (e.g. 60) and number of trials (e.g. 6) which events are more relevant.
For example:

*

*1st, 3rd, 21st, 45th ... (N total) events are good enough to approximate behavior of dataset.
That will allow me to discard  60-N events, and to deal with only N.

For now, I'm calculating covariance matrix, and take events for which correlation is smaller than some threshold.
Is there some official metric or math function for this?

A: What you are describing is not dimensionality reduction, but rather sampling. If your data is labeled (which I couldn't understand from your question), then most probably you would want to perform stratified sampling - a random sampling that ensures that each label is sampled with a probability that approximately equals to that in the original data set.
See this Wikipedia article on sampling techniques. It provides a list of good reading material on this matter

A: I think that any answer depends heavily on your notion of 'relevant' and also on the question why you want to do this.
Anyway, an approach that might work for you is sth like 'stemming'. This originates from natural language processing, where the events 'played' and 'playing' are both mapped to the equivalence class 'play'.
A way to do this for arbitrary real valued data is to use a clustering method (eg K-Means) with as many centroids as you want items in your new dataset. After fitting K-Means, you keep those centroids as the new dataset.


text: Q: How do I sync my iPhone 8's contacts to my 2014 Honda Accord? I have an iPhone 8 connected to my 2014 Accord via HandsFreeLink (this is different than CarPlay). However, it won't sync my phone book to my vehicle. I get the error "Unable to import phonebook". How can I import my contacts to my vehicle? I'm using iOS 11.4.


text:
Q: Preventing XSS attacks to dynamically created DOM webpages and dynamically generated javascript event handlers I have read the following article:
https://msdn.microsoft.com/en-us/library/bb355989.aspx
Now this article allows me to understand XSS vulnerability defense to a webpage that is statically made up of asp and html controls built on a webpage as in true markup layout fashion. I now understand that that control input should use not only server side in validation but input should validate length, range, format and type. The question I have is that I am trying to sanitize a website where the page layout controls are build on to the DOM object dynamically when the page loads. For example on the page load event methods add controls to the document object one at a time in the method that builds the entire webpage during that calling method. Also, control event handling is done by methods that send concatenated JavaScript strings, during page load,  as output to the page that handle page control events. I guess my question is, how do I use asp.net validation controls, regex checking, etc. functionally when everything is built, the DOM and JavaScript event handling on the loading of the webpage?

A: I'm afraid the MS article has misled you. It represents a misguided, discredited approach to handling injection issues. (ASP.NET Request Validation in particular is an unreliable waste of your time.)
Input validation is valuable for ensuring incoming data conform to expected business rules and doesn't contain confusing characters like control characters, but it is not a reliable means of preventing HTML or JS injection issues leading to cross-site-scripting.
The way to prevent injection issues is, whenever you are inserting text into a wider context, to encode the text to fit that context. So, when you're templating a string into HTML, HTML-escape it; when you're putting a parameter into a URL, URL-escape it; when you're writing a string into a


text:
Q: Convert internal.Writable to NodeJS.WritableStream I want to output sound to my speaker using ytdl-core and fluent-ffmpeg
I get the sound from yt and use ffmpeg to convert it to pcm and now i want to pipe it to my speaker
speaker uses internal.Writable
naudiodon uses NodeJS.WritableStream
when piping to speaker everything works
when piping to naudiodon I get a typescript error and hear nothing
What is the difference between the two streams and can I convert them, because I need to use naudiodon because there I can specify my output device
Edit:
WritableStream is a Web API and internal.Writable is from Node.js
Can I convert a Writable to a WritableStream?
Github Issue


text:
Q: Avoid rotation of EKEventEditViewController How to avoid rotation of EKEventEditViewController? In my case I need to restrict it to Portrait only. Can we change the navigation controller of EKEventEditViewController?

A: Found a workaround.
Create a subclass EKEventEditViewController, and in that class override
-(BOOL)shouldAutorotate{
//Does not support anything other than portrait
   return NO;
}

Then in use that custom class instead of EKEventEditViewController.


text:
Q: Cannot make https request to my Application Load Balancer - AWS I have and Application Load Balancer (AWS) that has 2 EC2 as targets.  I am also using Route 53 to route my domain name to my load balancer.  So all http requests to my domain name works, but my https request fails.  I do not understand why.  I have done the following:

*

*I created a domain name in route53 and have been issued with a SSL/TLS certificate through AWS Certificate manager.

*For my load  balancer I set up  listener for https:443 and attached the above certificate with it.

*The security group for my ec2 instances allow http and https requests (although I believe the load balancer ec2 target will communicate using http)

I am totally out of ideas.  I have read the aWS documentation, done what they have instructed and I am not able to make https request.  Please can someone advise?
Result of https  request:
"(red triangle)Not secure https(crossed out)" - this appears in the browser. but it connects anyway.

A: If you're trying to access via lifescienceecosystem.eu, without www or another sub-domain then you'll get this error. You'll need to reissue your cert for lifescienceecosystem.eu and *.lifescienceecosystem.eu (or www.lifescienceecosystem.eu if you only want www).

A: Can you clarify the following points

*

*Have you configured your certificate in the load balancer (ELB)?

*How you have configured your ELB to route HTTPS requests? 443 to port 80 of your EC2 OR 443 to 443 of your EC2?


text:
Q: what's the difference between Expires and Cache-Control headers? What's the difference between Expires and Cache-Control headers?

A: Heroku devcenter has an excellent article on this subject.
Quoting from it,

While the Cache-Control header turns on client-side caching and sets the max-age of a resource, the Expires header is used to specify a specific point in time the resource is no longer valid.

A: If you are using a CDN (Cloud Delivery Network) I recommend to use Cache-Control with a max-age time in seconds. For example Cache-Control: max-age=604800.
This prevents request-peaks to your origin-server: With "Expires Wed, 30 Oct 20xx 04:37:07 GMT" all browsers will request you at the same time.

A: According to this Google Developers article, HTTP Caching:

Cache-Control header was defined as part of the HTTP/1.1 specification
  and supersedes previous headers (e.g. Expires) used to define response
  caching policies. All modern browsers support Cache-Control, hence
  that is all we will need.

A: Cache-Control was introduced in HTTP/1.1 and offers more options than Expires.  They can be used to accomplish the same thing but the data value for Expires is an HTTP date whereas Cache-Control max-age lets you specify a relative amount of time so you could specify "X hours after the page was requested".
HTML Cache control is a very similar question and has a good link to a caching tutorial that should answer most of your questions (e.g., http://www.mnot.net/cache_docs/#EXPIRES).  To sum up though, Expires is recommended for static resources like images and Cache-Control when you need more control over how caching is done.

A: Cache-Control was defined in HTTP/1.1, tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds: Cache-Control: max-age=3600.
The Expires header field gives the date/time after which the response is considered stale. The Expires value is an HTTP-date timestamp: Expires: Tue, 18 Jul 2017 16:07:23 GMT.
If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.

A: Except for the private/public options of CC, I can't see any difference. When using Expires like "access plus 1 year/month/week/day", it works in exactly the same way as CC does.

A: If you are still interested, I leave this recommendation directly from google's boys.
https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
They prefer Expires before than Cache-Control


text:
Q: Loading and Cleaning the Data How to remove sign $ in columns?
import pandas as pd
sales= pd.read_csv("Gadget_Sales.csv")
sales['LastSpend'] = sales['LastSpend'].map(lambda x: x.lstrip('$-'))

I tried the above code, which removes the $ sign. The resulting data structure contains strings, but I want them as integers so I can perform multiplication on them.

A: Adding float(x.lstrip('$')) in the lambda will cast the elements to a float datatype. I have removed the - from the lstrip() so that values that are negative remain so
E.g.
# Assuming sales['LastSpend'] = ["$12.34", "$-56.78"]
sales['LastSpend'] = list(map(lambda x: float(x.lstrip('$')), sales['LastSpend']))
print(sales['LastSpend'])
# [12.34, -56.78]

# Assuming sales['LastSpend'] = "$-12.34"
sales['LastSpend'] = float(sales['LastSpend'].lstrip('$'))
print(sales['LastSpend'])
# -12.34


text:
Q: Can't connect a computer to the internet in a networking simulation I can't figure out what is wrong with my IPS and gateways, everything is working fine except meson's PC can't connect to the internet.
Here is a picture of the network interface where I have to connect computers to the internet and to each other

A: Ok I found the solution, took me a while to figure it out. But all I had to do was choose a non private subnet for the local area network where meson and ion are. So instead of using an IP address like 192.168.1.0/24 which are IP addresses mostly used for local area networks. I had to use ip addresses like 128.100.5.0/24 for example.


text:
Q: Send same json in the file at each script execution I'm writting a JSON and adding into a file.
I don't know how can I add the same JSON in the same array...
When I execute the script, i need to add the new value into the file and not overwritting
I just need to append the JSON. If I use appenFile, create 3 array and I need only 1 array (Look expected result)
Need help, thanks
var table = []

table.push({"executionDate":date,
  "issueID":key,
  "priority":{
     "jira": priority,
     "computed":score1
  },
  "expectedValue":{
     "jira": expected,
     "computed":score2
  }
})

var json = JSON.stringify(table);
fs.writeFile('myjsonfile.json', json, 'utf8', function (err) {
  if (err) console.error(err)
  })

Actual result:
 [{
  "executionDate": 25 / 03 / 2019,
  "issueID": 1,
  "priority": {
     "jira": important,
     "computed": 10
  },
  "expectedValue": {
     "jira": expected,
     "computed": 20
  }
}]

Expected resultat if I execute the script 2 times:
[{
  "executionDate": 25 / 03 / 2019,
  "issueID": 1,
  "priority": {
     "jira": important,
     "computed": 10
  },
  "expectedValue": {
     "jira": expected,
     "computed": 20
  }
},
{
  "executionDate": 25 / 03 / 2019,
  "issueID": 1,
  "priority": {
     "jira": important,
     "computed": 10
  },
  "expectedValue": {
     "jira": expected,
     "computed": 20
  }
},
{
  "executionDate": 25 / 03 / 2019,
  "issueID": 1,
  "priority": {
     "jira": important,
     "computed": 10
  },
  "expectedValue": {
     "jira": expected,
     "computed": 20
  }
}]

A: Im not sure if i understand it well but a fast solution is:

<html>
<script>
var table = [];
console.log(table);

function findInArrAndPush(obj){
 const found = table.some(el => el.issueID === obj.issueID);
 if (!found) table.push(obj);
 return table;
}
for(i=0;i<3;i++){
 var id = i;

 var objToAdd = {"executionDate":"01-01-1000",
  "issueID":id,
  "priority":{
     "jira": "1",
     "computed":"1"
  },
  "expectedValue":{
     "jira": "2",
     "computed":"2"
  }
};
console.log(findInArrAndPush(objToAdd));
//ADD TO FILE HERE
}

  </script>
<body>
</body>
</html>

the only thing you have to do here is print the result to the file.


text:
Q: repository and dataModel to return in specific cases I'm using webforms without any ORM, so I have a hard time to understand how to deal with data models in situation when I need specific fields that are not directly related to an object.
For example I have the stores table, and in one page I need to display all stores with their owner data, in another one - all stores with their billing information, and so on. Having a repository class, what should it return ? A dynamic object ? I cannot create a model for each case in particular,
Also, implementing a method for each of this cases in particular will result in a lot of methods and it will be hard to understand what's happening.
Could someone give me a hint, or some information, to understand how to deal with such cases ?
Sorry if my question is not to specific..


text:
Q: How to create a static local variable in python instance method? I'm coming from a C/C++ world and am having a hard time making all of the OOP analogies in python.  I wrapped my script in a class and now get this error in my log() 'private' instance method:
AttributeError: 'instancemethod' object has no attribute 'counter'
def __log(self, contents):
    sys.stdout.write(contents)

    # Append all writes after the first
    if not hasattr(self.__log, "counter"):
        self.__log.counter = 1
        f = open(self.output_filepath, 'w')
    else :
        f = open(self.output_filepath, 'a')

    f.write(contents)
    f.close()

A: self.__log.counter references to a counter variable which does not exist in the __log method.
if you need the counter variable to be part of the instance of the object, refer to it via self.counter
if you need the counter to be static to the class, define the variable in the class definition outside any methods. check this SO question
if you really really need the counter variable to be part of the instance method, the way to reference it is via ClassName.__log.counter
a good place to start learning OO concepts in python would be the python documentation.
https://docs.python.org/2/tutorial/classes.html

A: This you cant add attributes to methods, but you can modify their dict attribute:
class Test:
    def __log(self, contents):
        sys.stdout.write(contents)

        # Append all writes after the first
        if not "counter" in self.__log.__func__.__dict__:
            self.__log.__func__.__dict__["counter"]= 1
            f = open(self.output_filepath, 'w')
            print 'w'
        else :
            f = open(self.output_filepath, 'a')
            print 'a'

        f.write(contents)
        f.close()

a = Test()
a._Test__log('') #Prints w
a._Test__log('') #Prints a
b = Test()
b._Test_log('') #Prints a

A: Python doesn't have static local variables.  The best solution to what you want is to use a class attribute:
class WithLog(object):

    opened = False

    def log(self, contents):
        sys.stdout.write(contents)

        mode = "a" if self.__class__.opened else "w"
        with open(self.output_filepath, mode) as f:
            f.write(contents)

        self.__class__.opened = True

Of course, it might be better not to constantly open and close the log file....


text:
Q: How to resolve Error: The getter 'body1' isn't defined for the class 'TextTheme' in flutter? My flutter application is not able to run on 2.5.0-5.3.pre beta version. after then I searched for it then need to upgrade my flutter sdk so have upgraded to latest beta version  2.6.0-5.2.pre but still getting errors.
the errors with place_picker-0.9.19-nullsafety plugin. and not able to resolve it.
ERRORS LOG:
../../../../Workspace/flutter/.pub-cache/hosted/pub.dartlang.org/place_picker-0.9.19-nullsafety/lib/widgets/rich_suggestion.dart:35:89: Error: The getter 'body1' isn't defined for the class 'TextTheme'.
 - 'TextTheme' is from 'package:flutter/src/material/text_theme.dart' ('../../../../Workspace/flutter/packages/flutter/lib/src/material/text_theme.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'body1'.
      TextSpan(text: boldText, style: style.copyWith(color: Theme.of(context).textTheme.body1!.color)),
                                                                                ^^^^^
../../../../Workspace/flutter/.pub-cache/hosted/pub.dartlang.org/place_picker-0.9.19-nullsafety/lib/widgets/search_input.dart:60:65: Error: The getter 'body1' isn't defined for the class 'TextTheme'.
 - 'TextTheme' is from 'package:flutter/src/material/text_theme.dart' ('../../../../Workspace/flutter/packages/flutter/lib/src/material/text_theme.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'body1'.
          Icon(Icons.search, color: Theme.of(context).textTheme.body1!.color),
                                                                ^^^^^

FAILURE: Build failed with an exception.

* Where:
Script '/Users/brightroots/Workspace/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1005

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command '/Users/brightroots/Workspace/flutter/bin/flutter'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 31s

ERRORS:

MY CURRENT FUTTER VERSION:
Flutter 2.6.0-5.2.pre • channel beta • https://github.com/flutter/flutter.git
Framework • revision 400608f101 (8 days ago) • 2021-09-15 15:50:26 -0700
Engine • revision 1d521d89d8
Tools • Dart 2.15.0 (build 2.15.0-82.2.beta)

A: I was dealing with this error. In my case, it was because there was a dependency that was not compatible with flutter 2.5. I tried many solutions. But only this worked for me.
First add this to your pubspec.yaml
 charts_flutter:
    git:
      url: git://github.com/google/charts.git
      path: charts_flutter

as described on
this link.
If you have an error saying: remote end hung up unexpectedly while git cloning,
then run this commands
git config --global http.postBuffer 500M
git config --global http.maxRequestBuffer 100M
git config --global core.compression 0

as described on this answer.
This solved my problem.

A: Add them in dependencies and remove body1 from bodyText1
charts_flutter:
    git:
      url: git://github.com/google/charts.git
      path: charts_flutter

A: Please use charts_flutter: ^0.12.0

A: The error thrown on the logs seems to be thrown by the plugin that you're using: place_picker-0.9.19-nullsafety. The logs indicate that the issue comes from Theme.of(context).textTheme.body1
Checking the Flutter docs, body1 on TextTheme is defined as bodyText1. You might want to consider updating how body1 is being called in TextTheme. Otherwise, you can track this issue ticket filed on GitHub related to this issue.

A: Edit the lines in the dart package like below and it will work. Of course the author should do this, but you can edit it yourself as well :)
rich_suggestion.dart
Original: TextSpan(text: boldText, style: style.copyWith(color: Theme.of(context).textTheme.body1!.color)),
New: TextSpan(text: boldText, style: style.copyWith(color: Theme.of(context).textTheme.bodyText1!.color)),
search_input.dart
Original: Icon(Icons.search, color: Theme.of(context).textTheme.body1!.color),
New: Icon(Icons.search, color: Theme.of(context).textTheme.bodyText1!.color),

A: Guys usually we add dependencies before importing. but in this case first import that file(import 'package:charts_flutter/flutter.dart' as charts;) after that hover on package, it will give a option to add the dependencies then add the dependencies in this way. then your error will be solved.


text:
Q: Export SQL XML field to grid I am working with a table that has an XML field.  This is the XML data as it appears in the field (it is much larger, I cut it for brevity), but each entry still has the 3 basic attributes: label, value, and qty.
<CountLog>
  <CountEntry label="distance_range" value="00_09" qty="166" />
  <CountEntry label="distance_range" value="10_19" qty="186" />
  <CountEntry label="distance_range" value="20_29" qty="166" />
  <CountEntry label="distance_range" value="30_39" qty="147" />
  <CountEntry label="distance_range" value="40_49" qty="4" />
</CountLog>

My question, how can I pull out the quoted values for each CountEntry?  I have tried several things that have give me little to no results.
Mark


text:
Q: Add cluster to an existing table in oracle Is it possible to add cluster to an existing table? For example...
I have a table:
CREATE TABLE table_name(
t_id number PRIMARY KEY,
t_name varchar2(50));

Cluster:
CREATE CLUSTER my_cluster
(c_id NUMBER) SIZE 100;

Is there a command like: ALTER TABLE t_name ADD CLUSTER my_cluster(t_id);  or something like that?
Because I want table to look something like this:
CREATE TABLE table_name(
t_id number PRIMARY KEY,
t_name varchar2(50))
CLUSTER my_cluster(t_id);

And dropping all connected tables isn't really what I want to do.
Thanks

A: You really need to understand what a cluster really is. From the docs:

"Clusters are groups of one or more tables physically stored
  together because they share common columns and are often used
  together. Because related rows are physically stored together, disk
  access time improves."  (emphasis mine)

The point being, the tables in a cluster are co-located.  This is a physical arrangement. So, for the database to cluster existing tables we must drop and re-create them.
It is possible to minimise the downtime by building the clustered table under a different name. You will need to keep the data in synch with the live table until you are ready to swap.  You will need to restrict access to the database while you do this, to prevent data loss. Then you rename the old  table, rename the clustered table with the proper name, run the necessary grants and recompile invalid procedures, synonyms, etc.


text:
Q: Search and replace using regular expressions in Python I have a log file that is full of tweets. Each tweet is on its own line so that I can iterate though the file easily.
An example tweet would be like this:
@ sample This is a sample string $ 1.00 # sample

I want to be able to clean this up a bit by removing the white space between the special character and the following alpha-numeric character. "@ s", "$ 1", "# s"
So that it would look like this:
@sample This is a sample string $1.00 #sample

I'm trying to use regular expressions to match these instances because they can be variable, but I am unsure of how to go about doing this.
I've been using re.sub() and re.search() to find the instances, but am struggling to figure out how to only remove the white space while leaving the string intact.
Here is the code I have so far:
#!/usr/bin/python

import csv
import re
import sys
import pdb
import urllib

f=open('output.csv', 'w')

with open('retweet.csv', 'rb') as inputfile:
    read=csv.reader(inputfile, delimiter=',')
    for row in read:
        a = row[0]
        matchObj = re.search("\W\s\w", a)
        print matchObj.group()

f.close()

Thanks for any help!

A: Something like this using re.sub:
>>> import re
>>> strs = "@ sample This is a sample string $ 1.00 # sample"
>>> re.sub(r'([@#$])(\s+)([a-z0-9])', r'\1\3', strs, flags=re.I)
'@sample This is a sample string $1.00 #sample'

A: >>> re.sub("([@$#]) ", r"\1", "@ sample This is a sample string $ 1.00 # sample")
'@sample This is a sample string $1.00 #sample'

A: This seemed to work pretty nice.
print re.sub(r'([@$])\s+',r'\1','@ blah $ 1')


text:
Q: git takes huge time to build when I change my branch My eclipse if loaded with lot of code (12-15 projects). Now when I switch from one git branch to another, eclipse starts rebuilding entire work-space consuming roughly 40 mins :( Is there any way I can dictate git to build only classes where it find changes.

A: That is a very simple problem. In Eclipse you have normally all projects open at the same time. That need a lot of Resources because when you make changes Eclipse goes over the complete tree and check if there are changes or not.
First solution is to close all other projects and open only that project you're working in.
http://www.tutorialspoint.com/eclipse/eclipse_close_project.htm
Our the second one is to use another IDE with less overhead and a better performance. I don't write here some good IDEs otherwise we have here a Shitstorm because everybody mean that his IDE is better :D and it depends on your programming language.

A: Quoting the Git FAQ on Why isn't Git preserving modification time on files? here (please make sure to also read the non-quoted part of the FAQ):

Git sets the current time as the timestamp on every file it modifies, but only those. The other files are left untouched, which means build tools will be able to depend on modification time and rebuild properly.

So while Git does not maintain the modified time for files that change between branches, it does maintain the modified time for files that do not change. That said, you probably simply have a lot of changed files between your branches.


text:
Q: Chrome slightly changes alpha-value of RGBA color after setting it Please consider the following snippet:

var el = document.getElementById('x');
el.style.backgroundColor = "rgba(124, 181, 236, 0.25)";
alert(el.style.backgroundColor);

Testing

On Windows 8.1 this gives back the exact input for backgroundColor in IE 11 and Firefox 37, but in Chrome 43 it changes the alpha-value, and the alert says:

rgba(124, 181, 236, 0.247059)

Notice that the alpha-value unexpectedly returns 0.247059 instead of 0.25.
I've gone through the background-color spec as well as the rgba spec and more specifically the bit about alpha values, but failed to determine whether this is a bug or if the UA (in this case Chrome) is allowed to do this.
Does any of the relevant specs explain whether Chrome's behavior is "allowed"? As a bonus, can anyone explain why Chrome would subtly change the alpha-value?

Footnote: to check if it is the "setter" (el.style.backgroundColor = ...) is to blame I've also tried declaring the style on the element inside the DOM itself. This will have the same (unexpected) result. See this snippet:

document.addEventListener("DOMContentLoaded", function(event) {
  var el = document.getElementById('x');
  alert(el.style.backgroundColor);
});

Testing

A:
It's a known issue of Chrome, for quite a long time...

This is due to how Chrome calculates the computed style alpha value.
For example your input alpha value is 0.25.

*

*Chrome first transforms it into an 8bit level, 0.25 * 255 = 63.75.

*What's weird here is, the number is truncated in to an integer, 63.

*Then, Chrome uses the interger to get back to CSS3 color notation,
63/255 = 0.24705882352941178, approximately 0.247059.

It occurs not only when you set color with JS, but also with CSS. For example:


text:
Q: Synchronize access to HashMap from two threads in java I have two threads running ( One is Main Thread(Say Thread1) and another one is background thread (say Thread2)). I can access HashMap variable hashMap from Thread1 and Thread2. Thread1 modifies the hashMap and Thread2 reads the HashMap.
In Thread1 code will be:
synchronized(hashMap){
   //updating hashMap
}

In Thread2 code will be:
synchronized(hashMap){
     //reading hashMap
}

Can I synchronize the access to hashMap using synchronized block in this way?

A: Yes. But also you can use Collections.synchronizedMap utility method to make a hashmap thread safe:
Map yourMap = new HashMap();
Map synchronizedMap = java.util.Collections.synchronizedMap(yourMap);

Or you can use ConcurrentHashMap or Hashtable which are thread safe by default.

A: You should try using HashTable or ConcurrentHashMap. Both these classes are synchronized so you wouldnt have to deal with it yourself.
Also, consider using a Lock.
Do see:
1. Java Synchronized Blocks.
2. Intrinsic Locks and Synchronization.
3. Synchronization, Thread-Safety and Locking Techniques in Java and Kotlin.
4. On properly using volatile and synchronized.

A: I would use ReadWriteLock
ReadWriteLock rwl = new ReentrantReadWriteLock();

void read() {
    rwl.readLock().lock();
    try {
        ... read
    } finally {
        rwl.readLock().unlock();
    }
}

void write() {
    rwl.writeLock().lock();
    try {
        ... write
    } finally {
        rwl.writeLock().unlock();
    }
}


text:
Q: Dirac delta integral on the bounded set How to solve that an integral?
$$\int_{[0,10)}x^2 d\mu  $$ where $$\mu = \sum_{k=1}^{4} {{1}\over{k}} \delta_{k}$$
I know that $$\int_{X} {f(x) \delta_{x_0} (dx)}= f(x_{0}) $$ but in that example I don't know how to do it on the interval (0,10]. Does anyone know how to solve this?

A: Most likely how you're intended to solve this is to know the following two rules, or at least for them to be "intuitively obvious" to you if you haven't covered them in class specifically:

*

*$\int fd\delta_x=f(x)$

*$\int fd(\sum\lambda_i\mu_i)=\sum\lambda_i\int fd\mu_i$
You can use these rules to work out your integral.


text:
Q: Informatica target file I have a workflow which writes data from a table into a flatfile. It works just fine, but I want to insert a blank line inbetween each records. How can this be achieved ? Any pointer ?

A: Here, you can create 2 target instances. One with the proper data and in other instance pass blank line. Set Merge Type as "Concurrent Merge" in session properties.

A: Multiple possibilities -

*

*You can prepare appropriate dataset into a relational table, and afterwards, dump data from that into a flat file.  For preparation of that data set, you can insert blank rows into that relational target.

*Send a blank line to a separate target file (based on some business condition using a router or something similar), after that you can use merge files option (in session config) to get that data into a single file.


text:
Q: Is there any timing specs between APDU/Response pair in smart card? Command response pair
I couldn't find a clear specification about the period between two consecutive Command/Response Pair (T in the diagram).
for example, If I had sent a command to the card and received a response, What is the maximum period I can wait before the communication is not valid anymore? I need this because I'm willing to make use of this period to give me some flexibility in my design.

A: This is the block waiting time (which can be computed from the BWI part of TB3 in the ATR). If the card needs more time, it has to send a Waiting Time Extension (abbreviated WTX), before this elapses, which has to be acknowledged by the other side (typically the reader). If the acknowledge is not given both sides assume a communication error.
Note, that FWI and BWI from TA1 as well as the clock supplied to the card influence the time.


text:
Q: Android Studio got very slow and constantly "updating indices" There are more similar question on the SO, but I haven't found my answer on any of them so I am opening new one.
I am using:
Android Studio 2.2.3 (but was same with the 2.2.2)
Gradle 2.14.1
JRE 1.8.0
I am using it on the mac, OS X El Capitan (2.5 GHz, i5, 8GB RAM).
It has been working great until few weeks ago, and now it is so painfully slow. Most of the time it is "indexing/updating indices".
I am not that concerned about build time (it takes about 30-40sec, but I can live with that) as much as that constant indexing that makes coding almost impossible (overall responsiveness is pretty poor).
Is there anything in my gradle files that could cause this?
I do have some dependencies, but the app itself is relatively simple.
build.gradle //app
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {

compileSdkVersion 23
buildToolsVersion "23.0.2"

dataBinding {
    enabled = true
}

defaultConfig {
    applicationId "com.example.myproduct"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
   }
}
dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.+'
    compile 'com.android.support:support-v4:23.2.+'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.android.support:design:23.2.+'

    compile 'com.jakewharton.threetenabp:threetenabp:1.0.4'

    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'io.reactivex:rxjava:1.0.10'
    compile 'io.reactivex:rxandroid:1.1.0'

    compile 'com.google.android.gms:play-services-auth:8.3.0'
    compile 'com.facebook.android:facebook-android-sdk:4.16.1'
}

build.gradle//project
 buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        classpath 'com.google.gms:google-services:1.5.0-beta2'

       }
    }

    allprojects {
        repositories {
            jcenter()
        }
    }

    task clean(type: Delete) {
            delete rootProject.buildDir
    }

P.S.
I have enabled - offline work, parallel and daemon. I have increased VM heap size. I have uploaded to latest Android Studio. I have replaces maven with jcenter().
Is there anything I am missing?

A: Try to store Sdk on other drive and also try to invalidate cache and restart.
Hope this helps

A: I just deleted the .idea folder and restarted Android Studio then I pressed button "Sync Project with Gradle Files"

and everything goes fine.

A: It also happened to me,I just Sync 'app' and it was solved...
Or use this
Invalidate Caches / Restart under "File Menu"

A: Invalidate Caches / Restart solved my problem.
Thank you.

A: For the others having the same problem:
My android studio returned back to its original performance (which was ok).
It is hard to me to say what made an improvement because I have done lots of changes at once, here are few I recall:

*

*replaced maven with -> jcenter()

*set flag in properties to use default gradle wrapper

*updated android studio to latest version (at the moment 2.2.3)

*enabled gradle daemon - Configuration On Demand

*invalidate cache and restart(few times)

some of it I have tried before asking this question, but I think all came back to normal when I did last update to Android studio 2.2.3

A: Also, you can try:
Files -> Invalidate Caches / Restart...
This worked for me.

A: I got rid of constant "updating indices" issues by increasing the max heap size of Android Studio process.
To do so, change Studio's JVM options (Help -> Edit Custom VM Options...) to include -Xmx2g where 2g is the amount of memory enough to keep Studio happy with your project complexity.

A: Just go to File -> Invalidate Caches / Restart
Then on the dialog that opens select "Invalidate and Restart"
That's it.

A: I got the same problem with Android Studio 4.0.1. Pressing the sync button like suggested  in the top answer didn't solve the problem. It actually created a second loop. And I didn't want to invalidate the caches.
However I solved it easy by just restarting Android Studio.

A: Removing gradle caches is work in my case.
rm -rf /User/user/.gradle/caches

A: I've had the same problem, but only when having multiple 'packages' under 'app/java/com.example.projectname'
If you have multiple packages within your java folder, try this. It worked instantly for me.
In Android Studio's 'Project Window,' right click on 'app/java/com.example.android.projectname' then click 'Show in Explorer.' Move all of your '.java' files out of their sub-folder and place them all in the 'app/java/com.example.android.projectname' folder.
Next, go back into Android Studio and open up all of your '.java' files. At the top of your code you should see package com.example.android.projectname.subfolder;
Because you've removed the 'packages' and relocated the '.java' files, you need to change every '.java' file's package to read package com.example.android.projectname;
You'll also need to go into the manifest and change 'activity android:name=...'
Hopefully that works.

A: For me, there was a broken module, that had some weird kind of symlinks that caused indexing of all files in /usr/local, which resulted not only in long indexing, but also in a enormous caches created.
Simply unloading the module helped. Cmd+Shift+A (Search everything) and look for "Load/unload modules". Unload all modules you don't need. Restart IDE (invalidating caches might also help further) and problem with endless indexing should be fixed.

A: Sometimes invalidate caches donot work the way it's expected.
In that case, you should restart your machine.


text:
Q: Testing UITableView.rx.itemSelected callback in RxSwift I have a tableView bound to instance var myStrings: BehaviorRelay<[String]>, such that the label of each cell in the tableView is set to the value of each string in myStrings:
myStrings.bind(to: tableView.rx.items(cellIdentifier: cellReuseId, cellType: MyTableCell.self)) { row, str, cell in
            cell.textLabel?.text = str
        }.disposed(by: disposeBag)

I'm subscribed to item selection on the tableView.
tableView.rx.itemSelected.subscribe(onNext: { indexPath in
            let currentStr: String = try! self.tableView.rx.model(at: indexPath)
            self.delegate?.use(currentStr)
        }).disposed(by: disposeBag)

How would I go about testing the closure I have on my subscription to itemsSelected in a unit test?

A: Not sure why you'd need to use delegation if you're using RxSwift, but one way to test what you're after is to inject your table view into the object that uses it in your code snippet, and to also create a mock object that conforms to your table view cell's delegate (the one that's in your subscription that you want to test).  The former will allow you to create a table view in your unit test case and to programmatically select a cell in it.  The latter will then allow you to test that the delegate method called in your subscription is being called with the correct string.
To test your delegate, use a mock object that conforms to your delegate's protocol in your unit test, set up a "spy" for your method, and then run assertions against that object and its spy callback:
class MockDelegateObject: TableViewCellDelegate {
    var stubUse: (() -> String)?

    // MARK: - TableViewCellDelegate
    func use(_ cellString: String) {
        stubUse?(cellString)
    }
}

class MyTableViewTests: XCTestCase {
    func testCellString() {
        let testExpectation = expectation(description: #function)

        let expectedCurrentString = "Foo"

        // Create an instance of your mock object which conforms to your delegate; its spy method will get called with your cell text string when the delegate method is called in your subscription code
        let mockDelegateObject = MockDelegateObject()
        mockDelegateObject.stubUse = { cellString in
            XCTAssertEqual(expectedCurrentString, cellString)
            testExpectation.fulfill()
        }

        // Initialize your table view and do whatever you need to do to add your table view to a window, view controller, etc.
        let tableView = MyTableView()
        let sut = MyTableViewOwningObject(tableView: tableView)

        // Set your object's delegate to be the mock delegate we've created which will receive messages from the subscription in your code
        sut.delegate = mockDelegateObject

        // Do whatever it is you need to do to kick off your table view data loading/displaying, ultimately calling
        sut.loadData()

        // Tell your table view to select whichever cell you want
        let firstIndexPath = IndexPath(row: 0, section: 0)
        tableView.selectRow(at: firstIndexPath, animated: false, scrollPosition: .none)
        tableView.delegate?.tableView?(self.tableView, didSelectRowAt: firstIndexPath)

        waitForExpectations(timeout: 0.001)
    }
}


text:
Q: Python glob: sorting files of format [int]_[int] the same as windows name sort I have files that are sorted by name in windows like the following:
1_0
1_1
1_2
1_3
1_4
1_5
1_6
1_7
1_8
1_9
1_10
1_11
2_0
2_1

Per above the first integer before the _ should be the first sort, followed by the integer after the _. I want to sort in glob the same way. However, when I use sorted(glob.glob(files)) I get an order like the following instead:
1_1
1_10
1_11
1_12
1_13
1_14
1_15
1_16
1_17
1_18
1_19
1_2

For files of the above format, is there a simple way to make glob sort by name the same way as windows does?

A: You can give multiple keys to the sorting function in order of relevance
sorted(glob.glob(files), key=lambda x: (int(x.split('_')[0]), int(x.split('_')[1])))

['1_0', '1_1', '1_2', '1_3', '1_4', '1_5', '1_6', '1_7', '1_8', '1_9', '1_10', '1_11', '2_0', '2_1']


text:
Q: Binding Control when inside DataTemplate I'm trying to bind a combo box's font family to another combo box's font family. It works fine, until I put a data template inside the combo box I'm trying to pull from. See the code below:
<Window Height="350" x:Class="MainWindow" Width="525" FontFamily="Palatino Linotype" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <StackPanel Grid.Column="1" Name="ComboBoxStackPanel" Margin="6" VerticalAlignment="Top">
        <ComboBox FontFamily="Wingdings" Name="SS0">
            <ComboBox.ItemTemplate>
                <DataTemplate x:Name="SSD">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition SharedSizeGroup="Row" Height="Auto"/>
                        </Grid.RowDefinitions>
                        <TextBlock Name="SS1" FontSize="14" Text="{Binding}" FontFamily="Wingdings"/>
                    </Grid>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <ComboBox FontFamily="{Binding FontFamily, ElementName=SS1}" SelectedIndex="1">
            Test
            <ComboBoxItem FontStyle="Normal" FontWeight="Normal">Regular</ComboBoxItem>
            <ComboBoxItem FontStyle="Italic" FontWeight="Normal">Italic</ComboBoxItem>
            <ComboBoxItem FontStyle="Normal" FontWeight="Bold">Bold</ComboBoxItem>
            <ComboBoxItem FontStyle="Italic" FontWeight="Bold">Bold Italic</ComboBoxItem>
        </ComboBox>
    </StackPanel>
</Window>

I can access SS0 just fine, but when I try to access SS1, it fails. I've tried using RelativeSource, but I'm confused how to use it in this context.

A: the DataTemplate has a VisualTree property and you can use this to interrogate its contents, however the contents dont exist until the template is applied.


text:
Q: How simultaneously find documents and get their count from mongodb using mongoose My aim is to get books from the database on specific condition but at the same time i want to get their count as well. Below is my code. Here i have implemented pagination so i using limit() and skip() to get only required data for that particular page. I am doing a regex search on either title or author field and selecting documents for given genre. I am also sorting them in ascending or descending based on query.
const getAllBooks = asyncHandler(async (req, res) => {
  const page = req.query.page === undefined ? 1 : req.query.page;
  const limit = 5;
  const skip = page * limit - limit;
  const allGenres = ["action", "drama", "sci - fi", "romance", "comedy"];
  const reqGenre =
    req.query.genre === "" ? allGenres : req.query.genre.split(",");
  const search = req.query.search === undefined ? "" : req.query.search;
  const searchBy =
    req.query.searchBy === "title"
      ? { title: { $regex: search, $options: "i" } }
      : { author: { $regex: search, $options: "i" } };
  const sort = req.query.sort === "asc" ? 1 : -1;
  let sortBy;
  if (req.query.sortBy === undefined) {
    sortBy = { title: sort };
  } else if (req.query.sortBy === "author") {
    sortBy = { author: sort };
  } else if (req.query.sortBy === "title") {
    sortBy = { title: sort };
  }
  const books = await Book.find(searchBy)
    .where("genre")
    .in(reqGenre)
    .sort(sortBy)
    .skip(skip)
    .limit(limit)
    .select("-createdAt -updatedAt -__v");
  const documents = await Book.find(searchBy)
    .where("genre")
    .in(reqGenre)
    .sort(sortBy)
    .count();
  const total = documents / limit;
  res.status(200);
  res.json({ books, total });
})

Below is my model
const mongoose = require("mongoose");

const LibrarySchema = mongoose.Schema(
  {
    //denotes the title of the book
    title: {
      type: String,
      required: true,
    },
    // denotes the author of the book
    author: {
      type: String,
      required: true,
    },
    genre: {
      type: [String],
      required: true,
    },
  },
  {
    timestamps: true,
  }
);
module.exports = mongoose.model("LibraryModel", LibrarySchema);

Currently i am able to get books and their total for specific query on two separate calls to the database. But hypothetically if we have thousands of books in the database then this method will be very expensive. So i want to merge these both calls into one and get the result in one go. I tried to get a solution but could not find any. Any help is appreciated. Thanks in advance.

A: I think you can use $facet to generate two outputs:
db.collection.aggregate([
  {
    "$match": {
      // your searchBy query here
  },
  {
    "$sort": {
      // your sortBy query here
    }
  },
  {
    "$facet": {
      "result": [
        {
          "$skip": // your skip
        },
        {
          "$limit": // your limit
        },
        {
          "$project": {
            // your select
          }
        }
      ],
      "count": [
        {
          "$count": "count"
        }
      ]
    }
  },
  {
    "$project": {
      "result": 1,
      "count": {
        "$arrayElemAt": [
          "$count",
          0
        ]
      }
    }
  }
])

Example here with predefined values in the quey, you can use the objects you have created.
You can change aggregate objects by JS objects you have and should works fine.
JS snippet to create the query dinamically:

// mock req to avoid problems
const req = {
    query: {
        genre: ""
    }
}

const page = req.query.page === undefined ? 1 : req.query.page;
const limit = 5;
const skip = page * limit - limit;
const allGenres = ["action", "drama", "sci - fi", "romance", "comedy"];
const reqGenre = req.query.genre === "" ? allGenres : req.query.genre.split(",");
const search = req.query.search === undefined ? "" : req.query.search;
let matchQuery = {"$match":{}}
const searchBy = req.query.searchBy === "title"
        ? matchQuery["$match"] = { title: { $regex: search, $options: "i" } }
        : matchQuery["$match"] = { author: { $regex: search, $options: "i" } };
matchQuery["$match"]["genre"] = {"$in": reqGenre}
const sort = req.query.sort === "asc" ? 1 : -1;
let sortBy;
if (req.query.sortBy === undefined) {
    sortBy = { title: sort };
} else if (req.query.sortBy === "author") {
    sortBy = { author: sort };
} else if (req.query.sortBy === "title") {
    sortBy = { title: sort };
}
const query = [matchQuery,
  {
    "$sort": sortBy
  },
  {
    "$facet": {
      "result": [
        {
          "$skip": skip
        },
        {
          "$limit": limit
        },
        {
          "$project": {
            "createdAt": 0,
            "-createdAt": 0,
            "-updatedAt": 0,
            "-__v": 0
          }
        }
      ],
      "count": [
        {
          "$count": "count"
        }
      ]
    }
  },
  {
    "$project": {
      "result": 1,
      "count": {
        "$arrayElemAt": [
          "$count",
          0
        ]
      }
    }
  }]

  console.log(JSON.stringify(query))

This snippet creates the query si you can simply do const result = await Book.aggregate(query).
Note how the console.log() output is a valid Mongo query in this example


text:
Q: how to stop keyboard going down and coming up when using "readonly" parameter in text field in flutter i'm building a 6 digit otp widget using 6 text fields. i want to design in such a way that only focused textfield has to editable and other textfields has be only to show data but shouldn't editable . for this i have used "readOnly" property to true . every thing works fine . but the when the focus is moving from one texfield to other textfield keyboard is going down and comming up . but i want keyboad has be on the screen without moving when i moved from one textifeld to other text field . Can anyone please help me with this? Your assistance would be greatly appreciated.
This is the code that i've written :
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class OTPTextField extends StatefulWidget {
  const OTPTextField();

  @override
  OTPTextFieldState createState() => OTPTextFieldState();
}

class OTPTextFieldState extends State<OTPTextField> {
  final List<TextEditingController> _controllers =
      List.generate(6, (_) => TextEditingController());
  final List<FocusNode> _focusNodes = List.generate(6, (_) => FocusNode());

  FocusNode keyBoardFocus = FocusNode();

  final List<bool> _isActive = [true, false, false, false, false, false];
  late int previousIndex;

  void _onTextChanged(int index) {
    if (index != 5) {
      setState(() {
        _isActive[index] = !_isActive[index];
        _isActive[index + 1] = !_isActive[index + 1];
        print("this is from onTextChanged");
        print(_isActive);
      });
      FocusScope.of(context).requestFocus(_focusNodes[index + 1]);
    }
  }

  void onTextFieldTap() {
    final index = _isActive.indexOf(true);
    print("......" + index.toString() + ">>>>>>>");
    FocusScope.of(context).requestFocus(_focusNodes[index]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RawKeyboardListener(
        focusNode: keyBoardFocus,
        onKey: (keyEvent) {
          if (keyEvent.logicalKey == LogicalKeyboardKey.backspace &&
              keyEvent.runtimeType.toString() == "RawKeyDownEvent") {
            final index = _isActive.indexOf(true);
            print("this is triggered on keyboard listener on $index");
            if (index > 0) {
              setState(() {
                _isActive[index] = !_isActive[index];
                _isActive[index - 1] = !_isActive[index - 1];
                print(_isActive);
                FocusScope.of(context).requestFocus(_focusNodes[index - 1]);
                _controllers[index - 1].text = "";
              });
            }
          }
        },
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List.generate(6, (index) {
              return SizedBox(
                width: 35,
                height: 600,
                child: GestureDetector(
                  // behavior: HitTestBehavior.translucent,
                  onTap: () {
                    print("tap............tap,,,,,,,,,,");
                  },
                  child: TextField(
                    maxLength: 1,
                    autofocus: index == 0,
                    onTap: (() {
                      print("tap ..... tap.....");
                      onTextFieldTap();
                    }),
                    readOnly: !_isActive[index],
                    cursorColor: Colors.black,
                    cursorWidth: 2,
                    cursorRadius: const Radius.circular(5),
                    controller: _controllers[index],
                    focusNode: _focusNodes[index],
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                      ),
                    ),
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    keyboardType: TextInputType.number,
                    textInputAction: index == 5
                        ? TextInputAction.done
                        : TextInputAction.next,
                    onChanged: (value) => _onTextChanged(index),
                  ),
                ),
              );
            }),
          ),
        ),
      ),
    );
  }
}


text:
Q: Offset Google markers at the same address What can I incorporate into my current code below to offset markers, as markers at the same address don't show.
Here's example http://www.mediwales.com/mapping/test
UPDATE:
I've changed the way the map works by running it from a database.

A: add your 'get_posts(array' to the var markers for the MarkerCluster Manager to build the dynamic marker.
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
  'zoom': 13,
  'center': center,
  'mapTypeId': google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map"), options);

var mcOptions = {gridSize: 50, maxZoom: 15};
var markers = [...]; // Create the markers you want to add and collect them into a array.
var mc = new MarkerClusterer(map, markers, mcOptions);

Source:
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/docs/examples.html
V3 ClusterMarker Reference
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/docs/reference.html


text:
Q: How can I "clean up" my migration files in my Rails project? My db/migrate folder has grown quite large. Every time I need to go edit a migration file prior to running rake db:migrate it is a slight annoyance to scroll through them all and find the file and then scroll back up to collapse the folder.  Is there a way to "clean up" this folder once it's gotten this large?  Perhaps a way to consolidate the files down or put them in a sub folder?

A: You can safely put old migrations into subfolders.
Check the needs_migration? method that is used to determine if a migration is needed to be run or all migrations are already applied. This method compares all migration files from the default db/migrate folder with all (already applied) migrations that are present in the schema_migrations table in the database. The point is that the search for migration files is recursive.
Compare for yourself the following tests. The test calls the migrations method that returns the migrations defined on the file system and filters out the migration names.
ActiveRecord::Migrator.migrations(['db/migrate']).map(&:name)
# => ["CreateUsers", "CreateJobs", "AddBirthToUsers", "CreateDelayedJobs", ...]

Now move some of the migration files to a subfolder under db/migrate and repeat the same command and you will see that the output is exactly the same (you can e.g. count the number of returned entries). Thus, you can move migration files anywhere around under the main migration directory and they will behave the same for Rails.
Update: it didn't even occur to me, that you might have meant editing old migration files. You should never edit old migration files. Even a "consolidation" meaning "concatenating" old migration files would not work either, as the timestamp of the file determines the version of the migration (and using it the migrations are ordered). So, if it is understood that by cleaning the files you meant "getting them out of the way" when browsing them, you can move them to subfolders.


text:
Q: Changed from an i5 4440 to an i7 4790. The latter makes the CPU led turn red, while the first works fine. What can i do? Specs:

*

*Motherboard - ASUS Z87-Pro;

*CPU - i5 4440 (with Cooler Master Hyper 212 Evo V2);

*GPU - Gigabyte GeForce GTX 1070;

*PCU - Corsair VS550;

*RAM - 2 kits of G.SKILL Ripjaws DDR3 1600 CL9 2x8GB (32GB in total);

I had my PC set with the specs I just specified and all was running smoothly. Today I tried swapping my CPU for an i7 4790, which I had in another PC, but, when I tried booting it up, it turned on the CPU led (with Q-Code 00) and the fans, but did not give any other response (the monitor had no signal).
I tried swapping back to my old CPU and all was running smoothly again.
Tried updating the BIOS to the newer version through EZ Flash 2, and did not work with the new CPU, though it worked with the old one.
I then tried to update the BIOS through USB BIOS flashback and it still did not work with the new one (it worked with the old one).
At this moment I am really not sure what to do. I thought it might be due to a RAM issue, but since it works on the old one I'm really doubting that.
Appreciate any replies.

A:
Before using the new Intel 4th Gen Core processors, we suggest that you first download the BIOS updater for new Intel 4th Gen Core Processors and then update the BIOS using this tool.

Source

A: Apparently Q00 isn't unknown when replacing/upgrading CPU. There's a number of possible reasons like faulty PSU, faulty MoBo, faulty CPU, bent CPU pin, faulty or inconsistent RAM, BIOS/UEFI data...
The first result I got from Google is:
https://appuals.com/error-q-code-00-on-asus-motherboard/
There are also discussions in Asus forums, for example
https://rog.asus.com/forum/showthread.php?54418-Q-Code-00
https://rog.asus.com/forum/showthread.php?101472-How-to-fix-CPU-CODE-00
Hope this helps