text:
Q: Android check recognized sensors i need a little help: how to check recognized sensors?
Because a made a project and on gs2 has all the sensors(acc,gyro, etc.) but on galaxy ace there are only acc as i know.

A: This is most likely what you are looking for in checking the features programtically
PackageManager PM= this.getPackageManager();
boolean gps = PM.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS);
boolean acc = PM.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);

This link explains what you can do to filter your application in the marketplace, look specifically at the section
i think i found it...

A: 1.: Get SensorManager:
`mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);`

2.: Get Sensor list:
List< sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);

3.: Print the sensors:
for( Sensor s : sensorList) {
 Log.d("sensor", "Name=" + s.getName());
 Log.d("sensor", "Vendor=" + s.getVendor());
 Log.d("sensor", "Version=" + s.getVersion());
 Log.d("sensor", "MaximumRange=" + s.getMaximumRange());
 Log.d("sensor", "MinDelay=" + s.getMinDelay());
 Log.d("sensor", "Power=" + s.getPower());
 Log.d("sensor", "Type=" + s.getType());
}


text:
Q: @Autowired doesn't work correctly as expected in Spring components I have a very simple configuration and a big confusion that I need help resolving.
I have a BaseController which is annotated with @RestController. In this class I have a method that returns a String and is annotated with @GetMapping. I am reading properties file from it and displaying the application value. Till here, all works GOOD. Below are my files,
@RestController
public class BaseController {

    @Autowired
    Environment env;

    @GetMapping("/hello")
    public String hello() {
        String myAppName = env.getProperty("spring.application.name");
        return "From Controller -> " + myAppName;
    }
}

My application.properties file,
server.servlet.context-path=/BootEnv
server.port=8085
spring.application.name=EnvironmentAPITester

When I hit,

http://localhost:8085/BootEnv/hello

, I get proper response like below,
From Controller -> EnvironmentAPITester

Here in code, Environment variable is org.springframework.core.env.Environment;
All is GOOD till here.
Now I have created a new @Configuration class named ApplicationConfig. I want to read the properties file from that class as well and return the values. So below are the changes I did,
@RestController
public class BaseController {

    @Autowired
    Environment env;

    @GetMapping("/hello")
    public String hello() {
        String myAppName = env.getProperty("spring.application.name");
        return "From Controller -> " + myAppName;
    }

    @GetMapping("/helloConf")
    public String getDetails() {
        ApplicationConfig conf = new ApplicationConfig();
        String fromConfig = conf.details();
        return "From Config -> "+fromConfig;
    }
}

And the class below,
@Configuration
public class ApplicationConfig{

    @Autowired
    Environment env;

    public String details() {
        return env.getProperty("spring.application.name");
    }
}

Now when I hit,

http://localhost:8085/BootEnv/helloConf

I get a null pointer exception as the Environment variable is null and does NOT get auto configured. HOW? And WHY?
After googling, I came to a solution which asked me to implement EnvironmentAware interface and set the Environment variable that way. So below are the changes I had to make to my ApplicationConfig class,
@Configuration
public class ApplicationConfig implements EnvironmentAware{

    @Autowired
    Environment env;

    public String details() {
        return env.getProperty("spring.application.name");
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }
}

After doing this also, it still gave me null pointer exception for the same Environment variable value. Then I figured out that not only I had to remove the @Autowire annotation but I ALSO needed to make that variable static to make it work. So when I do,
//@Autowired
static Environment env;

It works perfectly. And when I hit,

http://localhost:8085/BootEnv/helloConf

I get proper response,
From Config -> EnvironmentAPITester

The confusion is WHY do I need to make it static so that it fills the value? Why the EnvironmentAware implementation can't set the Environment variable while it is still @Autowired?
And why in the first place, @Autowired does not fill the Environment variable when the class ApplicationConfig class is marked with @Configuration annotation? Even if I change this class annotation to @Service or @Repository or @Component the same issue persists of failing to@Autowire the Environment variable. How come?
I know it's a long post. But any clarification on this is highly appreciated as I am having hard time understanding this.
Thanks for your help in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting the node created by a document fragment If I insert a document fragment into the DOM like so:
const ul = document.querySelector("ul");
const fruits = ["Apple", "Orange", "Banana", "Melon"];

const fragment = new DocumentFragment();

for (const fruit of fruits) {
  const li = document.createElement("li");
  li.textContent = fruit;
  fragment.append(li);
}

ul.append(fragment);

Is there an API for getting the newly created li without using data attributes?

A: you can use index to get child node
ul.childNodes[0];

If you want to get child node by text content, you can do something like following:
Array.from(ul.querySelectorAll('li'))
  .find(el => el.textContent === 'Apple')


text:
Q: Заполнение ProgressBar Есть такой метод:
public static async void DownloadFile(string filename, IProgress<decimal> progress)
{
    progress.Report(0m);

    using (WebClient request = new WebClient())
    {
        request.Credentials = new NetworkCredential("login", "password");

        byte[] fileData = request.DownloadData("ftp://...." + filename);

        var pathNormalize = $"{MyPath.Desktop}\\{filename}".Replace("\r", string.Empty);

        using (var file = File.Create(pathNormalize))
        {
            await file.WriteAsync(fileData, 0, fileData.Length);
            var percent = 100m * ((decimal)file.Position / file.Length);
            progress.Report(percent);
        }
    }
}

Вызываю так:
var progress = new Progress<decimal>((p) =>
{
    progressBar1.Value = (int)Convert.ToDecimal(p)));

    if (progressBar1.Value >= progressBar1.Maximum)
    {
        progressBar1.Value = 0;
        MessageBox.Show("Completed!");
    }
});

FTP.DownloadFile(name, progress);

Проблема:
При вызове метода DownloadFile блокируется основной поток и в конце значение ProgressBar становится 100.
Если вызывать так:
Task.Run(() => FTP.DownloadFile(name, progress));

Основной поток не блокируется, но ProgressBar также перескакивает к значению 100.
При всём при этом, после скачивание файла не показывает текст Completed!.
Нашел на просторах интернета уже не один пример скачивания файла с FTP, но ни один так и не удалось подружить с ProgessBar.
Подскажите, пожалуйста, в чем проблема. Пытаюсь разобраться уже много времени.
upd:
public static void DownloadFile(string filename, DownloadProgressChangedEventHandler DownloadProgressChanged, System.ComponentModel.AsyncCompletedEventHandler DownloadCompleted)
{
    Thread thread = new Thread(() =>
    {
        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("login", "password");
            request.DownloadProgressChanged += DownloadProgressChanged;
            request.DownloadFileCompleted += DownloadCompleted;

            var pathNormalize = $"{MyPath.Desktop}\\{filename}".Replace("\r", string.Empty);
            request.DownloadFileAsync(new Uri("ftp://....." + filename), pathNormalize);
        }
    });
    thread.Start();
}

private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate {
        progressBar1.Value = e.ProgressPercentage;
    });
}

private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate {
        MessageBox.Show("Completed!");
    });
}

A: Проблема оказалось в том, что при скачивании с FTP с отображением прогресса, нужно для начала узнать размер файла.
Вот рабочий код:
public static void DownloadFile(string filename, DownloadProgressChangedEventHandler DownloadProgressChanged, System.ComponentModel.AsyncCompletedEventHandler DownloadCompleted)
{
    Thread thread = new Thread(() =>
    {
        var request = (FtpWebRequest)WebRequest.Create("ftp://......" + filename);
        request.Credentials = new NetworkCredential("login", "password");
        request.Method = WebRequestMethods.Ftp.GetFileSize;
        var response = (FtpWebResponse)request.GetResponse();

        using (Stream responseStream = response.GetResponseStream())
        {
            MainForm.bytes = response.ContentLength;
        }

        using (WebClient request_ = new WebClient())
        {
            request_.Credentials = new NetworkCredential("login", "password");
            request_.DownloadProgressChanged += DownloadProgressChanged;
            request_.DownloadFileCompleted += DownloadCompleted;

            var pathNormalize = $"{MyPath.Desktop}\\{filename}".Replace("\r", string.Empty);
            request_.DownloadFileAsync(new Uri("ftp://....." + filename), pathNormalize);
        }
    });
    thread.Start();
}

private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate {
        progressBar1.Value = (int)(((float)e.BytesReceived / (float)bytes) * 100.0);
    });
}

private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate {
        MessageBox.Show("Completed!");
    });
}

//где-то вызов
FTP.DownloadFile(name, DownloadProgressChanged, DownloadCompleted);


text:
Q: Some doubts about how to show posts in a custom theme? I am pretty new in WordPress theme development and I have some doubt about this WP function used to show my post in the homepage:
    <?php
        if ( have_posts() ) :
            // Start the Loop.
            while ( have_posts() ) : the_post();

                /*
                 * Include the post format-specific template for the content. If you want to
                 * use this in a child theme, then include a file called called content-___.php
                 * (where ___ is the post format) and that will be used instead.
                 */
                get_template_part( 'content', get_post_format() );

            endwhile;
            // Previous/next post navigation.
            twentyfourteen_paging_nav();

        else :
            // If no content, include the "No posts found" template.
            get_template_part( 'content', 'none' );

        endif;
    ?>

Intuitively I understood that as long as there are posts these are displayed in the homepage.
My doubt is related about this line of code:
get_template_part( 'content', get_post_format() );

Reading the documentation it seems to me that:
1) get_template_part: Load a template part into a template. So I think that by this line I am including a template part used to show a post (the structure of a post into my homepage), is it correct?
2) What exactly do get_post_format() ?

A: get_template_part() is including a template file from the active theme directory.
For example:
get_template_part('content') will include the template content.php from the theme folder.
When having two parameters, it will search for a template named firstParameter-secondParameter.php. So:
get_template_part( 'content', get_post_format() );

will include the content-{$post_format}.php file.
get_post_format() returns one of this defined formats:
aside
chat
gallery
link
image
quote
status
video
audio

or false. So the file included will be content.php or content-format.php

A: 1) Yes!
2) WordPress supports 9 post formats now, let's say if your theme support 2 of them: 'aside' and 'gallery', there should be the following code in your functions.php:
add_theme_support( 'post-formats', array( 'aside', 'gallery' ) );

You could build different content template part for each post format, and save them as 'content-aside.php' and 'content-galery.php' in your theme folder.
If you don't have those 2 files in your theme, get_template_part will automatically fallback to use the 'content.php' instead.

A: All the good WordPressers have already answered your questions, and I think they are successful in eliminating your doubts. So I'm not touching exactly into your question, but to the concepts.
Before starting theme developing, I think a raw theme can be very good to understand the concept behind each specific zones. I started theme development with my [virtual] teacher Ian Stewart's tutorial on how to develop a theme:

*

*How to Create a WordPress Theme: The Ultimate WordPress Theme Tutorial
Source Code of the entire tutorial is in Google Code Trunk. I'd suggest you to not just follow the tutorial, but to read the comments too. :)
get_template_part() is a theme function - not necessarily it loads only the post part - rather it can be anything. The code part (a portion of the code) you want to separate from the main file, in PHP we include that using include() function, but in WordPress, we do it using get_template_part().
The code you mentioned, separated the template part where the code to show the post resides. You can comment out that portion and can try the following to understand the basic:
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
//get_template_part( 'content', get_post_format() ); ?>
   <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

