text:
Q: Feign with Hystrix Fallback throwing bean error on startup I am working on an example from here about Feign and Hystrix. Without the Feign fallback property, everything works okay. But when I add the fallback property and create the fallback class that implements the feign clients interface, I get the following error
 Description:

Field customerClient in com.feign.demo.controllers.CustomerController required a single bean, but 2 were found:
    - customerClientFallback: defined in file [../ApplicationFeign/target/classes/com/feign/demo/clients/fallback/CustomerClientFallback.class]
    - com.feign.demo.clients.CustomerClient: defined in null

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Below is my Feign Client Interface :
@FeignClient(name = "CUSTOMERSERVICE", fallback = CustomerClientFallback.class, primary = false)
@RequestMapping(value = "customer")
public interface CustomerClient {

    @RequestMapping(method = RequestMethod.GET, value = "/getAllCustomers")
    List<Customer> getAllCustomers();

    @RequestMapping(method = RequestMethod.PATCH, value = "/{customerId}", consumes = "application/json")
    Customer update(@PathVariable("customerId") long customerId, @RequestBody Customer customer);

    @RequestMapping(method = RequestMethod.GET, value = "/{customerId}")
    Customer getCustomerById(@PathVariable("customerId") long customerId);

    @RequestMapping(method = RequestMethod.POST, value = "/", consumes = "application/json")
    Customer saveCustomer(@RequestBody Customer customer);

}

CustomerClientFallback implementation:
@Component
public class CustomerClientFallback implements CustomerClient {

    @Override
    public List<Customer> getAllCustomers() {

        return new ArrayList<Customer>();
    }

    @Override
    public Customer update(long customerId, Customer customer) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Customer getCustomerById(long customerId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Customer saveCustomer(Customer customer) {
        // TODO Auto-generated method stub
        return null;
    }

}

Application Class:
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableHystrix
@EnableHystrixDashboard
public class ApplicationFeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationFeignApplication.class, args);

    }

}

Spring cloud version :
Greenwich.SR1

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>

Bellow is a modification but it does not work as well.
@RestController
public class CustomerController {

    @Autowired
    private CustomerClient customerClient;

    @Autowired
    public CustomerController(@Qualifier("customerClientFallback") CustomerClient customerClient) {
        this.customerClient = customerClient;
    }

    @RequestMapping(path = "/getAllCustomers", method = RequestMethod.GET)
    public ResponseEntity<Object> getAllCustomers() {
        List<Customer> customers = customerClient.getAllCustomers();
        return new ResponseEntity<>(customers, HttpStatus.OK);

    }

