text:
Q: Netsuite Phptoolkit Could not determine customer compid Trying to get the customer information using phptoolkit
Here's my code:
function getCustomer(){
  $service = new NetSuiteService();

  $request = new GetRequest();
  $request->baseRef = new RecordRef();
  $request->baseRef->account_id = "252206";
  $request->baseRef->type = "customer";
  $getResponse = $service->get($request);

  if (!$getResponse->readResponse->status->isSuccess) {
     echo "GET ERROR";
  } else {
     $customer = $getResponse->readResponse->record;
     echo "GET SUCCESS, customer:";
     echo "\nCompany name: ". $customer->companyName;
     echo "\nInternal Id: ". $customer->internalId;
     echo "\nEmail: ". $customer->email;
  }
}

And getting error like this.

Fatal error: Uncaught SoapFault exception: [soapenv:Server.userException] Could not determine customer compid in phptoolkit/NSPHPClient.php:338 Stack trace: #0 phptoolkit/NSPHPClient.php(338): SoapClient->__soapCall('get', Array, NULL, Array) #1 phptoolkit/NetSuiteService.php(145953): NSPHPClient->makeSoapCall('get', Object(GetRequest)) #2 netsuite.php(23): NetSuiteService->get(Object(GetRequest)) #3

A: Base on the netsuite documentation
RecordRef only accept internalId and type
$request->baseRef = new RecordRef();
$request->baseRef->internalId = "252206";
$request->baseRef->type = "customer";

A: You need to know the company ID and put it in your settings file. Also need user email address, password, role Internal ID and app ID. These are used to create a passport.
If your integration uses token based authorization, the requirements are different.
Look in the samples in the toolkit.


text:
Q: How to bootstrap weld-osgi version 2 in SE application It's really not funny. There is no information in internet how to run weld-osgi second version (2.1.2.final) in se app. Instructions for ver 1 don't work.
Let the developers be ashamed that they didn't provide necessary samples. I wrote them here.
So, I have and OSGi activator and I want to get beans from it. In GF4 I used this:
private BeanManager getBeanManager() throws NamingException
{
  try{
   InitialContext initialContext = new InitialContext();
            return (BeanManager)  initialContext.lookup("java:comp/BeanManager");
   }
  catch (NamingException e) {
            System.out.println("Couldn't get BeanManager through JNDI");
            return null;
   }
}

But in SE application I can't get it through JNDI.
Also I tried:
Weld weld=new Weld();
BeanManager beanManager=weld.getBeanManager();

But at the second line I get

Caused by: java.lang.IllegalStateException: Singleton is not set. Is
  your Thread.currentThread().getContextClassLoader() set correctly?

How can I use CDI starting from activator? What is my mistake?
EDIT:
What I did - I found two source code of two programs that use it, but it's really no so easy to write on their base (at least for me). The first is here and the second is here

A: The weld-osgi subproject is not supported anymore with Weld 2. Instead, integration with OSGi is provided using the Pax CDI project.
Pax CDI documentation can be found here: https://ops4j1.jira.com/wiki/display/PAXCDI/Pax+CDI
Additional information can be found at:
- http://karaf.apache.org/manual/latest/users-guide/cdi.html
- https://github.com/weld/core/blob/master/examples/osgi/README.md

redpajama_set_name: RedPajamaStackExchange


text:
Q: angularjs + ui.bootstrap pagination wrong total pages number Can't comment the main post, so need to post new question.
I'm trying to implement the pagination solution from this thread, written by Scotty.NET(the top rated answer), but facing a strange issue:
My custom code is in this plunker(http://plnkr.co/edit/Mdsy2x) and explains the issue. If I set $scope.numPerPage as any number except '10' - I'm getting wrong total pages number. For example if I generate 450 todo's and set in $scope.numPerPage = 5; - I get a total of 45 pages and 225 items showed and so any number except 10 give wrong result

A: you you just need to add the items-per-page attribute:
<pagination
      total-items="todos.length"
      items-per-page="numPerPage"
      ng-model="currentPage"
      max-size="maxSize"
      class="pagination-sm"
      boundary-links="true">
  </pagination>

It's default value is 10, that's why it worked well only with 10 items per page.


text:
Q: How to duplicate and rename a file when folder content changes - Linux or php script? I'm exporting .csv file when a new order is made on my site running under prestashop. The site is hosted in a Plesk VM and I need to duplicate the .csv file of the order and rename it to .txt when the .csv is exported. I need to do this operation to connect the .csv with an ERP software.
I don't know how to exactly solve this. My options are:

*

*Create a php script (but I need to store somewhere the folder changes history in order to compare)

*Create a linux script (no idea how to do)

*Create a cron task.


text:
Q: ¿Cómo podía agregar a una calculadora simple que al tomar una decisión esta repita o deje de repetir el resultado? Muy buen día, disculpen por la pregunta es que tenia una duda acerca de como repetir la operación una y otra vez hasta que el usuario diga que ya no, es decir, Al  inicio solicita la operación a realizar y al término deberá preguntar al usuario ¿Desea volver a ejecutar otra operación S/N?, donde el usuario deberá ingresa S o N.
aquí esta el código, les agradecería mucho la ayuda en verdad por favor y disculpen las molestias
    varA=parseFloat(prompt("introducas un numero"));
    varB=parseFloat(prompt("introducas un numero otro numero"));
    varC=parseFloat(prompt("introducas un ultimo numero"));
    signo=prompt("ponga un signo");

    if(signo == '+') {
    resultado=(varA+varB+varC);
    }else if(signo == '-'){
    resultado=(varA-varB-varC);
    }else if(signo == '*'){
    resultado=(varA*varB*varC);
    }else if(signo == '/'){
    resultado=(varA/varB/varC);
    }
    document.write(resultado);

A: Deberías envolver todo en una declaración while. Lo que haya dentro se va a ejecutar mientras la condición dada sea verdadera. Para eso declaramos una variable otra en true, para que acceda a la primer operación siempre (también podrías usar do while para esto).
Entramos al while y lo primero que hacemos es todo tu codigo, donde se ingresan las variables y se realiza la operacion.
Finalmente, le pedis otro valor de entrada al usuario, el cual debe ser true o false para saber si quiere continuar o no. Si responde true se vuelve a ejecutar el bucle while, en el momento que responda false el bucle no se vuelve a ejecutar.
let otra = true;

while(otra){
    varA=parseFloat(prompt("introducas un numero"));
    varB=parseFloat(prompt("introducas un numero otro numero"));
    varC=parseFloat(prompt("introducas un ultimo numero"));
    signo=prompt("ponga un signo");

    if(signo == '+') {
    resultado=(varA+varB+varC);
    }else if(signo == '-'){
    resultado=(varA-varB-varC);
    }else if(signo == '*'){
    resultado=(varA*varB*varC);
    }else if(signo == '/'){
    resultado=(varA/varB/varC);
    }
    document.write(resultado);

    // aca le pedis que ingrese (por teclado, apretando un boton, lo
    // que sea) si desea ejecutar otra operacion, y asignas este valor
    // (true o false) a la variable "otra".

    // otra = true  <- se vuelve a ejecutar el bucle
    // otra = false <- se detiene el bucle
}

Es necesario modificar la variable otra en el bucle while, SIEMPRE, para que de alguna forma pueda tomar como resultado false, de lo contrario siempre sería true y entraría un bucle infinito


text:
Q: How to validate both greater than AND less than I am writing validation for a book management system, and I want to make it so that if the length of the ISBN entered is either less than or greater than 13 or 10, it displays the error message, however it says that there is an unexpected '<' whenever I try the following.
  if(strlen($_POST['isbndelete'] (< 13 || 10) || (> 13 || 10)))
  {
    $error="The length of the ISBN is incorrect.";
    echo $error;
    return false;
  }

All help is appreciated!

A: Your main issue is that your condition is not valid PHP. You should read more about conditional statements syntax.

Validing ISBN length
ISBNs are either 10 or 13 characters.
So you can simply check if your string does not contain exactly 10 and does not contain 13 characters either, like this:
$len = strlen($_POST['isbndelete']);
if ($len != 10 && $len != 13) {
  $error = "The length of the ISBN is incorrect.";
  echo $error;
  return false;
}


text:
Q: Uploadify - button image css As I know uploadify button are able to customize the css of the button ... How bout the button image ?
In my current uploadify button I'm using:
'buttonImage' : "images/jpg_icon.png", // image size 50x50

The image doesn't show single ... it repeat and repeat ...
I tried css it in uploadify.css:
.uploadify {
   position: relative;
   margin-bottom: 1em;
   background-repeat:no-repeat;
}

but so far button image are set in uploadify JS ...
Any suggestion to do it ? Thanks a lot


text:
Q: Narrowing type conversion in C++ using pointers I have been having some problems with downward type conversion in C++ using pointers, and before I came up with the idea of doing it this way Google basically told me this is impossible and it wasn't covered in any books I learned C++ from. I figured this would work...
long int TheLong=723330;
int TheInt1=0;
int TheInt2=0;
long int * pTheLong1 = &TheLong;
long int * pTheLong2 = &TheLong + 0x4;

TheInt1 = *pTheLong1;
TheInt2 = *pTheLong2;

cout << "The double is " << TheLong << " which is "
     << TheInt1 << " * " << TheInt2 << "\n";

The increment on line five might not be correct but the output has me worried that my C compiler I am using gcc 3.4.2 is automatically turning TheInt1 into a long int or something. The output looks like this...

The double is 723330 which is 723330 * 4067360

The output from TheInt1 is impossibly high, and the output from TheInt2 is absent.
I have three questions...
Am I even on the right track?
What is the proper increment for line five?
Why the hell is TheInt1/TheInt2 allowing such a large value?

A: int is probably 32 bit, which gives it a range of -2*10^9 to 2*10^9.
In the line long int * pTheLong2 = &TheLong + 0x4; you are doing pointer arithmetic to a long int*, which means the address will increase by the size of 0x4 long ints. I guess you are assuming that long int is twice the size of int. This is absolutely not guaranteed, but probably true if you are compiling in 64 bit mode. So you want to add half the size of a long int -- exactly the size of an int under your assumption -- to your pointer. int * pTheLong2 = (int*)(&TheLong) + 1; achieves this.
You are on the right track, but please keep in mind, as others have pointed out, that you are now exploring undefined behaviour. This means that portability is broken and optimization flags may very well change the behaviour.

By the way, a more correct thing to output (assuming that the machine is little-endian) would be:
cout << "The long is " << TheLong << " which is "
     << TheInt1 << " + " << TheInt2 << " * 2^32" << endl;

For completeness' sake, a well-defined conversion of a 32 bit integer to two 16 bit ones:
#include <cstdint>
#include <iostream>

int main() {
    uint32_t fullInt = 723330;
    uint16_t lowBits  = (fullInt >>  0) & 0x0000FFFF;
    uint16_t highBits = (fullInt >> 16) & 0x0000FFFF;

    std::cout << fullInt << " = "
        << lowBits << " + " << highBits << " * 2^16"
        << std::endl;

    return 0;
}

Output: 723330 = 2434 + 11 * 2^16

A:
Am I even on the right track?

Probably not.  You seem confused.

What is the proper increment for line five?

There are none.  Pointer arithmetic is possible only inside arrays, you have no arrays here.  So
long int * pTheLong2 = &TheLong + 0x4;

is undefined behavior and any value other than 0 (and possibly 1) by which you'd replace 0x4 would also be UB.

Why the hell is TheInt1/TheInt2 allowing such a large value?

int and long int often have the same range of possible values.

A: TheInt2 = *pTheLong2;

This invokes undefined behavior, because the C++ Standard does not give any guarantee as to which memory location pTheLong2 is pointing to, as it's initlialized as:
long int * pTheLong2 = &TheLong + 0x4;

&TheLong is a memory location of the variable TheLong and pTheLong2 is initialized to a memory location which is either not a part of the program hence illegal, or its pointing to a memory location within the program itself, though you don't know  where exactly, neither the C++ Standard gives any guarantee where it's pointing to.
Hence, dereferencing such a pointer invokes undefined behavior.


text:
Q: C++ FFTW forward backward DFTvalues get wrapped Hello StackOverflow community,
i have a problem with the dft algorithm of the fftw library.
All i want to do is to transform a certain pattern forward and backward to receive the input pattern again, of course there will be some sort of filtering in between the transformations later on.
So, what my program does atm is:

*

*Create a test signal

*Filter or "window" the test signal with a value of 1.0 or 0.5

*Copy the test signal to a fftw_complex data type

*Perform a forward and backward dft

*Calculate the magnitude, which is called phase here

*Copy and adjust data for display purposes, and finally display the images via OpenCV

My problem is that when is use no filtering my backward transformed image is wrapped somehow and i can't calculate the correct magnitude, which should be indentical to my input image / test signal.
When i set the fitler/"window" to a value of 0.5 the backward transformation works fine, but my input image is just half as bright as it should be.
The following image illustrates my problem: (from top left to bottom right)
1. Input signal, 2. Real part of backward transformation, 3. From backward transformated data calculated magnitude, 4. Input signal multiplied with 0.5, 5. Real part of backward transformation, 6. From backward transformated data calculated magnitude.
http://imageshack.com/a/img538/5426/nbL9YZ.png
Does anybody have an idea why the dft performs in that way?! It's kind of strange...
My code looks like this atm:
/***** parameters **************************************************************************/
int     imSize                                          = 256;
int     imN                                             = imSize * imSize;

char*   interferogram                                   = new char[imN];
double* spectrumReal                                    = new double[imN];
double* spectrumImaginary                               = new double[imN];
double* outputReal                                      = new double[imN];
double* outputImaginary                                 = new double[imN];
double* phase                                           = new double[imN];

char*   spectrumRealChar                                = new char[imN];
char*   spectrumImaginaryChar                           = new char[imN];
char*   outputRealChar                                  = new char[imN];
char*   outputImaginaryChar                             = new char[imN];
char*   phaseChar                                       = new char[imN];

Mat     interferogramMat                                = Mat(imSize, imSize, CV_8U, interferogram);
Mat     spectrumRealCharMat                             = Mat(imSize, imSize, CV_8U, spectrumRealChar);
Mat     spectrumImaginaryCharMat                        = Mat(imSize, imSize, CV_8U, spectrumImaginaryChar);
Mat     outputRealCharMat                               = Mat(imSize, imSize, CV_8U, outputRealChar);
Mat     outputImaginaryCharMat                          = Mat(imSize, imSize, CV_8U, outputImaginaryChar);
Mat     phaseCharMat                                    = Mat(imSize, imSize, CV_8U, phaseChar);

/***** compute interferogram ****************************************************************/
fill_n(interferogram, imN, 0);
double value = 0;
double window = 0;

for (int y = 0; y < imSize; y++)
{
    for (int x = 0; x < imSize; x++)
    {
        value = 127.5 + 127.5 * cos((2*PI) / 10000 * (pow(double(x - imSize/2), 2) + pow(double(y - imSize/2), 2)));

        window = 1;
        value *= window;

        interferogram[y * imSize + x] = (unsigned char)value;
    }
}

/***** create fftw arays and plans **********************************************************/
fftw_complex*       input;
fftw_complex*       spectrum;
fftw_complex*       output;
fftw_plan           p_fw;
fftw_plan           p_bw;

input               = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * imN);
spectrum            = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * imN);
output              = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * imN);
p_fw                = fftw_plan_dft_2d(imSize, imSize, input, spectrum, FFTW_FORWARD, FFTW_ESTIMATE);
p_bw                = fftw_plan_dft_2d(imSize, imSize, spectrum, output, FFTW_BACKWARD, FFTW_ESTIMATE);