<?php the_title(); ?>

<?php the_content(); ?>

<?php
endwhile;
endif;
?>

Sorry, I's not actually with your question, but I tried to pass the concept, and I believe CONCEPT WITH DIFFERENT PERCEPTIONS IS THE KEY TO KNOWLEDGE.
EDIT
You may also start with the _s starter theme. Get it directly from GitHub:

*

*_s / underscores theme - GitHub


text:
Q: Is it possible to mark an assembly as deprecated? I'd like to produce a warning message when users compile code that references an assembly we're planning on removing. The contents of this assembly have been merged with another, and I'd like to encourage users to stop referencing the old assembly.
Unfortunately, it looks like ObsoleteAttribute is not valid for assemblies. Is there any other way to cause a compiler warning when a project referencing an assembly is built?
Thanks.
EDIT: For clarification, here's what the assemblies look like before and after the merge
Before the merge:
Assembly1:
namespace A.B.C {
    class C1
    ...
}

Assembly2:
namespace A.B.D {
    class D1
    ...
}

After the merge:
Assembly1:
(empty)

Assembly2:
namespace A.B.C {
    class C1
    ...
}

namespace A.B.D {
    class D1
    ...
}

Before the merge, users referenced both Assembly1 and Assembly2. After the merge, they only need to reference Assembly2, but I'd rather produce a warning that Assembly1 is no longer necessary than break their builds by removing Assembly1 right away.
It sounds like I should use type forwarders to make sure that programs that have already been built against these assemblies continue to work without requiring recompilation, but I don't want to leave stub classes in Assembly1 just to flag the assembly as obsolete.

A: Mark each of the classes in the old assembly as unusable.
This worked for me:
[Obsolete("Deprecated.  Use 'Substitute' class in 'NewAssembly' instead.")]
public class OutdatedClass : IDisposable, IXmlSerializable
{
    //code...
}

When attempting to compile, I got tons of warning about using that class.
You can make it a compile error to reference the assembly by passing True as the second parameter to the attribute.
[Obsolete("Deprecated.  Use 'Substitute' class in 'NewAssembly' instead.", true)]

public class OutdatedClass : IDisposable, IXmlSerializable
{
    //code...
}

I just tested that, and it also worked (i.e. - compiling failed)

A: I don't see anything specific on MSDN. You could, however, create your own assembly attribute but only if you think it is that important. Then again, doing so does not prevent someone from using it and I'm not sure how you could even let someone know that it has been deprecated.
Honestly, I think I would place [Obsolete] on the publicly accessible classes.
Based on what I read on @Eric's post and the link he provided along with WS' comment, use [TypeForwardedTo].

A: When moving types from one assembly to another the correct thing to do is to use a type forwarder, not to mark the old assembly classes as obsolete.
See: "CLR Hoser - The Wonders of Whidbey Factoring Features – Part I: Type Forwarders" by Richard Lander (2005)


text:
Q: How to express the curvature in polar coordinates with DSolveChangeVariables (or without it)? The curvature k[x] of a plane curve y==y[x] is given by
k[x] == RealAbs[y''[x]]/(1 + y'[x]^2)^(3/2)
(see Wiki for info).
The above relation can be treated as an ODE in y[x] with a known k[x]. Is it possible to express that relation
in the polar coordinates, making use of  a new command in version 13.1 DSolveChangeVariables?
The documentation says about "Cartesian" -> "Polar" only for PDEs.

A: Yes, it can be done in two steps.
First,
DSolveChangeVariables[Inactive[DSolve][k[x] == RealAbs[y''[x]]/(1 + y'[x]^2)^(3/2), y,x],
 y, θ, x == r[θ]*Cos[θ]]

Inactive[DSolve][ k[Cos[θ] r[θ]] ==  RealAbs[(-(( Derivative[1][ y][θ] (-Cos[θ] r[θ] -  2 Sin[θ] Derivative[1][r][θ] +  Cos[θ] ( r^′′)[θ]))/(-r[θ] \ Sin[θ] + Cos[θ] Derivative[1][r][θ])^2) + ( y^′′)[θ]/(-r[θ] Sin[θ] +  Cos[θ] Derivative[1][ r][θ]))/(-r[θ] Sin[θ] +  Cos[θ] Derivative[1][r][θ])]/(1 +  Derivative[1][ y][θ]^2/(-r[θ] Sin[θ] +  Cos[θ] Derivative[1][r][θ])^2)^( 3/2), y, θ]

Second,
DSolveChangeVariables[Inactive[DSolve][k[Cos[θ] r[θ]] ==
RealAbs[(-((Derivative[1][
      y][θ] (-Cos[θ] r[θ] -
       2 Sin[θ] Derivative[1][r][θ] +
       Cos[θ] (r^′′)[θ]))/(-r[θ]
Sin[θ] + Cos[θ] Derivative[1][r][θ])^2) + (
    y^′′)[θ]/(-r[θ] Sin[θ] +
    Cos[θ] Derivative[1][
      r][θ]))/(-r[θ] Sin[θ] +
   Cos[θ] Derivative[1][r][θ])]/(1 +
   Derivative[1][y][θ]^2/(-r[θ] Sin[θ] +
     Cos[θ] Derivative[1][r][θ])^2)^(3/2),
   y, θ], r, θ,  y[θ] == r[θ]*Sin[θ]] // Simplify

Inactive[DSolve][ k[Cos[θ] r[θ]] ==  RealAbs[( r[θ]^2 + 2 Derivative[1][r][θ]^2 -  r[θ] ( r^′′)[θ])/(r[θ] Sin[θ] -  Cos[θ] Derivative[1][r][θ])^3]/(( r[θ]^2 +  Derivative[1][r][θ]^2)/(r[θ] Sin[θ] -  Cos[θ] Derivative[1][r][θ])^2)^(3/2), r, θ]

$k(\cos (\theta ) r(\theta ))=\frac{\left| \frac{r(\theta )^2-r''(\theta ) r(\theta )+2 r'(\theta )^2}{\left(r(\theta ) \sin (\theta )-\cos (\theta ) r'(\theta )\right)^3}\right| }{\left(\frac{r'(\theta )^2+r(\theta )^2}{\left(\sin (\theta ) r(\theta )-\cos (\theta ) r'(\theta )\right)^2}\right)^{3/2}}$


text:
Q: Javascript/Jquery : How Loop value date range In normal Loop, we can loop number :
for(var i=1; i <= 4; i++){
 console.log(i);//result : 1,2,3,4
}

And this case, i want to do loop with value date, so i can get date range.
for(var i="11-04-2018"; i <= "14-04-2018"; i++){
  console.log(i);
  //hope can like this result : 11-04-2018,12-04-2018,13-04-2018,14-04-2018
}

But i know that's code, will be error :(
Hope someone can understand what i mean :)
Thanks..

A: Finally, I know how to loop value date:
Just do like this, and work:
var now = new Date(2018, 5, 12);
var daysOfYear = [];
for (var d = new Date(2018, 5, 10); d <= now; d.setDate(d.getDate() + 1)) {
    daysOfYear.push(new Date(d));
}
console.log(daysOfYear)

source: Javascript loop between date ranges


text:
Q: How to play Mortal Kombat Arcade Kollection in offline 2-player versus mode without Xbox 360 controller under Win XP? I have Mortal Kombat Arcade Kollection on Steam and had some problems playing it with a non-Xbox 360 USB controller - basically the Y-axis (vertical) is inverted and certain buttons are not recognized properly in the menu. Controller options in pause menu suggest compatibility only with Xbox 360 controller.
Is it possible to play 2-player versus mode on one computer using keyboard & non-Xbox 360 USB controller?


text:
Q: An integer divisible by 8 and 15 must also be divisible by 24. Why? I have a question on the GRE that says "If an integer is divisible by both 8 and 15, then the integer must also be divisible by" and the choices are:

*

*16

*24

*32

*36

*45

The answer is 24. I guess I could figure out that the first common multiple of 8 and 15 is 120 and plug in the numbers, but is there a more sophisticated way to do it? Something that follows from the properties of 8 and 15? It happens that 24 is the only number that goes into 120 but what if it wasn't? Is there a way to prove that 24 is the only one that works?

A: If $K$ is divisible by $a$ and $K$ is divisible by $b$ then $K$ is divisible by the least common multiple of $a$ and $b$.  ANd $K$ is divisible by all factors of the least common multiple of $a,b$.
The least common multiple of $8$ and $15$ is $8*15 = 120$.  And the factors of $120$ are $1,2,3,4,5,6,8,10,               12,15,20,24,30,40,60,120$ and those will all divide the integer.  $24$ is the only one on the list.
Of course you don't have to create the entire list.  You just have to know $120$ divide the integer so anything that divides $120$ will also divide the integer.  And $24$ is the only thing on the list that divides $120$.
More detail:
$8 = 2^3$ and $15 = 3^15^1$ and the least common multiple of $8$ and $15$ is $2^33^15^1$ and that divides our integer.  So any number of the form $2^a3^b5^c$ where $a$ is at most $3$, $b$ is at most $1$ and $c$ is at most $1$ (and they can be $0$) will divide the integer.  But if any of the factors have larger powers or if the have primes other than $2,3,5$ we can't know they divide the integers.
$16 = 2^4$ that's out because $4 > 3$.
$24 = 2^3*3^1$ that's okay because $3 \le 3$ and $1 \le 1$.
$32 = 2^5$ that's out because $5 > 3$.
$36 = 2^2*3^2$ and that's out because $2 > 1$.
$45= 3^2*5^1$ and that's out because $2 > 1$.

A: If this integer is divisible by $8$ and $15=3×5,$ then it is perforce divisible by $8$ and $3,$ and consequently, by $8×3$ as well.

A: The prime numbers tell you everything here. The list of possible answers are relatively small so I'd begin by factoring each out:
$$16 = 2^4$$
$$24 = 8 \cdot 3 = 2^3 \cdot 3$$
$$32 = 2^5$$
$$36 = 6^2 = 2^2 \cdot 3^2$$
$$45 = 3^2 \cdot 5.$$
Now, a number divisible by $8 = 2^3$ must have at least $3$ factors of $2$ and a number divisible by $15 = 3 \cdot 5$ must have at least one factor of $3$ and at least one factor of $5$.
Let's now take a look at the list of possible answers. $16$ and $32$ won't work since we only require $3$ factors of $2$. $36$ and $45$ won't work because we require just one factor $3$. Hence the only remaining possibility among the list is $24$ (this case can be verified to be fine but I'd probably fill in $24$ and move on since it's the GRE).