    @RequestMapping(path = "/{customerId}", method = RequestMethod.GET)
    public ResponseEntity<Object> get(@PathVariable() long customerId) {
        try {
            Customer c = customerClient.getCustomerById(customerId);
            if (c != null) {
                return new ResponseEntity<>(c, HttpStatus.OK);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Customer Not Found");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @RequestMapping(path = "/{customerId}", method = RequestMethod.PATCH)
    public ResponseEntity<Object> UpdateCustomer(@PathVariable() Long customerId, @RequestBody Customer customer) {
        Customer c;
        try {
            c = customerClient.update(customerId, customer);
            if (c != null) {
                return new ResponseEntity<>(c, HttpStatus.OK);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Customer Not Found");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @RequestMapping(path = "", method = RequestMethod.POST)
    public ResponseEntity<Object> saveCustomer(@RequestBody Customer customer) {
        Customer c;
        try {
            c = customerClient.saveCustomer(customer);
            return new ResponseEntity<>(c, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
}

A: It seems there is a problem due to using CustomerClient.java feign client in your controller class.
Please make sure you are adding qualifier
@Autowired
private CustomerClient customerClient;

@Autowired
public CustomerController(@Qualifier("customerClientFallback") CustomerClient customerClient ) {
    this.customerClient= customerClient;
}

This should works now.
I will suggest you to look into FallBackFactory for more power on feign exception handling,

A: This is known bug in Spring Cloud, see:
https://github.com/spring-cloud/spring-cloud-netflix/issues/2677

A: Remove the autowired annotation from the field, you are already injecting the dependency in the constructor.
private CustomerClient customerClient;

@Autowired
public CustomerController(@Qualifier("customerClientFallback") CustomerClient customerClient) {
    this.customerClient = customerClient;
}

Its also safer to use constructor dependency injection instead of field injection - with field injection you allow anyone to create an instance of your class in an invalid state. In the constructor the dependencies are clearly specified and also it is easier to test your code (mock the dependencies and use them in the constructor)
Also, when you annotate an Interface or Class with @RequestMapping Spring will register a handler even if you have a @FeignClient annotation - and since you have an implementation of this interface you should remove it to avoid any issues with ambiguous mapping.
Like so
@FeignClient(name = "CUSTOMERSERVICE", fallback = CustomerClientFallback.class, primary = false)
public interface CustomerClient {

    @RequestMapping(method = RequestMethod.GET, value = "/getAllCustomers")
    List<Customer> getAllCustomers();

    @RequestMapping(method = RequestMethod.PATCH, value = "/{customerId}", consumes = "application/json")
    Customer update(@PathVariable("customerId") long customerId, @RequestBody Customer customer);

    @RequestMapping(method = RequestMethod.GET, value = "/{customerId}")
    Customer getCustomerById(@PathVariable("customerId") long customerId);

    @RequestMapping(method = RequestMethod.POST, value = "/", consumes = "application/json")
    Customer saveCustomer(@RequestBody Customer customer);

}

A: The Error seems to be because of the @RequestMapping provided at the class/interface level.
In your case because of @RequestMapping(value = "customer") in CustomerClient.java


text:
Q: c# Save Multidim ArrayList to Properties.Settings Is it possible to save a multidimensional ArrayList to the Properties.Settings? I get errors when i try to.
If not, is there any other way i can save some sort of multidimensional thingie to the Properties.Settings?

A: Ah, I remember fighting with Properties.Settings... never a fun battle :(. The quick and dirty option would be to use different separator characters to do a string "serialization" (in quotes because a real serialization would be much better about handling edge cases etc.). Something like this:
int[][] myArray = GetArrayFromElsewhere();
string stringVersion = string.Join(";", myArray.Select(subArray => string.Join(",", subArray)));
Properties.Settings.StringVersion = stringVersion;

You could also use esoteric Unicode characters instead of ; and ,, so as to avoid accidentally splitting a string, and you could use a loop (or probably recursion) to generalize this to any number of dimensions.
But, this is of course a quick and dirty workaround. The real solution would be to do some sort of serialization of the multidimensional array. You might be able to get away with just some simple XmlSerializer or BinaryFormatter or even JavaScriptSerializer code---actually, I think the last of those might work really well---but if you need to get more complicated, this question discusses a similar solution for a hash table, with lots of gory details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How To Print And Read Strings From stdio I need to know how to read input from and print answers to the user. How do I go
about doing this using char arrays?
This the code I am working with
int array[500];
char array2[200];
printf("Please Enter The number of names: ");
scanf("%d",&num);

for(i=0;i<num;i++){
    array[i]=0;
    array2[i]="";
}
printf("\nPlease Enter names:");
for(i=0;i<num;i++){
    scanf("names: %s",array2[i]);
}
for(i=0;i<num;i++){
    printf("\n %s",array2[i]);
}

A: This is ok:
#include <stdio.h>

#define MAX_PEOPLE 128

static inline clear()
{
    while (getchar() != '\n');
}

int main()
{
    int num, i;
    int array[500];
    char array2[MAX_PEOPLE][200];
    printf("Please Enter The number of names: ");

    while (1)
    {
        if (scanf("%d",&num) != 1 || num > MAX_PEOPLE)
        {
            clear();
            printf("Again: ");
            continue;
        }

        break;
    }

    for(i = 0; i < num; i++)
    {
        array[i] = 0;
        array2[i][0] = '\0';
    }

    printf("\n");
    for(i = 0; i < num; i++)
    {
        printf("Please Enter names: ");
        scanf("%s",array2[i]);
    }

    printf("\n");
    for(i = 0; i < num; i++)
    {
        printf("arr[%d] = %s\n", i, array2[i]);
    }

    return 0;
}


text:
Q: Reinitialising Fragment when closing activity I have an Activity with a fragment, this fragment has a map in it and some markers.
I run a service in the background that changes the position of the markers.
Each Marker has a boolean "isDrawn" and whenever the boolean is set to false the map is updated by adding drawing the marker ( I use LiveData to observe the markers)
Whenever I close the Activity that contains the fragment I call onDestroyView, which sets isDrawn of every marker to false. That way when I open the Activity again, the markers get drawn one more time. All of this works fine.
The problem is this: in the Fragment I can tap on the markers, which opens a view that has a button which opens another Activity, when I close this Activity (With BackButton) and if a marker changed its position (through the service)  when I was in said Activity, I find that there are two of the same marker on the map.
Any idea what I could do? Should I remove the fragment and create it again when I close the activity? is that possible? if so how should I proceed?

A: Here you can try 2 options

*

*Try creating a static variable and and store some flag values.

*check whether the Fragment is visible with the help of isVisible() or getUserVisibleHint()

A: You must be using this method to add a marker to the map.
public final Marker addMarker (MarkerOptions options);

take one variable of type Marker and store the reference of it which is returned by addMarker (MarkerOptions options);
like
if(marker!=null){
 marker.remove(); //will clear the previous one, it might be null at first.
}
marker=addMarker(yourOptions);//will add the latest one


text:
Q: Edge Animate Change SVG Image on Mouseover I am new to Edge Animate and JavaScript as well.  I have a map and currently I have text displaying or colors changing as the moues moves over a specific country.  What I want to happen is when the I mouseover the country I would like for the image to pop-out and enlarge.  So for example when I mouseover France France becomes larger and a different color and then when the mouse leaves the larger France area the map returns to the original map.  Is this possible?

A: Also you can use following fast trick:

*

*Create "france_default" layer.

*Create "france_mouse_over" layer.

*On mouseover hide "france_default" layer.


text:
Q: How to prove that $f_n(x):=x^n$ is not a Cauchy sequence in $C[0,1]$ under the norm $\|f\|= \sup|f(x)|$?
How to prove that $f_n(x)=x^n$ is not a Cauchy sequence in $C[0,1]$ under the norm $\|f\|= \sup_{x\in [a,b]}|f(x)|$, by showing that it does not satisfy the definition of a Cauchy sequence?

A: Note that if $f_n(x)=x^n$ is Cauchy then since $(C[0,1],||.||_\infty)$ is complete so $f_n\to f$ where $f(x)=$\begin{cases} 0 &\text{$0\le x<1$}\\ 1& x=1\end{cases} must be in $C[0,1]$ but it is not so.
Alternatively,if the sequence is Cauchy
$||f_n-f_m||=\sup_{x\in [0,1]}|f_n(x)-f_m(x)|=\sup|x^n-x^m|\to 0$;
But on Putting $n=2m ;x=\dfrac{1}{2^{2m}}$; We have $||f_n-f_m||=\dfrac{1}{4}\neq 0$

A: For a fixed $n \ge 1$ and for $m \ge n$,
$$
             \|x^n-x^m\|=\max_{x\in[0,1]}(x^n-x^m) \ge (x^n-x^m)|_{x=1/2^{1/n}}
         = \frac{1}{2}-\left(\frac{1}{2}\right)^{m/n},
$$
Hence,
$$
         \|x^n-x^m\| \ge \frac{1}{4} \mbox{ whenever } \left(\frac{1}{2}\right)^{m/n} \le \frac{1}{4},
$$
which occurs whenever $m/n > 2$, or $m > 2n$. So $\{ x^n \}_{n=1}^{\infty}$ cannot be a Cauchy sequence in $C[0,1]$.

A: Fix $N\in\mathbb{N}$. Note that:
$$ \| f_N-f_{2N}\|=\sup_{0\le x\le 1} |x|^N|1-x^N|\ge (2^{-1/N})^N|1-(2^{-1/N})^N|=2^{-1}(1-2^{-1})=1/4$$
Since $N$ was arbitrary, this shows that the definition fails with $\varepsilon=1/4$.

A: You want to show that
$$
\forall\epsilon>0,\exists N,\forall n,m:n,m>N\implies\|x^n-x^m\|=\max_{x\in[0,1]}|x^n-x^m|<\epsilon\tag{$\star$}
$$
is not satisfied.

Proposition: Every $\epsilon\in(0,1)$ fails to satisfy $(\star)$.

Proof: Choose any $\epsilon\in(0,1)$, $N\in\mathbb{N}$ and $m>N$. Let $x_0\in(0,1)$ be such that
$$
x_0^m=\epsilon+\frac{1-\epsilon}{2}
$$
Now, since $x_0^n\to0$ as $n\to\infty$, we see that upon choosing $n>m$ large enough we obtain
\begin{align}
|x_0^n-x_0^m| &= x_0^m-x_0^n\\
&=\epsilon+\frac{1-\epsilon}{2}-x_0^n\\
&>\epsilon
\end{align}
Remark: The idea is that for fixed $x_0$ and $m$, the value $x_0^m-x_0^n$ tends to $x_0^m$. Hence all we needed was to make sure that $x_0^m>\epsilon$.


text:
Q: yup.js Validate number field is larger than sibling, or nullable I'm using Yup.js to validate some form fields.
I have two integer fields, Year Built & Year Renovated.
Year Built is a required field, Year Renovated is not.
Year renovated can be left blank, however if there is a value it should be larger than year built (for a renovation certainly must occur after the date it was built).
I believe I need to use yup's ref() as well as yup's when() function. I've tried the following:
let currentYear = new Date().getFullYear();
yup.object().shape({
  yearBuilt     : yup.number().integer().min(1700).max(currentYear+1).required(),
  yearRenovated : yup.number().integer().when(
                    '$yearRenovated', (yearRenovated, schema)=>{
                        return yearRenovated > 0 ?
                            schema.min(yup.ref('yearBuilt')).max(currentYear+1) :
                            schema.transform(emptyStringToNull).nullable()
                    }
                )
})

* The transform function, emptyStringToNull simply checks if value === '' and returns null if so.
The above does allow null values, as well as does correctly check for an integer. However it does not properly evaluate yearRenovated > yearBuilt. How do I properly check that if yearRenovated is not null, that it is greater than yearBuilt?
Thank you all so much for your help.

A: const schema = Yup.object({
  // -- snip --
  billAmount: Yup.number().nullable(),
  approvedAmount: Yup.number()
    .typeError("you must specify a number")
    .notRequired()
    .when("billAmount", (billAmount: any, schema: any) => {
      return schema.test({
        test: (approvedAmount: any) => {
          if (!approvedAmount) return true;
          return approvedAmount < billAmount;
        },
        message: "Approved Amount not gether then billAmount",
      });
    }),
});

A: @JQuense, the owner of the repo had an eloquent solution, using moreThan():
const schema = yup.object().shape({
    yearBuilt: yup
      .number()
      .integer()
      .min(1700)
      .max(currentYear+1)
      .required(),
    yearRenovated: yup
      .number()
      .integer()
      .nullable()
      .moreThan(yup.ref("yearBuilt")) //<-- a whole lot neater than using a when conditional...
      .max(currentYear+1)
});

Hope that helps! Thank you @JQuense.

A: Yup (Less than or Equal To):  https://github.com/jquense/yup/issues/538#issuecomment-495340254
If you end up needing a less than or equal to implementation (<=) consider this:
number().max(5) // is <= 5


text:
Q: MPMovieViewController next/previous button event I am new to Swift
I am using MPMovieviewcontroller
when i click next or previous button then no event occurs
here is code
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var i : Int = 0

var movieplayer : MPMoviePlayerController!

var arr = ["Akbar","Serial","ak"]
override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    self.becomeFirstResponder()
    startplaying()

}

override func canBecomeFirstResponder() -> Bool {
    return true
}
override func remoteControlReceivedWithEvent(event: UIEvent) {
    if event.subtype == UIEventSubtype.RemoteControlNextTrack
    {
        i++
        startplaying()
      println(event.subtype)
    }
}
func startplaying()
{
 if i <= 2
 {
 let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov")
let url = NSURL.fileURLWithPath(path!)

movieplayer = MPMoviePlayerController(contentURL: url)
}

movieplayer.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
movieplayer.view.sizeToFit()

movieplayer.scalingMode = MPMovieScalingMode.AspectFill
movieplayer.fullscreen = true

movieplayer.controlStyle = MPMovieControlStyle.Fullscreen

movieplayer.movieSourceType = MPMovieSourceType.File
movieplayer.prepareToPlay()

self.view.addSubview(movieplayer.view)
}

When i debug this code then remoteControlReceivedWithEvent function did not execute
I get donm help from here

A: Try this
func startplaying() {
    if i <= 2 {
        let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov")
        let url = NSURL.fileURLWithPath(path!)
    movieplayer.contentURL = NSURL.fileURLWithPath(url)
}

Read more: Play MP4 using MPMoviePlayerController() in Swift

A: Here I do next/Previous Manully using button
I hope it is proper way to next/previous operation
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var movieplayer : MPMoviePlayerController!
var arr = ["ak","Serial","Akbar"]
var i = 0
override func viewDidLoad() {
    super.viewDidLoad()
    startplaying()
}
@IBOutlet var views: UIView!
var flag = 0
@IBOutlet var next: UIButton!
@IBOutlet var pre: UIButton!
@IBOutlet var play: UIButton!
func startplaying()
{
if i >= 0 && i <= 2
{
 let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov")
 let url = NSURL.fileURLWithPath(path!)
 movieplayer = MPMoviePlayerController(contentURL: url)

    movieplayer.view.frame = CGRect(x: 0, y: 0, width: 320, height: 450)
    movieplayer.view.sizeToFit()

    movieplayer.scalingMode = MPMovieScalingMode.AspectFill
    movieplayer.fullscreen = true

    movieplayer.controlStyle = MPMovieControlStyle.Embedded

    movieplayer.movieSourceType = MPMovieSourceType.File
    movieplayer.repeatMode = MPMovieRepeatMode.One

    movieplayer.prepareToPlay()

   // self.view.addSubview(movieplayer.view)
    self.views.addSubview(movieplayer.view)
  }
  else
  {
    println("No Video Avaliable")
    movieplayer.stop()
  }
}

@IBAction func Previous(sender: AnyObject) {
    if i >= 0
    {
      i--
      startplaying()
    }
    else
    {
      println("No Video Avaliable")
      movieplayer.stop()
    }

}

@IBAction func Pause(sender: AnyObject) {
    if flag == 0
    {
     play.setTitle("Pause", forState: UIControlState.Normal)
     movieplayer.pause()
      flag = 1
    }
    else
    {
        play.setTitle("Play", forState: UIControlState.Normal)
        movieplayer.play()
        flag = 0
    }
}

@IBAction func next(sender: AnyObject) {
    if i <= 2
    {
     i++
     startplaying()
    }
    else
    {
      println("No Video Avaliable")
        movieplayer.stop()
    }
}


text:
Q: Regular expressions filter, with multiple conditions Once again, I'm really bad with reg, I wonder if some1 could help me with this matching expression, with this posibles cases:
case 1 =  |ABC:(n)
case 2 =  ABC:(n)
case 3 =  ABC:(n)|

where (n) is an integer.
so If I have an array which looks like this:
 ["ABC:2", "BVD:3", "BDS|ABC:3", "ABC:5|QWE:3"];

my filter after split, should return this:
 [2, 3, 5]

here is a jsfiddle
I will appreciate any help,
Thanks in advanced!

A: Just add another line in your existing code that will split each of the parts by |, so that you get an array of the ABC:(n) parts:
var arr = oObj.split(",");
arr = $.map(arr, function(item) { return item.split("|"); });

// or, in native JS:
arr = Array.prototype.concat.apply([], arr.map(function(item) { return item.split("|"); }));

No regex required at all!


text:
Q: Algorithm Behind Auto Contrast Feature in Photoshop I am struggling with pre-processing images in image recognition.
Up to now, I have tried:

*

*my custom solution like this in python
image_with_better_contrast = round(image/255,0) * 255

*Histogram Equalization (better than previous)

*CLAHE (Contrast Limited Adaptive Histogram Equalization) (best of three)

But recently I compared CLAHE with the Auto Contrast feature of Photoshop on gray scale images - and results of Auto Contrast are impressive. I am excited to know about algorithm behind this feature.
Note: I know that Photoshop is proprietary software, and its code may be closed source. So any hint related to improving the CLAHE results, or any other algorithm, would be by me appreciated.

A: While CLAHE Algorithm is local by nature Photoshop's Auto Contrast is probably a global method.
I'd say it works on the Histogram of the image only by stretching the values in the image - Image Normalization.
For instant, take RGB image and for each channel stretch its histogram as following (MATLAB Code):
for ii = 1:numChannels
    mOutputImage(:, :, ii) = (mOutputImage(:, :, ii) - max(max(mOutputImage(:, :, ii)))) ./ (max(max(mOutputImage(:, :, ii))) -  min(min(mOutputImage(:, :, ii))));
end

Another approach would be Histogram Equalization.
Probably Photoshop is doing something more Advanced.
Maybe like doing it in the YUV Color Space, mixing the two or using more robust methods which looks on the percentiles of the histogram.
But this is the direction you should experiment with.


text:
Q: Run Xdebug on Laravel 8 with Sail & PhpStorm on Ubuntu I have Ubuntu 18.04 and a fresh installation of Laravel 8. I want to use Xdebug together with Sail. I followed the instructions as follows:

*

*Added SAIL_XDEBUG_MODE=develop,debug to env

*Run sail build --no-cache and sail up -d

*Run docker inspect -f {{range.NetworkSettings.Networks}}{{.Gateway}}{{end}} <container-name> to get the IP of my docker container

*Added SAIL_XDEBUG_CONFIG="client_host=172.19.2.1" to env (IP from step 3)

Next I continued with the instruction from PhpStorm for debugging:

*Validated that Xdebug is active by sail php -v.

*Enabled listening to debug connection in PhpStorm

*Set a breakpoint and also enabled Break at first line in PHP scripts

*Installed Xdebug Helper browser extension for Chrome

*Clicked on debug in extension (bug is now green)

*Refresh page, page builds very slowly, but loads completely (which should not be the case, it should hang on a breakpoint)

If I switch to PhpStorm, then no dialog pops up. However, according to the instructions, there should be some instructions.

Reload the page in the browser and return to PhpStorm. In the Incoming
Connection From  dialog, select the path mappings so
that PhpStorm can map the remote files on the web server to the local
files in your project.

Hera are my debug settings:

What am I missing?

A: Thanks to the helps of @LazyOne I got it working. I just had to skip step 3 & 4 in my instructions.
Or in other words, I had to follow the instructions of https://laravel.com/docs/8.x/sail#debugging-with-xdebug but ignore the Linux Host IP Configuration section, although I am on Linux. Looks like this section is not appropriate for Ubuntu?


text:
Q: timeit.timeit method error "expected an indented block" As I am learning Python 3.5 and I wanted to start comparing time on different code.
I have tried the timeit.timeit module on a couple other simple statements and got it to work.
I can't get it to work on the below code and get the error below:
Traceback (most recent call last):
File "C:\Users\ASUS\Desktop\pythoncode\class_gen.py", line 10, in <module>
    print(timeit.timeit(",".join(["#"+i+j for i in listTags for j in listTags if i != j])))
  File "C:\Python35\lib\timeit.py", line 213, in timeit
    return Timer(stmt, setup, timer, globals).timeit(number)
  File "C:\Python35\lib\timeit.py", line 133, in __init__
    code = compile(src, dummy_src_name, "exec")
  File "<timeit-src>", line 7
    _t1 = _timer()
      ^
IndentationError: expected an indented block"""

The code I am using is:
import itertools
import timeit

listTags = [ "TOT" , "WBA", "BUR", "SOU"]

print(timeit.timeit(",".join(["#" + "".join(t) for t in itertools.permutations(listTags, 2)]))

print(timeit.timeit(",".join(["#"+i+j for i in listTags for j in listTags if i != j])))

I have tried it with and without the number=number keyword to no avail.

A: You have to pass a python code as string in the timeit call.
You were passing the evaluated value of your expression (#TOTWBA,#TOTBUR,#TOTSOU,#WBATOT,#WBABUR,#WBASOU,#BURTOT,#BURWBA,#BURSOU,#SOUTOT,#SOUWBA,#SOUBUR) to be executed.
Moreover, you have to pass listTags literally, or using setup expression, as timeit runs in a different interpreter: it's not aware of your previously defined variables.
I rewrote the first timeit call using single quotes to protect your statement and added a setup call to define the listTags variable.
import itertools
import timeit

print(timeit.timeit('",".join(["#" + "".join(t) for t in itertools.permutations(listTags, 2)])',setup='listTags = [ "TOT" , "WBA", "BUR", "SOU"]'))

I get a time as a result: 5.2231671576142285: it's working

A: @Jean is correct, you need to pass it as a string to timeit (wrap it up in single quotes ') in order for it to work correctly. You also need to pass the appropriate setup for name look-ups to succeed.
Still, it is interesting to note why this happens, though.
When you try and timeit with:
print(timeit.timeit(",".join(["#" + "".join(t) for t in itertools.permutations(listTags, 2)]))

you should realize that the argument gets evaluated. timeit is eventually called with the argument:
timeit.timeit('#TOTWBA,#TOTBUR,#TOTSOU,#WBATOT,#WBABUR,#WBASOU,#BURTOT,#BURWBA,#BURSOU,#SOUTOT,#SOUWBA,#SOUBUR')

Inside timeit, this is formatted into a default template that gets timed; it's easy to re-create that template to see what Python tries to execute:
template = """
def inner(_it, _timer{init}):
    {setup}
    _t0 = _timer()
    for _i in _it:
        {stmt}
    _t1 = _timer()
    return _t1 - _t0
"""
src = template.format(stmt=",".join(["#"+i+j for i in listTags for j in listTags if i != j]), setup='', init='')

So, what gets executed is:
>>> print(src)
def inner(_it, _timer):

    _t0 = _timer()
    for _i in _it:
        #TOTWBA,#TOTBUR,#TOTSOU,#WBATOT,#WBABUR,#WBASOU,#BURTOT,#BURWBA,#BURSOU,#SOUTOT,#SOUWBA,#SOUBUR
    _t1 = _timer()
    return _t1 - _t0

Which, if you try and execute normally in your REPL, would result in an IndentationError since the for loop only has a comment in its body (which gets removed during parsing). Executing:
for i in [1, 2]:
    # foo
print('fooing')

Results in:
  File "<ipython-input-58-634beff715a1>", line 3
    print('fooing')
        ^
IndentationError: expected an indented block


text:
Q: How do we edit Realm database using Realm Browser? I have been working on a workout app, for iOS using Swift. I have to create multiple workout objects (about 300) which vary in names. Hence creating a loop to add names would be difficult.
Hence, I am using Realm Browser to directly edit the default.Realm file, created by my app. Now all the objects are in the file, however when I edit any row's value, and then reopen the database, the changes do not persist.
Is there any other way to do this?
class WorkoutSession: Object {
    dynamic var name = ""
    dynamic var date = NSDate()
    dynamic var completed = false
    dynamic var note = ""
    dynamic var caloriesBurnt:Int = 0
    dynamic var workoutLengthInString = "0 mins"
}

All the sessions go inside the Workout Type Class
class WorkoutType: Object {
    dynamic var workoutTypeName = ""
    let workoutSessions = List<WorkoutSession>()
}

A: Turns out that this was a bug in the browser. Our update is in the release process. Meanwhile you can get a prerelease, which fixes the issue.


text:
Q: Pure css implementation of google photos I'm trying to accomplish layout same of google photos and come across to this page https://github.com/xieranmaya/blog/issues/6 . My question is about the final output of his work which can be viewed on this page. https://xieranmaya.github.io/images/cats/cats.html . When you inspect element one of the photos you can see this line

My Question is what computation did he use to get the value of flex-grow and flex-basis since it's not mentioned on the tutorial?

A: Here you can see that with jQuery I simulate the flex grow effect as seen in the Angular version.
$('img').each(function() {  //Cycle all the images
var img = $(this);

//Apply flex settings
img
    .css('flex-grow', img.width() * 100 / img.height())
    .css('flex-basis', img.width() * 240 / img.height() + 'px');
});

Fiddle


text:
Q: Wrapping Node.js callbacks in Promises using Bluebird How do I wrap a Node.js callback using a Promise in Bluebird? This is what I came up with, but wanted to know if there is a better way:
return new Promise(function(onFulfilled, onRejected) {
    nodeCall(function(err, res) {
            if (err) {
                onRejected(err);
            }
            onFulfilled(res);
        });
});

Is there a cleaner way to do this if only an error needs to be returned back?
Edit
I tried to use Promise.promisifyAll(), but the result is not being propagated to the then clause. My specific example is shown below. I am using two libraries: a) sequelize, which returns promises, b) supertest (used for testing http requests), which uses node style callbacks. Here's the code without using promisifyAll. It calls sequelize to initialize the database and then makes an HTTP request to create the order. Bosth console.log statements are printed correctly:
var request = require('supertest');

describe('Test', function() {
    before(function(done) {
        // Sync the database
        sequelize.sync(
        ).then(function() {
            console.log('Create an order');
            request(app)
                .post('/orders')
                .send({
                    customer: 'John Smith'
                })
                .end(function(err, res) {
                    console.log('order:', res.body);
                    done();
                });
        });
    });

    ...
});

Now I try to use promisifyAll, so that I can chain the calls with then:
var request = require('supertest');
Promise.promisifyAll(request.prototype);

describe('Test', function() {
    before(function(done) {
        // Sync the database
        sequelize.sync(
        ).then(function() {
            console.log('Create an order');
            request(app)
                .post('/orders')
                .send({
                    customer: 'John Smith'
                })
                .end();
        }).then(function(res) {
            console.log('order:', res.body);
            done();
        });
    });

    ...
});

When I get to the second console.log the res argument is undefined.
Create an order
Possibly unhandled TypeError: Cannot read property 'body' of undefined

What am I doing wrong?

A: You are not calling the promise returning version and not returning it either.
Try this:
   // Add a return statement so the promise is chained
   return request(app)
            .post('/orders')
            .send({
                customer: 'John Smith'
            })
            // Call the promise returning version of .end()
            .endAsync();


text:
Q: How to call a function from a class binded to an element with the id of this element? Here is my code :
<html>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Kalendae/0.7.1/kalendae.css" type="text/css" charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Kalendae/0.7.1/kalendae.standalone.js" type="text/javascript" charset="utf-8"></script>
<body>
<script type="text/javascript">
        function myFunction() {
            alert("toto");
        document.getElementById("testKal").draw(); // i want to activate the draw function of auto-kal
    }
</script>

<img src="https://www.dropbox.com/s/hz8nrhh0yosvpgy/calendar.png?dl=1" id="imgTest" onclick="myFunction()"> <input type="text" class="auto-kal" id="testKal">
</body>
</html>

I want that when i click on the calendar picture , the calendar of the input text pop.
It's the function draw of kalendae.
I've also tried to activate the click() function of testKal when the image is clicked  :
<html>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Kalendae/0.7.1/kalendae.css" type="text/css" charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Kalendae/0.7.1/kalendae.standalone.js" type="text/javascript" charset="utf-8"></script>
<body>
<script type="text/javascript">
        function myFunction() {
            alert("toto");
        document.getElementById("testKal").click(); // i want to activate the draw function of auto-kal
    }
</script>

Here is a fiddle with the draw function :
https://jsfiddle.net/bussiere/wfj7bk3m/6/
And one with trying to pass the click :
https://jsfiddle.net/bussiere/6hdsL1n8/

A: You need to trigger focus event of input
document.getElementById("testKal").focus();

A: document.getElementById("testKal").focus();

https://jsfiddle.net/56jnr937/


text:
Q: Checking if IP address is correct using RtlIpv4StringToAddressA and RtlIpv6StringToAddressA (C++). Convertion of data type problem I am trying to create a function which returns a BOOL after checking if an IP address string is IPv4 or IPv6:
static BOOL checkIp(CString strIPAddr)
{
    BOOL result(FALSE);
    PCSTR ip = ((PCSTR)(PCTSTR)strIPAddr);
    PCSTR Terminator;
    in_addr aIpv4;
    in6_addr aIpv6;

    if ((RtlIpv4StringToAddressA(ip, true, &Terminator, &aIpv4) == STATUS_SUCCESS))
    {
        result = TRUE;
    }
    else if ((RtlIpv6StringToAddressA(ip, &Terminator, &aIpv6) == STATUS_SUCCESS))
    {
        result = TRUE;
    }

    return result;
}

In debug mode, after providing 127.0.0.1, FALSE is returned. I think there is some problem with the data type: Error reading characters of String.

Thanks in advance!

A: You are casting a PCTSTR (const TCHAR*) to a PCSTR (const char*).  You are compiling for Unicode, so PCTSTR maps to const wchar_t*, not to const char* like you are expecting. That would explain why your debug window shows ip is just "1" and not "127.0.0.1".
Get rid of the casts altogether, and use the W functions instead of the A functions.
static bool checkIp(CString strIPAddr)
{
    PCWSTR ip = strIPAddr;
    LPCWSTR Terminator;
    in_addr aIpv4;
    in6_addr aIpv6;

    return (
        (RtlIpv4StringToAddressW(ip, TRUE, &Terminator, &aIpv4) == STATUS_SUCCESS) ||
        (RtlIpv6StringToAddressW(ip, &Terminator, &aIpv6) == STATUS_SUCCESS)
    );
}


text:
Q: Evaluate the surface area of the cone delimited by the plane
Surface is the cone $z^2=x^2+y^2$ delimited by the plane $z=0$ and
  $x+2z=3$.

Well, the first thing I thought is to devide it in two parts, the one that is a simple cone and the other part. But I'm a bit lost of how do I find the proper parametrization for this surface.


text:
Q: How to make sticky header table in bootstrap vue I'm new to using javascript and vuejs technology, and I have case like this
I've using table components from BootstrapVue like this :
<b-table
   style="white-space: nowrap;"
   v-else
   bordered
   hover
   responsive
   class="position-relative mb-0"
   :per-page="perPage"
   :current-page="currentPage"
   :items="items"
   :fields="fields"
   :sort-by.sync="sortBy"
   :sort-desc.sync="sortDesc"
   :sort-direction="sortDirection"
   :filter="filter"
   @filtered="onFiltered"
   >
</b-table>

And I've tried sticky-header but I don't think it's suitable, because what I expect is a sticky header without any restrictions on scrolling inside the table, but scrolling outside the table/body and with the addition of a sticky header table when it reaches the top.
https://codesandbox.io/s/sticky-vuetify-table-header-3o0km?file=/pages/index.vue:1240-1283
That is an example I want to do on my page, but I'm struggling and can't find an answer for the Bootstrap Vue framework.
How do I style my table so that it looks like the example above?


text:
Q: Format a text box as a number in a report I have a text box, FuelGal, in a report which has a calculated value,
=FuelLb/6

Where FuelLb is another text box in the same report. In the report, the property of FuelGal is set to General Number, and the allowed decimals is set to 1.  When the report is generated, the value is correct, but not limited to one decimal.

A: Set the Format property of the textbox in the report to: 0.0


text:
Q: Reasoning for union type to fail to allow property look up This has mystified me for a long time:

Basically the situation is:
interface NLUAddOpts{}
interface NLURunOpts{
  treeify: boolean
}

const fn = function(opts: NLUAddOpts | NLURunOpts){
  if(opts.treeify){  // compilation error

  }
}

Why!? If you are just reading a property, but not a subproperty of that property, then shouldn't it just compile? At least it should compile if it's in an if-check.
On the other hand, if it was an assignment:
const treeify = opts.treeify;

I guess I could see why it wouldn't compile.
What's the best way to solve this one?

A: The answer is pretty simple, you have stated that opts has a type NLUAddOpts OR NLURunOpts. This means you can only access properties that are common to both types otherwise TS has no way of knowing if the property actually exists.
Now, if a NLURunOpts will always have the property treeify and NLUAddOpts will never have it then you can do the following:
if ('treeify' in opts) {
    // opts is now of 'NLURunOpts' type
}

You could also define a type guard:
function isRunOpts(opts: any): opts is NLURunOpts {
    return opts.treeify !== undefined;
}

if (isRunOpts(opts)) {
    // opts is now of 'NLURunOpts' type
}

Otherwise you could do the following:
if((opts as NLURunOpts).treeify) {

}

Which asserts that opts is of type NLURunOpts


text:
Q: Priority Queue of Objects Giving Wrong Value on One Call of Peek() So I have this assignment for a Java class, I hit a bit of a road block.  My code is working fine except on the last iteration of a loop, where peek() gives the wrong value.  Every other iteration it gives the correct value, so I am lost as to why it gives the wrong value.
My assignment is to make a priority queue of boxes.  We read float values from a text file, and then fill the boxes with the values.  No box can have a total sum greater than 1.0.
The data from the text file is: 0.1, 0.6, 0.11, 0.765, 0.01, 0.42, 0.1492,0.667, 0.333, 0.111
Code:
 Box Class:
public class box implements Comparable<box>
{
//instance variables
private ArrayList<Float> values;
private Float totalValue=0.0f;

public box ()
{
    values = new ArrayList<Float>();
}
public box(Float val)
{
    values = new ArrayList<Float>();
    values.add(val);
}

//add new values to the box
public void addVal(Float newVal)
{
    values.add(newVal);
}
/*
 * Adds up all the values in the box, returns sum as Float.
 */
public Float findSum()
{
    totalValue=0.0f;
    for(Float val : values)
    {
        totalValue=totalValue+val;
    }
    return totalValue;
}

}
Code for comparator
        import java.util.Comparator;
    public class boxComparator implements Comparator<box>
   {
        //compare method for boxes
        public int compare(box a, box b)
        {
        if (a.findSum()>b.findSum())
            return 10;
        else if (a.findSum()<b.findSum())
            return -10;
        else
            return 0;

    }
}

Code for PackingBoxes (contains Main):
    import java.util.;
    import java.io.;
public class PackBoxes
{
public static void main(String[] args)
{
        ...
        boxComparator compSum = new boxComparator();

        ...
     *Strategy A: As each new item is processed, it is placed in the
     *            fullest box that can hold it.
     */
    System.out.println("=========");
    System.out.println("Packing via most-filled strategy:");
    System.out.println();

    //Create new priorityqueue of boxes for strategy A
    PriorityQueue<box> boxesA = new PriorityQueue<box>(11,compSum);
    //add first box to queue
    boxesA.add(new box());

    //for each loop, goes through arrayList L
    for(Float x : L)
    {

        //if element + sum of current box is less than 1 put element
        //into the current box

        if(x + boxesA.peek().findSum() <1)
        {
            boxesA.peek().addVal(x);
        }
        //if element + sum of current box is greater than 1, then make
        // a new box
        else
        {
            boxesA.add(new box(x));
        }

    }
    System.out.println(boxesA.size()+" boxes were used.");

    //print queue
    while(!boxesA.isEmpty())
    {
        System.out.println(boxesA.poll().findSum());
    }

}

After much debugging, I've found that the program does the following:
Read 0.1, 0.6, 0.11 put in box 1.  Read .765, does't fit in box 1, create box 2.  Read .01 put in box 2 (which is smallest total sum).  Read 0.42, doesn't fit in box 2, create box 3.  Put .1492 in box 3.  Read .667, create box 4.  Read .333 put in box 3 (box 3 has smallest current sum).  read .111, doesn't fit in box 3, create box 5
The bolded part is the problem.  It should read .111 and try and put it into box 4, with .667.  But when I use peek it brings up the box with, 0.42, 0.1492, 0.33, for a total sum of .9022.  Since 0.667 is smaller than 0.9022 I don't understand why peek() isn't giving me box 4.  Any help here would be greatly appreciated.
Edit:  Tried to delete code that wasn't part of the problem.

A: The problem as far as I can tell is that you do not re-order the boxes when you put .333 in box 3. When you do that, box 3 is no longer the least full box - it should no longer be on top of the queue. Box 4 should be moved to the top of the queue. But since box 3 stays on top of the queue, next time you try to insert an item, it looks at box 3 (the top item of the queue). When it fails to insert into box 3, it makes a new box.
To solve this, all you need to do is place a simple sort function for your queue after you add a new value or a new box. That way the box that is the least full will always be on top.


text:
Q: Debugging a Sentiment Analyzer I'm attempting my first shot at NLP using Python's NLTK module to run a sentiment analysis on select tweets. I have been following this tutorial and have downloaded the Sentiment140 Tweet Corpus as my training data set since this is for educational purposes only (contains ~1.6m hand classified tweets).
My code can be found here. Please note that this is being done in Python 2, in an iPython Notebook.
Question Part 1
I'm testing my code with 10,000 rows from the training set to see if it works before feeding it all 1.6m rows. When I run the code, line 96 returns None:
print classifier.show_most_informative_features(32)
Most Informative Features
None

However, the tutorial suggests I should see something like the following:
Most Informative Features
contains(not) = False          positi : negati =      1.6 : 1.0
contains(tired) = False          positi : negati =      1.2 : 1.0
contains(excited) = False          negati : positi =      1.2 : 1.0
contains(great) = False          negati : positi =      1.2 : 1.0
contains(looking) = False          positi : negati =      1.2 : 1.0
contains(like) = False          positi : negati =      1.2 : 1.0
contains(love) = False          negati : positi =      1.2 : 1.0
contains(amazing) = False          negati : positi =      1.2 : 1.0
contains(enemy) = False          positi : negati =      1.2 : 1.0
contains(about) = False          negati : positi =      1.2 : 1.0
contains(best) = False          negati : positi =      1.2 : 1.0
contains(forward) = False          positi : negati =      1.2 : 1.0
contains(friend) = False          negati : positi =      1.2 : 1.0
contains(horrible) = False          positi : negati =      1.2 : 1.0

I'm using line 96 as an indicator to tell me whether or not the classifier works. In terms of fixes that I've already tried: I saw a comment in the tutorial that suggested line 87 should be:
training_set = nltk.classify.util.apply_features(extract_features, tweets)

instead of what it currently is:
training_set = nltk.classify.apply_features(extract_features, tweets)

I tried both of these variations.
I'd like to iron this out before I run the full 1.6m row data set through to train the classifier.
Here are all of my import statements for the notebook (some import statements are used in other areas of the notebook):
import pandas as pd
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap
from pandas.tseries.resample import TimeGrouper
from pandas.tseries.offsets import DateOffset
import nltk
from nltk.corpus import stopwords
from nltk import FreqDist
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import subjectivity
from nltk.sentiment import SentimentAnalyzer
import nltk.sentiment.util
import csv
import re
import networkx as nx
import time
%matplotlib inline
%pylab inline

Question Part 2
How do I tweak this code to return the polarity scores themselves. Something like:
compound: -0.6759, neg: 0.41, neu: 0.59, pos: 0.0

Based on this NLTK page, it seems like I would call the .polarity_socres() method, but I'm not sure where in my code I'd even do that. Here is their code that returns the above:
sid = SentimentIntensityAnalyzer()
for sentence in sentences:
    print(sentence)
    ss = sid.polarity_scores(sentence)
    for k in sorted(ss):
        print('{0}: {1}, '.format(k, ss[k]), end='')


text:
Q: what does projection $\pi$ mean? I am reading a paper where I encountered the following -
\begin{equation}
Z(x) = \pi_{[-c,c]^{n}} (\nabla F(x)-x)
\end{equation}
what does the first term mean? Its mentioned in the paper that $\pi_{[-c,c]^{n}} (q)$ is projection and it acts components wise on q - Which I cannot understand. Can someone elaborate on it?

A: Let me try my shot at it. I believe x is a vector, e.g.
grad of F(x) = <Fx1, Fx2>
q = <Fx1, Fx2> - <x1, x2>
q = (Fx1 - x1)i + (Fx2 - x2)j
q is a vector of component i & j.


text:
Q: echoing javascript inside of php, can't get quotes right I want to have some javascript execute based on some php if statement, but I can't get the quotes around my link correct .. In console it shows that a ) is missing from the following line. I'm sure I messed up the quotes, it was correct when I just had it javascript, but now mixing with echo I can't get it. I'm using single quotes around the whole thing and doubles inside. The rest is working, please take a look and help me fix this line. Thanks!
$(this).append("Schedule Appointment   ");

if ($mode== 'view' && $action==''){
    echo '';

A: Either vary the quote types, or start escaping. e.g. with this raw (and broken) snippet:
.append("");

you actually have code 3 levels deep. There's the original Javascript (layer 1):
.append("");
        ^--------------layer 1--------------------------------^

Then there's the embedded HTML (layer 2):
.append("");
                 ^-------^         ^----------layer 2---------^

And then there's the sub-embedded Javascript (layer 3):
.append("");
                                                 ^-------^

IN every case, you have to use the quotes appropriate for the layer you're embedding within. So to embed your layer 2 quotes within layer 1, use escapes:
.append("");

So now you've got valid Javascript at layer 1. But the HTML itself is still broken, because once that snippet is embedded in the DOM, you end up with

                          ^---start attribute
                                        ^---end attribute
                                                   ^--start unterminated attribute

So now you have to worry about embedding layer 3 in layer 2. Since it's Javascript-in-html:
.append("\");
                 ^--------^----------^ etc... layer 2-in-1 escapes
                                                    ^^^^^--------^^^^^ layer 3-in-1 quotes

Basically - you always have to consider the context in which the code will be seen. If you're embedding HTML in javascript, any quotes in HTML must also be valid Javascript. If you're embedding Javascsript in HTML, then any JS quotes must also produce valid HTML. And when you're nesting languages 3 or 4 levels deep, you have to consider ALL of the layers. Every layer must itself be valid to all of the parent layers.

A: Use single quotes .. IE
$(this).append('Schedule Appointment   ');


text:
Q: Showing that a group of order 6 contains an element of order 2 and order 3. (Without Cauchy) Prove that a group a non-abelian of order 6 is isomorphic to $S_3$. Prove that every abelian group of order 6 is isomorphic to $Z/{6Z}$.
Here are some hints: start by showing that every group $G$ of order 6 must have an element
$x$ of order 2 and an element $y$ of order 3. This in fact follows from some general theorems
but I want you to argue directly using only what we covered in class. (A typical problem
here is why can't all the elements different from 1 have order 3. If this is the case, show
that there are two cyclic groups $K_1,K_2$ of $G$ of order 3 such that $K_1 \cap K_2 = \left\{1\right\}$. Calculate
$|K_1K_2|$.)
Having shown that, if $G$ is abelian show it implies the existence of an element of order
6. In the non-abelian case show that we must have $xyx^{-1} = y^2$ and that every element in
$G$ is of the form $x^ay^b$, $a = 0, 1, b = 0, 1, 2$. Show that the map $x\to (1 2)$, $y\to (1 2 3)$
extends to an isomorphism.
Hi. I am trying to prove the hint. But I cannot conclude that the group has an element of order 2 and one of order 3. I have the following:
My Solution. Suppose $\forall g\in G,\ g\neq e,\ |g|=3$. Let $g,h\in G,\ g\neq h$. Then $\langle g\rangle\cap \langle h\rangle=\left\{e\right\}$. Indeed, $\langle g\rangle=\left\{e,g,g^2\right\} and \langle h\rangle=\left\{e,h,h^2\right\}$. If $g=h^2\Rightarrow gh=h^3=e\Rightarrow h=g^{-1}\wedge h^2=g^{-2}\Rightarrow \langle h\rangle=\left\{e,g^{-1},g^{-2}\right\}=\left\{e,g,g^2\right\}$.
In general, if $G=\left\{e,g_1,g_2,g_3,g_4,g_5\right\}$ then $\langle g_i\rangle=\langle g_1\rangle,\ i=2,3,4,5$.
Now, $G=\bigcup_{i=1}^{5} \langle g_i\rangle=\left\{e,g_1^2,g_1^2\right\}$ a contradiccion with $|G|=6$.
Now, $|\langle g\rangle \langle h\rangle|=9$ a contradiction with $|G|=6.$
Therefore, exists $g\in G,\ g\neq e$ such that $|g|\in \left\{2,6\right\}$.
Now,    can't all the elements different from 1 have order 2.
Suppose that for all $g\in G,g\neq e,\ |g|=2 \Rightarrow G$ abelian $\Rightarrow S=\left\{e,g,h,gh\right\}$ subgroup of $G$ but $|S|\not\mid |G|$ a contradiction.
Therefore, exists $g\in G,\ g\neq e,\ |g|\in\left\{3,6\right\}$.
Why exists $x,y\in G$ such that $|x|=2, |y|=3$?
Actualization 1. I ahve proves this exists $x,y\in G$ such that $|x|\in \left\{2,6\right\}$ and $|y|\in\left\{3,6\right\}$.
If $|x|=6$ then $|x^3|=2$ and $|x^2|=3$. Therefore $x^3, x^2$ are elements in $G$ of order 2 and 3 respectively.
If $|x|=2$ then x is the element of order 2. If $|y|=6$ similary. If $|y|=3$ then $x,y$ are elements of order 2 and 3.
Now, if $G$ abelian $|(xy)|=6$ then $G\simeq Z_6$. If $G$ no abelian. How proves that $xyx^{-1}=y^2$?
Actualization 2. Let $G$ non aebelian. $ [G:\langle y\rangle ]=2$ then $\langle y\rangle$ normal in $G$ then $x\langle y\rangle=\langle y\rangle$. therefore $xyx^{-1}\in \left\{e,y,y^2\right\}$ then $xyx^{-1}=y^2$ (other cases are contradiction)

A: For showing that there are elements of order 2 and 3, let's first look into the possibility of orders of nonidentity elements which are 2,3,6.
If you have an element of order 6, you are done (why?).
Otherwise suppose all the elements($\neq 1$) are of order 2 then $G$ must be abelian. In that case $G$ is a $\mathbb Z/2$ vector space of finite dimension hence of cardinality $2^k$ for some k>0, contradiction.
So, if your group has an order 2 element it must have one order 3 element.
Now suppose it has all the nonidentity elements of order 3
Then write elements, $\{1, a, a^2\}$ next choose some element $b$ outside this collection argue that $\{b, b^2\}$ is disjoint from the above collection. Now there will still be another nonidentity element let's say $c$ in G. Show that, $c^2 \notin \{1, a, a^2, b, b^2,c\}$. Hence a contradiction.

A: You can use sylow theorem. According to $6 = 2*3$ and that every prime order group is cyclical group, we can easily prove the question in your title.


text:
Q: How much loan you owed after 20 years Statement: Paying down a mortgage: you took a $\$200000$ home mortgage at an annual interest rate of 3%.suppose that the loan is amortized over a period of 30 years and let P(t) denote the amount of money(in thousands of dollars) that you owe on the loan after t years.A reasonable estimate of the rate of change of P is given by $ P'(t)=-4.1107e^{0.03t} $. What is the amount of money owed on the loan after 20 years?
I tried to solve it
$$ \frac{dP}{dt}=-4.1107\cdot e^{0.03t} $$
$$ dP=-4.1107\cdot e^{0.03t}dt $$
$$ \int dP=\int-4.1107\cdot e^{0.03t}dt $$
$$ P=-\frac{4.1107}{.03}\cdot e^{0.03t}+c $$
$$ P=-137.023333\cdot e^{0.03t}+c $$
$$ at~ t=0 ~P=200$$
$$ 200=-137.023333+c $$
$$ c=337.023333 $$
$$ P=-137.023333\cdot e^{0.03t}+337.023333 $$
$$ at~ t=20 $$
$$ P=-137.023333e^{.6}+337.023333 $$
$$ P_{20}\approx 87.35054 \cdot1000 $$
So answer is approximately 87350.54.Am i doing anything wrong ?


text:
Q: What 2 and 4 decimal number has the largest difference against its double IEEE754 representation? We know that fractional numbers that are powers of 2 like 0.25 (2^-2) or 0.0625 (2^-4) can be represented exactly in a floating point or double type variable.
Any fractional number that is also an exact sum of a power of 2 can also be exactly represented.
However, 0.01 cannot be exactly represented. It will be 0.009999999999999787 when stored as a double type value (binary64).
So, I am wondering whether there is a value or values that will present with the largest discrepancy.


text:
Q: Convert List to Image I have the following .ico image, read using image4j library:
List<BufferedImage> BI = ICODecoder.read("aImage.ico");

Next I want to set this image as a frame icon:
myFrame.setIconImage((Image)BI);

Error: java.lang.ClassCastException
I need to convert the type List<\BufferedImage> to the type Image. Any help would be appreciated.

A: You could consider using...
myFrame.setIconImage(BI.get(0));

List is a list of stuff (or technically Objects, in your case, BufferedImages), where as setIconImage expects just one...
Alternatively, you could take advantage of of JFrame's capability of providing multiple different images at different resolutions by using...
myFrame.setIconImages(BI);

Which is probably what you were after in the first place...

A: In this code
 List<BufferedImage> BI = ICODecoder.read("aImage.ico");

you are loading into a List
so when you try to do myFrame.setIconImage((Image)BI); you will not be able to convert a list into an image.
try a .get(0) on the list to return the Image.


text:
Q: Wordpress | Apply function/filter to specific template (featured image function filter) I have the following code in my tweaks plugin.
add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );

function sqhse_news_featimgmove( $content ) {
    $content = preg_replace( "/<\/p>/", "
" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "

", $content, 1 );
    return $content;
}

What it does:
It adds the featured image after the first paragraph which is great and exactly what I need.
The problem: The code applies itself to single.php (great that's where I need it) but it also applies itself to single-training_courses.php (a template for a custom post type).
The help required: Apply the code to single.php and not any sub single templates such as single-training_courses.php
Is this achievable? and if so how may I achieve this?

A: You can use get_post_type() WordPress function and wrap your code inside an if statement as follow:
add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );

function sqhse_news_featimgmove( $content ) {
    if( get_post_type() == 'post' ) {
        $content = preg_replace( "/<\/p>/", "
" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "

", $content, 1 );
        return $content;
    }
    return $content;
}

A: The filter you're using, the_content, as you've discovered will apply to all content areas. You need to add a conditional to check the post type you're on and adjust accordingly. My suggestion would be to use is_singular().
add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );

function sqhse_news_featimgmove( $content ) {
    if ( is_singular( 'post' ) ) {
        $content = preg_replace( "/<\/p>/", "
" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "

", $content, 1 );
    }

    return $content;
}

When dealing with filters make sure you always return a value. If you have a conditional for example keep the return statement outside of it.
https://codex.wordpress.org/Function_Reference/is_singular


text:
Q: How can I fix this error_ Failed to process: /Users/cheese/Desktop/android1/Myapp/app/build/intermediates/javac/debug/classes When I build my app.. That error occurred..How can I fix it?
`
* What went wrong:
Execution failed for task ':app:dexBuilderDebug'.
> There were multiple failures while executing work items
   > A failure occurred while executing com.android.build.gradle.internal.dexing.DexWorkAction
      > Failed to process: /Users/Desktop/android1/Myapp/app/build/intermediates/javac/debug/classes
   > A failure occurred while executing com.android.build.gradle.internal.dexing.DexWorkAction
      > Failed to process: /Users/Desktop/android1/Myapp/app/build/intermediates/javac/debug/classes

* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:dexBuilderDebug'.
    at
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.
    at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:140)
    at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:117)
    at com.android.build.gradle.internal.dexing.DexWorkActionKt.process(DexWorkAction.kt:175)
    ... 34 more
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete, origin: /Users/Desktop/android1/Myapp/app/build/intermediates/javac/debug/classes/kr/myapp/HomeActivity$3 2.class

BUILD FAILED in 11s

`
I tried!!!!!!!!!But it doesn't work ㅠㅠ


text:
Q: Text being cut off by second page I'm new to creating a band app, and I've created a basic 2 page app.
Both pages are "MSBand_ScrollingText" but on the first page the text is being cut off by the second page? Is there a way to stop this from happening?
I've attached this image to show you the problem:

A: The clipping of the text is a firmware issue that's being investigated.
There's nothing that can be done in your app to stop it.


text:
Q: Installing mod_wsgi in Apache2.4 on Windows 7 x64 My current setup Python3.5 x64, Apache2.4
I am learning Python and django. I want to run django app using Apache.
I download mod_wsgi binary from here http://www.lfd.uci.edu/~gohlke/pythonlibs/
I picked up this one: mod_wsgi-4.4.23+ap24vc14-cp35-cp35m-win_amd64.whl
I got mod_wsgi.so after extract. I added that file in apache modules directory.
After that I added following code in httpd.conf file
    LoadModule wsgi_module modules/mod_wsgi.so

    WSGIScriptAlias / C:/djangoprojects/mysite/mysite/wsgi.py
    WSGIPythonPath /C:/djangoprojects/mysite

    <Directory C:/djangoprojects/mysite/mysite>
    <Files wsgi.py>
    Require all granted
    </Files>
    </Directory>

But I am getting following error.
     httpd.exe: Syntax error on line 183 of C:/Apache24/conf/httpd.conf: Cannot load modules/mod_wsgi.so into server: The specified module could not be found.

I am not able to load mod_wsgi module. Need help.

A: I checked my installation and found that python for all was missing.
I reinstall python3.5 with custom configurations  and enable python for all option.


text:
Q: unable to install ui-grid-auto-fit-columns for Angularjs 1.6 project I am working with Angularjs 1.6 and ui-grid 4.4.2 and I hit a snag. I need my grid column widths to expand to the widest content in the column. I found an NPM Package that does this but I am unable to install it.
When I include the package in my angular module I get the following error:
Unhandled exception at line 5014, column 9 in http://localhost:29236/Scripts/angular.js
0x800a139e - JavaScript runtime error: [$injector:modulerr] Failed to instantiate module CRNApp due to:
Error: [$injector:modulerr] Failed to instantiate module ui.grid.autoFitColumns due to:

Error: [$injector:nomod] Module 'ui.grid.autoFitColumns' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Part of my Angular definition:
(function () {
    'use strict';

    angular.module('CRNApp', ['ui.bootstrap', 'ui.grid', 'ui.grid.autoFitColumns', 'ui.grid.autoResize', 'ui.grid.emptyBaseLayer', 'ui.grid.selection', 'toaster','ngAnimate']);

    MainController.$inject = ['$scope', '$http', '$uibModal', '$log', 'uiGridConstants', '$rootScope','toaster'];

    angular.module('CRNApp')
    .controller('MainController', MainController);

The installation instructions are at https://github.com/Den-dp/ui-grid-auto-fit-columns
The install command is: npm install ui-grid-auto-fit-columns -S
After I typed int he NPM install command I saw a new set of folders appear:

I am inexperienced with Angularjs and NPM so I am not sure what I am doing wrong. Any ideas?

A: I forgot to import the .js file in my bundleconfig.cs file.


text:
Q: NullReferenceException when dragging control onto Form This problem started occurring yesterday: I am trying to drag a button onto a form in a Windows Forms application, but when I do this I get a NullReferenceException (see screenshot  here)
When I don't use drag & drop, it works fine.
I'm using Windows 10 1803 together with Visual Studio Community Edition 2017 (version 15.9.14)
Any ideas on what may have caused this? Thanks in advance!

A: Turns out it has nothing to do with Visual Studio or Windows. My second monitor is attached to my laptop with a VGA cable, and it turns out, when I upscale the monitor, the designer in Visual Studio acts weird.
I noticed it because dragging controls worked when visual studio was displayed on my laptop screen, but not on my VGA monitor.
Turning the scale back to 100% (right mouse click on desktop > display settings) solved the issue for me.
Hope this helps someone.

A: Have you tried deleting Visual Studio AppData folder? It is usually at %LOCALAPPDATA%\Local\Microsoft\VisualStudio.
You can also try out Visual Studio Community edition 2019. Maybe in new version this problem won't occur.


text:
Q: How to normalise a Union Type (T | Option[T])? I have the following case class:
case class Example[T](
    obj: Option[T] | T = None,
)

This allows me to construct it like Example(myObject) instead of Example(Some(myObject)).
To work with obj I need to normalise it to Option[T]:
  lazy val maybeIn = obj match
    case o: Option[T] => o
    case o: T => Some(o)

the type test for Option[T] cannot be checked at runtime
I tried with TypeTest but I got also warnings - or the solutions I found look really complicated - see https://stackoverflow.com/a/69608091/2750966
Is there a better way to achieve this pattern in Scala 3?

A: I don't know about Scala3. But you could simply do this:
case class Example[T](v: Option[T] = None)

object Example {
 def apply[T](t: T): Example[T] = Example(Some(t))
}

One could also go for implicit conversion, regarding the specific use case of the OP:
import scala.language.implicitConversions

case class Optable[Out](value: Option[Out])

object Optable {
  implicit def fromOpt[T](o: Option[T]): Optable[T] = Optable(o)
  implicit def fromValue[T](v: T): Optable[T] = Optable(Some(v))
}

case class SomeOpts(i: Option[Int], s: Option[String])

object SomeOpts {
  def apply(i: Optable[Int], s: Optable[String]): SomeOpts = SomeOpts(i.value, s.value)
}

println(SomeOpts(15, Some("foo")))

A: We have a specialized Option-like type for this purpose: OptArg (in Scala 2 but should be easily portable to 3)
import com.avsystem.commons._

def gimmeLotsOfParams(
  intParam: OptArg[Int] = OptArg.Empty,
  strParam: OptArg[String] = OptArg.Empty
): Unit = ???

gimmeLotsOfParams(42)
gimmeLotsOfParams(strParam = "foo")

It relies on an implicit conversion so you have to be a little careful with it, i.e. don't use it as a drop-in replacement for Option.
The implementation of OptArg is simple enough that if you don't want external dependencies then you can probably just copy it into your project or some kind of "commons" library.

A: EDIT: the following answer is incorrect. As of Scala 3.1, flow analysis is only able to check for nullability. More information is available on the Scala book.

I think that the already given answer is probably better suited for the use case you proposed (exposing an API can can take a simple value and normalize it to an Option).
However, the question in the title is still interesting and I think it makes sense to address it.
What you are observing is a consequence of type parameters being erased at runtime, i.e. they only exist during compilation, while matching happens at runtime, once those have been erased.
However, the Scala compiler is able to perform flow analysis for union types. Intuitively I'd say there's probably a way to make it work in pattern matching (as you did), but you can make it work for sure using an if and isInstanceOf (not as clean, I agree):
case class Example[T](
    obj: Option[T] | T = None
) {
  lazy val maybeIn =
    if (obj.isInstanceOf[Option[_]]) {
      obj
    } else {
      Some(obj)
    }
}

You can play around with this code here on Scastie.
Here is the announcement from 2019 when flow analysis was added to the compiler.


text:
Q: XMLHttpRequest is not working on chrome version 23 & above I have created the chrome extension & added the crx file into chrome extension section.This .crx file was created using javascript & manifest.json files.From java script,i am giving XMLHttpRequest to my java servlet  after every 10 sec time interval.I have tested this on chrome version 18 &19,its working properly but when i am trying to add .crx file in chrome version 23 then XMLHttpRequest not working.
 The javaScript code is :-
try{

    var xmlhttp;
    if (window.XMLHttpRequest){
      xmlhttp=new XMLHttpRequest();
      }
    else{
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200){
       /* document.getElementById("myDiv").innerHTML=xmlhttp.responseText;*/
       // alert(xmlhttp.responseText);
          if(xmlhttp.responseText!="?"){
              chrome.browserAction.setBadgeText({text : xmlhttp.responseText});
              chrome.browserAction.setIcon({path:"images/IconGreen.png"});
              chrome.browserAction.setBadgeBackgroundColor({color : [ 208, 0, 24, 255 ]});
          }
          else{
              chrome.browserAction.setBadgeText({text :"?"});
              chrome.browserAction.setIcon({path:"images/IconGrey.png"});
              chrome.browserAction.setBadgeBackgroundColor( {color:[190, 190, 190, 230]});
          }
        }
      };
    xmlhttp.open("GET"," http://127.0.0.1:8888 /engile/realTimeUpdateCountServlet",true);
    xmlhttp.send();

} catch (err) {
    alert(err.message);

}

& manifest.json is
{

  "name": "A Chrome Extension",
  "version": "4.4.0",
  "background": { "scripts": ["background.js"] },
  "permissions": [
     "tabs",
    "webNavigation",
    "http://*/*",
    "chrome.action"
  ],
  "web_accessible_resources": [
    "278CB17EDF811DAFF4CBD7790CBE8C06.cache.html"
  ],
  "browser_action": {
    "name": "Make this page red",
    "default_icon": "images/IconGrey.png"

  },
  "manifest_version": 2
}

Please give me any suggestion on it.

A: Problems in you code

*

*"browser_action": { "name": "Make this page red", there is no argument called name, it has to be "default_title"

*"permissions": ["tabs","webNavigation", "http://*/*", "chrome.action"], there is no permission called chrome.action add a relevant permission from documentation.


text:
Q: Print Magento Invoice Data To TCPDF File I have followed the instruction in the link ->
TCPDF With Magento, now I want to call the TCPDF library from Invoice.php file at app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php because I want to print the invoice data to a TCPDF invoice.
How to use the functions to get the invoice data and print it to a TCPDF file?
Here are the functions which prints invoice data to a PDF file generated by Zend framework.
<?php

class Mage_Sales_Model_Order_Pdf_Invoice extends Mage_Sales_Model_Order_Pdf_Abstract
{
    /**
     * Draw header for item table
     *
     * @param Zend_Pdf_Page $page
     * @return void
     */
    protected function _drawHeader(Zend_Pdf_Page $page)
    {
        /* Add table head */
        $this->_setFontRegular($page, 10);
        $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
        $page->setLineWidth(0.5);
        $page->drawRectangle(25, $this->y, 570, $this->y -15);
        $this->y -= 10;
        $page->setFillColor(new Zend_Pdf_Color_RGB(0, 0, 0));

        //columns headers
        $lines[0][] = array(
            'text' => Mage::helper('sales')->__('Products'),
            'feed' => 35
        );

        $lines[0][] = array(
            'text'  => Mage::helper('sales')->__('SKU'),
            'feed'  => 290,
            'align' => 'right'
        );

        $lines[0][] = array(
            'text'  => Mage::helper('sales')->__('Qty'),
            'feed'  => 435,
            'align' => 'right'
        );

        $lines[0][] = array(
            'text'  => Mage::helper('sales')->__('Price'),
            'feed'  => 360,
            'align' => 'right'
        );

        $lines[0][] = array(
            'text'  => Mage::helper('sales')->__('Tax'),
            'feed'  => 495,
            'align' => 'right'
        );

        $lines[0][] = array(
            'text'  => Mage::helper('sales')->__('Subtotal'),
            'feed'  => 565,
            'align' => 'right'
        );

        $lineBlock = array(
            'lines'  => $lines,
            'height' => 5
        );

        $this->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
        $this->y -= 20;
    }

    /**
     * Return PDF document
     *
     * @param  array $invoices
     * @return Zend_Pdf
     */
    public function getPdf($invoices = array())
    {
        $this->_beforeGetPdf();
        $this->_initRenderer('invoice');

        $pdf = new Zend_Pdf();
        $this->_setPdf($pdf);
        $style = new Zend_Pdf_Style();
        $this->_setFontBold($style, 10);

        foreach ($invoices as $invoice) {
            if ($invoice->getStoreId()) {
                Mage::app()->getLocale()->emulate($invoice->getStoreId());
                Mage::app()->setCurrentStore($invoice->getStoreId());
            }
            $page  = $this->newPage();
            $order = $invoice->getOrder();
            /* Add image */
            $this->insertLogo($page, $invoice->getStore());
            /* Add address */
            $this->insertAddress($page, $invoice->getStore());
            /* Add head */
            $this->insertOrder(
                $page,
                $order,
                Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID, $order->getStoreId())
            );
            /* Add document text and number */
            $this->insertDocumentNumber(
                $page,
                Mage::helper('sales')->__('Invoice # ') . $invoice->getIncrementId()
            );
            /* Add table */
            $this->_drawHeader($page);
            /* Add body */
            foreach ($invoice->getAllItems() as $item){
                if ($item->getOrderItem()->getParentItem()) {
                    continue;
                }
                /* Draw item */
                $this->_drawItem($item, $page, $order);
                $page = end($pdf->pages);
            }
            /* Add totals */
            $this->insertTotals($page, $invoice);
            if ($invoice->getStoreId()) {
                Mage::app()->getLocale()->revert();
            }
        }
        $this->_afterGetPdf();
        return $pdf;
    }

    /**
     * Create new page and assign to PDF object
     *
     * @param  array $settings
     * @return Zend_Pdf_Page
     */
    public function newPage(array $settings = array())
    {
        /* Add new table head */
        $page = $this->_getPdf()->newPage(Zend_Pdf_Page::SIZE_A4);
        $this->_getPdf()->pages[] = $page;
        $this->y = 800;
        if (!empty($settings['table_header'])) {
            $this->_drawHeader($page);
        }
        return $page;
    }
}

A: In order to completely avoid Zend_Pdf from the playground, you need to rewrite Mage_Sales_Model_Order_Pdf_Invoice::getPdf() method. Your custom getPdf() should somewhat look like this:
<?php
class [Namespace]_[Module]_Model_Order_Pdf_Invoice extends Mage_Sales_Model_Order_Pdf_Invoice
{
    public function getPdf($invoices = array())
    {
        foreach ($invoices as $invoice) {

            //get invoice order
            $order = $invoice->getOrder();

            //set registry current order as invoice order.
            $currentOrder = Mage::registry('current_order');
            if (!$currentOrder) {
                Mage::register('current_order', $order);
            }
            if ($currentOrder->getId() != $order->getId()) {
                Mage::unregister('current_order');
                Mage::register('current_order', $order);
            }

            //your tcpdf stuffs comes here
            $tcpdf = new TCPDF_TCPDF();

            //using magneto's default invoice print html file for preparing invoice content
            $request = Mage::app()->getRequest();
            $html = $request->getLayout()
                ->createBlock('sales/order_print_invoice', 'sales.order.pdf.invoice')
                ->setTemplate('sales/order/print/invoice.phtml')
                ->toHtml();

            $tcpdf->AddPage();

            $tcpdf->writeHTML($html, true, false, true, false, '');

            $tcpdf->lastPage();

            return $tcpdf->Output('sales_order_invoice_'.time().'.pdf', 'I');
        }

    }
}

I don't have previous experience with tcpdf. But from the above code, you will get the idea. getPdf() is the function which is responsible for using zend_pdf library to generate invoice pdf. By rewriting this method, you can use tcpdf in order to generate invoice pdf.
Here what we are doing is, using Magento's default invoice print phtml file to generate invoice pdf content. This invoice phtml file uses the class Mage_Sales_Block_Order_Print_Invoice class instance and it requires Mage::registry('current_order') to be set in order to render it.
Hope you can you use this as a starting point.


text:
Q: Accessing SQL Server 2005 with PYODBC I build an application to do some number crunching with wxpython. I have to access the data from SQL Server 2005 for my purpose. I am using PYODBC and when I asked my server adminstrator, he provided me the server name and unique data ID for the database.
I don't see the syntax to access database with unique data ID in PYODBC as something like:
Conn=pyodbc.connect('DRIVER={SQL Server};SERVER=USMDUBEDAS215;DATABASE=spam;UID=usr,PWD=pwd')

when you have a database and table name. How can you access the database with server-name and Data_ID?
I don't know from where to start.

A: Try to look at the following link: http://code.google.com/p/pyodbc/wiki/GettingStarted
Link to connect method: http://code.google.com/p/pyodbc/wiki/Module#connect
Using the link above you can find the following sample code:
#Make a direct connection to a database and create a cursor.

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
print 'name:', row[1]          # access by column index
print 'name:', row.user_name   # or access by name

I have tried it in our env and all works as expected


text:
Q: Can certifying an application protect it from viruses that inject itself into the program? I'm having troubles of Windows Defender telling me that I have viruses in my EXEs.
It's a ramnit type, the one that would hide itself in executables and html files.
Could certifying the app using the tool provided in Visual Studio installation prevent the virus from slipping in?
I've seen my installers in storage that is downloaded from various sources completely intact.


text:
Q: Is there a way to create Access form dynamically? Problem: I have a couple of views (Access ADP with SQL Server). I want to create a basic continuous form for those views, one form for each view. These views contain totally differences column name depend on the module they are in.
Say one view may be about Student Score with 10 columns. Other may be about Student Skills in the past with 20 columns. However, there are one thing in common for these forms is a StudentID column, which allows user to double-click. By doing so, it call Student Form.
Right now, I manually create these continuous forms for each view repeatedly. I am thinking to myself it should be good if I can create it dynamically. For example, if we change or add a new view. I have no need to change column for these forms because it generates on the fly each time it is called.
I am not sure that it is possible to do that in Access ADP.

A: You seem to be looking for Application.CreateForm Method (Access)
To quote:
This example creates a new form in the Northwind sample database based on the Customers form, and sets its RecordSource property to the Customers table. Run this code from the Northwind sample database.
Sub NewForm()
    Dim frm As Form

    ' Create form based on Customers form.
    Set frm = CreateForm( , "Customers")
    DoCmd.Restore
    ' Set RecordSource property to Customers table.
    frm.RecordSource = "Customers"
End Sub


text:
Q: Trivial questions about measures Assume $ (X,\mathcal{P}(X),\mu)$ is a measure space.
and assume $X$ is not countable.

*

*Do all singeltons must have the same measure?

*Do all finite subsets of $X$ must have finite measure?

*Do sets with the same cardinality have the same measure ?

Thank in advance.

A: Consider $X=[0,1]$ and the dirac measure $\mu = \sum_{x \in [0,1]\cap \mathbb{Q}} \delta_x$ on all elements in $[0,1] \cap \mathbb{Q}$. Then all three statements do not hold. So the answer is no to all three statements.


text:
Q: Sort a hash of arrays by one of the arrays in ruby In Ruby, is there a short and sweet way to sort this hash of arrays by score descending:
scored = {:id=>[1, 2, 3], :score=>[8.3, 5, 10]}

so it looks like this?:
scored = {:id=>[3, 1, 2], :score=>[10, 8.3, 5]}

I couldnt find an example where I can sort arrays within a hash like this? I could do this with some nasty code but I feel like there should be a 1 or 2 liner that does it?

A: You could use sort_by
scored = {:id=>[1, 2, 3], :score=>[8.3, 5, 10]}

scored.tap do |s|
  s[:id] = s[:id].sort_by.with_index{ |a, i| -s[:score][i] }
  s[:score] = s[:score].sort_by{ |a| -a }
end
#=> {:id=>[3, 1, 2], :score=>[10, 8.3, 5]}

A: order = scored[:score].each_with_index.sort_by(&:first).map(&:last).reverse
  #=> [2,0,1]
scored.update(scored) { |_,a| a.values_at *order }
  #=> {:id=>[3, 1, 2], :score=>[10, 8.3, 5]}

If scored is to not to be mutated, replace update with merge.
Some points:

*

*Computing order makes it easy for the reader to understand what's going on.

*The second line uses the form of Hash#merge that employs a block to determine the values of keys that are present in both hashes being merged (which here is all keys). This is a convenient way to modify hash values (generally), in part because the new hash is returned.

*I sorted then reversed, rather than sorted by negated values, to make the method more rubust. (That is, the elements of the arrays that are the values can be from any class that implements <=>).

*With Ruby 2.2+, another way to sort an array arr in descending order is to use Enumerable#max_by: arr.max_by(arr.size).to_a.

The first line could be replaced with:
arr = scored[:score]
order = arr.each_index.sort_by { |i| arr[i] }.reverse
  #=> [2,0,1]

A: Here is one possible solution. It has an intermediate step, where it utilizes a zipped version of the scores object, but produces the correct output:
s = scored.values.inject(&:zip).sort_by(&:last).reverse
#=> [[3, 10], [1, 8.3], [2, 5]]

result = { id: s.map(&:first), score: s.map(&:last) }
#=> { :id => [3, 1, 2], :score => [10, 8.3, 5] }


text:
Q: Conditions for changing the order of summation in $ \sum_{i=1}^\infty \sum_{j=1}^\infty a_{ij}$ I am reading a lecture note here and it says the following:

If we have a doubly indexed family of nonnegative numbers $a_{ij}, \
 i, \ j \in \mathbb{N}$ and if either (i) the numbers are nonnegative,
  or (ii) the sum $\sum_{(i,j)} a_{ij}$ is absolutely convergent, then
$$ \sum_{i=1}^\infty \sum_{j=1}^\infty a_{ij} =  \sum_{j=1}^\infty
 \sum_{i=1}^\infty a_{ij} = \sum_{(i,j) \in \mathbb{N}^2} a_{ij}$$
More important, we stress that the first equality need not hold in the
  absence of conditions (i) and (ii).

I am not sure why the last comment holds regarding the first equality where we change the order of the summation. Is there any well known counter-example?


text:
Q: How to start new activity with TabGroup Following code shows when I log out then another activity log in in called.
    public void logoutUser(){
    // Clearing all data from Shared Preferences
    editor.clear();
    editor.commit();

    // After logout redirect user to Loing Activity
    Intent i = new Intent(_context, Login.class);
    TabGroupActivity parentActivity = (TabGroupActivity) _context;
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    //_context.startActivity(i);
   // parentActivity.startChildActivity("Login", i);

}

The last two lines of code are commented as I have used both of them but force closes the app. Following is the logcat output.
01-08 15:13:56.219: D/AndroidRuntime(877): Shutting down VM
01-08 15:13:56.219: W/dalvikvm(877): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-08 15:13:56.249: E/AndroidRuntime(877): FATAL EXCEPTION: main
01-08 15:13:56.249: E/AndroidRuntime(877): java.lang.NullPointerException
01-08 15:13:56.249: E/AndroidRuntime(877):  at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
01-08 15:13:56.249: E/AndroidRuntime(877):  at com.fabletechnologies.utils.SessionManagement.logoutUser(SessionManagement.java:102)
01-08 15:13:56.249: E/AndroidRuntime(877):  at com.fabletechnologies.smartaway.DashboardActivity$1.onClick(DashboardActivity.java:54)
01-08 15:13:56.249: E/AndroidRuntime(877):  at android.view.View.performClick(View.java:2408)
01-08 15:13:56.249: E/AndroidRuntime(877):  at android.view.View$PerformClick.run(View.java:8816)
01-08 15:13:56.249: E/AndroidRuntime(877):  at android.os.Handler.handleCallback(Handler.java:587)
01-08 15:13:56.249: E/AndroidRuntime(877):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-08 15:13:56.249: E/AndroidRuntime(877):  at android.os.Looper.loop(Looper.java:123)
 1-08 15:13:56.249: E/AndroidRuntime(877):  at android.app.ActivityThread.main(ActivityThread.java:4627)
01-08 15:13:56.249: E/AndroidRuntime(877):  at java.lang.reflect.Method.invokeNative(Native Method)
01-08 15:13:56.249: E/AndroidRuntime(877):  at java.lang.reflect.Method.invoke(Method.java:521)
01-08 15:13:56.249: E/AndroidRuntime(877):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-08 15:13:56.249: E/AndroidRuntime(877):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-08 15:13:56.249: E/AndroidRuntime(877):  at dalvik.system.NativeStart.main(Native Method)

Complete Code is here.
    public class SessionManagement extends Activity{
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE=0;

// Sharedpref file name
private static final String PREF_NAME = "LoginLogoutPref";

// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)
public static final String KEY_NAME = "fullname";

// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";

// Constructor
public SessionManagement(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

/**
 * Create login session
 * */
public void createLoginSession(String fullname, String email){
    // Storing login value as TRUE
    editor.putBoolean(IS_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_NAME, fullname);

    // Storing email in pref
    editor.putString(KEY_EMAIL, email);

    // commit changes
    editor.commit();
}

/**
 * Check login method wil check user login status
 * If false it will redirect user to login page
 * Else won't do anything
 * */
public void checkLogin(){
    // Check login status
    if(!this.isLoggedIn()){
        // user is not logged in redirect him to Login Activity
        Intent i = new Intent(_context, Login.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }

}

/**
 * Get stored session data
 * */
public HashMap<String, String> getUserDetails(){
    HashMap<String, String> user = new HashMap<String, String>();
    // user name
    user.put(KEY_NAME, pref.getString(KEY_NAME, null));

    // user email id
    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

    // return user
    return user;
}

/**
 * Clear session details
 * */
public void logoutUser(){
    // Clearing all data from Shared Preferences
    editor.clear();
    editor.commit();

    // After logout redirect user to Loing Activity
    Intent i = new Intent(_context, Login.class);
    TabGroupActivity parentActivity = (TabGroupActivity) getParent();
  //  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    //_context.startActivity(i);
    parentActivity.startChildActivity("Login", i);

}

/**
 * Quick check for login
 * **/
// Get Login State
public boolean isLoggedIn(){
    return pref.getBoolean(IS_LOGIN, false);
}

}
Please help me how to start Login Activity
*Thanks in advance*

A: TabHost tabHost;
TabSpec spec1;
TabSpec spec2;
TabSpec spec3;

        tabHost=getTabHost();

        spec1=tabHost.newTabSpec("Tab 1");
        spec1.setIndicator("Tab !",null);
        Intent in1=new Intent(this,Activity1.class);
        in1.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        spec1.setContent(in1);

        spec2=tabHost.newTabSpec("Tab 2");
        spec2.setIndicator("Tab 2",null);
        Intent in2=new Intent(this,Activity2.class);
        in2.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        in2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        spec2.setContent(in2);

        spec3=tabHost.newTabSpec("Tab3");
        spec3.setIndicator("Tab3",null);
        Intent in3=new Intent(this,Activity3.class);
        in3.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        in3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        spec3.setContent(in3);

        tabHost.addTab(spec1);
        tabHost.addTab(spec2);
        tabHost.addTab(spec3);

Try Using Tab Activity Like this


text:
Q: Query XML Event Log Data using SQL <Events>
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="ASP.NET 4.0.30319.0" />
<EventID Qualifiers="32768">1309</EventID>
<Level>3</Level>
<Task>3</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2014-10-10T01:37:16.000000000Z" />
<EventRecordID>14870</EventRecordID>
<Channel>Application</Channel>
<ComputerXXXXX</Computer>
<Security />
</System>
<EventData>
<Data>3005</Data>
<Data>An unhandled exception has occurred.</Data>
<Data>10/10/2014 02:37:16</Data>
<Data>10/10/2014 01:37:16</Data>
<Data>f68c3bc5c6594c02bf13a5a99a0627a3</Data>
<Data>8138</Data>
<Data>15</Data>
<Data>0</Data>
<Data>/LM/W3SVC/3/ROOT-1-XXXXXX</Data>
<Data>Full</Data>
<Data>/</Data>
<Data>C:\Web\XXXXX\</Data>
<Data>XXXXX</Data>
<Data />
<Data>31428</Data>
<Data>w3wp.exe</Data>
<Data>Domain\User</Data>
<Data>HttpException</Data>
<Data>Exception of type 'System.Web.HttpException' was thrown.
at System.Web.Handlers.TraceHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at etc
</Data>
<Data>http://XXX/trace.axd</Data>
<Data>/trace.axd</Data>
<Data>XXX.XXX.XX.XX</Data>
<Data />
<Data>False</Data>
<Data />
<Data>XXXXX</Data>
<Data>57</Data>
<Data>XXXXXX</Data>
<Data>False</Data>
<Data>   at System.Web.Handlers.TraceHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context)  at etc

</Data>
 </EventData>
</Event>

...
etc
</Events>

I have saved some Windows Event logs as XML, I have inserted these into SQL using the following method:
CREATE TABLE XmlSourceTable
(
      RecordId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
      XmlData XML NOT NULL
)
GO

INSERT INTO XmlSourceTable(XmlData)
SELECT
    *
FROM OPENROWSET (BULK 'C:\xmlfile.xml', SINGLE_CLOB)
AS XMLData

I am attempting to query the XML using the following method but cannot get it to work at all.
SELECT
      WEvent.query('System') as SystemFragmentXML
FROM
      XmlSourceTable CROSS APPLY
      XmlData.nodes('/Events/Event') AS WindowsEvent(WEvent)

Can anyone help me out?

A: Your XML has default namespace declared at <Event> node level. So basically that node, and all of it's descendants are in the same namespace.
You need to register a prefix that point to the default namespace, and use that prefix in the XPath, for example :
;WITH XMLNAMESPACES('http://schemas.microsoft.com/win/2004/08/events/event' as d)
SELECT
      WEvent.query('d:System') as SystemFragmentXML
FROM
      XmlSourceTable CROSS APPLY
      XmlData.nodes('/Events/d:Event') AS WindowsEvent(WEvent)

A: First of all, your XML is broken - you have several XML elements (like <Computer>) that aren't properly closed and you're missing a closing </Events>.
Once I had fixed these issues, then the next problem is that you're blatantly ignoring the XML namespace that's defined on the <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> node.
Try this query (using native XQuery support instead of legacy OPENROWSET):
;WITH XMLNAMESPACES ('http://schemas.microsoft.com/win/2004/08/events/event' AS we)
SELECT
      XC.query('we:System') as SystemFragmentXML
FROM
      dbo.XmlSourceTable
CROSS APPLY
      XmlData.nodes('/Events/we:Event') AS XT(XC)


text:
Q: How to mock method to return value X at first call, and Y on rest calls? How to mock method to return value X at first call, and Y on rest calls?
Below solution works, but I don't want to write $Y so many times:
$o->expects($this->any())
      ->method('foo')
      ->will($this->onConsecutiveCalls($X, $Y, $Y, $Y, $Y, $Y));

Below solution will return $Y everytime:
$o->expects($this->any())
    ->method('foo')
    ->will($this->returnValue($Y));
$o->expects($this->at(0))
    ->method('foo')
    ->will($this->returnValue($X));

A: You can do this by using an anonymous function within PHPUnit's returnCallback function instead of onConsecutiveCalls. However, this is more lines of code than just simply typing $Y for each return value, so I'd only use the below version if every call to doSomething after the first call needs to return the same value any number of times:
class Example
{
    function doSomething() { }
}

// within your test class
public function testConsecutiveCallbacks()
{
    $counter = 0;
    $stub = $this->createMock(Example::class);
    $stub
        ->method('doSomething')
        ->will($this->returnCallback(function () use (&$counter) {
            $counter++;
            if ($counter == 1) {
                return 'value for x';
            }
            return 'value for y';
        }));
    $this->assertEquals('value for x', $stub->doSomething());
    $this->assertEquals('value for y', $stub->doSomething());
    $this->assertEquals('value for y', $stub->doSomething());
    $this->assertEquals('value for y', $stub->doSomething());
}