/***** copy data ****************************************************************************/
for (int i = 0; i < imN; i++)
{
    input[i][0] = double(interferogram[i]) / 255.;
    input[i][1] = 0.;
    spectrum[i][0] = 0.;
    spectrum[i][1] = 0.;
    output[i][0] = 0.;
    output[i][1] = 0.;
}

/***** FPS algorithm ************************************************************************/
fftw_execute(p_fw);

fftw_execute(p_bw);

for (int i = 0; i < imN; i++)
{
    phase[i] = sqrt(pow(output[i][0], 2) + pow(output[i][1], 2));
}

/***** copy data ****************************************************************************/
for (int i = 0; i < imN; i++)
{
    spectrumReal[i] = spectrum[i][0];
    spectrumImaginary[i] = spectrum[i][1];

    outputReal[i] = output[i][0] / imN;
    outputImaginary[i] = output[i][1];
}

SaveCharImage(interferogram, imN, "01_interferogram_512px_8bit.raw");
SaveDoubleImage(spectrumReal, imN, "02_spectrum_real_512px_64bit.raw");
SaveDoubleImage(spectrumImaginary, imN, "03_spectrum_imaginary_512px_64bit.raw");
SaveDoubleImage(outputReal, imN, "03_output_real_512px_64bit.raw");

DoubleToCharArray(spectrumReal, spectrumRealChar, imSize);
DoubleToCharArray(spectrumImaginary, spectrumImaginaryChar, imSize);

DoubleToCharArray(outputReal, outputRealChar, imSize);
DoubleToCharArray(outputImaginary, outputImaginaryChar, imSize);

DoubleToCharArray(phase, phaseChar, imSize);

/***** show images **************************************************************************/

imshow("interferogram", interferogramMat);
imshow("spectrum real", spectrumRealCharMat);
imshow("spectrum imaginary", spectrumImaginaryCharMat);
imshow("out real", outputRealCharMat);
imshow("out imaginary", outputImaginaryCharMat);
imshow("phase", phaseCharMat);

int key = waitKey(0);

A: Here are some lines of your code :
char*   interferogram  = new char[imN];
...
double value = 0;
double window = 0;

for (int y = 0; y < imSize; y++)
{
   for (int x = 0; x < imSize; x++)
   {
      value = 127.5 + 127.5 * cos((2*PI) / 10000 * (pow(double(x - imSize/2), 2) + pow(double(y - imSize/2), 2)));

      window = 1;
      value *= window;

      interferogram[y * imSize + x] = (unsigned char)value;
   }
}

The problem is that a char is between -128 and 127, while unsigned char ranges from 0 to 255. In interferogram[y * imSize + x] = (unsigned char)value;, there is an implicit cast to char.
It does not affect the output if window=0.5, but it triggers a change if window=1 as value becomes higher than 127. This is exactly the problem that you noticed in your question !
It does not affect the first displayed image since CV_8U corresponds to unsigned char : interferogram  is therefore cast back into a unsigned char*. Take a look at Can I turn unsigned char into char and vice versa? to know more about char to unsigned char cast.
The problem occurs at input[i][0] = double(interferogram[i]) / 255.; : if window=1, interferogram[i] may be negative and input[i][0] becomes negative.
Change all char to unsigned char and it should solve the problem.
You may also change
outputReal[i] = output[i][0] / imN;
outputImaginary[i] = output[i][1];

for
outputReal[i] = output[i][0];
outputImaginary[i] = output[i][1];

Calls to fftw seems to be fine.


text:
Q: Taking query from the user input How can I ask the user to put his query after executing some lines of codes?Eg-
woman(X):-
  ( X=18->write('yes'),nl
    ;
  ).
man(Y):-
  ( X=18->write('yes'),nl
    ;
  ).
main:-
 woman(18),
  write('Enter your query'),nl,
  "**HERE I WANT USER TO CALL ANY QUERY EITHER woman(X) or man(X) ??Can I Do it????**

I want to first execute main and then the user has to enter his query.Is this possible??I know he can directly call the query but can he do it after executing main?


text:
Q: What would an observer in the most distant galaxy see? Perhaps this has been asked before and perhaps it's rather trivial, but what would an observer on the most distant astronomical object see? Would they see only the CMB in one direction and us in the other direction, or would they see essentially the same thing as us, i.e. a universe of diameter $8.8\times 10^{26}$ m which looks uniform in every direction? If it's the later case, doesn't this imply that the cosmos has infinite mass?

A: I'm interpreting this question as "what lies beyond the observable universe?", asked in different words. The answer to that is "we don't know", because things that are beyond the observable universe are by definition not observable, so there could be invisible pink unicorns out there which we cannot prove doesn't exist. Any possible answer is therefore speculation.
Still, the natural answer would be "more of the same". That I think is the assumption of most astronomers, albeit knowing full well that it is an unknowable question. See e.g. this popular-level article.
Another way of interpreting the question is whether an observer in a very far away galaxy will see things differently from us. This is asking about homogeneity - is the universe the same at every point? This is a fundamental assumption in deriving the Friedmann-Robertson-Lemaitre-Walker metric, which in turn underpins modern cosmology. So the answer is we expect the observer to see the same things as us. Caveat: homogeneity is an assumption. We have good reason to believe the universe is not very inhomogeneous, but we cannot prove it is homogeneous from some more fundamental theory. Neither can we fly a probe to Andromeda and test homogeneity that way. If the universe isn't homogeneous then the FRLW metric would have to be modified, but that doesn't rewrite cosmology entirely, since the more basic theory - general relativity - remains valid.


text:
Q: Position a fixed element below another fixed element I have two fixed elements, one of which can either have
display: block or display: none. The other fixed element is always going to be visible. I want the elements to stick to the top of the website, while having them not overlay each other.
The only proposed solution I found is in these questions:
How to position a fixed div under another fixed div?
Fixed element below fixed element without JS

Put your two divs inside another container div and set that one as
  fixed.

I can't do that however, as both of these elements are on different positions in the code, which I am not able to change.
Here's a code snippet demonstrating my problem:

nav,
.secondmenu {
  position: fixed;
  height: 120px;
  opacity: 1;
  top: 0;
  width: 100%;
  background: lightgrey;
}

.secondmenu {
  height: 50px;
  background: grey;
  opacity: 1;
  z-index: 2;
}

body {
  height: 1000px;
}