A: We prove the following general result:
If
$p, q \in \Bbb P \tag 1$
are distinct primes and
$n \in \Bbb Z \tag 2$
with
$p^3 \mid n, \; q \mid n, \tag 3$
then
$p^3q \mid n; \tag 4$
for we have
$\gcd(p^3, q) = 1; \tag 5$
hence by Bezout's identity there exist $a, b \in \Bbb Z$ such that
$ap^3 + bq = 1; \tag 6$
we multiply this through by $n$:
$ap^3n + bqn = n; \tag 7$
we also have
$p^3 \mid n \Longrightarrow n = p^3x, \; x \in \Bbb Z, \tag 8$
$q \mid n \Longrightarrow n = qy, \; y \in \Bbb Z; \tag 9$
we substitute (8) and (9) into (7):
$ap^3qy + bqp^3x = n, \tag{10}$
whence
$p^3q(ay + bx) = n \Longrightarrow p^3q \mid n. \tag{11}$
Now taking
$p = 2, q = 3  \tag{12}$
yields the specific result that
$24 = 2^3 \cdot 3 \mid n. \tag{13}$
Note Added in Edit, Wendesday 13 November 2019 9:50 AM PST:  It is perhaps worth noting that our result here may easily be extended from the case $p^3 \mid n$ to the case $p^k \mid n$ for arbitrary $k \in \Bbb N$; indeed, one need merely walk through the above with $p^3$ replaced by $p^k$ to see that this is so.
It is also likely worth pointing out that
$\gcd(p, q) = 1 \Longrightarrow \gcd(p^k, q) = 1, \; \forall k \in \Bbb N; \tag{14}$
indeed, we may write
$ap + bq = 1, \; a, b \in \Bbb Z; \tag{15}$
focussing for the moment on the case $k = 2$ we multiply (15) through by $p$:
$ap^2 + bqp = p; \tag{16}$
then
$\gcd(p^2, q) = d > 1 \Longrightarrow d \mid p^2, \; d \mid q; \tag{17}$
by virtue of (16) this implies
$d \mid p \Rightarrow \Leftarrow \gcd(p, q) = 1; \tag{18}$
this contradiction forces
$\gcd(p^2, q) = 1; \tag{20}$
this logic may be extended to general $k \in \Bbb N$ by an inductive argument: if
$\gcd(p^k, q) = 1, \tag{21}$
we multiply (15) by $p^k$:
$ap^{k + 1} + bqp^k = p^k; \tag{22}$
now if
$\gcd(p^{k + 1}, q) = d > 1, \tag{23}$
as above we have
$d \mid p^{k + 1}, \; d \mid q \Longrightarrow d \mid p^k, \tag{24}$
which of course is precluded by (21); therefore
$\gcd(p, q) = 1 \Longrightarrow \gcd(p^k, q) = 1, \; \forall k \in \Bbb N. \tag{25}$
End of Note.


text:
Q: How do WWDC presenters paste text during demos? During demos in the WWDC videos, the presenter will often paste code into Xcode to save having to type it in. How are they pasting each different snippet without switching to another app to copy it?

A: Apple used custom code called "Demo Monkey" whose source code is available on GitHub.

A: You can create custom Xcode snippets. Snippets can include from one method to whole program.
Check this article on NSHipster, for me is one of the best explanations of this that I found.

A: They could be using an app that binds keyboard shortcuts to multiple clipboards, such as CopyClip.


text:
Q: Cómo evitar valores repetidos en barchart de reporte jaspersoft tengo un problema al generar un reporte con varios registros de personas, en el cual pinto una grafica de scores tipo BarChart como este:

La gráfica esta en un detail band, ya que se debe pintar por cada persona que venga en los registros.
El problema está en que cuando son varios registros, las gráficas pintan el mismo valor para todas las personas, lo cual esta mal. Estoy usando jaspersoft studio 6.6 y spring boot.
<barChart>
                <chart isShowLegend="false" evaluationTime="Report">
                    <reportElement isPrintRepeatedValues="false" x="191" y="194" width="170" height="110" uuid="65065fea-fdcc-447d-8f6a-84f741e1a563"/>
                    <chartTitle/>
                    <chartSubtitle/>
                    <chartLegend/>
                </chart>
                <categoryDataset>
                    <dataset>
                        <datasetRun subDataset="dataSetScore" uuid="d1192fc3-de24-49be-baf6-c028bc66146b">
                            <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{listaScore})]]></dataSourceExpression>
                        </datasetRun>
                    </dataset>
                    <categorySeries>
                        <seriesExpression><![CDATA["SERIES 1"]]></seriesExpression>
                        <categoryExpression><![CDATA[$F{anio}]]></categoryExpression>
                        <valueExpression><![CDATA[$F{score}]]></valueExpression>
                    </categorySeries>
                </categoryDataset>
                <barPlot isShowLabels="true" isShowTickLabels="true" isShowTickMarks="true">
                    <plot>
                        <seriesColor seriesOrder="0" color="#5670DB"/>
                    </plot>
                    <itemLabel color="#000000">

                    </itemLabel>
                    <categoryAxisFormat>
                        <axisFormat labelColor="#000000" tickLabelColor="#000000" verticalTickLabels="true" axisLineColor="#000000">
                            <labelFont>

                            </labelFont>
                            <tickLabelFont>

                            </tickLabelFont>
                        </axisFormat>
                    </categoryAxisFormat>
                    <valueAxisFormat>
                        <axisFormat labelColor="#000000" tickLabelColor="#000000" axisLineColor="#000000">
                            <labelFont>

                            </labelFont>
                            <tickLabelFont>

                            </tickLabelFont>
                        </axisFormat>
                    </valueAxisFormat>
                    <rangeAxisMinValueExpression><![CDATA[0]]></rangeAxisMinValueExpression>
                    <rangeAxisMaxValueExpression><![CDATA[1000]]></rangeAxisMaxValueExpression>
                </barPlot>
            </barChart>

A: Ya lo resolví, el problema estaba en la propiedad llamada Evaluation Time del chart. El valor por defecto es Evaluation Time = Report y lo cambié a Evaluation Time = Band.

Los datos los paso con un field de tipo lista


text:
Q: How to restart my minikube kubernetes cluster in AWS instance, after stopping and starting that instance? I had a t2.micro server running where i had deployed Minikube, however due to memory issue i scared up the server size. For which i had to stop and start the instance.
But now after restarting, when i try with kubectl commands i get the below error.
root@ip-172-31-23-231:~# kubectl get nodes
The connection to the server 172.31.23.231:6443 was refused - did you
specify the right host or port?

So, how can i bring my earlier kube cluster up once i restart my AWS instance?

A: I had the same error. In my case minikube was not running. I started it with
minikube start

A: There are few methods to fix this issue.
Solution: 1
If all components are Stopped and if you run some commands you will get information to start the cluster again. This is usually solving this kind of issue. Starting the minikube cluster again won't delete anything from your cluster.
Example
$ minikube logs
  The control plane node must be running for this command
  To start a cluster, run: "minikube start"
---
$ minikube status
minikube
type: Control Plane
host: Stopped
kubelet: Stopped
apiserver: Stopped
kubeconfig: Stopped
timeToStop: Nonexistent
---
$ minikube start
---
$ minikube status
minikube
type: Control Plane
host: Running
kubelet: Running
apiserver: Running
kubeconfig: Configured
timeToStop: Nonexistent

Solution: 2 use followed commands
$ sudo -i
$ swapoff -a
$ exit
$ strace -eopenat kubectl version

Solution: 3 Restart docker service
$ sudo service docker restart

And wait ~20-40 seconds
Solution: 4
As the last option if everything else fails, you can delete and create a new Minikube.
$ minikube delete
  Deleting "minikube" in docker ...
  Deleting container "minikube" ...
---
$ minikube start

This option unfortunately will delete all your resources from the cluster. It will create cluster from scratch.
Useful information and commands:

*

*Minikube Troubleshooting guide

*$ minikube logs

*$ minikube dashboard

*$ minikube status

A: check this :
run -> minikube status
host: Running
kubelet: Running
apiserver: Running
kubectl: Correctly Configured: ...

if isn't running -> minikube start
then check the dashboard -> minikube dashboard


text:
Q: Finding joint likelihood function for linear regression Let $Y_i=\alpha_0+\beta_0 X_i + \epsilon_0$, where $\epsilon_i \sim N(0, \sigma_0^2)$ and $X_i \sim N(\mu_x,\tau_0^2)$ are independent.
The data $(X_i, Y_i)$ are generated from $Y_i=\alpha_0+\beta_0 X_i + \epsilon_0$.
I have to find the joint likelihood function, which is given by:
$L_n(${$X_i, Y_i$}$, \alpha, \beta, \mu_x, \sigma^2, \tau^2) = \prod_{i=1}^n f(X_i, Y_i)=\prod_{i=1}^n f_x(X_i)f_{.|X_i}(Y_i)$.
I thought that $f(X_i, Y_i)=\frac{1}{2 \pi \sigma_X \sigma_Y \sqrt{1-\rho^2}}  \exp \left\{-\frac{1}{2 (1-\rho^2)}\bigg[\bigg(\frac{x-\mu_X}{\sigma_X}\bigg)^2
   +\bigg(\frac{y-\mu_Y}{\sigma_Y}\bigg)^2-2\rho \frac{(x-\mu_X)(y-\mu_Y)}{\sigma_X \sigma_Y} \bigg] \right\}$.
But I don't know how to put this in terms of the parameters given or if this is correct. I know that $Y|X \sim (\alpha_0+\beta_0 X, \sigma^2)$. Should I use this for $\mu_Y$ and $\sigma_Y$ such that I have $\alpha$ and $\beta$ in the function?
Thank you in advanced.

A: Just take the expression you already wrote for the likelihood and plug in the two densities.
\begin{align}
f_X(X_i) &= \frac{1}{\sqrt{2 \pi \tau_0^2}} e^{-(X_i - \mu_x)^2/2\tau_0^2}
\\
f_{\cdot \mid X_i}(Y_i)
&= \frac{1}{\sqrt{2 \pi \sigma_0^2}} e^{-(Y_i - (\alpha_0 + \beta_0 X_i))^2/2\sigma_0^2}
\end{align}


text:
Q: Diagnose NoClassDefFoundError during Spring Boot when class is available to ClassLoader I have a Java/Maven project (POM-based) which builds and launches fine when using java -jar on the uber JAR produced by my Maven build on the command line, using the spring-boot-maven-plugin:
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <version>2.0.3.RELEASE</version>
                    <configuration>
                        <mainClass>com.company.Application</mainClass>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

The JAR is created (~100MB), and launches as expected.
However, I'm unable to launch this same application in Eclipse using the right-click -> Run As -> Java Application configuration on the main class I've defined in my POM. It's a Maven project, and M2E is up-to-date/refreshed, etc.
The error is:
java.lang.NoClassDefFoundError: Could not initialize class org.slf4j.LoggerFactory

So clearly some dependency issues with the logging frameworks. However: My first head-scratcher was, why does this work in Maven using the CLI, and fail in Eclipse using M2E?
So I went and looked at the classpaths, and they seem identical. (Looking at the Maven Dependencies list in Eclipse, and the BOOT-INF directory contained in my uber JAR.) The interesting bits are:
slf4j-api        1.7.25
log4j-over-slf4j 1.7.25
logback-core     1.2.3
logback-classic  1.2.3
commons-logging  1.1.3