Might be there or not and overlays the other navigation

Some other stuff separating the two from each other with relative position

What I want and things to keep in mind:

*

*If both elements are visible, they should be fixed on top of the page, while one is below the other

*If only the second element is visible, I want the second one to be fixed at the top of the page

*The first element can change its visibility using inline styles (display:none <-> display:block, even without reloading the website)

*Javascript/Jquery solutions are fine

A: this could bo done adding a 'top' with the height of the first nav to the second, like i did here.
Note: This is not the complete solution: If you want to show the second nav only you could do this using js by setting the 'top' back to 0.

nav,
.secondmenu {
  position: fixed;
  height: 120px;
  opacity: 1;
  top: 0;
  width: 100%;
  background: lightgrey;
}

.secondmenu {
  height: 50px;
  background: grey;
  opacity: 1;
  z-index: 2;
  top: 120px;
}

body {
  height: 1000px;
}

Might be there or not and overlays the other navigation

Some other stuff separating the two from each other with relative position

A: Creating a holder for both of them is the proper approach.
But in your case you can position both of them fixed.
and when the other one is hidden or shown you can handled both elements style(i.e. top and left properties) via Javascript
Try like below

A: Have you tried Sticky Kit? http://leafo.net/sticky-kit/
Sticky-kit provides an easy way to attach elements to the page when the user scrolls such that the element is always visible.


text:
Q: Saving and calling multiple variables from ruby method Maybe I've been staring at my Ruby book to the point where words don't mean anything anymore, but I thought I might as well ask.
What I'm looking to do is, rather than passing a bulk of variables through my function headers, or instead of using global variables, I'm looking to save my variables within a method, and call upon them at multiple times, throughout my functions.  What I'm realistically having an issue with, is scope.
def DateGrab()
 print "\nEnter the date you're looking for (Month/Day): "
 longdate = gets.strip.split(/\/| /)
 if longdate[0].length > 3
   month = longdate[0].slice(0..2)
 else
   month = longdate[0]
 end
  day = longdate[1]
  year = `date | awk '{print $6}'`.strip
  grepdate = "#{day}/#{month}/#{year}"
  date = Date.parse("#{day}-#{month}-#{year}").strftime('%m%d%Y').strip
end

I'm looking to pass "grepdate" and "date" through multiple functions, and I feel that using a method would be easier, but every time I try to call the variable, I get a "undefined local variable or method" error.

A: You want to look at instance variables. You can set them via @grepdate = "something" These instance variables are accessible throughout your class and in all methods of that class.


text:
Q: Find the command and options used by NetBeans IDE I am using a the NetBeans 7.x IDE.   I have a Netbeans Application module.  I use the Build and the Run buttons from the IDE. The module runs just fine when I press Run Project or F6 button.  I like to run
this from the command line.  Since everything was build automatically for
me I have no idea where things are or how to run it.  There are several jar files in the project/build/public-package-jars.  Is there a way  to see what command and options the Run Project is using ?

A: Go to the root of the application (or wherever there is a build.xml file) on the command line and run ant -p.  That will list all of the available options for building and running the application.


text:
Q: Lodash chaining issue I am having trouble getting the value of my chain. I believe it has something to do with the returns in my code.
      let wrapper = _.chain($scope.meetings)
    .orderBy($scope.meetings, function(o) { return new moment(o.meetingDate); }, ['asc'])
    .filter($scope.meetings, function(o) { return moment(o.meetingDate).isAfter(begin) && moment(o.meetingDate).isBefore(end); })
    .forEach($scope.meetings, function(o) { o.createdBy = $scope.myData[0].fullName;})
    .value();

I am getting an empty array as the value

A: as @gruff-bunny said, solve was to remove the variable from my orderBy, filter, and forEach. In the end, my function looks like this.
        $scope.meetings = _.chain($scope.meetings)
      .orderBy(function(o) { return new moment(o.meetingDate); }, ['asc'])
      .filter(function(o) { return moment(o.meetingDate).isAfter(begin) && moment(o.meetingDate).isBefore(end); })
      .value();


text:
Q: Combine LDAP filters i have 2 ldap queries and i want to combine them into one. From the first one i want to get rid of the static whenchanged with the parameters from the second one that counts 30 days in the past.
Get-ADUser -LDAPFilter '((mailNickname=id*)(whenChanged>=20170701000000.0Z))(userAccountControl=514)(|(memberof=CN=VPN1,OU=Vpn,OU=Domain Global,OU=Groups,OU=,DC=am,DC=bm,DC=cm,DC=dm)(memberof=CN=VPN2,OU=Vpn,OU=Domain Global,OU=Groups,OU=,DC=am,DC=bm,DC=cm,DC=dm))'| export-csv C:\Users\ADMIN\Desktop\Groupmembers.csv

Get-ADUser -LDAPFilter {(useraccountcontrol=514)} -Properties whenChanged | Where-Object {$_.whenChanged -gt (Get-Date).AddDays(-30)} |export-csv C:\Users\ADMID023896\Desktop\Groupmembers.csv

Thanks for any help in advance

A: $mydate = get-date ((get-date).AddDays(-30)) -format "yyyyMMdd000000.0Z"
Get-ADUser -LDAPFilter "((mailNickname=id*)(whenchanged>=$mydate)...)"

Note the change of quotes in the LDAP filter to double rather than single quotes


text:
Q: Installing Debian on Embedded system with serial console or network console (PCH) I have an embedded system based on the Intel-Atom with PCH which we are busy developing. In the embedded environment I have:

*

*A Serial console through the PCH which means this doesn't work with the standard kernel. (as CONFIG_SERIAL_PCH_UART_CONSOLE is required)

*The SATA drive is only available in the embedded environment and can't be taken out for install.

*I can boot via USB drive.

*The system does have ethernet via the PCH which I have not yet confirmed to work.

I have managed to build a custom Linux 3.16.7 kernel that can be booted with console=uartPCH0,115200 and then displays a console on the serial line.
However, to move from here to an actual installation seems to be problematic.
I am unable to convince debian-installer to be built using my custom kernel.
My current theory is a double bootstrap process where I first bootstrap an installation into a usb-drive and then boot that and then bootstrap an installation into the SATA drive on the system?
Any better suggestions?
I'm not sure if there is some way to install via a network console?
The system requires the e1000e driver which I assume will be built into the standard debian installer ISO's, however so far I was unable to find very clear documentation on how to convince the install system to boot and then open up ssh/telnet.
Any hint ?

A: I managed to solve my problem with debootstrap, here is a quick run-down of the process I followed.

*

*unmount usb

*Partition the USB (4GB)
Zap out GPT with gdisk, as my board didn't want to boot GPT.
Created just one linux partition, nothing else.
I had lots of problems getting a usb drive bootable on my embedded system.

*mkfs.ext4 /dev/sdb1

*mount /dev/sdb1 /media/usb

*debootstrap jessie /media/usb http://my.mirror/debian
I highly recommend setting up something like apt-cacher

*chroot /media/usb
Mount all these:
mount -t devtmpfs dev /dev
mount -t devpts devpts /dev/pts
mount -t proc proc /proc
mount -t sysfs sysfs /sys

*Edit /etc/fstab : (I use nano for editing normally)
proc /proc proc defaults 0 0
sysfs /sys sysfs defaults 0 0
UUID=xxxx / ext4 errors=remount-ro 0 1

to write UUID into file use: blkid -o value -s UUID /dev/sdb1 >> /etc/fstab

*house-keeping:
apt-get install locales
dpkg-reconfigure locales
apt-get install console-setup
dpkg-reconfigure keyboard-configuration (optional?)
apt-get install console-data
passwd root
adduser linuxuser

*Install grub and kernel
apt-get install grub-pc
I installed grub into both /dev/sdb and /dev/sdb1 but you can use install-mbr for /dev/sdb I think
apt-get install linux-image-686-pae

*now edit /etc/default/grub:
uncomment GRUB_TERMINAL=console
add GRUB_GFXPAYLOAD_LINUX=text
to GRUB_CMDLINE_LINUX_DEFAULT add: console=tty0 console=ttyPCH0,115200
run upgrade-grub2

*edit /etc/default/console-setup :
CODESET="guess"
FONTFACE=
FONTSIZE=
VIDEOMODE=

*create /etc/kernel-img.conf with this inside:
image_dest = /
do_symlinks = yes
do_bootloader = yes
do_bootfloppy = no
do_initrd = yes
link_in_boot = no

*Now install custom kernel with dpkg -i
For me 2 options was important:
CONFIG_SERIAL_PCH_UART=y
CONFIG_SERIAL_PCH_UART_CONSOLE=y
although I did highly customize the kernel after that.
Currently I am compiling 3.14 with the rt-patch from linux-source-3.14 I downloaded out of wheezy-backports

*Other things to do before restarting (optional)
edit /etc/modules to force drivers to load
edit /etc/network/interfaces
echo myHostName > /etc/hostname
apt-get install telnetd
apt-get install openssh-server

At this stage I could boot the usb on my target embedded system and repeat the whole process again to install debian on the SATA drive. Obviously I needed to install things like debootstrap on the usb drive first to facilitate this but that was minor.

A: You can activate the network console of the Debian Installer via preseeding. The Installation Guide actually contains the following example:

# Use the following settings if you wish to make use of the network-console
# component for remote installation over SSH. This only makes sense if you
# intend to perform the remainder of the installation manually.
#d-i anna/choose_modules string network-console
#d-i network-console/authorized_keys_url string http://10.0.0.1/openssh-key
#d-i network-console/password password r00tme
#d-i network-console/password-again password r00tme

You have to uncomment the anna/choose_modules setting. If you want to login with your SSH key, make the public key accessible via some URL and uncomment the network-console/authorized_keys_url setting. If you want to use a password, uncomment the other two settings.
Of course, you also have to preseed all previous questions, because you have no interface to answer them before the network console is started up by the above settings. In a DHCP environment this means you'll also need something like

d-i debian-installer/language string en
d-i debian-installer/country string US
d-i debian-installer/locale string en_US.UTF-8
d-i keyboard-configuration/xkb-keymap select us

Instead of adding a preseed.cfg file to your initrd (which your bootloader may not support directly), you can supply all these settings on the kernel command line like
linux language=en country=US locale=en_US.UTF-8 keymap=us anna/choose_modules=network-console network-console/authorized_keys_url="http://..." initrd=initrd.gz

(see the list of abbreviations).


text:
Q: On using "gone down" Is this a correct use for gone down?

Many websites could have gone down during the years.

What I want to say, is the websites do not exist any more. I want to use gone down, but not sure if it is correct here.

A: Gone down would mean that the people maintaining the website were no longer able to keep maintaining it and it eventually went offline. This is more frequently used for saying that a website has gone down due to technical issues or even hacking.

Google has gone down due to technical issues in the servers.

You could've also said that "many websites have been taken down over the years", that would mean that maybe the government or some higher power took these websites from the web because of criminal activity or misuse of information.

MegaUpload has been taken down by the government after allegedly uploading illegal content to their servers.

It all depends on your context, but there, are two expressions you could use.


text:
Q: Image Absolute source path with jQuery This code gives something like ../movies/1.png, the exact src attribute:
$("img").attr("src");

How do I get absolute path of an image with jQuery?
I want to get something like http://site.com/movies/1.png, not ../movies/1.png

A: This can easily be done by accessing the .src property directly on the <img>:
$('img')[0].src;

example: http://jsfiddle.net/9mKz2/
(I didn't test it on all browser right now)


text:
Q: How to remove the underscore from Android Text input? I am currently developing a multi-platformed app for use on IOS/Android/Windows phone.
I am trying to create a 'themed' text input, where all buttons/inputs/text look identical throughout all aspects of the devices by using DevExtreme (typescript).
I have almost completed it, although below shows my problem with android:

This shows a blue 'underscore' on text input. For my system, this is NOT wanted.
Is there a way of editing my css file as to force remove this from the android platform?
I have previously tried removing the text decoration:
text-decoration: none;

But this did not work.
Anyone got any ideas/solutions to remove this?
Some of my css file so far:
[type=text]{
     padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;
  border: 2px solid rgba(0, 0, 0, 0);
  border-color:none;
  -webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
background-color: #585757;
color:#cfcfcf;
}
[type=text]:focus{

    box-shadow: 0 0 5px rgba(81, 203, 238, 1);
  padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;
  border: 2px solid rgba(81, 203, 238, 1);
  -webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
background-color: #585757;
color:#cfcfcf;
}

[type=text]:active{
    margin: 5px 1px 3px 0px;
    border: 2px solid transparent;

    border-color: blue;
    -webkit-box-shadow: 0 0 8px blue;
       -moz-box-shadow: 0 0 8px blue;
            box-shadow: 0 0 8px blue;

            -webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
background-color: #585757;
color:#cfcfcf;

}

Is there an element to remove this from an android device?

A: you can do it bey setting the Background Drawable of the EditText to null
editText.setBackgroundDrawable(null)

A: Try this css styles to say to the all links without underline
A:link {text-decoration: none}
A:visited {text-decoration: none}
A:active {text-decoration: none}


text:
Q: Creating multiple columns for different values in 1 single row this is pretty simple and I can't get my head around how to do it! I'm trying to do a:
=TEXTJOIN(", ",TRUE,G:G)

But not sure how to group it by business.
In excel, I have a data set which is like the below:

Business
Location

Mary's
United Kingdom

Mary's
United States

Mary's
Canada

Bill's
Bolivia

Bill's
Canada

Adam's
Iceland

Adam's
United States

But for each of these businesses, I need to convert it to this:

Business
Location

Mary's
United Kingdom, United States, Canada

Bill's
Bolivia, Canada

Adam's
Iceland, United States

Can anyone give any tips?
Thanks!


text:
Q: How can I tell which one of these numbers is greater? I have two very large numbers how do I tell which one is greater. The two numbers are $$\sum^{9(10^{99}) } _{i=1}i^9$$
and
$9^{9^{9^{9^{9^{9^{9^{9^{9^{9}}}}}}}}}$

A: The power tower is much larger. Note that you have to solve it from above.
So, you start with $9^9$ . Then you take $9$ to the power of that number and so on. If you are at $9\uparrow 9\uparrow 9\uparrow 9$, you will have left the sum in the dust because it is smaller than $(9\times 10^{99})\times (9\times 10^{99})^9=(9\times 10^{99})^{10}=9^{10}\times 10^{990}$

A: $$\sum^{9\times10^{99} } _{i=1}i^9 <\sum^{9\times10^{99} } _{i=1} \left( 9\times10^{99}\right)^9=\left( 9\times10^{99}\right)^{10}<9^{2000}$$
OP can you take it from here? Hint: $9^9>2000$


text:
Q: JScrollpane: Add element when scroll to bottom I have applied JScrollpane to a

.Now I need to add more
 when scroll to bottom of that
 through ajax.
Any idea?
TIA
Jaya

A: You need to use the 'jsp-scroll-y' event. This event is triggered when the user scrolls the y bar. More info on the event here. Since browsers trigger this event more than once each time, instead of using jQuery's normal .bind or .on, I use jQuery debounce plugin to prevent browsers from firing the function more than once every 200ms. You can download JQuery debounce here. So let's say your structure is like this:

 ...

 ...

 ...

The javascript to achieve your goal using JQuery would look like:
var container = $('#container');
var list = $('#list');

// initialize the scroll pane
container.jScrollPane();

// bind the event
container.debounce('jsp-scroll-y', function(event, scrollPositionY, isAtTop, isAtBottom) {
    if (isAtBottom) {
        $.ajax({
            type: 'GET',
            async: true,
            dataType: 'html',
            url: '/path/to/more/elements',
            success: function(data) {
                if (data.length) {
                    list.append(data);
                    container.jScrollPane('reinitialise');
                } else {
                    container.unbind('jsp-scroll-y');
                }
            },
        });
    }
}, 200);

Of course, in this scenario, '/path/to/more/elements' should return li elements, and nothing when you are done receiving everything. I use a page index that I increment in the AJAX success function to get new elements. You get send this page index to the server using data in the ajax calls or in the URL (it depends of the implementation on the server).


text:
Q: Chart from 2 columns of data I have 2 columns of data which are comma delimited. eg below -
Time,DataSent
00:00:02,1635807
00:00:11,7153658
00:00:19,31766
00:00:27,31319
00:00:35,30179
How can I use python to chart one against the other?

A: Usually use pandas for creating charts in python.
One way to do that with your data structure:
import pandas as pd

string = 'Time,DataSent 00:00:02,1635807 00:00:11,7153658 00:00:19,31766 00:00:27,31319 00:00:35,30179'
cols = ''.join(string.split()[0]).split(',')
data = ','.join(string.split()[1:]).split(',')
col0 = data[::2]
col1 = [ds for ds in data if ':' not in ds]
df = pd.DataFrame({cols[0]: col0, cols[1]: col1})
print(df)

Output:
       Time DataSent
0  00:00:02  1635807
1  00:00:11  7153658
2  00:00:19    31766
3  00:00:27    31319
4  00:00:35    30179


text:
Q: Change DevExpress gridview datasource I am going to get datasource of a gridview and then add some columns to it and again populate new datasource in that gridview.
I use this code:
    try
    {
        if (!dt.Columns.Contains("Message_ID"))
        {
            dt.Columns.Add("Message_ID", typeof(int));
            dt.Columns.Add("Message_Status", typeof(String));
            dt.Columns.Add("cost", typeof(long));
        }

        List<string> phonelist = new List<string>();

        foreach (DataRow dr in dt.Rows)
        {
            phonelist.Add(dr["phone"].ToString().TrimEnd());
        }

        results = api.Send(Properties.Settings.Default.SMS_Number, phonelist, message, Kavenegar.SDK.Models.Enums.MessageType.AppMemory, DateTime.MinValue);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["Message_ID"] = 123;//results[i].ID;
            dt.Rows[i]["Message_Status"] = "fgh";//results[i].StatusText;
            dt.Rows[i]["cost"] =  123;//results[i].Cost;
        }

        gridecontrol.DataSource = null;
        gridecontrol.DataSource = dt;
        gridecontrol.RefreshDataSource();
    }
    catch (Exception ex)
    {
         System.Windows.Forms.MessageBox.Show(ex.Message, "Error message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

But I have a problem, gridview doesn't refresh with new datasource. I tried it with a fresh gridview and it seems that my datasource works fine and new columns supplies in it. But if I have a datasource in gridview I can't supply it with new datasource, I do not get any errors or something like that.

A: try to call the gridView.PopulateColumns() method after you set the gridControl's DataSource.  This will force the grid to recreate columns in your View and thus the new data will be visible.


text:
Q: jquery why doesn't this text show up I am trying to teach myself jquery, (not so successfully so far)  why doesn't the div with id fill get updated when i click submit?

  <form name="login">
    Administrative Login

Username:

    <input name="username" type="text" id="username" />

Password

    <input name="password" type="password" id="password" />

    <input type="Submit" id="go">

A: You need to cancel the default action of the submit button by returning false in the click handler:
$(document).ready(function(){
    $("input#go").click(function() {
        $("div#fill").load('test1.txt');
        return false;
    });
});

By returning false, the form is not being submitted normally, the browser stays on the same page and the AJAX call that you are performing to fetch the text.txt file from your server has enough time to execute.
As an alternative I would recommend you subscribing to the submit event of the form instead of the click event of the submit button:
$(document).ready(function(){
    $("form").submit(function() {
        $("div#fill").load('test1.txt');
        return false;
    });
});

This will ensures that the AJAX call will be executed everytime the form is submitted, not only if the submit button is clicked. But of course that will depend on your requirements.


text:
Q: How to Add Geometric Figures to a Tree using Forest and Tikz? First of all, I want to thank the community for the help I obtained in my first question, some days ago. Having said that, I want to ask you for some help again, if I may. Essentially, I am currently using the powerful package Forest to draw Game Theory trees and, so far, so good. But now, I am faced with something that I do not know how to do and that is not explained in the (rather complex) manual of the Forest package. Essentially, I have a game (tree) with three nodes, each node being the beginning of a sub-game. I basically need to make clear that there are three sub-games in the tree. The graphical representation of what I am looking for is something like this:

The tree that I have drawn looks like this one (and I would like to keep it):

In a nutshell, I would like to draw the red squares of the first tree (Picture 1) on my tree (Picture 2). However, I probably need rhombus, given the form of my tree. Finally, I provide you with the code I am currently using for my tree:
\begin{center}
\begin{forest} for tree={l sep=4em, s sep=8em, anchor=center}
[$P_1$, circle, draw,
    [{2, 2}, edge label={node[midway,left]{$D$}}]
    [$P_2$, edge label={node[midway,right]{$A$}}, circle, draw,
        [{1, 1}, edge label={node[midway,left]{$d$}}]
        [$P_1$, edge label={node[midway,right]{$a$}}, circle, draw,
            [{0, 0}, edge label={node[midway,left]{$D$}}]
            [{3, 3}, edge label={node[midway,right]{$A$}}]]]]
\node[above=30pt,align=center,anchor=center] {\textbf{Figure IV.} Extensive Form of a Centipede Game Variant};
\end{forest}
\end{center}

What do I need to add/change to include these squares?
Thank you all in advance.
Best Regards,
Héctor.

A: A solution to use the istgame package:

\documentclass{standalone}

\usepackage{istgame}

\begin{document}
\begin{istgame}[font=\footnotesize]
\xtdistance{15mm}{25mm}
\istrooto(0){$P_1$}
  \istb{D}[l]{2,2}
  \istb{A}[r]
  \endist
\istrooto(1)(0-2){$P_2$}
  \istb{d}[l]{1,1}
  \istb{a}[r]
  \endist
\istrooto(2)(1-2){$P_1$}
  \istb{D}[l]{0,0}
  \istb{A}[r]{3,3}
  \endist
\xtSubgameBox(0){(0-1)(2-2)}
\xtSubgameBox(1){(1-1)(2-2)}[inner sep=18pt]
\xtSubgameBox(2){(2-1)(2-2)}[inner sep=16pt]
%\xtSubgameBox(2){(2-1)(2-2)}[solid,rounded corners=0pt,inner sep=16pt]
\end{istgame}

\end{document}

It is your choice whether to add options like [solid,rounded corners=0pt] or color.

A: Not exactly a rhombus, but you can modify the angles and distances if that matters.
\documentclass[tikz, border=10pt, multi]{standalone}
\usepackage{forest}
\usetikzlibrary{shapes.geometric,fit}
\begin{document}
\begin{forest}
  /tikz/my edge label/.style={inner sep=5pt, midway},
  /tikz/rhombus/.style={trapezium, trapezium left angle=105, trapezium right angle=75, draw=red},
  my rhombus/.style n args=2{
    tikz={\node [fit=#1, rhombus, inner sep=#2] {};},
  },
  for tree={
    l sep=4em,
    s sep=11em,
    anchor=center,
    fit=rectangle,
    calign=fixed edge angles,
    before typesetting nodes={
      if n'=1{
        edge label/.wrap value={\noexpand node [my edge label,right] {$#1$} }
      }{
        edge label/.wrap value={\noexpand node [my edge label,left] {$#1$} }
      },
    },
    if n children=0{}{
      circle,
      draw,
    }
  }
  [$P_1$, my rhombus={() (current bounding box.west) (current bounding box.south east)}{12.5pt}
    [{2, 2}, edge label=D]
    [$P_2$, edge label=A, my rhombus={() (!1) (!2 2)}{7.5pt}
      [{1, 1}, edge label=d]
      [$P_1$, edge label=a, my rhombus={() (!1) (!2)}{2.5pt}
        [{0, 0}, edge label=D]
        [{3, 3}, edge label=A]
      ]
    ]
  ]
\end{forest}
\end{document}


text:
Q: DevExtreme React Grid Anyone know how to change the fontSize of the TableHeaderRow in a DevExtreme React Grid?
Here's an example of code from the website (https://devexpress.github.io/devextreme-reactive/react/grid/demos/featured/data-editing/) that I have been working with

import * as React from 'react';
import {
  SortingState, EditingState, PagingState,
  IntegratedPaging, IntegratedSorting,
} from '@devexpress/dx-react-grid';
import {
  Grid,
  Table, TableHeaderRow, TableEditRow, TableEditColumn,
  PagingPanel, DragDropProvider, TableColumnReordering,
} from '@devexpress/dx-react-grid-material-ui';
import Paper from '@material-ui/core/Paper';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import Input from '@material-ui/core/Input';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import TableCell from '@material-ui/core/TableCell';

import DeleteIcon from '@material-ui/icons/Delete';
import EditIcon from '@material-ui/icons/Edit';
import SaveIcon from '@material-ui/icons/Save';
import CancelIcon from '@material-ui/icons/Cancel';
import { withStyles } from '@material-ui/core/styles';

import { ProgressBarCell } from '../../../theme-sources/material-ui/components/progress-bar-cell';
import { HighlightedCell } from '../../../theme-sources/material-ui/components/highlighted-cell';
import { CurrencyTypeProvider } from '../../../theme-sources/material-ui/components/currency-type-provider';
import { PercentTypeProvider } from '../../../theme-sources/material-ui/components/percent-type-provider';

import {
  generateRows,
  globalSalesValues,
} from '../../../demo-data/generator';

const styles = theme => ({
  lookupEditCell: {
    paddingTop: theme.spacing.unit * 0.875,
    paddingRight: theme.spacing.unit,
    paddingLeft: theme.spacing.unit,
  },
  dialog: {
    width: 'calc(100% - 16px)',
  },
  inputRoot: {
    width: '100%',
  },
});

const AddButton = ({ onExecute }) => (
  <div style={{ textAlign: 'center' }}>
    <Button
      color="primary"
      onClick={onExecute}
      title="Create new row"
    >
      New
    </Button>
  </div>
);

const EditButton = ({ onExecute }) => (
  <IconButton onClick={onExecute} title="Edit row">
    <EditIcon />
  </IconButton>
);

const DeleteButton = ({ onExecute }) => (
  <IconButton onClick={onExecute} title="Delete row">
    <DeleteIcon />
  </IconButton>
);

const CommitButton = ({ onExecute }) => (
  <IconButton onClick={onExecute} title="Save changes">
    <SaveIcon />
  </IconButton>
);

const CancelButton = ({ onExecute }) => (
  <IconButton color="secondary" onClick={onExecute} title="Cancel changes">
    <CancelIcon />
  </IconButton>
);

const commandComponents = {
  add: AddButton,
  edit: EditButton,
  delete: DeleteButton,
  commit: CommitButton,
  cancel: CancelButton,
};

const Command = ({ id, onExecute }) => {
  const CommandButton = commandComponents[id];
  return (
    <CommandButton
      onExecute={onExecute}
    />
  );
};

const availableValues = {
  product: globalSalesValues.product,
  region: globalSalesValues.region,
  customer: globalSalesValues.customer,
};

const LookupEditCellBase = ({
  availableColumnValues, value, onValueChange, classes,
}) => (
  <TableCell
    className={classes.lookupEditCell}
  >
    <Select
      value={value}
      onChange={event => onValueChange(event.target.value)}
      input={(
        <Input
          classes={{ root: classes.inputRoot }}
        />
)}
    >
      {availableColumnValues.map(item => (
        <MenuItem key={item} value={item}>
          {item}
        </MenuItem>
      ))}
    </Select>
  </TableCell>
);
export const LookupEditCell = withStyles(styles, { name: 'ControlledModeDemo' })(LookupEditCellBase);

const Cell = (props) => {
  const { column } = props;
  if (column.name === 'discount') {
    return <ProgressBarCell {...props} />;
  }
  if (column.name === 'amount') {
    return <HighlightedCell {...props} />;
  }
  return <Table.Cell {...props} />;
};

const EditCell = (props) => {
  const { column } = props;
  const availableColumnValues = availableValues[column.name];
  if (availableColumnValues) {
    return <LookupEditCell {...props} availableColumnValues={availableColumnValues} />;
  }
  return <TableEditRow.Cell {...props} />;
};

const getRowId = row => row.id;

class DemoBase extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      columns: [
        { name: 'product', title: 'Product' },
        { name: 'region', title: 'Region' },
        { name: 'amount', title: 'Sale Amount' },
        { name: 'discount', title: 'Discount' },
        { name: 'saleDate', title: 'Sale Date' },
        { name: 'customer', title: 'Customer' },
      ],
      tableColumnExtensions: [
        { columnName: 'amount', align: 'right' },
      ],
      rows: generateRows({
        columnValues: { id: ({ index }) => index, ...globalSalesValues },
        length: 12,
      }),
      sorting: [],
      editingRowIds: [],
      addedRows: [],
      rowChanges: {},
      currentPage: 0,
      deletingRows: [],
      pageSize: 0,
      pageSizes: [5, 10, 0],
      columnOrder: ['product', 'region', 'amount', 'discount', 'saleDate', 'customer'],
      currencyColumns: ['amount'],
      percentColumns: ['discount'],
    };
    const getStateDeletingRows = () => {
      const { deletingRows } = this.state;
      return deletingRows;
    };
    const getStateRows = () => {
      const { rows } = this.state;
      return rows;
    };

    this.changeSorting = sorting => this.setState({ sorting });
    this.changeEditingRowIds = editingRowIds => this.setState({ editingRowIds });
    this.changeAddedRows = addedRows => this.setState({
      addedRows: addedRows.map(row => (Object.keys(row).length ? row : {
        amount: 0,
        discount: 0,
        saleDate: new Date().toISOString().split('T')[0],
        product: availableValues.product[0],
        region: availableValues.region[0],
        customer: availableValues.customer[0],
      })),
    });
    this.changeRowChanges = rowChanges => this.setState({ rowChanges });
    this.changeCurrentPage = currentPage => this.setState({ currentPage });
    this.changePageSize = pageSize => this.setState({ pageSize });
    this.commitChanges = ({ added, changed, deleted }) => {
      let { rows } = this.state;
      if (added) {
        const startingAddedId = rows.length > 0 ? rows[rows.length - 1].id + 1 : 0;
        rows = [
          ...rows,
          ...added.map((row, index) => ({
            id: startingAddedId + index,
            ...row,
          })),
        ];
      }
      if (changed) {
        rows = rows.map(row => (changed[row.id] ? { ...row, ...changed[row.id] } : row));
      }
      this.setState({ rows, deletingRows: deleted || getStateDeletingRows() });
    };
    this.cancelDelete = () => this.setState({ deletingRows: [] });
    this.deleteRows = () => {
      const rows = getStateRows().slice();
      getStateDeletingRows().forEach((rowId) => {
        const index = rows.findIndex(row => row.id === rowId);
        if (index > -1) {
          rows.splice(index, 1);
        }
      });
      this.setState({ rows, deletingRows: [] });
    };
    this.changeColumnOrder = (order) => {
      this.setState({ columnOrder: order });
    };
  }

  render() {
    const {
      classes,
    } = this.props;
    const {
      rows,
      columns,
      tableColumnExtensions,
      sorting,
      editingRowIds,
      addedRows,
      rowChanges,
      currentPage,
      deletingRows,
      pageSize,
      pageSizes,
      columnOrder,
      currencyColumns,
      percentColumns,
    } = this.state;

    return (
      <Paper>
        <Grid
          rows={rows}
          columns={columns}
          getRowId={getRowId}
        >
          <SortingState
            sorting={sorting}
            onSortingChange={this.changeSorting}
          />
          <PagingState
            currentPage={currentPage}
            onCurrentPageChange={this.changeCurrentPage}
            pageSize={pageSize}
            onPageSizeChange={this.changePageSize}
          />

          <IntegratedSorting />
          <IntegratedPaging />

          <CurrencyTypeProvider for={currencyColumns} />
          <PercentTypeProvider for={percentColumns} />

          <EditingState
            editingRowIds={editingRowIds}
            onEditingRowIdsChange={this.changeEditingRowIds}
            rowChanges={rowChanges}
            onRowChangesChange={this.changeRowChanges}
            addedRows={addedRows}
            onAddedRowsChange={this.changeAddedRows}
            onCommitChanges={this.commitChanges}
          />

          <DragDropProvider />

          <Table
            columnExtensions={tableColumnExtensions}
            cellComponent={Cell}
          />

          <TableColumnReordering
            order={columnOrder}
            onOrderChange={this.changeColumnOrder}
          />

          <TableHeaderRow showSortingControls />
          <TableEditRow
            cellComponent={EditCell}
          />
          <TableEditColumn
            width={120}
            showAddCommand={!addedRows.length}
            showEditCommand
            showDeleteCommand
            commandComponent={Command}
          />
          <PagingPanel
            pageSizes={pageSizes}
          />
        </Grid>

        <Dialog
          open={!!deletingRows.length}
          onClose={this.cancelDelete}
          classes={{ paper: classes.dialog }}
        >
          <DialogTitle>
Delete Row
          </DialogTitle>
          <DialogContent>
            <DialogContentText>
              Are you sure to delete the following row?
            </DialogContentText>
            <Paper>
              <Grid
                rows={rows.filter(row => deletingRows.indexOf(row.id) > -1)}
                columns={columns}
              >
                <CurrencyTypeProvider for={currencyColumns} />
                <PercentTypeProvider for={percentColumns} />
                <Table
                  columnExtensions={tableColumnExtensions}
                  cellComponent={Cell}
                />
                <TableHeaderRow />
              </Grid>
            </Paper>
          </DialogContent>
          <DialogActions>
            <Button onClick={this.cancelDelete} color="primary">
Cancel
            </Button>
            <Button onClick={this.deleteRows} color="secondary">
Delete
            </Button>
          </DialogActions>
        </Dialog>
      </Paper>
    );
  }
}

export default withStyles(styles, { name: 'ControlledModeDemo' })(DemoBase);

The font size of the text labelling the columns (e.g. product, region, amount) is fixed, and I see no parameters that can change it. Any ideas?

A: I think there are a few ways around this, the way I have used is having a fully controlled component.
Looks a little like this
<TableHeaderRow cellComponent={this.ExampleHeaderCell} />

Where ExampleHeaderCell is a component that would look something like this
 ExampleHeaderCell = (props: any) => (<TableHeaderRow.Cell
                className={exampleClass}
                {...props}
                key={column.name}
                getMessage={() => column.title}
            />)

From there you can pass it a class as shown with exampleClass
You can take this further and have it customised for a particular column.
ExampleHeaderCells = (props: any) => {
    const exampleClass = css({ backgroundColor: "blue" })
    const { column } = props
    if (column.name === "name") {
        return (
            <TableHeaderRow.Cell
                className={exampleClass}
                {...props}
                key={column.name}
                getMessage={() => column.title}
            />
        )
    }
    return <TableHeaderRow.Cell {...props} key={column.name} getMessage={() => column.title} />
}

The example above is returning a specific cell with the exampleClass if the column name is equal to "name". Otherwise it just returns the regular TableHeaderRow.Cell


text:
Q: Is it efficient to create a new column in SQL Server and find only matching data in the new column? I am wondering if the following process is efficient, or if there is a better way to go about this:
Table consists of 4 relevant columns:

*

*Id

*Date of Birth (1984-03-19)

*First Name (John)

*Last Name (Doe)

I want to concatenate these columns to create '1984-03-19 John Doe' as a new column. Then I want to take a list of values (there is a .csv file containing DOB, First, Last name) in this format and only pull the Id from the table when there is a match.
The table has millions of rows, so I am wondering if there is a more efficient way to write this query.
This is for an ad hoc request.

A: You should load the CSV file into a table.  Let's call it CSV.
We'll call your original table t.
Then you want a simple JOIN:
select t.id
from csv join
     t
     on t.firstname = csv.firstname and
        t.lastname = csv.lastname and
        t.dob = csv.dob;

Voila!  Done.  No concatenation.
For performance, you want an index on t(firstname, lastname, dob) with the columns in any order.


text:
Q: Network Internet Egress from Americas to China on SFTP server I set up an instance 10 days ago with an installation of Centos to use as a backup system. I followed this tutorial:
https://medium.com/@biancalorenpadilla/sftp-google-cloud-storage-d559fd16e074
Looking at the billing I see this:
Compute Engine  Network Internet Egress from Americas to China  79.08 Mebibyte
http and https are blocked. SSH random 12 character password. Nothing in the instances logs since the day I set it up.
Could that amount of data come from people probing the ports or has the server likely been breached?

A: There might be chances that you have been affected by a DDOS attack. And to mitigate this or avoid in future you should implement egress filtering [1].
Since egress traffic is within the customer's control as you are responsible for the configuration of your Virtual Machines and firewalls, consider securing your project using best practices [2] or such as creating an egress firewall rule to allow traffic only to intended IP addresses.
You can make use of VPC flow logs [3] that could help monitor the traffic (egress) coming from your instances and filter out any unintended IP address accessing the VM with use of egress firewall.
You need to put some authentication/authorization in front of the server to ensure that it tries to prevent potential attacks by some bots (which may scan all IPs and attempt to connect to every port). Kindly follow best practices at these links [4]
[1]https://www.sans.org/reading-room/whitepapers/firewalls/egress-filtering-faq-1059
[2] https://cloud.google.com/files/GCPDDoSprotection-04122016.pdf
[3] https://cloud.google.com/vpc/docs/using-flow-logs
[4] https://cloud.google.com/security


text:
Q: Error defining Enum in class: TypeError: 'module' object is not callable I have a Python package containing a module:

myPackage
|----> myModule

where I want to define an enum as a static property of the module.  I'm using the enum34 module for Python 2.7 in Houdini
#myModule.py
from enum import Enum
class DebugStates(Enum):
    release = 1
    debug = 2

In another Python file i then try to import myModule:
#OtherPython.py
from myPackage import myModule

which is executed when Houdini starts up.  This executes without errors, but when I try and pull up a Python console I get this error and Houdini crashes:
"Traceback (most recent call last):
  File \"<stdin>\", line 1, in <module>
TypeError: 'module' object is not callable
"

A: Le sigh, I just figured it out, I was changing my module names to protect the innocent in my question.  In real life I was trying to call my module "globals" thinking that the package would act like a namespace boundary.  Apparently not a good idea.


text:
Q: How to empty the offcanvas input form? I am getting double entry in the table I am trying to enter new data in the DataTables through an offcanvas Form. Everything is working perfect for the first entry. When I try the second entry the first entry information are still saved in the form and it adds 2 new entries in the table (first and second entry). When I try again, button adds 3 new entries, and so on... I would appreciate any help. What am I missing?
The code for buttons on Offcanvas is:
<div class="col-sm-12">
<button type="submit" class="btn btn-primary data-submit me-sm-3 me-1">Submit</button>
<button type="reset" class="btn btn-outline-secondary" data-bs-dismiss="offcanvas">Cancel</button>
</div>

The code for a new entry is:
function newEntry() {

    google.script.run.withSuccessHandler(loadIdCustomer).loadNextId();

    var formAddNewRecord = document.getElementById('form-add-new-record'),
        offCanvasElement = document.querySelector('#add-new-record');

    setTimeout(() => {

      // To open offCanvas, to add new record
      offCanvasEl = new bootstrap.Offcanvas(offCanvasElement);

      // Empty fields on offCanvas open
      (offCanvasElement.querySelector('.dt-full-name').value = ''),
      (offCanvasElement.querySelector('.dt-city').value = ''),
      (offCanvasElement.querySelector('.dt-website').value = ''),
      (offCanvasElement.querySelector('.dt-assignedUser').value = '');

      // Open offCanvas with form
      offCanvasEl.show();

    }, 200);

    // Form validation for Add new record
    fv = FormValidation.formValidation(formAddNewRecord, {
      fields: {
        basicFullname: {
          validators: {
            notEmpty: {
              message: 'The name is required'
            }
          }
        },
        basicCity: {
          validators: {
            notEmpty: {
              message: 'Post field is required'
            }
          }
        },
        assignedUser: {
          validators: {
            notEmpty: {
              message: 'The Email is required'
            },
          }
        },
      },
      plugins: {
        trigger: new FormValidation.plugins.Trigger(),
        bootstrap5: new FormValidation.plugins.Bootstrap5({
          eleValidClass: '',
          rowSelector: '.col-sm-12'
        }),
        submitButton: new FormValidation.plugins.SubmitButton(),
        autoFocus: new FormValidation.plugins.AutoFocus()
      },
      init: instance => {
        instance.on('plugins.message.placed', function (e) {
          if (e.element.parentElement.classList.contains('input-group')) {
            e.element.parentElement.insertAdjacentElement('afterend', e.messageElement);
          }
        });
      }
    });

  // Add New record
  // On form submit, if form is valid
  fv.on('core.form.valid', function () {
    var $new_name = $('.add-new-record .dt-full-name').val(),
      $new_city = $('.add-new-record .dt-city').val(),
      $new_website = $('.add-new-record .dt-website').val(),
      $new_assignedUser= $('.add-new-record .dt-assignedUser').val();

    var $newEntry = [];
        $newEntry.push("");
        $newEntry.push("");
        $newEntry.push(nextID);
        $newEntry.push($new_name);
        $newEntry.push($new_city);
        $newEntry.push($new_website);
        $newEntry.push($new_assignedUser);
        $newEntry.push(1);
        $newEntry.push("");

      var dt_basic_table = $('.datatables-basic');
      var  dt_basic = dt_basic_table.DataTable();

    if ($new_name != '') {
      dt_basic.row
        .add($newEntry)
        .draw();

      nextID++;
      $newEntry = [];

      // Hide offcanvas using javascript method
      offCanvasEl.hide();

    }
  });

  };

JavaScript for a new entry is:


text:
Q: Angular momentum and torque in gyroscope In my textbook (Kleppner), the principle of a gyrocompass is given to be
"A flywheel free to rotate about two perpendicular axes tends to orient its spin axis parallel to the axis of rotation of the system."
While explaining the working, they do a step that I don't understand.

This is the first part of explanation which I understand.
I get that (moment of inertia)*(angular acceleration) will make a contribution to the rate of change of angular momentum along AB.

Now this is the second part of their explanation. They explain that the
spin angular momentum
that is rotating with omega is also
trying to have a component in the total angular momentum along AB
This is where I get confused. In my mind, the rotating spin angular momentum can never have a component on AB. It will always stay perpendicular to AB and will not contribute in the change in total angular momentum along AB.
I think I am missing something here. All I know is that if
TORQUE ALONG A DIRECTION IS ZERO, ANGULAR MOMENTUM WILL NOT CHANGE ALONG THAT DIRECTION
WHAT I DON'T KNOW IS THAT WHAT WILL HAPPEN IF THE DIRECTION ITSELF IS MOVING.
I would highly appreciate answers that are not extremely advanced. I know RIGID BODY DYNAMICS till EULER'S EQUATIONS

A: It seems to me that in the schematic diagrams in the screenshots that you present something essential is missing.
The idea of a mechanical gyrocompass is that the spin axis of the gyroscope wheel eventually becomes aligned with the externally imposed rotation.
For a gyrocompass that externally imposed rotation is of course the Earth's rotation.
Let me introduce a naming scheme for the axes.

I define three axes:

*

*Roll axis - the gyroscope wheel spins around the roll axis.

*Pitch axis - motion of the red frame.

*Swivel axis - motion of the yellow frame.

The following youtube video, Gyrocompass, shows a demonstration on table top scale.
The gyroscope used in that video has friction in all the bearings.
By contrast: in the idealized case we have that all parts move without any frictions. Without any friction the spin axis of the gyroscope wheel would never become aligned wih the Earth's axis. Instead the externally imposed rotation (Earth rotation) would cause the spin axis of the gyroscope wheel to sweep out a cone, never becoming aligned with the Earth axis.
In the video the wheel spin axis does become aligned, thanks to the friction in the bearings. Due to that friction the cone that the spin axis of the gyroscope sweeps out shrinks, so that eventually the spin axis becomes aligned with the externally applied rotation.
The mechanical gyrocompass is a design that is obsolete now, superseded by instruments that perform the same function, but that internally operate with fiber optic rotation measurement or rotation measurement with MEMS technology
I can hardly find any quality information about gyrocompasses. The Encyclopedia Britannica article about Gyrocompass is the best I have encountered so far
Additional resource:
On the website of the San Francisco Maritime National Park Association:
the Service manual for the Sperry Mark XIV, Mod. 1, 17-1400D Gyrocompass, which generously also contains an appendix with extended discussion of the fundamental principles of the Gyro-compass
The Sperry design includes finely tuned damping (involving mercury) so that when the gyrocompass is started from a zero spin state it settles on the geometric north in the shortest time possible.

Coming back to the treatment of gyrocompasses in the Kleppner textbook.
As far as I can tell the statements in the parts of the textbook that you copied are at odds with how gyrocompasses actually work.
That is, as far as I can tell the statements about gyrocompasses in that textbook are erroneous.

A: The rotation of the turntable will exert a torque on the axle AB. That torque vector is directed upward, is transmitted to the axle of the wheel, and will cause the angular momentum vector of the wheel to swing upward and eventually stabilize in the vertical position.  Your equations predict the rate at which this swing will occur.  In swinging up, the wheel develops an angular momentum about the AB axle, (it vector directed along the axle).  This momentum will carry it beyond the vertical position and lead to oscillations (perhaps damped by friction).

A: Although Cleonis's answer provides a bunch of excellent detail, perhaps a physical model will help understand what's going on:

*

*Gyroscopic precession in its usual form goes on forever.

*Friction that opposes the precession can/will provide a torque.

*That torque opposes the precession by tending to align the momentum axis, essentially reducing the size of the precessional circle

*Once that process runs its course, the gyroscope stabilizes with its axis aligned and can be used as a compass.
To understand those middle two steps, imagine you're looking parallel to Earth's axis. You'll see the gyroscope tip rotating in a circle around that, let's say counter-clockwise. Friction opposing that at every point is a torque toward you, pulling the gyroscope's L vector to point toward you, hence make a smaller precession circle. That repeats until it's aligned.

A:
In my mind, the rotating spin angular momentum can never have a
  component on AB. It will always stay perpendicular to AB and will not
  contribute in the change in total angular momentum along AB.
I think I am missing something here. All I know is that if TORQUE
  ALONG A DIRECTION IS ZERO, ANGULAR MOMENTUM WILL NOT CHANGE ALONG THAT
  DIRECTION WHAT I DON'T KNOW IS THAT WHAT WILL HAPPEN IF THE DIRECTION
  ITSELF IS MOVING.

You have the right doubt, and when in doubt, best to revert to the fundamentals to seek resolution. Let us recall the basic principles:

*

*Rate of change of angular momentum in an inertial frame is equal to the torque of external forces (assuming torque of internal forces is zero).

*A vector can be changed by changing the magnitude or the direction.
Keeping the above two principles in mind, we first choose the inertial frame to be the lab frame (in which the entire assembly is rotating about the vertical with angular speed $\Omega$). Let us station the origin of the lab frame at the center of the gyrocompass which is clearly stationary in the lab frame.
Next, although the direction $AB$ is changing in space, imagine a fixed moment in time $\ t = t_{o}$. At $\ t=t_o$, $AB \ $ will point in a fixed direction in space. The torque equation (principle 1 above) then tells us that the torque in direction $AB$ at $\ t = t_o$ is equal to the instantaneous rate of change of angular momentum in the direction of $AB$. Mathematically, this means calculating $\frac{\mathrm{d}\vec{L}}{\mathrm{d}t}$ at $t=t_o$ and taking its projection along $AB$.
As already explained by Kleppner-Kolenkow, the component of torque on the system along axis $AB$ in the lab frame about our chosen origin is zero (they are assuming that the center of mass of the gyroscope is at its geometrical center and no friction on the axle $AB$). So, the only task at hand is to calculate $\frac{\mathrm{d}\vec{L}}{\mathrm{d}t}$ at $t=t_o$ along $AB$.
Now, to do the calculation for $\big(\frac{\mathrm{d}\vec{L}}{\mathrm{d}t}\big)_{t=t_o}$, note that the "spin angular momentum" has a vertical as well as a horizontal component. But the horizontal component is precessing about the vertical with angular velocity $\Omega$ (because the entire assembly is rotating about the vertical)! This implies that the "direction" of the horizontal component of "spin angular momentum" in the lab frame is constantly changing. By principle 2 (stated above), this precession leads to a contribution in the expression for $\big(\frac{\mathrm{d}\vec{L}}{\mathrm{d}t}\big)_{t=t_o}$.
I'd now recommend (re-)reading the previous section in the same chapter of this book (probably goes by the name "gyroscope precession"; also check out this for visualization). The essence of that section is that in case of a purely precessional motion $-$ imagine a vector, $\vec{V}$, of fixed length, spinning about a fixed axis with instantaneous angular velocity $\vec{\omega} \ -$ we have
$$ \frac{\mathrm{d}\vec{V}}{\mathrm{d}t} = \vec{\omega} \times \vec{V}$$
In this particular case, $\vec{\omega} = \Omega \ \hat{k}$, and $\vec{V}$ is the horizontal component of the "spin angular momentum" (because remember the entire assembly is spinning about the vertical and so the horizontal component of the "spin angular momentum" is precessing too). The only minor caveat here is that $\vec{V}$ might change in magnitude $-$ however, this contributes nothing in the direction $AB$ because ($\vec{V}$ is directed perpendicular to $AB$). Clearly then, the precessional contribution in the direction $AB \ $ is given by $\Omega L_s \sin \theta $,  and happens to be the only other contribution to $\big(\frac{\mathrm{d}\vec{L}}{\mathrm{d}t}\big)_{t=t_o}$ along $AB$ apart from the usual $I_{\perp}\ddot{\theta} \ - $ and this is exactly what Kleppner-Kolenkow are claiming.
Thus, we have,
$$ \boxed{ \bigg(\frac{\mathrm{d}\vec{L}}{\mathrm{d}t}\bigg)_{t=t_o}\cdot\vec{e}_{AB} =  I_{\perp}\ddot{\theta} + \Omega L_s \sin \theta = 0 }$$
where $\vec{e}_{AB}$ is a unit vector in the direction $AB$.
While this heuristically proves the torque equation, I'd still suggest using Euler's equations or explicitly writing out the components of $\vec{L}$ in the lab frame and taking time derivatives in order to not miss other contributions in more complex setups.
Besides this, as explained by others, friction damps this (pendulum like) oscillatory motion in $\theta$, eventually aligning the axis of the gyroscope with the axis about which the platform is spinning ($\theta = 0$).
Note: This problem just illustrates the principle of a gyrocompass $-$ for an actual gyrocompass device the spinning platform is the earth.
Hope this helps.


text:
Q: how can I change the color of error text in bootstrap? When you check out my fiddle: http://jsfiddle.net/5WMff/1311/ and e.g. put incorrect email address, you can see this:
Email Please enter a valid email address.
we will not send spam

The first text appears in bold black and the second one in red. I want the first one to appear in red and the second one should stay as it was at the very beginning. How can I do that?
I'm using standard validator:
$('#invoiceForm').validate({
    rules: {
        companyName: {
            minlength: 2,
            required: true
        },
        contactName: {
            minlength: 2,
            required: true
        },
        email: {
            required: true,
            email: true
        },
        address1: {
            minlength: 2,
            required: true
        }
    },
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('success').addClass('has-error');
    },
    success: function (element) {
        element.addClass('valid')
            .closest('.form-group').removeClass('error').addClass('has-success');
    }
});

A: You're adding a class to the .form-group which contains the validation error. There are then CSS rules keyed off this class which are what is causing the style change. You can override this CSS to achieve what you require. Try this:
.has-error label.error {
    color: #a94442;
}
.has-error .help-block {
    color: #737373;
}

Updated fiddle


text:
Q: How to switch b/w admob and facebook ads in android app I am developing a app in which I want to switch ads between admob and facebook audience network from my backend or admin panel. Can anyone help me implement this. Has anyone tried it, if yes then can you share your code and is it allowed on playstore. Looking forward to your response.
And I dont wish to use mediation. I wish to change from code.


text:
Q: Why is div clearing? I have two divs with a float:left property and some width to them. They are wrapped in a container which has an overflow: hidden property.
When I change the size of my browser to be smaller in the horizontal direction I want a horizontal scroll bar to appear when the width of the window is too narrow for to display the two divs side by side. But what is happening is that the div is clearing down underneath the first div.
How can I make it so that the div does not go down when the window is too small and instead will always stay in the same row as the first div and a horizontal scroll bar will appear?
Here is my html:

    Content 1

    Content 2

and here is my css:
.col-container{
  overflow: hidden;
}

.col {

    float: left;
}
.col-1{
    width: 30%;
    margin-right: 30px;
}

.col-2{
    background-color: blue;
 }

and here is a fiddle with this html and css.

A: To make sure the two-cols don't clear you must set a minimum-width to their container:
.col-container{
    overflow: hidden;
    min-width: 150px;
}

Here is your jsfiddle with the above update:
https://jsfiddle.net/3s963o9o/2/
Another option is not to use float, but to change the structure to flexbox.

A: use flexbox for that instead

.col-container {
  display: flex
}
.col {
  flex: 1;
}
.col-1 {
  flex: 0 30%;
  margin-right: 30px;
  background: red;
}
.col-2 {
  background-color: blue;
}

    Content 1

    Content 2


text:
Q: Infer child component generics from parent type I would like to create a table component which utilizes components to define the columns like this:

interface UsageModel {
  title: string;
}

const Usage = () => {
  const data: UsageModel[] = [{ title: "Stack Overflow" }]
  return

    <TableField header="Title">{row => row.title}</TableField>

}

This works technically but Typescript doesn't know the type of row (resulting in unknown) which is kinda annoying because you have to explicitly type every field.
I was expecting Typescript to get the generic type because of the typed children prop of the table but I guess this doesn't work because of how JSX is implemented?
Does anyone know of a way to teach Typescript how to do this?
EDIT: I've created a Playground with a working example here.
The table code (minus the implementation) looks like this:
import { Component, ReactElement, ReactNode } from "react"

export interface TableFieldProps<T> {
  children: ((row: T) => ReactNode) | ReactNode
  header?: ReactNode
}

export class TableField<T> extends Component<TableFieldProps<T>> {
}

export interface TableProps<T> {
  data: T[]
  children: TableFieldElement<T> | TableFieldElement<T>[]
}

type TableFieldElement<T> = ReactElement<TableFieldProps<T>, typeof TableField>

export function Table<T>({ data, children }: TableProps<T>) {
  return (
)
}

The compiler options of typescript look like this:
{
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2021",
    "module": "esnext",
    "jsx": "react-jsx",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true
}

A: The best idea I came up with, rather than exporting a react functional component directly was to export a generic function that will return a react component and infer the generic types to the children.
This is possible, because we expect only a specific child type in the
 which is <Column /> (or <TableField /> in your case)
Take a look on the sandbox here:
https://codesandbox.io/s/wonderful-babbage-neqdyg
But basically, to simplify things, the idea is:
type ColumnType<T> = React.ReactElement<ColumnProps<T>>;

interface ColumnProps<T> {
  header?: React.ReactNode;
  children?: (row: T) => React.ReactNode;
}

interface TableProps<T> {
  data?: Array<T>;
  children?: ColumnType<T>[] | ColumnType<T>;
}

const createColumn = <T extends unknown>() => (props: ColumnProps<T>) => (<></>);

export const createTable = <T extends unknown>() => {
  const Table = (props: TableProps<T>) => {
    return (
{/* table rendering goes here */}
)
  };

  // here is the point where we infer the generic arg to a child
  Table.Column = createColumn<T>();

  return Table;
}

And the usage is:
import { createTable } from "./Table"

interface UsageModel {
  title: string;
}

const Table = createTable<UsageModel>();

const App = () => {
  return (

{row => row.title}

)
}


text:
Q: How to flip y axis in a bar3d() plot? I use bar3d() to plot a 3D barchart, and I'd like to flip the y axis. I've tried to use invert_yaxis(), but it seems effectless. I've also tried manually reverse the values in the list with [::-1], but it didn't help either. It keeps displaying the 3D barchart in the very same way.
Any idea how can I flip the y axis?
Here's an example how it's not working for me (not even with 3D line plots):
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d.axes3d import Axes3D

fig1 = figure(1)

ax11 = subplot(2, 2, 1, projection='3d')
ax11.plot([1, 2, 3, 4], [1, 2, 3, 4])

ax12 = subplot(2, 2, 2, projection='3d')
ax12.invert_xaxis()
ax12.plot([1, 2, 3, 4], [1, 2, 3, 4])

ax21 = subplot(2, 2, 3)
ax21.plot([1, 2, 3, 4])

ax22 = subplot(2, 2, 4)
ax22.invert_xaxis()
ax22.plot([1, 2, 3, 4])

show()

And the plot looks like this: http://we.tl/cqSsecVy6P
Thanks,
Daniel

A: If I understand the question correctly I think the problem is that matplotlib rotates the 3D plot. To remedy this just set the initial viewing angle using ax.view_init(elev, azim). Taking the matplotlib hist3d demo then we just have
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4)

elements = (len(xedges) - 1) * (len(yedges) - 1)
xpos, ypos = np.meshgrid(xedges[:-1]+0.25, yedges[:-1]+0.25)

xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

ypos_inv = ypos
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
ax.view_init(ax.elev, ax.azim+90)
plt.show()

Here I have rotated the axis by 90 degrees which flips one of the axis but not the other.


text:
Q: How to remove Escape character in a string I created an API that accepts one string parameter, but when i tried "" as a searchterm, the output result has an escape character. How can I remove this? Thank you
searchterm = searchterm.Replace(@"\", String.Empty);

I tried this but still having escape character.
This is my code c#
public static JToken getRelatedKeywordsApiSpTable(string searchterm)
{
  JObject results = new JObject();
  searchterm = searchterm.Replace(@"\", String.Empty);
  DataSet ds = SearchData.getRelatedKeyword(searchterm);
  DynamicCollabObject relatedkeywords = new DynamicCollabObject(ds);
  results.Add("RelatedKeywords", relatedkeywords.dobject);
  return results;
}

public static DataSet getRelatedKeyword(string searchterm)
{
    List<SqlParameter> parameters = new List<SqlParameter>();
    parameters.Add(new SqlParameter("@st", searchterm));
    return SQLDAL.runSPWithParams(SearchSPs.getRelatedKeywordApi, parameters, SearchSettings.badlands);
}

This is my endpoint
[HttpGet]
[Route("relatedkeyword/{searchterm}")]
public IHttpActionResult RelatedKeywordApiTable(string searchterm)
{
    return Ok(SearchBusiness.getRelatedKeywordsApiSpTable(searchterm));
}

My SP
select top 20 relatedkeyword as Keyword, [count] as [Count]
from Transform_DIM_RelatedKeyword_Count  WITH (NOLOCK)
where searchterm=@st
order by count desc

Output:
{
  "RelatedKeywords": [
    {
      "Keyword": "\"\"",
      "Count": 7
    }
    ]
}

My expectation should look like actual input searchterm


text:
Q: Choosing an implementation of a function with a given signature I want have some piece of code where I want to call a function foo with different implementations of foo residing in different modules.
Like
foo :: String -> IO[String]

module A:
foo :: String -> IO[String]
foo x = whatever

module B:
foo :: String -> IO[String]
foo x = whatever (different)

and then call the appropriate function based on some parameter. I could do with qualified imports:
import qualified ModuleA as A
import qualified ModuleB as B

bar :: String -> String -> IO[String]
bar moduleToChoose x = case moduleToChoose of
    "A" -> A.foo x
    "B" -> B.foo x
    _ -> Uh oh...

This, however basically screams "There is a so much more elegant™ solution to this but you just don't get it!" Is there a better solution?

A: Modules aren't first class in Haskell, and so there is no way to use them directly as parameters. In any case, an improvement on your solution would be using a sum type to encode the distinction in a richer and safer way. That can feel pretty natural given meaningful names for modules, types and values (i.e., names that actually reflect what you are trying to do):
import qualified Formatting.Mimsy as Mimsy
import qualified Formatting.Slithy as Slithy

data FormattingStyle = Mimsy | Slithy

foo :: FormattingStyle -> String -> IO [String]
foo style x = case style of
    Mimsy  -> Mimsy.foo x
    Slithy -> Slithy.foo x

You might want to take this a step further and encode the case switch using a type class:
class Fooer a where
    foo :: a -> String -> IO [String]

data Mimsy = Mimsy

instance Fooer Mimsy where
    foo _ x = undefined -- etc.

data Slithy = Slithy

instance Fooer Slithy where
    foo _ x = undefined -- etc.

Another possibility is to use newtype wrappers around String and a Fooable class, akin to Lee Duhem's answer. Either way, using classes for that feels like overkill to me, so I'd stick with the simple sum type solution.
Yet another approach is using records of functions instead of type classes. That, too, is overkill here, though arguably less so than using classes:
data Fooer = Fooer { foo :: String -> IO [String] }

-- Export only mimsy and slithy, and not the Fooer constructor.

mimsy :: Fooer
mimsy = Fooer { foo = Mimsy.foo }

slithy :: Fooer
slithy = Fooer { foo = Slithy.foo }

A: I would change bar to take the auxiliary funcion directly as a parameter, instead of using a selector parameter.
bar :: (String -> IO [String]) -> String -> IO [String]

Outside the function (possibly in my Main.hs) I would construct the following map:
strategies :: M.Map String (String -> IO [String])
strategies = M.fromList [("A",A.foo), ("B",B.foo)]

This map allows us to decouple the aggregation of the known implementations from the selection of what implementation to use.
The process of looking into the map and constructing the actual bar' :: String -> IO [String] function in which we are interested should be relegated to the outermost layers of your program. That way, dependencies are minimized and "strategy not found" errors are detected sooner.

A: One possible solution is using user-defined typeclass, like this:
FooClass.hs
module FooClass (FooClass(..)) where

class FooClass a where
    bar :: a -> IO [String]

A.hs
module A where

import FooClass

data A = A String deriving (Show)

foo :: A -> IO [String]
foo (A s) = return ["A", s]

instance FooClass A where
    bar = foo

B.hs
module B where

import FooClass

data B = B String deriving (Show)

foo :: B -> IO [String]
foo (B s) = return ["B", s]

instance FooClass B where
    bar = foo

After all those code, you can use them like this:
t.hs
import FooClass
import A
import B

main = do
    a <- bar (A "bar")
    b <- bar (B "bar")
    putStrLn $ show (a, b)

Testing:
$ runhaskell t.hs
(["A","bar"],["B","bar"])


text:
Q: Sumar valor de Inputs en React js de forma dinamica Estoy aprendiendo React, mi intención es crear 3 inputs de tipo numero y un cuarto el cual muestra la sumatoria total de los anteriores en tiempo real.
Logro mostrar la sumatoria total pero al momento de cambiar el valor de un input, la sumatoria total sigue incrementando teniendo en cuenta los valores anteriores.
<input type='number' onChange={ e => setResultado(resultado + parseFloat(e.target.value))}/>

Luego probe crear un useState para cada input de la siguiente manera:
<input type='number' value={input1} onChange={ e => setInput1(parseFloat(e.target.value))}/>

pero en esta ultima no logro mostrar la sumatoria en tiempo real, ¿podría ser utilizadon un useEffect?

A: Lo que entiendo de la pregunta que hiciste es que estas teniendo 3 inputs de tipo number y un 4 input que refleja la suma de los 3 inputs, prepare ese ejemplo
export default function App() {

  const [number, setNumber] = useState({one: 0, two: 0, three: 0})
  const [suma, setSuma] = useState()

  useEffect(()=>{
    const { one, two, three } = number
    setSuma(Number(one) + Number(two) + Number(three))
  },[number])

  const handleInput = (event) => {
    const { name, value } = event.target
    setNumber({...number, [name]: value})
  }

  return (
    <div className="App">
      <input className="input" onChange={handleInput} name="one" value={number.one} placeholder="Ingesa un numero (1)"/>
      <input className="input" onChange={handleInput} name="two" value={number.two} placeholder="Ingesa un numero (2)"/>
      <input className="input" onChange={handleInput} name="three" value={number.three} placeholder="Ingesa un numero (3)"/>
      <input value={suma}/>
    </div>
  );
}

paso a explicar como es que funciona esta porción de código, el hook number contiene un objeto con los valores de los 3 principales inputs, el hook suma es el que contiene la suma de los 3 inputs, la funcion handleInput es la que controla los 3 inputs principales, desde el event.target destructuro el campo name y el campo value, el campo name es el atributo name de los inputs, entonces lo que hago es actualizar el valor del hook number, como es un objeto, lo que hago es decirle que va a seguir teniendo el mismo valor con un simple ...number y luego hago uso del name como clave para actualizar solamente ese campo sin alterar los demas, y utilizo el value para asignarle el nuevo valor, luego hago uso del useEffect para actualizar el hook suma cada vez que el hook number cambie, destructuro el hook number, y luego prosigo con la suma, utilizo el constructor Number para poder sumar los numero ya que js no sabe que por defecto es un numero y de no utilizar el constructor este mismo se concatenarían y no sumarian, espero que hayas entendido mas o menos por donde va la mano, te dejo un ejemplo para que puedas interactuar con el código, saludos