So, I debugged. I placed a breakpoint on NoClassDefFoundError, and captured this. Note that the debugger is paused on the thrown exception, and the watch expression in the upper-right is getClass().getClassLoader().classes, which is a Vector.
How is it possible that we're throwing on LoggerFactory, even though this very class is present in the current ClassLoader? Where should I look next?

Edit: Since it's causing some confusion, the class in which Eclipse has caught this error (Category.java) is not one of my classes. It's inside a dependency (see Eclipse titlebar) and as a result cannot be modified.


text:
Q: Django : Hellosignup callback url not coming to view I have registered a app at Hellosign and using locally for a django project.
While restringing the app it required the domain url for OAuth callbacks since i'm using the localhost, i have given a callback url genereated by https://ngrok.com/.
like: https://1a2df3ef.ngrok.com/test/oauth
Django oauth url mapping is like
url(r'^hellosign/oauth', 'hellosignup_oauth'),

view
def hellosignup_oauth(request):
    code = request.GET.get('code')
    return render(request, 'hello.html', {'code': code})

On authorization, a request is made like
https://1a2df3ef.ngrok.com/test/oauth?&code=17c2264f2a24741c&state=900e06e2

and ngrok recives the request like
 hellosign/oauth

there seems to be two issues:
1) ngrok should receive request hellosign/oauth?&code=17c2264f2a24741c&state=900e06e2 instead of hellosign/oauth.
2) hellosign/oauth view is not being called on  request hellosign/oauth
Any insight ?

A: This shouldn't be an issue, but it looks like you've got an empty URL parameter (i.e., "?&"). Could it be that Django is seeing the empty first parameter and dropping the 2nd?


text:
Q: How to recover from GNOME 3.2 freeze? I have Ubuntu 11.10 installed and am using GNOME 3.2. I am left with no other option than to restart gdm or to reboot the system, when GNOME freezes.
GNOME freezes at times when resuming from suspend and every time I search in the dashboard, inspite of having GNOME 3.2 compatible theme installed.
Is there any option to restart shell from tty? Or is there any other solution to recover from the freeze?

A: Typically when gnome-shell fails to respond you can do 1 of two things:

*

*Alt+F2 and if you get a dialog for executing commands type restart

*Ctrl+Alt+F2 to switch to terminal console 2 (tty2), login and try killing gnome-screensaver and/or restarting a replacement gnome-shell with: pkill gnome-screensaver switch back to tty7 ( Ctrl+Alt+F7) to check your Gnome screen, if not, go back to tty2 and gnome-shell --display :0.0 --replace & (which was suggested before by steve and msdin respectively)

If both fail, then you need to restart your display manager (gdm, lightdm, kdm). Typically: sudo service gdm restart

A: I have been having a similar problem.  When screen saver / lock is supposed to engage, instead the screen freezes (showing what the screen was showing prior).  The mouse is enabled, but cannot see a login box.  I haven't tried what is suggested by msdin (typing password blind).  But the following did work for me, from Earl C Ruby III:

To unlock a locked-up desktop:

*

*Ctrl-Alt-F1 will give you a text-based terminal login.

*Log in with your user name and password.

*Type: "killall gnome-screensaver"

*Ctrl-Alt-F7 to get back to the (now unlocked) Gnome 3 desktop.

A: Try switching to another tty (Ctrl-Alt-F1), login, then at the prompt type:
gnome-shell --display :0 --replace

Then switch back to the GUI (Ctrl-Alt-F7).
Also, are you sure its actually frozen? I have a problem where the password dialog isn't visible after the screen locks. Its actually there though and if you blind type your password and hit enter the screen unlocks. You might want to try that first.

A: I've had a similar problem.  I'm not sure if the only workaround I've found will work for you but it's worth a try.
I switch over to tty1 (Ctrl+Alt+F1) and log in which hopefully you can do.  If you can't even switch then your problem is worse than mine!  But assuming you make it that far I've found that putting the computer to sleep and bringing it back up again at least makes the computer responsive again.  It's really not an ideal solution.  But to do this
cd /etc/acpi
sudo ./sleep.sh

After that just hit the power button to bring it back up.  If you switch back to your graphical terminal (Ctrl+Alt+F7) things might be responsive again.
Not ideal but it's better than a full restart especially if you had important stuff not yet saved.
I haven't yet found what is causing this otherwise there could be hope for a better solution.  Somebody in the thread I linked to suggested that gnome-screen-saver is causing the problems but killing it after a freeze didn't fix anything and killing it at the start of a session didn't prevent a freeze for me.


text:
Q: ESLint prefer-arrow-callback on array.map import React from 'react';

export default class UIColours extends React.Component {
  displayName = 'UIColours'

  render() {
    const colours = ['black', 'red', 'white', 'orange', 'green', 'yellow', 'blue', 'darkblue', 'lilac', 'purple', 'darkPurple'];
    return (

            {colours.map(function(colour, key) {
              return (

{colour}

              );
            })}

   );
  }
}

12:26  error    Unexpected function expression                  prefer-arrow-callback

I've looked at the map documentation and can't find a good example of multiple parameters.

A: That ESLint rule occurs because you have an anonymous function as a callback, so it's suggesting that you use an arrow function instead. To use multiple parameters with arrow functions you need to wrap the parameters with parentheses, e.g.:
someArray.map(function(value, index) {
  // do something
});

someArray.map((value, index) => {
  // do something
});

As always, the MDN docs for arrow functions has a very detailed explanation of the variations that can be used with arrow functions.
Alternatively, you could just disable that ESLint rule or change it so that it won't warn about named callbacks. The documentation for that ESLint rule is prefer-arrow-callback.

A: You could rewrite the map like this:
{colours.map(colour => (
  <div key={`colour-${colour}`} className={`strong color-swatch bg-${colour}`}>

{colour}

)}

Given colour names seem to be unique, you could use them as keys without a problem.


text:
Q: % Increase value in number record my dataset
name date        record
A    2018-09-18      95
A    2018-10-11     104
A    2018-10-30     230
A    2018-11-23     124
B    2020-01-24      95
B    2020-02-11     167
B    2020-03-07      78

As you can see, there are several records by name and date.
Compared to the previous record, I would like to see the record that rose the most.
output what I want
name record_before_date record_before record_increase_date record_increase increase_rate
A            2018-10-11           104           2018-10-30             230        121.25
B            2020-01-24            95           2020-02-11             167         75.79

I`m not comparing the lowest to the highest, but I want to check the record with the highest ascent rate when the next record comes, and the rate of ascent.
increase rate formula = (record_increase - record_before) / record_before * 100
Any help would be appreciated.
thanks for reading.

A: Use:
#get percento change per groups
s = df.groupby("name")["record"].pct_change()
#get row with maximal percent change
df1 = df.loc[s.groupby(df['name']).idxmax()].add_suffix('_increase')
#get row with previous maximal percent change
df2 = (df.loc[s.groupby(df['name'])
         .apply(lambda x: x.shift(-1).idxmax())].add_suffix('_before'))
#join together
df = pd.concat([df2.set_index('name_before'),
                df1.set_index('name_increase')], axis=1).rename_axis('name').reset_index()
#apply formula
df['increase_rate'] = (df['record_increase'].sub(df['record_before'])
                                            .div(df['record_before'])
                                            .mul(100))
print (df)
  name date_before  record_before date_increase  record_increase  \
0    A  2018-10-11            104    2018-10-30              230
1    B  2020-01-24             95    2020-02-11              167

   increase_rate
0     121.153846
1      75.789474


text:
Q: Select userid and sum of total amount of books a user has made on all loans I would like to get an output which displays the personID and the total sum of books the user has made throughout every loan.
Member:

PersonID

1

2

Loan:

PersonID
LoanID

1
1

1
2

2
3

OrderLine:

LoanID
BookID

1
1

1
2

1
3

2
4

2
5

3
6

3
7

Expected output:

PersonID
Total sum of books

1
5

2
2

Edit:
I have tried a couple of things, as I've been at this for about three hours now. Most of my attempts have been scrapped but this is one attempt I came up with which wasn't able to do my problem.
SELECT SUM(TOTAL) AS Test FROM (
    SELECT COUNT(*) AS TOTAL FROM Person AS P
    WHERE P.PersonID IN (
        SELECT PersonID FROM Loan AS L
        WHERE L.LoanID IN (
            SELECT LoanID FROM Orderline AS OL
            WHERE L.LoanID = OL.LoanID
            )
        )
    GROUP BY P.PersonID
) AS TOTAL;

A: If you want to count duplicated books :
SELECT
        PersonID,
        count(*) as 'Total sum of books'
FROM
        Loan l
INNER JOIN
        OrderLine o on l.LoanID = o.LoanID
GROUP BY PersonID

For including users with 0 loan:
SELECT
        m.PersonID,
        CASE
             WHEN c.PersonID is not NULL THEN c.cpt
             ELSE 0
        END as 'Total sum of books'
FROM
        Member m
FULL JOIN
    (
         SELECT
                PersonID,
                count(*) as cpt
         FROM
                Loan l
         INNER JOIN
                OrderLine o on l.LoanID = o.LoanID
         GROUP BY PersonID
    ) as c ON m.PersonId = c.PersonId

It's not the most elegant way to do it, but I think it's one of the easiest to understand.
With the full join will give you one counter (cpt) per user. If there is no match then cpt will be NULL.


text:
Q: razor pages DropDownListFor; How to set different background color for each item in Dropdownlist? I have one dropdown .This dropdown are bind from database with id, item
But I have in database 3 columns id, item and color.
for example

ID:1 Item: Pen Color:red in the database
  ID:2 Item: Pencil Color:orange in the database

What I need to do it's to set for each item the right  color from client side.
in this case the Background Color of the Item Pen will be red and
the Background Color of the Item Pencil will be orange.
Thanks
PageModel class, properties for the AssetList:
public class CreateModel : PageModel
{
    ...
    public SelectList AssetList { get; set; }
    ...
}

then  onGet():
var asset = from c in _context.Asset
                           select c;
AssetList = new SelectList(Asset, "ID", "Item");

and the page:
<div class="form-group">
  <select asp-for="AssetCode" class="form-control"
        asp-items="@Model.AssetList">
    <option value="">-- Select --</option>
  </select>
</div>

A:     <select asp-for="WhiteChoice">
        <option value="">Keuze witkleur...</option>
        @foreach(var li in Model.products.whitecolors)
        {
            <option value="@li.ProductAddedValue" style="background-color: @li.hexcolor">@li.Title</option>
        }
    </select>


text:
Q: How does the Raft algorithm guarantee consensus if there are multiple leaders? As the paper says:

Election Safety: at most one leader can be elected in a given term. §5.2

However, there may be more than one leader in the system. Raft only can promise that there is only one leader in a given term. So If I have more than one client, wouldn't I get different data? How does this allow Raft to be a consensus algorithm?
Is there something I don't understand here, that someone could explain?

A: Only a candidate node which has a majority of votes can lead. Only one majority exists in cluster the other node cannot hear from a majority without contacting at least one node which has already voted for another leader. The candidate who hears of the other leader will step down. Here is a nice animation which shows how it happens: http://thesecretlivesofdata.com/raft/#election

A: Yes you are right. There can be multiple leaders at the same time, but not in the same term, so the guarantee still holds. A possible situation is in a 3-server (A, B, C) cluster, A becomes elected. And then a network partition happens and the cluster is separated into 2 partitions: {A} and {B, C}. In this case, A would not step down as it does not receive any RPC with a higher term and remains a leader. In the majority partition, a new leader can still be elected. But notice that this new leader is in a greater term than A.
Then how about the request from the client? Two cases.
1. For a WRITE request, the leader cannot reply to the client unless the entry log committed, which is impossible for the outdated leader. So no problem. Only the true leader would be able to commit the entry by replicating it on a majority of servers.
2. For a READ-ONLY request, the leader can get away without consulting the log or committing the entry. You are right and this is explicitly mentioned in the paper at the end of section 8.

Read-only operations can be handled without writing anything into the log. However, with no additional measures, this would run the risk of returning stale data, since the leader responding to the request might have been superseded by a newer leader of which it is unaware. Linearizable reads must not return stale data, and Raft needs two extra precautions to guarantee this without using the log. First, a leader must have the latest information on which entries are committed. The Leader Completeness Property guarantees that a leader has all committed entries, but at the start of its term, it may not know which those are. To find out, it needs to commit an entry from its term. Raft handles this by having each leader commit a blank no-op entry into the log at the start of its term. Second, a leader must check whether it has been deposed before processing a read-only request (its information may be stale if a more recent leader has been elected). Raft handles this by having the leader exchange heartbeat messages with a majority of the cluster before responding to read-only requests.

Hope this helps.

A: this is the question I asked three years ago. Right now, I can answer the question myself.
The key point here is that even the read operation, the client need to go through the raft protocol. If the client request the old leader, the old leader launch AppendEntry to confirm that whether it is the newest leader. It will notice that it is the old leader or the AppendEntry is timeout, then it will return to client timeout or error.

A:   Every machine in the cluster compares its current term against the term it recieves along with all the requests it gets from the other machines. And whenever a "leader" tries to act as a leader, it will not get a majority accepts from the rest of the cluster since the majority of the machines have greater term then the "leader". That guarantees that only the actual leader will be able to reply on clients requests.
  Additionally, according to Raft, this "leader" will become a follower immediately after it recieves a reject with a greater term.


text:
Q: Automatic Email Function I have a code for private sub function for sending automatic emails. I sourced the code from Pete Leaning
ACCESS 2007 - Automatically Send and Email Using Outlook Upon a Specific Event
I attempted to turn it into a function myself using the code below. However it doesn't work. I have a feeling I have set it up completely wrong. Also I'd like the body of the email to contain the the entire record information if possible.
Option Explicit
Public Started As Boolean
Public oApp As Outlook.Application
Public oItem As Outlook.MailItem
Function AutoEmail()

'Automatic Email to send notifications to selected user
If Combo99.Text = "SM" Or "TW" Or "LM" Or "LV" Or "SV" Then

    On Error Resume Next
    'Get Outlook if it's running
    Set oApp = GetObject(, "Outlook.Application")
    If Err <> 0 Then
         'Outlook wasn't running, start it from code
         Set oApp = CreateObject("Outlook.Application")
        Started = True
    End If

                     Set oItem = oApp.CreateItem(olMailItem)
                     With oItem
                        .To = "google@google.com"
                        .Subject = "AutoEmail Test"
                        .Body = "Please enjoy this complimentary email. If this worked please email back."
                        'Send the email
                        .Send
                    End With

                                    Set oItem = Nothing
                                    If Started Then
                                        oApp.Quit
                                    End If

'Display message to the user
MsgBox "A model that is on the watch list has been selected. An Automatic Email has been sent", vbOKOnly, AutoEmail

Else
        'Do nothing
End If

End Function

A: There are two issues with this code line ...
If Combo99.Text = "SM" Or "TW" Or "LM" Or "LV" Or "SV" Then

*

*The combo's Text property is available only when it has focus.  When focus shifts to a different control, such as when the user clicks a command button, use Combo99.Value instead.

*When you use Or between conditions, you must repeat the item from the left side of the = sign again for each Or.
Consider these two If statements ...
If strLetter = "a" Or "b" Then
If strLetter = "a" Or strLetter = "b" Then

The first throws an error, but the second does not.
If you prefer to compare something to a list of values, you can use Select Case.
Select Case Me.Combo99.Value
Case "SM", "TW", "LM", "LV", "SV"
    ' insert code to send email
Case Else
    ' no email
End Select


text:
Q: Kubernetes aggregation certificates - apiserver client authentication allowed names Definitions I'm using in this question:

*

*Main apiserver: the core kube-apiserver

*Extension apiserver: an addon like metrics-server

I am reading through the configure aggregation layer guide and I don't understand the main apiserver's use of --requestheader-allowed-names. In section Kubernetes Apiserver Client Authentication it says:

The connection must be made using a client certificate whose CN is one of those listed in --requestheader-allowed-names. Note: You can set this option to blank as --requestheader-allowed-names="". This will indicate to an extension apiserver that any CN is acceptable.

It makes it sound like the main apiserver is responsible for setting this. Surely the extension apiserver would be in control of this and determine what is acceptable? Why configure this on the main apiserver at all? I.e. The client certificate common names are what they are and it's up to the extension apiserver to accept/reject these?
Or is that doc section mixing options that are passed to both the main and extension apiservers?

A: I think I understand now why the main kube-apiserver needs this allowed names list: The kube-apiserver is a frontend for all the extension apiservers. So the requests always go through kube-apiserver first; it aggregates the requests and then passes them onto the correct backend extension apiserver. Hence it'll need to know which CN's to accept. I.e. a request to an extension server would go:
client request -> kube-apiserver -> extension-apiserver

The extension apiserver would then also check the CN once it received the request after it was routed there by main kube-apiserver.


text:
Q: Javascript onkeyup/onkeydown input I am playing with a very simple little shooter to learn about easeljs, tweenjs, and canvas coding.  I've run into a problem that's stumped me.
I get an unexpected end of input error in Chrome and it indicates line 1.  Whats up with that?
Note that in the code below I have commented out all of the keyboard input code.  The error no longer appears.  When I uncomment either the document.addEventListener or window.addEventListener input code the error is thrown again.  And further experimentation led me to believe it has to do with the event object but beyond that I have no idea.
Hope someone can help!
window.addEventListener('load', eventWindowLoaded, false);

function eventWindowLoaded() {
    init();
}

function init() {
    console.log("init hit");
    canvas = document.getElementById("canvas");
    stage = new Stage(canvas);

    createStarField();

    shipImg = new Image();
    shipImg.onload = onShipLoaded;
    shipImg.src = "ship1.png";

    Ticker.setFPS(30);

    Ticker.addListener(window);

 /*   document.addEventListener('keydown', function(event) {
        switch(event.keyCode)  {
            case 37: // left
                moveLeft = true; moveRight = false;
                break;

            case 38: moveUp = true; moveLeft = false;
                break;

            case 39: moveRight = true; moveLeft = false;
                break;

            case 40: moveDown = true; moveUp = false;
                break;
        }
    }, false);

    document.addEventListener('keyup', function() {
        switch(e.keyCode) {
            // left
            case 37: moveLeft = false;
                break;
            // up
            case 38: moveUp = false;
                break;
            // right
            case 39: moveRight = false;
                break;
            // down
            case 40: moveDown = false;
                break;
    }
}, false);
*/

/*function onKeyDown(e) {
    //if(!e) { var e = window.event; }

    switch(e.keyCode) {
        // left
            case 37: moveLeft = true; moveRight = false;
            break;

            case 38: moveUp = true; moveLeft = false;
            break;

            case 39: moveRight = true; moveLeft = false;
            break;

            case 40: moveDown = true; moveUp = false;
            break;
    }
}

function onKeyUp(e) {
   // if(!e) { var e = window.event; }
    switch(e.keyCode) {
        // left
        case 37: moveLeft = false;
            break;
        // up
        case 38: moveUp = false;
            break;
        // right
        case 39: moveRight = false;
            break;
        // down
        case 40: moveDown = false;
            break;
    }
*/
    function checkMovement() {
        if(moveLeft)
        {
            ship.x -= speed;
            if(ship.x < 0)
                ship.x = 640;
        }
        else if(moveRight)
        {
            ship.x += speed;
            if(ship.x > 640)
                ship.x = 0;
        }

        if(moveUp)
        {
            if(ship.y - speed > 24)
                ship.y -= speed;
        }
        else if(moveDown)
        {
            if(ship.y + speed < 460)
                ship.y += speed;
        }
    }

    function onShipLoaded() {
    ship = new Bitmap(shipImg);
    ship.regX = ship.image.width * .05;
    ship.regY = ship.image.height * 0.5;
    ship.x = 320;
    ship.y = 450;

    stage.addChild(ship);
}

function createStarField() {
    console.log("create star field");
    stars = new Array();

    g = new Graphics();
    g.setStrokeStyle(1);
    g.beginStroke(Graphics.getRGB(255,255,255));
    g.beginFill(Graphics.getRGB(255,255,255));
    g.drawCircle(0,0,1);

    for(var i = 0; i < 100; ++i) {
        var s = new Shape(g);
        stars.push(s);
        s.x = randRange(10,630);
        s.y = randRange(-250, 470);
        s.scaleX = randRange(0.5, 2);
        s.scaleY = s.scaleX;
        s.alpha = Math.random() + 0.2;

        stage.addChild(s);
    }
}

function randRange(min, max) {
    return Math.floor(Math.random()*(max - min)) + min;
}

function tick() {
    console.log("tick hit");
    updateStarField();
    checkMovement();
    stage.update();
}

function updateStarField() {
    console.log("updateStarField()");
    var curStar;
    var limit = stars.length;
    for(var i = 0; i < limit; ++i) {
        curStar = stars[i];
        curStar.y += 4
            if(curStar.y > 480) {
                curStar.x = randRange(10,630);
                curStar.y = -randRange(20, 450);
            }
    }
}

A: The last commented out onKeyUp(e) function lacks a closing curly brace (})


text:
Q: Error installing any ruby version with RVM on OSX Guys I'm about to kill myself with this one!
I had some problems with RVM installing multiple versions of Ruby, and following a thread on Stackoverflow I decided to remove it completely. After reinstalling RVM, I am unable to install any Ruby version at all.

*

*Mac OS X

*RVM 1.20.10 stable

*Homebrew 0.9.4

Here are some logs:

rvm install 2.0.0-p0

or:

rvm install 2.0.0-p195 --autolibs=enabled

Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.8/x86_64/ruby-2.0.0-p0.
Continuing with compilation. Please read 'rvm mount' to get more information on binary rubies.
Installing requirements for osx, might require sudo password.
Already up-to-date.
Installing required packages: autoconf, automake, libtool, pkg-config, libyaml, readline, libxml2, libxslt, libksba, openssl…
Error running 'requirements_osx_brew_libs_install autoconf automake libtool pkg-config libyaml readline libxml2 libxslt libksba openssl',
please read /Users/admin/.rvm/log/ruby-2.0.0-p0/1368903329_package_install_autoconf_automake_libtool_pkg-config_libyaml_readline_libxml2_libxslt_libksba_openssl.log

Logfile reads:
[2013-05-18 22:55:29] requirements_osx_brew_libs_install
Error: No such keg: /usr/local/Cellar/autoconf
There were package installation errors, make sure to read the log.
Check Homebrew requirements github.com/mxcl/homebrew/wiki/Installation

brew doctor

Your system is ready to brew.

brew cleanup

Removing: /Library/Caches/Homebrew/automake-1.13.1.tar.gz…
Error: Permission denied — /Library/Caches/Homebrew/automake-1.13.1.tar.gz

brew reinstall autoconf

Error: No such keg: /usr/local/Cellar/autoconf

Help!

A: After installing RVM, You'll want to run
rvm requirements

to see if anything else is required to install ruby and rails first.
here is the similar question asked rvm install ruby

A: I ran into the same issue, you need to manually install all the required packages using Brew. For me I had to run the following installs:
brew install autoconf
brew install automake
brew install libtool
brew install apple-gcc42
brew install libyaml
brew install libxslt
brew install libksba
brew install openssl

You just need to keep running "rvm requirements" and reading the log and installing the packages needed until there are no more errors.

A: This solved problem for me

sudo chown -R `whoami` /Library/Caches/Homebrew/

A: I had the same problem
brew install pkg-config

worked for me

A: I aswell ran into the permission problem. My /usr/local/opt where the packages are linked had permissions root:wheel. I changed permissions by doing
sudo chown -R <localuser>:staff /usr/local/opt

where of course "localuser" is your local user you used to install brew.
Then aswell I had to run
brew reinstall autoconf

and so on instead of just "install", since brew always kept on saying the lib already was installed (yet not linked). "reinstall" simply forces a new install of the package. that did the trick for me.
Hope this helps someone with similar problems.

A: User which is running brew should have write access to This entire directory path
/Library/Caches/Homebrew/Formula
No need to change ownership just write permission. then running rvm works

A: I was encountering similar issues, particular around the install of openssl098. I came across this Homebrew issue, tried rvm get head as suggested, and now rvm works perfectly.

A: I'd try to install Xcode Command Line Tools before.

A: Try
rvm reinstall ruby-2.3.1 --with-openssl-dir=`brew --prefix openssl`

rvm openssl on Mojave


text:
Q: Spring MVC send email on registration I'm trying to send an email to a user once their account is registered, I can get my code to work in a separate project (simple form input etc) however when I try to add the same code to my app it gives me the following error
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException error

Could not autowire method: public void com.finalProject.school.controller.AppController.setMailSender(org.springframework.mail.javamail.JavaMailSender); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.mail.javamail.JavaMailSender] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

Here is my code for adding the new user to the database (which works fine) with the code to send an email which is what is giving me errors
@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result, @RequestParam("firstName") String firstName,
        @RequestParam("password") String password, @RequestParam("email") String emailAddress,
        ModelMap model, Model model2) {

    if (result.hasErrors()) {
        return "registration";
    }

    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
        FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
        result.addError(ssoError);
        return "registration";
    }

    String status = null;

    try {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true,"UTF-8");
        helper.setFrom("Administrator");
        helper.setTo(emailAddress);
        helper.setSubject("Registration confirmation");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("firstName", firstName);
        params.put("password", password);

        String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "spring/emailRegistration.vm", "UTF-8", params);

        helper.setText(text, true);
        mailSender.send(message);
        status = "Confirmation email is sent to your address (" + emailAddress + ")";
    } catch (MessagingException e) {
        status = "There was an error in email sending. Please check your email address: " + emailAddress;
    }

    model2.addAttribute("message", status);

    userService.saveUser(user);

    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    //return "success";
    return "registrationsuccess";
}

Any ideas of how to fix this ?
App Config Class
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:component-scan base-package="com.finalProject.school" />

A: If you are using spring boot, you probably have not included following properties in your application.properties file.
spring.mail.host = smtp.gmail.com
spring.mail.username = abc@abc.com
spring.mail.password = xyz
spring.mail.port=587
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.protocol=smtp

UPDATE
Ok. Put the following in your configuration file.
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="myemail1@gmail.com" />
    <property name="password" value="password!" />

    <!-- The name of the property, following JavaBean naming conventions -->
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
</bean>


text:
Q: TypeError: list indicies must be integers, not str foo = ("PandaBears")
l = list(foo)
random.shuffle(l)
Output = ''.join(l)
print(Output)

I have been at this code for ages trying to figure out the problem but I have had no luck. A few hours before it was working perfectly with absolutely no trouble - I haven't even changed / upgraded python either.
The error is coming from

l = list(idf)

and I have tried using [] instead of ().
Any improvements on this code would be appreciated

A: The parenthesis are useless here:
foo = ("PandaBears")

Just write:
foo = "PandaBears"  # str

If you want a singleton tuple, add a trailing comma:
foo = ("PandaBears",)  # tuple

If foo is a string, the following statement construct a list of letters:
l = list(foo)

Don't know what is diff.


text:
Q: How to capture POST data with contact form7 I have this hook in my functions.php:
add_action( 'wpcf7_mail_sent', 'myfunction' );

I want to post the values when the form is sent.
I have a field like this: [textarea your-message].
How do i capture the POST data from this?
for example when the form is sent i want to echo the post value of  [textarea your-message] in myfunction(){}

A: Try this :
add_action( 'wpcf7_sent', 'your_wpcf7_function' );

function your_wpcf7_function( $contact_form ) {
$title = $contact_form->title;
$submission = WPCF7_Submission::get_instance();

if ( $submission ) {
    $posted_data = $submission->get_posted_data();
}
   if ( 'MyContactForm' == $title ) {

    $firstName = $posted_data['first-name'];
    $lastName = $posted_data['last-name'];

   }
}

A: You need to access the $WPCF7_ContactForm object.
In your hooked function, you'd access the field you want like this:
yourFunction(&$WPCF7_ContactForm) {
    $text_area_contents = $WPCF7_ContactForm->posted_data['your-message'];
}

A: You can retrieve form fields data through wpcf7_posted_data
add_filter( 'wpcf7_posted_data', function( $data ) {
  echo $data['your-name'];
} );

A: This is how I used and its work for me to receive contact form 7 data after successe mail send and I used this data to send another server through API
add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function( $contact_form ) {
    $title = $contact_form->title;
    $submission = WPCF7_Submission::get_instance();
    if ( $submission ) {
        $posted_data = $submission->get_posted_data();
    }
   if ( 'Reagistation' == $title ) {
        $name = strtolower($posted_data['text-name']);
        $name = strtolower(str_replace(' ', '_',  $name));
        $email = strtolower($posted_data['email']);
        $phone = strtolower($posted_data['phone']);
        $Areyouarealtor = $posted_data['Areyouarealtor'];
        $ayor = strtolower($Areyouarealtor['0']);

 }
}

A: Try This

add_action('wpcf7_before_send_mail','dynamic_addcc');
function dynamic_addcc($WPCF7_ContactForm){
    $currentformInstance  = WPCF7_ContactForm::get_current();
    $contactformsubmition = WPCF7_Submission::get_instance();
    if($contactformsubmition){
    $posted_data = $contactformsubmition->get_posted_data();
    }
}


text:
Q: How to move a button to "center-bottom" in ionic2 How to set something to be in center horizontally and bottom vertically?
I tried to use flex as class="layout horizontal" like in Polymer...
<ion-content class="layout vertical">

<button danger round class="center">Hibás</button>
</ion-content>

A: It is a question of style (CSS) rather than framework (Ionic) I use the following which works well.
<ion-content padding class="">

Some content

    <button block>Submit</button>

</ion-content>

And in my style sheet (app/theme/app.core.scss):
.bottom {
  padding: $content-padding;
  position: fixed;
  bottom:0;
  left: 0;
  right: 0;
}

A: Not really an Ionic2 question, more CSS styling issue.
Try something similar to trying to align html button at the center of the my page


text:
Q: Is it enough to declare a function as transaction_safe, so they can be used thread-safe? Is enough just to declare all of the functions as transaction_safe in some my class, so its can be used as thread-safe in transactions atomic_noexcept, atomic_cancel, atomic_commit from Experimental Transactional Memory TS?
As known there are Transactional Memory TS (ISO/IEC TS 19841:2015) in the Experimental C++ standard libraries. Simple examples are here: http://en.cppreference.com/w/cpp/language/transactional_memory
Also there is Technical Specification for C++ Extensions for
Transactional Memory: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4514.pdf
Page 34:
23.4 Associative containers [associative]
23.4.4 Class template map [map]
23.4.4.1 Class template map overview [map.overview]

In 23.4.4.1 [map.overview], add "transaction_safe" to the declarations of all
variants of the begin and end member functions and to
the declarations of size, max_size, and empty.

I.e. if Transactional Memory will commit to the C++ Standard, then can we simply do something like this and will it thread-safe?
#include<map>
#include<thread>

std::map<int, int> m;

int main() {

 std::thread t1([&m]() {
  atomic_cancel
  {
   m[1] = 1;    // thread-safe
  }
 } );

 t1.join();

 return 0;
}

Unfortunately, I can't reproduce example with atomic_cancel {} even with key -fgnu-tm on GCC  6.1: https://godbolt.org/g/UcV4wI
And will enough just to declare all of the functions as transaction_safe in some my class, so its can be used as thread-safe - if I will call its in scope: atomic_cancel { obj.func(); }?

A:
The compound-statement in an atomic block is not allowed to execute
  any expression or statement or call any function that isn't
  transaction_safe

std::map<int, int>::operator[] wouldn't be a transaction_safe method, so you couldn't call it in atomic_cancel. It would be a compile time error.


text:
Q: Eclipse code formatting: Line width ignored for some situations In my eclipse formatter i set the eclipse max line width to 140 unfortunately that does not count for  something like this where the given text width is longer than 140:
assertThat(rte.getMessage(),
                is("lorem ypsum sfdasdasd asdasdh asfpojkasgkl asdfjkhklasg asdjklhagjklhag asdjklhasdjkf asghjkahghjkag asghjkajkhag asghjkahgjkhagjkl asgjklhagjkhajkg aghjkhadgjklhalkg asdgjklhagjklhagl asdgjklhasjklhjklag asgjkhaksjhjkag"));

Another problem occurs in lines like this:
private void test(final String something, final boolean something2, final Path something3, final boolean something4)throws IOException,JDOMException

Is there a possibility to let eclipse also format this?


text:
Q: Can I change a width or any other style of an element px by px as I scroll down with Javascript? I have a div with a width of 100px, I want to reduce the width by 1px on every scroll step so it looks as if the div is animated when I scroll down or up the page. So when I scroll down a 100 steps the div disappears. How can I do that?

A: A simple solution using a few lines of jQuery.
$(window).on('scroll', function(e){
     $('#box').css("width", 100-$(window).scrollTop());
});

http://jsfiddle.net/vwrr6Lv1/1/
EDIT:
If you need to start doing fancier animations, I recommend checking out jQuery Transit which supports CSS3 transforms and transitions, e.g
$(window).on('scroll', function(e){
    $('#box').transition({'perspective':'100px', 'rotateY': 100-$(window).scrollTop()}, 0);
});

http://jsfiddle.net/vwrr6Lv1/3/
jQuery Transit is a great extension of jQuery.animate that supports CSS3 transitions and transforms. http://ricostacruz.com/jquery.transit/

A: you can use skrollr.js to achive animation on scroll. but other than this you also can add animate.css, parallax effects as they used in the site you mentioned


text:
Q: IIS Configuration LifeCycle, Security for ASP.net Webservies I have created a web service using ASP .Net. My web service contains a web config file, which stores security information of our Microsoft Dynamics Axapta AOS server, username and password for Axapta authentication.
My web service calls a Dynamics Axapta web service and exchanges some data. I have deployed my ASP .Net web service to IIS 7.0 which is located in DMZ zone. Now i have to give web service address to a payment service. This payment service should only know the web service address and the methods of this web service. This is my first time, i am developing such a service stored in IIS:
My question is:
How i need to configure IIS? (Authentication)
Which security tips i need to follow?
What should i do, to make my web config file to be secure?
How i need to allow this payment service to my local server?
Any suggestions and explanation will be huge help to me, because i am newbie to this topic.
Thanks a lot, sincerely, Ilkin.

A: Your IIS Application Pool should run as custom account identity (like domain\svc-ax-payment-user). Then add this Active Directory user to AX users and grant / add it to role with access to required roles. In this scenario password is saved securely in IIS.

Another option is to encrypt password with machine key (eg. your IIS server is not trusted in AX domain).
aspnet_regiis.exe -pef "appSettings" C:\web_app_dir

Run this command as administrator.
Check How To: Encrypt Configuration Sections for more information.
You can also create your own Machine Key for your application. In this case your web.config is portable and not bound to one specific server.


text:
Q: Combining two types of conditions to replace strings with regular expressions in QGIS I have a string with commas at the beginning, at the end and sometimes two or more commas after each other: ,,, as can see at the bottom. I tried to remove the commas in a way to have a comma separated string, using regular expressions.

*

*Deleting all commas at the beginning and the end of the string works fine:
regexp_replace (text, ('^,{1,}|,{1,}$'),'')

*Replacing two or more commas with a single one inside the string works fine, too:
regexp_replace (text, (',{2,}'),',')
However, how to combine these two cases? Like:

*

*If there is a comma at the beginning or the end: delete it

*If there are two or more commas, replace it with one.

Is this possible in one single regex_replace string? What works is combining them - so the solution I'm looking for should accomplish what the follwoing expression with two regexp_replace statements does, but using just a single regexp_replace function:
regexp_replace (
    regexp_replace (text, ('^,{1,}|,{1,}$'),''),
    (',{2,}'),','
)

old_text        new_text

,1              ->  1
1,              ->  1
1,,2            ->  1,2
,,,1,2,3,4,     ->  1,2,3,4
,1,2,3,4,5,,,   ->  1,2,3,4,5
1,2,3,,,,,,6,7, ->  1,2,3,6,7

A: Would you consider skipping the dark arts of regex for an array expression?
This should do the trick.
array_to_string(array_filter(string_to_array(test,','),@element !=''),',')

For a purely regex solution try this:
regexp_replace(test,'^,*|,*$|(,)\\1+','\\1')


text:
Q: Zurb Foundation - dropdown not working I am using a new Foundation version 6.2.2 and trying to make a dropdown menu in my top bar. I am calling the scripts like this:

And this is my view where I have a dropdown menu:

{{ Auth::user()->first_name }} {{ Auth::user()->last_name }}

                 Logg ut

I get no errors in the console, and I have the same setup in other project that works fine, so I have no idea what is wrong with it.

A: don't forget to include the css:
(6.2.2)
https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.2/foundation.min.css
(6.2.3)
https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.3/foundation.min.css


text:
Q: How to make a shallow copy of a list in Python I am trying to implement an algorithm in Python to generate all Permutations of a list. But I In my for loop I wish to keep the original prefix and rest lists intact, and therefore I am trying to make a copy of those lists using newprefix and newrest, however on printing the variable rest at each iteration, I see that even the variable rest is getting modified! How can I make a shallow copy of the list in Python? Or is there another issue with my attempted logic?
def perm(prefix, rest):
    if len(rest) == 0:
        print prefix
    for i in range(len(rest)):
        #prints in the for loop are just for debugging
        print "rest:", rest
        print "i=", i
        newprefix = prefix
        newprefix.append(rest[i])
        newrest = rest
        newrest.pop(i)
        print "old pre : ", prefix
        print "newpre=", newprefix
        print "newrest=", newrest
        perm(newprefix, newrest)

perm([], ['a','b','c'])

A: To make a shallow copy, you can slice the list:
newprefix = prefix[:]

Or pass it into the list constructor:
newprefix = list(prefix)

Also, I think you can simplify your code a little:
def perm(prefix, rest):
    print prefix, rest

    for i in range(len(rest)):
        perm(prefix + [rest[i]], rest[:i] + rest[i + 1:])

perm([], ['a','b','c'])

A: import copy

a = [somestuff]
b = copy.copy(a) # Shallow copy here.
c = copy.deepcopy(a) # Deep copy here.

The copy module is worth knowing about.
https://docs.python.org/3/library/copy.html
(Python 2) http://docs.python.org/2/library/copy.html


text:
Q: Putting React app into production with Webpack React newbie here. I'm just about finished my first React app but running into issues with putting it into production
Currently, I'm attempting to run
NODE_ENV=production webpack -p

with a script in my package.json file.
Everything runs without issue but the script doesn't seem to be outputting the correct production index.html file. For instance, all of the JS and CSS files have a question mark and random characters appended to the end of them like this
href="/css/app.css?287deee1465dba65696e"

Also the production index.html file only seems to have what's written in the /src/index.html which is in my dev environment but I want it to be what's in /src/App.js where the meat of my code is written.
I must have something off somewhere but since I'm fairly new to both Webpack and React, I'm not sure where to begin to look. Below is my index.js, index.html, and a segment of my webpack.config.js that involves putting the code in production.
index.js
//const css = require('./app.scss');
const css = require('./style/style.scss');

import React from 'react';
import ReactDOM from 'react-dom';
import anime from 'animejs';
import {App} from './App.js';

ReactDOM.render(
  <App />,
  document.getElementById('root')

);

index.html(src)
<!DOCTYPE html>

     <meta charset="UTF-8">
     <title><%= htmlWebpackPlugin.options.title %></title>

Webpack

webpack.config.js
var isProd = process.env.NODE_ENV ===  'production'; //true or false

var cssDev = ['style-loader', 'css-loader', 'sass-loader'];

var cssProd =   ExtractTextPlugin.extract({

fallback: 'style-loader',

            use: ['css-loader','sass-loader'],
            publicPath: '/dist'
        })
var cssConfig = isProd ? cssProd : cssDev;

module.exports =  {

entry:{
    app: './src/index.js',
    slideshow: './src/js/slideshow.js',
    shapallax: './src/js/shapallax.js',
    yona: './src/js/yona.js',
},
output: {
    path: path.resolve(__dirname, "dist"),
    // path: __dirname + '/dist',
    filename: '[name].bundle.js'
},

I'm sure there are details I'm missing out that would be useful for solving this so please let me know the correct things to be looking for and asking.

A: I managed to figure out the issue which was fairly simple. In my webpack.config.js I had to change the filename in my ExtractTextPlugin setup. After removing a forward slash I had at the beginning of the path, I was able to get everything to output correct in my /dist folder. The final working setup is shown below.
 new ExtractTextPlugin({
        filename: 'css/[name].css',
        disable: !isProd,
        allChunks:true
    }),


text:
Q: What is the equivalent of AWS elastic beanstalk in GCP? Is Elastic Beanstalk of AWS an answer to GAE of GCP?
Are there any benchmark comparisons between the two?

A:
Is Elastic beanstalk of AWS an answer to GAE of GCP?

Yes, in a nutshell, you can think of it like that.
There's an article by Google showing side-by-side comparisons of AWS and Google Cloud products, listing them as IaaS and PaaS:
Service     AWS                             Google Cloud Platform
-----------------------------------------------------------------
IaaS        Amazon Elastic Compute Cloud    Compute Engine
PaaS        AWS Elastic Beanstalk           App Engine

However, it is worth noting that at least AWS Elastic Beanstalk is not strictly a PaaS solution, I would describe it more as a management layer on top of EC2. From their FAQ:

Q: How is AWS Elastic Beanstalk different from existing application containers or platform-as-a-service solutions?
Most existing application containers or platform-as-a-service solutions, while reducing the amount of programming required, significantly diminish developers' flexibility and control. Developers are forced to live with all the decisions predetermined by the vendor–with little to no opportunity to take back control over various parts of their application's infrastructure. However, with AWS Elastic Beanstalk, developers retain full control over the AWS resources powering their application. If developers decide they want to manage some (or all) of the elements of their infrastructure, they can do so seamlessly by using Elastic Beanstalk's management capabilities.

I don't think it's possible to compare these platforms with benchmarks. There is still a lot you can configure on this platforms and performance will mostly depend on your configuration and (even more) your application code.
It comes down to differences in pricing, easy-of-use and the availability of other services on these platforms.


text:
Q: Set custom class for Modal popup Magento 2 I have different popups and each popup has different styles, Anyone know how I can restyle each Modal by adding custom class or something.
Here one of my modal popup code:

Get first popup

First popup content

A: Go to your script code and add one line code: modalClass: 'question-modal' check below script.

    require(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {
            var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                modalClass: 'question-modal',
                buttons: []
            };

            var popup = modal(options, $('#question-popup'));
            $("#question-me").on('click',function(){
                $("#question-popup").modal("openModal");
            });

        }
    );

A: Different parameters can be used for Modal Popup creation by the reference of the file : vendor/magento/module-ui/view/base/web/js/modal/modal.js

A: You could use "modalClass" to set a particular class for each modal. See all of the possible modal paremeters in the following file:
 vendor/magento/module-ui/view/base/web/js/modal/modal.js


text:
Q: Trying to access data-attribute value of clicked option . I have several 'page' options in select element, each option has values derived from database.
<select name="page_id" title="page id" class="form-control" id="page">
                                    @forelse($pages as $page)
                                        <option data-slug="{{$page->slug}}" {{($page->id==$c_page->id) ? 'selected' : ''}} value="{{$page->id}}">{{$page->title}}</option>
                                    @empty
                                        <option value=""> No Pages Found</option>
                                    @endforelse
                                </select>

I'm trying to get 'slug'value of 'clicked/chosen' option into javascript.
$(function () { /* DOM ready */
        $("#page").change(function () {
            alert($('option').data('slug'));
        });
    });

But this only returns the 'slug' value of 'page' option that is at the top. How can I get the value from other option elements?

A: You need to use :selected selector and use this the current element context (for which event handler is attached).
$("#page").change(function () {
    var slug = $('option:selected', this).data('slug');
});

As a runnable snippet:

$(function() {
  $(".page").change(function() {
    var slug = $('option:selected', this).data('slug');
    console.log('slug: ' + slug);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="page">
  <option data-slug="first option">first
  <option data-slug="second option">second
  <option data-slug="third option">third
</select>
<select class="page">
  <option data-slug="first option of second page">first
  <option data-slug="second option of second page">second
  <option data-slug="third option of second page">third
</select>


text:
Q: hibernate query builder for lucene time range I am building a lucene query for an indexed object to determine if current time lies between the range of start Time and end Time. I'm unable to get the exact lucene query .
org.apache.lucene.search.Query luceneQuery5=queryBuilder3.bool()
    .must(queryBuilder3.keyword().onFields("TimeDependentProfileKey").matching("TimeKey").createQuery())
    .must(queryBuilder3.range().onField("StartTime").above(new Time(0)).createQuery())
    .must(queryBuilder3.range().onField("StopTime").below(new Time(0)).createQuery()).createQuery();`

The lucene query which was generated looks like:
+TimeDependentProfileKey:3 +StartTime:[19700101000000000 TO *] +StopTime:[* TO 19700101000000000]

how do i change the format of timestamp, can anyone please help me.

A: By searching for a date object, you are deferring formatting to hibernate.  I would consider the format you specified as functional, though perhaps not ideal.  If you want to use your own formatting, you must deal in strings, be consistent in your formatting, and make sure your format will work well for sorting and range queries as a string.
If you want to have hibernate handle formatting dates for you, you need to define your date field with a @DateBridge(resolution = ...) annotation.  This ensures that hibernate will format dates effective for correct range querying and sorting in lucene, and allows you to query against the field with date objects instead of strings.


text:
Q: How to get files from another branch on different PC Basically, on one PC I created a branch, let's say new_branch and made some changes there. Now I want to get the whole repository from that branch on a different PC.
The problem is that when I'm using:
git checkout new_branch

I get the message that the new_branch does not exist. And by default I'm on master.
How can I do that?

A: Once cloned on the new PC, you can do a:
git checkout -b new_branch origin/new_branch
# or better
git checkout --track origin/new_branch

By default, a clone checks out the master branch, and creates remote tracking branches in the remotes/origin namespace: you you see all those remote tracking branches with git branch -r.
See more with "Difference between git checkout --track origin/branch and git checkout -b branch origin/branch".
If you use the --track option, your local branch will have the remote tracking branch has its upstream branch.
By default, a simple git push would push that local branch on the same branch of the origin repo.


text:
Q: designed component does not update at runtime in C# I have designed a simple component like this:
public sealed partial class MySimpleComponent : Control
{
    public PictureBox picRed=new PictureBox();

    public MySimpleComponent()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        InitializeComponent();
        this.Controls.Add(picRed);
        picRed.Image = global::InterLockingV1.Properties.Resources.RedLamp1;
        picRed.SizeMode=PictureBoxSizeMode.StretchImage;
        picRed.Dock=DockStyle.Fill;
    }

    public MySimpleComponent(IContainer container)
    {
        container.Add(this);
        InitializeComponent();
    }
}

when i compile my code, i can see the component in toolbox and can drag it on the form, it works well at design time (I can see the redlamp image in  picturebox), but when i execute the program, no image apears on the picturebox,
i tried to change it at runtime, but nothing changed:
MySimpleComponent1.picRed.Image=Image.FromFile(@"MyImagePath");

whould you please help me to tackle the problem?

A: Try putting the code in Form_Load event


text:
Q: ADO.Net or Entity Framework in Visual Studio 2008 If you were programming a small database application in .NET 2008 right now would use plain ADO.Net or ADO.Net Entity Framework or some of both both?
I'm using Visual Studio 2008 to learn .Net. I already do quite a bit of programming in MS Access VBA but I've decided it's time to move past the desktop and past the 90's. My question is partially about what I should learn but also very much about what I should actually use in the real world.

A: Technically Entity Framework is the evolution of ADO.Net. Do yourself a favor and dump data sets in favor of a more robust ORM. At this point nobody should be passing around DataSets anymore.
It is worth noting that Entity Framework is not your only option when it comes to ORMs. There is NHibernate, SubSonic, LINQ to SQL, etc... All of which will work just fine in 2008. EF 1 is not fully baked in my opinion.

A: I would not use the version of Entity Framework that comes with VS 2008.  Entity Framework with VS2010 is fine.
I likely wouldn't use ADO.NET either as I always seem to end up writing my own custom ORM then.
For .NET 3.5 / VS 2008, I would recommend NHibernate.  Linq To Sql is maybe an option if you want to get started quickly and can throw away the project after you are done (since any project with a long life will probably have to be rewritten to use EF or NHibernate anyway).
So, try NHibernate first, if the learning curve is too intimidating, drop back to LinqToSql or EF.  Once you've learned one ORM, learning the second ORM is much easier.
Also, you can read a lot more on choosing an ORM for .NET here:
NHibernate, Entity Framework, active records or linq2sql

A: If your database is small enough and you don't have a lot of queries, do ADO.NET, but if you are taking anything of scale, do the Entity Framework as it will be worth the overhead.  The data generation and native query keywords will drastically reduce errors.

A: If you learning, use EF. Whats the point of going backwards.
It makes dev a LOT easier. The ADO/Dataset way of doing things is dead.
Also if you moving to the web then it is nice to use EF with WCF data services. Its a neat trick to know.
Secondly, why use 2008. IF you learning, get the latest tools. The express editions are really great.


text:
Q: How to ignore field repr in pydantic? When I want to ignore some fields using attr library, I can use repr=False option.
But I cloud't find a similar option in pydantic
Please see example code
import typing
import attr

from pydantic import BaseModel

@attr.s(auto_attribs=True)
class AttrTemp:
    foo: typing.Any
    boo: typing.Any = attr.ib(repr=False)

class Temp(BaseModel):
    foo: typing.Any
    boo: typing.Any  # I don't want to print

    class Config:
        frozen = True

a = Temp(
    foo="test",
    boo="test",
)
b = AttrTemp(foo="test", boo="test")
print(a)  # foo='test' boo='test'
print(b)  # AttrTemp(foo='test')

However, it does not mean that there are no options at all, I can use the syntax print(a.dict(exclude={"boo"}))
Doesn't pydantic have an option like repr=False?

A: It looks like this feature has been requested and also implemented not long ago.
However, it seems like it hasn't made it into the latest release yet.
I see two options how to enable the feature anyway:
1. Use the workaround provided in the feature request
Define a helper class:
import typing
from pydantic import BaseModel, Field

class ReducedRepresentation:
    def __repr_args__(self: BaseModel) -> "ReprArgs":
        return [
            (key, value)
            for key, value in self.__dict__.items()
            if self.__fields__[key].field_info.extra.get("repr", True)
        ]

and use it in your Model definition:
class Temp(ReducedRepresentation, BaseModel):
    foo: typing.Any
    boo: typing.Any = Field(..., repr=False)

    class Config:
        frozen = True

a = Temp(
    foo="test",
    boo="test",
)
print(a)
# foo='test'

2. pip install the latest master
I would suggest doing this in a virtual environment. This is what worked for me:
Uninstall the existing version:
$ pip uninstall pydantic
...

Install latest master:
$ pip install git+https://github.com/samuelcolvin/pydantic.git@master
...

After that the repr argument should work out of the box:
import typing
from pydantic import BaseModel, Field

class Temp(BaseModel):
    foo: typing.Any
    boo: typing.Any = Field(..., repr=False)

    class Config:
        frozen = True

a = Temp(
    foo="test",
    boo="test",
)
print(a)
# foo='test'


text:
Q: Argument not being passed to function I have created a PSObject and I want to pass the properties to another function which will then output the results, but it's not passing the property.
In the code below the $VMHostObject.Name is coming up blank in the Enter-CellData function but the data is there in the PSObject.
`Enter-CellData -WorkSheet $ws1 -CellRow $row -CellColumn $Column -Data $VMHostObject.Name`

$VMHostObject = New-Object -TypeName PSObject -Property @{
            "Name" = $h.Name
            "ID" = $h.Id
            "HypervisiorName" = $view.Config.Product.Name
            "HypervisiorVersion" = $view.Config.Product.Version
            "HypervisiorBuild" = $view.Config.Product.Build
            "Make" = $view.Hardware.SystemInfo.Vendor
            "Model" = $view.Hardware.SystemInfo.Model
            "CPUSocketCount" = $view.Hardware.CPUInfo.numCPUPackages
            "CPUCoreCount" = $view.Hardware.CPUInfo.numCPUCores
            "LogicalCPUCount" = $view.Hardware.CPUInfo.numCPUThreads
            "CPYType" = $view.Hardware.CpuPkg.Discription
            "Memory" = [math]::Round([math]::Round($h.MemoryTotalGB, 2), 2)
            "Nics100MB" = $100mbNIC
            "Nics1GB" = $1GBNIC
            "Nics10GB" = $10GBNIC
            "NicsOther" = $otherNIC
            "DatacenterName" = $DataCenter
            "ClusterName" = $Cluster
        }
function Enter-CellData
{
    [CmdLetBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [string]$WorkSheet,
        [parameter(Mandatory = $true)]
        [int]$CellRow,
        [parameter(Mandatory = $true)]
        [int]$CellColumn,
        [parameter(Mandatory = $true)]
        [string]$Data
    )
$WorkSheet.Cells.Item($CellRow, $CellColumn) = $Data
$script:Column++

}

A: Ive figured it out in the enter-celldata function I have the wrong data types ive entered the correct ones now and it works
param
    (
        [parameter(Mandatory = $true)]
        [Object]$WorkSheet,
        [parameter(Mandatory = $true)]
        [int]$CellRow,
        [parameter(Mandatory = $true)]
        [int]$CellColumn,
        [parameter(Mandatory = $true)]
        [PsObject]$Data
    )


text:
Q: Convert input hour from source timezone to UTC I need to convert the input hours(12 hour format) from source timezone to UTC.
Like if I give 10 AM, Asia/Kolkata, I need converted it to 3:30 PM as per the offset in UTC.

A: use gmdate() function to get your desired result
http://php.net/manual/en/function.gmdate.php

A: $the_date = strtotime("2010-01-19 00:00:00");
echo date_default_timezone_get();
echo date("Y-d-mTG:i:sz",$the_date);
echo date_default_timezone_set("UTC");
echo date("Y-d-mTG:i:sz", $the_date);

A: try this it works perfectly for me ..
$timezone = 'Asia/Kolkata';
echo $stored_time = date('Y-m-d H:i:s');
date_default_timezone_set($timezone);
$timestamp = strtotime($stored_time);
$local_time = $timestamp + date('Z');
$local_date = date('Y-m-d H:i:s', $local_time);
echo $local_date;

it is answered by me already for this question : PHP adjust time zone for date