Complex Differentiability of $f(x+iy)=\frac{(1+i)x^3-(1-i)y^3}{x^2+y^2}$

Question: I am tasked with showing that $$f(x+iy)=\frac{(1+i)x^3-(1-i)y^3}{x^2+y^2}\text{ if }x+iy\neq0;\quad f(0)=0$$
satisfies the Cauchy-Riemann  equations at $0$, despite not being differentiable at $0$. We have $$u(x,y)=\frac{x^3-y^3}{x^2+y^2},\quad v(x,y)=\frac{x^3+y^3}{x^2-y^2}$$
And evaluating $u_x,v_x,u_y,v_y$, they don't satisfy the equations... which is fine, because they don't have to work everywhere, just zero... however they're not even defined at zero!
In a hint we are told to consider $x\rightarrow0$ along $y=x$ and $y=0$, but making these substitutions of $y$ into the partial derivatives yields constants that still don't satisfy $u_x=v_y$ and $u_y=-v_x$... So I'm stuck as to how to procede, or even as to whether I've already done something wrong...
Answer: $u_x(0,0)=\lim_{h \to 0} \frac {u(h,0)-u(0,0)} h=\lim_{h \to 0} 1=1$. Compute the other four partial derivatives at the origin and verify that C-R equations are satisfied.
Now $\frac {f(x+ix)-f(0)} {x+ix}\to \frac i {1+i} \neq 1$ whereas the limit along $y=0$ is $1$. Hence $f$ is not differentiable at $0$.
Comment: Thanks for your answer - It helps a lot, but I don't see how you evaluate $u(0,0)$? - or is it just $0$ since $f(0)=0$
Comment: @Gentleman_Narwhal it is given that $f(0)=0$. So $u(0,0)=\Re f(0)=0$.
Comment: So I reevaluated $\frac{f(x+ix)-f(0)}{x+ix}$ but I get $2(i+1)$
Comment: @Gentleman_Narwhal Sorry, there was  a mistake. Please read my answer now.
Comment: Thanks, I suspected that's what was required


WebRequest doomed to failure when starting from parallel thread

Question: Consider following console application:
public static void Request(string url)
{
  ThreadPool.QueueUserWorkItem((state) =>
  {
    try
    {
      var request = WebRequest.Create(url);
      request.Timeout = 5000;
      request.GetResponse();
    }
    catch (Exception e)
    {
      Console.Out.WriteLine(e);
    }
    Console.Out.WriteLine(url);
  });
}

static void Main(string[] args)
{
  Request("http://google.com?q=a");
  Request("http://google.com?q=b");
  Request("http://google.com?q=c");
  Request("http://google.com?q=d");
  Thread.Sleep(20000);

  Console.In.ReadLine();
}

Output will finish for 2 urls. But for the rest it will throw "The operation has timed out".
I know that there is a limit of parallel connections by default set to two. If I increase it to three then three will finish up.
I.E:
ServicePointManager.DefaultConnectionLimit = 3;

But my question is - why the rest of them doesn't finish up, but throws the operation has timed out instead ?
Answer: Because the timeout includes the time the process was waiting in line for a connection to become available.
The timeout to represents "I want to wait at most 5000ms after I call GetResponse() to get my response" not "I want to wait at most an additional 5000ms after GetResponse() has waited for a unlimited amount of time to get its turn in the queue."
Now, you wonder, "but the query is so quick, it should not take more than 5000ms to complete!". The problem comes from the fact you did not close the response you got from GetResponse, from the MSDN:

You must call the Close method to close the stream and release the
  connection. Failure to do so may cause your application to run out of
  connections.

Calling Dispose() implicitly calls Close(), so if you update your code to dispose of your response then the used connection will become freed and one of the waiting requests will then be able to start up.
public static void Request(string url)
{
  ThreadPool.QueueUserWorkItem((state) =>
  {
    try
    {
      var request = WebRequest.Create(url);
      request.Timeout = 5000;
      using(var response = request.GetResponse())
      {
          Console.Out.WriteLine("Response - " + url);
      }
    }
    catch (Exception e)
    {
      Console.Out.WriteLine(e);
    }
    Console.Out.WriteLine("Method End - " + url);
  });
}

static void Main(string[] args)
{
  Request("http://google.com?q=a");
  Request("http://google.com?q=b");
  Request("http://google.com?q=c");
  Request("http://google.com?q=d");
  Thread.Sleep(20000);

  Console.In.ReadLine();
}

Comment: I totally forgot Response is IDisposable :)


How does rounding work when converting from integers to IEEE 754 floating point numbers?

Question: There are many values that can be represented precisely as a 64-bit long but not as a 64-bit double. (A trivial example: 262-1.)  Is the rounding away from zero, towards zero, or to nearest possible value given the spacing?
Comment: `2^62` can be represented exactly as a double.
Comment: Yeah, a simple example of a long not precisely representable as a double is 2⁶²-1.
Comment: The rounding mode can be set with the `fesetround()` function.
Answer: Floating point semantics matching IEC 60559 (IEEE 754) are defined in Annex F of the standard, which technically is optional, but without which C's floating point is so underspecified as to be meaningless. Assuming Annex F, which specifies (F.3 ¶1):

The conversions from integer to floating types provide the IEC 60559 conversions from integer to floating point.

Rounding takes place according to the currently active rounding mode. Rounding mode can be set by fesetround from fenv.h, but many compilers do not properly support fenv functionality and erroneously allow operations to be reordered across mode changes, so in practice you should probably leave it at the default (nearest/to-even).
In the absence of Annex F, conversion from integers is one of the few floating point operations that C specifies with any concreteness (22.214.171.124 ¶2):

If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner.

Annex F constrains the implementation-defined choice to agree with IEC 60559. Pretty much all real-world C implementations target Annex F, even if they don't conform to it 100%. Thus my own answers, and answers by a number of users on this site, generally assume that questions about C and floating point are treating Annex F as baseline.
Comment: Common C implementations follow the floating-point rounding mode and have that default to round-to-nearest, ties-to-even, but the C standard does not seem to require either of these, per [chqrlie's answer](https://stackoverflow.com/a/63679430/298225).
Comment: Annex F does. Without Annex F, floating point semantics are so underspecified they can literally be random.
Comment: Annex F is not obligatory. Wishing the behavior to be well specified does not make it so. chqrlie's answer is correct. This one is incorrect.
Comment: Many of us consider Annex F a core part of the language, as (1) it's impossible to do anything meaningful with floating point without at least a large subset of it, and (2) pretty much all real-world implementations target it, even if they don't conform 100%.
Comment: Re "Many of us consider": Wishing does not make it so. It is not an obligatory part of the language. This answer is wrong. You could at least qualify the claim that rounding takes place as depending on Annex F. Then, at least, the answer would contain correct statements, although it would still be incomplete, as it would not answer OP's unqualified question.
Comment: @EricPostpischil: Updated.
Comment: @EricPostpischil: Just noticed too that the question is tagged `ieee-754`...
Answer: The behavior seems to be implementation defined. Here is the relevant paragraph of the C Standard:

188.8.131.52 Real floating and integer
When a value of integer type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner.
If the value being converted is outside the range of values that can be represented, the behavior is undefined. Results of some implicit conversions may be represented in greater range and precision than that required by the new type (see 22.214.171.124 and 18.104.22.168).
Comment: Annex F fills in the definition, though.


Enabling KSM: Restart of libvirtd necessary?

Question: I've just enabled ksm on one of our hypervisors with lots of running VMs (qemu-kvm) that all are using the same operating system. Anyway, pages_sharing and pages_shared both still show 0:
root@myserver:~# cat /sys/kernel/mm/ksm/run
1
root@myserver:~# cat /sys/kernel/mm/ksm/pages_sharing
0
root@myserver:~# cat /sys/kernel/mm/ksm/pages_shared
0
root@myserver:~# grep KSM /boot/config-`uname -r`
CONFIG_KSM=y

May I have to restart libvirtd or even restart the virtual machines to see some effect? I already restarted a few similar VMs but pages_sharing and pages_shared are both still 0...
I was hoping to activate the feature without interrupting virtual machines.
Some system infos:
root@myserver:~# grep KSM /boot/config-`uname -r`
CONFIG_KSM=y

root@myserver:~# uname -a
Linux myserver 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u1 (2016-09-03) x86_64 GNU/Linux

root@myserver:~# dpkg --list | grep qemu
ii  qemu-kvm                         1:2.1+dfsg-12+deb8u6         amd64        QEMU Full virtualization on x86 hardware
ii  qemu-system-common               1:2.1+dfsg-12+deb8u6         amd64        QEMU full system emulation binaries (common files)
ii  qemu-system-x86                  1:2.1+dfsg-12+deb8u6         amd64        QEMU full system emulation binaries (x86)
ii  qemu-utils                       1:2.1+dfsg-12+deb8u6         amd64        QEMU utilities

Comment: You should not need to restart anything; KSM takes effect immediately when you set `/sys/kernel/mm/ksm/run`. Have you run into a kernel bug? Your kernel does seem to be out of date. As does the rest of the system. Consider updating the kernel or upgrading to Debian stable.
Comment: Yes I know, unfortunately on short-term upgrading the system is not an option due to different reasons.
What I see is that /sys/kernel/mm/ksm/pages_volatile is increasing fast while pages_shared, pages_sharing and even pages_unshared stays on 0.
On a similar hypervisor (slightly newer kernel: 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2) ksm works without any problem but on this machine ksm was enabled right after boot time (and before booting any virtual machine).
Comment: I woluldn't do anything else until you can get the system up to date.
Answer: About two days after activating KSM I now see pages_sharing and pages_shared counting up.
Not sure why as no changes have been made to the system since activating KSM.


Simple REST API calls using Spring?

Question: Okay I'm having a simple REST API that is now running. I also got a mobile app (Android) that would be ready for some network communication. But here is the thing:
I now got a fancy API created with Spring that I can use with Http-Requests:
package com.helloworld

@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(ModelMap model) {
        model.addAttribute("msg", "JCG Hello World!");
        return "helloWorld";
    }
}

This is all fine but how would I use this API in my Android mobile App? What I mean is that I don't know how to make those calls more elegantly and simple! I don't want to write for every request on my API something like this:
class HelloWorldTask extends AsyncTask<String, String, String> {

    private String url = "http://192.168.42.229:8080/HelloWorldExample/helloWorld/displayMessage/" + msg;

    @Override
    protected String doInBackground(String... uri) {

        String msg = "";
        for(String m : uri) { msg += m; }

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        return restTemplate.getForObject(url, String.class, "Android");
    }
}

Is there any way to avoid this? To be honest I believed that I would be able to just import something like a helloworld-api.jar after building my REST API project and then do something like this:
import com.helloworld

public void getServerHello() {

    HelloWorldController api;

    HelloWorld helloWorld = api.getHelloWorldMapping();
    helloWorld.displayMessage("How are you?");
}

And that this will be it. So is there a way to do something like this when writing a Spring REST API or will I really have to use something like a URI-builder and create for all kind of requests an additional class <whatever>Task extends AsyncTask<?, ?, ?> by myself?
Since the API is clearly defined it should be possible to do something like this, but is it?
I hope my question is clear - please let me know if not.
Comment: Could you clarify your examples? getServerHello() doesn't map well to the controller. What should getHelloWorldMapping() and displayMessage() do? Also, do you realize that REST is resource-based API (i.e. not RPC). I get a feeling that SOAP might be better fit for your needs ...
Comment: @qbd Well this is supposed to be a simple *pseudo* code example but what `displayMessage()` is supposed to do is basically just to run something similar like `HelloWorldTask.execute()`. I don't want to write this by myself as I think there should be a way to generate a "*client-side-interface*"-library extracted from a well defined REST API or something like that for me to use easily. To my usecase: I need a server that handles mobile App clients as well as provide an API for a web interface. I don't know if REST is here really my best choice but is it the wrong one?
Answer: import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.itech.payroll.dto.ComypanyDTO;
import com.itech.payroll.dto.EmployeeDTO;
import com.itech.payroll.dto.User;
import com.itech.payroll.repo.PayrollRepo;
import com.itech.payroll.service.PayrollService;
import com.itech.payroll.service.UserService;
/**
 * REST API Implementation Using REST Controller
 * */
@RestController
public class RestReqCntrl {

    @Autowired
    private UserService userService;

    @Autowired
    private PayrollService payrollService;

    //-------------------Create a User--------------------------------------------------------

    @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    public ResponseEntity<User> registerUser(@RequestBody User user,    UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating User " + user.getFirstName());

        boolean flag = userService.registerUser(user);

         if (flag)
         {
             user.setStatusCode(1);
             user.setStatusDesc("PASS");
         }else{
             user.setStatusCode(0);
             user.setStatusDesc("FAIL");

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
    }

    //-------------------Authenticating the User--------------------------------------------------------

    @RequestMapping(value = "/authuser", method = RequestMethod.POST)
    public ResponseEntity<User> authuser(@RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating User " + user.getFirstName());

        boolean flag = userService.authUser(user);

         if (flag)
         {
             user.setStatusCode(1);
             user.setStatusDesc("PASS");
         }else{
             user.setStatusCode(0);
             user.setStatusDesc("FAIL");

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
        return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
    }

    //-------------------Create a Company--------------------------------------------------------
    @RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
    public ResponseEntity<String> registerCompany(@RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
        String result ="";
        boolean flag = payrollService.registerCompany(comypanyDTO);

         if (flag)
         {
             result="Pass";
         }else{
             result="Fail";

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
        return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
    }

    //-------------------Create a Employee--------------------------------------------------------
    @RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
    public ResponseEntity<String> registerEmployee(@RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
        String result ="";
        boolean flag = payrollService.registerEmpbyComp(employeeDTO);

         if (flag)
         {
             result="Pass";
         }else{
             result="Fail";

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
        return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
    }

    //-------------------Get Company Deatils--------------------------------------------------------
    @RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
    public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("getCompanies getCompanies ");
        List<ComypanyDTO> comypanyDTOs =null;
        comypanyDTOs = payrollService.getCompanies();
        //Setting the Respective Employees
        for(ComypanyDTO dto :comypanyDTOs){

            dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
        return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
    }

}

Comment: jackson-annotations-2.5.0.jar, jackson-core-2.5.3.jar, jackson-databind-2.5.3.jar   these jars are need to be import
Comment: Thanks for your elaborate answer. Could you explain your code a bit?
Answer: Annotate your method with @ResponseBody
@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET, produces="application/json")
    @ResponseBody
    public String hello(ModelMap model) {
        model.addAttribute("msg", "JCG Hello World!");
        return "helloWorld";
    }
}

If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The above example will result in the text helloWorld being written to the HTTP response stream.
Write a Http Android client which sends the Http Request to your Spring app, the response will be in JSON format. Parse the JSON via Jquery & display the data.
Answer: In my current project we have similar setting with a Java client and a RESTful backend based on Springs REST API. We use apache-cxf-rs-client-api to call our REST services from the clients.

Create an Interface for your Methods in your HelloWorldController.
Add apache-cxf-rs-client-api to your project (take a look for more information).
Now you can call the interface on the client and Apache CXF will do the rest for you.
Comment: Looks nice and useful. Gonna' take it :)
Answer: Check out Volley or Retrofit. The latter is especially useful for setting up client side API calls super fast.
When I do something like this I usually reuse the server model if available (when I do both the client and the server for example).
Otherwise you can just convert a json to a pojo class and use it with Retrofit.
Answer: To write a api you need to follow below pattern:
package com.helloworld
@Controller
@RequestMapping("/api")
public class HelloWorldController {
    @ResponseBody
    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    public String hello() {
        return "helloWorld";
    }
}

For more detail step by step learning you can follow link.

Simple REST API calls using Spring?


Existe alguma maneira de usar script como arquivos de configuração no python?

Question: No PHP, podemos utilizar um script PHP para apenas retornar valores, o que é muito útil para criar arquivos de configurações para uma aplicação.
Exemplo DB.php
return array(
  'host' => 'localhost',
  'username' => 'username',
  ...
);

index.php
$config = include 'DB.php';

print_r($config);

// Retorna o array contendo os valores retornados em "DB.php"

Ao tentar "imitar" isso em Python, não obtive êxito, pois me gerou um erro.
Exemplo db.py
return [
    1, 2, 3
]

Resultado:

'return' outside function

Nesse caso, se eu quissesse carregar um arquivo em python, apenas para fins de retorno de dados para configuração, como eu poderia fazer?
Answer: Sim, é possível. A maneira mais difundida disso é fazer como o framework Django faz: Criando um arquivo (settings.py, por exemplo) e importando-o em outro módulo. Veja:
.
├── main.py
├── config.py
├── __init__.py
├── foo
|   ├── __init__.py
|   └── ...

Então, se nosso módulo de configurações config.py fosse parecido com isso:
APPNAME = "Foo"
# server
SERVER = {
  "host": "1184.108.40.206",
  "port": 8980,
}

Então você poderia importar em main.py ou em qualquer outro módulo o namespace do arquivo de configurações, dessa forma:
# current mod: main.py

import config

xpto_connect(config.SERVER["host"], config.SERVER["port"])

Ou ainda importar partes do arquivo de configurações, somente as que você precisa:
# current mod: main.py

from config import SERVER, APPNAME

xpto_connect(SERVER["host"], SERVER["port"])

Como você pode ver, é extremamente fácil e me parece bem melhor que o modo que o PHP faz. ;)
Também, a instrução return somente pode ser usada na definição e escopo de função, por isso você está recebendo um erro.
Nota
Diferentemente de PHP, você deve ter um arquivo chamado __init__.py ao lado do arquivo (mesmo nível no diretório) que você quer importar (que seria include, em PHP). Esse arquivo pode ser vazio.
Comment: Pensando bem na sua resposta, até parece com o jeito que é feito no Django
Answer: De acordo com essa resposta no SOEN, creio que uma boa solução seria utilizar um arquivo json e analisá-lo pelo python.
Isso pode ser feito através do módulo json.
Exemplo JSON:
{
   "version" : "2.1",
}

Exemplo Python:
import json

config = json.load(open('composer.json'))

print(config['version']) # Imprime "2.1"

Comment: Acho que esse exemplo está misturado entre JavaScript e Python ;)
Comment: Eu estava me referindo à `var` e o comentário precedido por `//` ao invés de `#` (antes de você corrigir; agora está correto). Mas dá pra entender a sua sugestão sem problema.
Comment: Ok, @sergiopereira. não tem isso em `python` :)
Answer: Eu não conheço uma maneira de fazer idêntica ao PHP, usando imports diretamente. Mas dá sim para usar um arquivo .py para configuração se você criar alguma convenção.
Por exemplo:
# em config/db.py
config = {
    'hostname': 'localhost',
    'port': 1234
}

# em seu script principal
db_config_file = 'config/db.py'
db_cfg = dict()
with open(db_config_file) as config_file:
    exec(compile(config_file.read(), db_config_file, 'exec'), db_cfg)
print db_cfg['config']

A convenção que usei é que o arquivo de configuração precisa definir uma variável config. Se você utilizar alguma convenção semelhante e aplicá-la para todos seus arquivos de configuração, você pode então colocar essa lógica de ler o arquivo em uma função utilitária.


How to convert Plist data to JSON format?

Question: i am using plist to save my data locally when network connection is not available, and when network is available i want to sync my locally saved data to the web server.In this process i want to convert my plist data to JSON data and post that data to web server. Can any one help me one this?
Comment: EitherDictOrArray (according to the top level of you data) can be used to read from/converted into plist data ((with some limitations on object classes)). EitherDictOrArray can be read from/converted into JSON (with some limitations on object classes). What have you tried?
Answer: You can access data from plist in dictionary format thenceforth serialize it to get json string.
NSString *path = [[NSBundle mainBundle] pathForResource:@"yourPlistName" ofType:@"plist"];
NSData* data = [NSData dataWithContentsOfFile:path];
NSDictionary* dict= [NSPropertyListSerialization propertyListFromData:data
                                                     mutabilityOption:NSPropertyListImmutable
                                                               format:NSPropertyListXMLFormat_v1_0
                                                     errorDescription:NULL];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                    options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

-----SWIFT 3-----
if let url = Bundle.main.url(forResource:"yourPlistName", withExtension: "plist") {
do {
 let data = try Data(contentsOf:url)
 let dict = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String:Any]
  let jsonData = try JSONSerialization.data(withJSONObject: dict , options: .prettyPrinted)
   // jsondata  your required data
   } catch {
  print(error)
 }
}

Comment: Your answer is in Swift and the author tagged the question as Objective-C
Comment: Still upvoting this answer, because other answers use deprecated methods `dictionaryWithContentsOfFile` / `initWithContentsOfFile`. This one is easy to rewrite to Objective-C
Comment: Thanks @mag_zbc . I have updated ans in objective -c . I have not tested it yet as I am away from my system.
Answer: You can do that with this code:
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

Answer: Use the code below
NSString * plistPath = @"data.plist";
NSMutableDictionary *plistData = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath];
NSError * err;
NSString * jsonStr = nil;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:plistData options:0 error:&err];
jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Answer: My plist was an NSArray, not an NSDictionary, so I had to do this:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"myPlist" ofType:@"plist"];
NSArray *menuArray = [[NSArray alloc] initWithContentsOfFile:plistPath];
NSError *err;
NSString *jsonStr = nil;
NSData *jsonData = [NSJSONSerialization  dataWithJSONObject:menuArray options:0 error:&err];
jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


Android Repository Implementation with Interface

Question: Usually, I use an Interface for my repositories:
interface UserRepository {
    fun add()
    fun get(userId): User
    .....
}

I have three types of Repositories (InMemory, Database, and Network):
They all implement UserRepository:
UserInMemoryRepository - UserDatabaseRepository - UserNetworkRepository
But my network doesn't have any add user API
What is the best practice here?

Remove my UserRepository interface
Leave an empty add user method
...... (Any better approach)
Comment: You should have only one RepositoryImpl, inside it has logic when getting data from memory or database or network
Comment: @CôngHải That's not how Google Samples implement this
Comment: Please take a look here https://developer.android.com/jetpack/docs/guide. Inside UserRepository it manage both memory cached and remote network.
Answer: Leaving add() empty doesn't goes in pair with SOLID principles.
If more than one class should override some method, then you shouldn't remove interface either.
What I would do is create interface:
interface Repository {
    fun get(userId): User
}
...
interface UserRepository : Repository {
     fun add()
}

Then your "Network" can implement Repository, and the rest of classes implement UserRepository.
Of course naming of interfaces is up to you, but according to 'I' in SOLID it is better to have more dedicated interfaces rather than one multifunctional


I can't get my first else statement to print its output

Question: score = int(raw_input('Enter a score: '))

if score >20:
 print 'You achieved an A'

**else:
  if score <=10 and score >= 19:
    print 'You achieved a C'**

Blockquote: If I were enter 13 here I would hope it would output 'You achieved a C', however it outputs nothing.

  else:
    if score <10:
     print 'You failed'

Comment: I think you got the signs opposite. `if score >=10 and score <= 19`. But if you mention your exact error then we can help you
Comment: a score cannot be less than or equal to ten AND greater than or equal to 19.  it's impossible
Answer: This condition
if score <=10 and score >= 19

will never evaluate to true because there is no such number that is less than 10 and greater than 19.
Perhaps you meant
if score >=10 and score <= 19

i.e. greater than 10 and less than 19


Installing lilypond on Big Sur

Question: Has anyone here installed lilypond on Big Sur (Mac)? The .dmg file and brew install --cask lilypond both informed me that the distributed version of lilypond only work with macOS versions up to Mojave...
Comment: That would imply parts of it are still 32-bit. Mojave was the last OS to support any 32-bit at all. Did you look at the lilypond page? https://lilypond.org/macos-x.html
Comment: Yes, though I didn't see anything regarding Mac 11.x, which is what I'm on. But I also didn't see anything about brew and there was a cask, so I thought perhaps there was a distribution not specified on the lilypond page that would be compatible with Big Sur...
Answer: I have found that for Lilypond, MacPorts is the only reliable way to get a new version on newer macOS builds.
I have my MacPorts install working happily alongside my homebrew install, with default settings for both.
Once you get MacPorts installed, lilypond is as simple as
sudo port install lilypond

If you have any trouble installing it, i.e. a conflict with a brew package, you can use trace mode to install it using only MacPorts files:
sudo port -t install lilypond

Comment: One thing to note: if you have a TeX install already, i.e. from homebrew or MacTeX, you can use the `mactex` variant, via `sudo port install lilypond +mactex`. You may have to configure some things, see the lilypond notes via `port notes lilypond`

This will usually speed up the install a bit, because Lily needs tex for installation, but not runtime.
Comment: Does anyone know why Lilypond is so badly supported on macOS?? (Since I already use Homebrew for lots of stuff, I've been using a Lilypond cask — but that only works up to 10.14 Mojave. And I quail at the idea of installing _another_ entire package manager, and 23 support packages — probably with shedloads of further dependencies — simply for this one application.)
Comment: I believe its because there is some (perceived) licensing issue between an Apple provided library and a GNU one, which lilypond is licensed under. MacPorts "works" because it compiles it.

It would, of course, be possible to get a Homebrew tap working that compiled Lilypond, and use it, but I haven't found one that does it yet.

As for the leaf dependencies with MacPorts, its pretty easy to reclaim most of them, my Ly install isn't too space hungry
Comment: Dunno if this is a coincidence, but I've just updated Homebrew, and find there's now a straight Lilypond formula, with a 64-bit executable! \o/ No GUI; just the command-line version — but that's all I use anyway. A web search finds [this 22-hour-old announcement](https://firstname.lastname@example.com/msg146249.html). Apparently it uses Guile 2 (not 1.8 like other versions of Lilypond) so may have teething problems — but it just rendered 3 pages of mine just about identically, so first impressions are great!

Installing lilypond on Big Sur


"npm install react react-dom --save-dev", there is no introduced dependency package in the "package.json" file~

Question: npm Execution error
There is no import dependency package, such as: {react, react-dom}
ths very much~
Answer: I know the answer is my node before the installation is not uninstalled (uninstall), making the installation is always wrong, before trying a lot of ways are invalid, I re-uninstall the software, re-installed, and now all modules are Ok, Thanks in advance~


Google ads scripts: newVideoAd This is not implemented yet. For currently supported API

Question: 8/3/2022 13:40:32   NotImplementedError: This is not implemented yet. For currently supported API, see: https://developers.google.com/google-ads/scripts-beta/docs/reference/adsapp/adsapp
at Ha (adsapp_compiled:298:11)
at new $y (adsapp_compiled:13027:5)
at qC.newVideoAd (adsapp_compiled:15250:12)
at Object.<anonymous> (adsapp_compiled:18396:54)

    var youtubeVideoId = "youtubeVideoId";
    var adGroupName = "adGroupName" // name of my target video ad group
    var displayUrl = "display-url.com";
    var finalUrl = "https://final-url.com";

    var assetOperation = AdsApp.adAssets().newYouTubeVideoAssetBuilder()
        .withName(adName)
        .withYouTubeVideoId(youtubeVideoId)
        .build();
    var videoAsset = assetOperation.getResult();

    var videoAdGroup = AdsApp.videoAdGroups()
        .withCondition(`Name = '${adGroupName}'`)
        .withLimit(1)
        .get()
        .next();

    var videoAdOperation = videoAdGroup.newVideoAd().inStreamAdBuilder()
        .withVideo(videoAsset)
        .withAdName(adName)
        .withDisplayUrl(displayUrl)
        .withFinalUrl(finalUrl)
        .build()
        .getResult();

    // Code crash before next statement

    if(videoAdOperation.isSuccessful()) {
        var videoAd = videoAdOperation.getResult();
        Logger.log("VideoAd " + videoAd.getName() + " created.");
    } else {
        Logger.log(videoAdOperation.getErrors());
    }

Code breaks after videoAdGroup.newVideoAd().inStreamAdBuilder().
Following the google ads script docs everything should works nice.

But when I compile the script, I always get the next error:

I have just found in a Google ads scripts forum somebody who has the same problem here but no solution.
Answer: The problem is that beta mode which is active by default. Must be switched off for this action.

As a negative point, switch off Beta mode will not allow you to use javascript arrow functions, neither js classes.


print() clears console with pytesseract

Question: I followed a tutorial on a webpage to code a program to recognize text in images, the code it's very straightforward and it's the following.
    import cv2, pytesseract
    pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'

    img = cv2.imread('test_image.jpeg')
    text = pytesseract.image_to_string(img)

    print(text)
    print('done')

where "test_image.jpeg" is an image (with some text) placed in the same folder where the program has been saved.
I already installed cv2 and pytesseract and the installation was successful as they are in the list of modules installed.
But when I run the program, it clears the console (working on Spyder, Python 3.8) and it just prints 'done'.
I've made some checks and the problem is the line "print(text)", when it runs it, it clears the console.
I tried to use another output function, sys.stdout.write(text), and it does the same thing.
I tried to uninstall numpy and cv2 and reinstalled them.
I checked if text was a string with "print(type(text))" and it says string.
I checked in the Variable Explorer if just before printing the 'text' variable had the right text in it, and it had it, so everything in "background" should be ok.
Now I'm thinking I might just missing something easy that I can't see, could you help me? Thank you! :)
Comment: If you see the content inside, `text` may end with a series of linefeeds or some other control character.
Comment: ^ try `print(repr(text))`, that should show if any control characters are there. If i remember right, tesseract might do something like print an absurd amount of newlines, like tevemadar said.
Comment: I tried and yes, there were four \n and one \x0c, and I removed them and it's ok, thanks :).
I have a friend who tried the same code yesterday (on Visual Studio Code) and it worked fine for him. Do you know why?
Answer: As noticed in the comment you can solve the problem printing repr(text)
    print(repr(text))

You can notice that there are (at least in my case) a lot of \n and one \x0c, that is a sort of 'new page' escape sequence. These come from the way pytesseract works.
So the easier way to fix the problem I found is to delete them through
    text = text[:-5]

The number of escape sequences depends on the image, but you could create a function to identify and delete them, for example, starting from the end, you delete every escape sequence you find.
Answer: Building on the previous answer by Matte, you can check for the existence of escape sequences by printing
print(repr(text))

To get rid of the escape sequence you have two options:

You strip the OCR result to remove all whitespace at the beginning or end of the string. This works regardless of how many \n or \x0c characters there are at the end.
text = text.strip()

You change or remove the page separator used by tesseract (by default this is \x0c, see https://tesseract-ocr.github.io/tessdoc/FAQ.html#tesseract-400).
text = pytesseract.image_to_string(img, config="-c page_separator=''")

print() clears console with pytesseract


When a QB slides, is it considered a dead ball?

Question: I was watching the Niners-Lions game last week and saw something that has me a little confused. I was under the impression that when a quarterback slides in the NFL, the play is considered dead when the player hits the ground. In this video, 49er QB Alex Smith starts sliding and then is hit. I know the timing is really close, but it seems like the defender (safety John Wendling) moved after Smith was already going down. In the instance that a player is hit after the play is dead, I thought there was supposed to be a penalty like unnecessary roughness. I haven't been able to find a rule about QB slides anywhere, except some speculation on it.
First, is the play dead after a QB slides, regardless of whether he is hit? Second, if it is dead on the slide, is there a penalty for hitting the QB after the slide?
Answer:
First, is the play dead after a QB slides, regardless of whether he is hit?

If the QB slides feet-first, then yes, the play is dead.

Second, if it is dead on the slide, is there a penalty for hitting the QB after the slide?

Not if the defender has "committed himself, and the contact is unavoidable."

Rule 7, Section 2 of the NFL Rulebook describe a "Dead Ball."
Article 1 describes when an official shall declare the ball dead. Letter (d) states:

When a runner declares himself down by sliding feet first on the
  ground. The ball is dead the instant the runner touches the ground
  with anything other than his hands or his feet;

Additionally, a note states:

Defenders are required to treat a sliding runner as they would a
  runner who is down by contact.
A defender must pull up when a runner begins a feet-first slide. This does not mean that all contact by a defender is illegal. If a defender has already committed himself, and
  the contact is unavoidable, it is not a foul unless the defender commits some other act, such as helmet-to-helmet contact or by driving his forearm or shoulder into the head or neck are of the runner.
Comment: Although not penalized, Wendling was fined for the hit (http://detroit.sbnation.com/detroit-lions/2012/9/21/3370236/john-wendling-fine-alex-smith-lions). Officiating with the replacement referees might have been a factor.
Comment: In the above case, based on these rules, should a penalty have been called?
Comment: I would think so. The QB slide seemed to take place before the defender "committed himself" to make contact.
Comment: I figured the replacement refs missed the call. Thanks.
Answer: This is a comment but just too long of one to go in comments.  Both other answers are kind of right. This answer has the rule cited but you can look at the rule for 20 seconds and figure out that it is missing a lot of clarity.
The rules committee will certainly address the shortcomings of this rule in the offseason.  If you watched the Packers game last night (11/20/16 vs Redskins) you will note that Rodgers went head first twice and both times he was declared to have given himself up.  One of the times he got up and tried to run more... what a mess the NFL has gotten themselves into.
Not only is there a large amount of ambiguity on what it means to give oneself up, but there is a no frills circumvention to this rule - slide head first.   Nobody can hit you because maybe you did give yourself up and then if they don't hit you, you can get up and start running again.  Completely ridiculous.  And this is only an NFL problem, as other leagues the knee down is a down play.  To make matters worse 80-90% of the slides are by QBs.
So the "correct" answer at this point in time is that there is a rule that clearly states that a player is down at the beginning of their slide when going feet first (the NFL hasn't spotted this right all year and gives QBs 1-2 yards extra per slide).  Letter d - addressing feet first sliding - isn't even how it is called in games.  The rule says "the instant a runner touches the ground".  That is not how NFL referees call it.  The runner is down as soon as he starts his slide, which affords him extra protection from being hit.  This is unarguable since there are 20 late hits a year that happen far from the runner beginning his slide but close to when the runners body hits the ground.
Now the other side of this is when the QB slides head first.  This wasn't meant to be a dead ball, however to keep up with player safety and the horribly vulnerable position a player is in (head facing the defense, laying on the ground), NFL referees have in almost all cases this year declared the player as giving himself up when the QB slides head first (I simply can't remember a non-QB sliding head first that wasn't touched - please comment if there is one).
So Rodgers being the smart QB he is tried to use a loophole to gain protection and then get back up.  The referees were smarter than Rodgers in both cases and declared that he declared himself down.  To me this is rather interesting because unlike the feet first slide, and to go along with the "down or not" ambiguity, we also have an issue with the spot of the ball.
On a face first slide you are moving forward.  If you are talking about the inches of the game and not safety you certainly would want your defensive player cremating Rodgers to physically knock his body backwards.  All coaches know that if you pat a sliding player on the back, the referees are more apt to give him a few extra inches (feet) after the touch.  If you stop him in his tracks, you might help your cause by a few inches.  Then you have the QB with the ability to possibly get up because the rules don't clearly say he is down.
This basically makes the referees make a both strategic and safety decision on every head first slide.  I think the NFL will continue to rule to QB down on any slide and amend the rules ASAP.  As a coach I could certainly see telling your players...  Just hover a couple yards from him after a slide and lay him out if he gets up without a whistle.
Answer: If a qb is running he becomes runner and can be hit like any other player. The play is over whether he slides feet or head first.. ( he is giving himself up) any player can give themself up.. no penalties if a defender is in the process
Comment: @PhilipKendall - I added a long comment/answer.  I think you are being a little hard on this person.  The NFL referees have basically called it like this all year.
Comment: This answer doesn't provide any references, and contradicts another answer. Could you provide some links to official sources to back up your points please?
Comment: @TrueDub this doesn't really seem to me to contradict the other answer in any of the significant points: they both say that the play is over once a runner begins a slide, and that a defender can hit the sliding player only if they were already committed to the action before the slide started.
Comment: My reading of the first answer is that only a feet-first slide counts as declaring himself down. "Contradicts" is probably too strong a word, but this answer expands the criteria, but without backing it up. I've also noticed how old this question is, thought it was a lot newer.


How to sight read piano sheet faster in any key?

Question: So I learned this trick from youtube that you can read notes relatively.

I can see that the first 2 notes in this piece is a G4, instead of figuring out what the third note is, I just press the key a SECOND up from the second note, and for the fourth note, I just press the key a SECOND down from the third note, and for the fifth note, I just press the key a FOURTH up from the fourth note, so basically I press based on the relationship of the future note and my last note, I don't actually think about what specific note I'm pressing, I only think in relationships.
This trick is easy in key of C, where there are only white notes and skipping down and up relatively is easy.
But what if the key is C# major or Cb major with lots of accidentals?

Should I modify this trick with more sophistication, like more detailed mapping of major and minor seconds, fourths, and so on?
Or are there some other tricks for fast reading in ANY key?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/104526/discussion-on-question-by-john-how-to-sight-read-piano-sheet-faster-in-any-key).
Answer: As you noticed this relative aproach is useful but has its limitations.
I think the first step is to learn your scales. Learn them one sharp and one flat at a time. And build your way around the circle of fifths. In a key with little flats or sharps your trick of relative reading will still work, but you will have to stay aware that some notes will be flatened or sharped, and you will have to look out for them. In G major for example the F will be sharpened, all the other notes will stay on the white keys.
It also helps that you will hear it if you miss a sharp or flat.
While you work your way further and further around the circle of fifths, you will also have to build your absolute note reading. Being able to read an F or a B when you see one. The best way to do this is to do work away from the keyboard. Just take a score and read note for note and shout out (or sing!) every note you read. Flash cards can help too.
At some point these two approaches will click together.
Comment: +1 for learn your scales. Practice those scales up and down and in thirds and whatever variation comes to mind until you no longer have to think about the accidentals of each scale. Then you can take one look at the key signature and your relative reading will work like a charm. That's how I do it. My teacher used to have me practice a scale a week around the circle of fifth.
Answer: In key C it is quite easy to see, translate and play certain intervals, one of the reasons C is usually the first key to be explored in tutorials, particularly on piano. Those white keys seem simpler!
Once one gets into key sigs of 3,4 or more sharps or flats, more especially when the music contains accidentals (those at the beginning aren't!), it gets increasingly more difficult to read what each next interval is - having to remember which notes are sharp or flat in each key.
Your idea may work partially, but knowing each and every key with its 'changed notes' is essential. So one needs to learn all the scales anyway.And knowing all intervals may or may not help in the bigger picture. Two of us so far have picked up the glaring error in 'Happy b'day'!
I wish there was an easy way into sight-reading. Perhaps it's the holy grail, but on piano at least, your method will give all sorts of problems.
Having said that, it works somewhat on guitar, which has a different way to play in each key. I aired a method a long time ago, and have taught it to students. It does use intervals as its basis. Having established two octave pattern across the fingerboard for either major or minor scale, it's quite easy to follow the pattern of diatonic intervals as the melody unfolds.
As Albrecht says, though, sight-reading (successfully) is a lot more than merely reading the notes and playing them. Similar to a child 'barking at print'. I'll leave you to figure that out!
Answer: Your way is one approach to play music. It is really just "playing" by imitating, guessing and listening. But as you see you don't get far this way.
You have come  to the point where you realize there has to be another way! I call it "working". This means you should study some basic theory about keys, scales, chords, harmony, chord progression and functions (tonic, dominant and subdominant.
This doesn't mean you have to study music, just consult some piano tutorials or look up some questions in this SE.
Then you will understand why the sharpened note in bar 5 (l.h.)  isn't A# but Bb and why this chord is a C7 chord.
So you have to learn as next what is a triad and tetrad especially a dominant 7 chord. It would lead too far to explain in this answer the whole theory. Basic theory of music is a systematic introduction to the basic terms and will give you the fundamental requirement build your own playroom of music.
You will be able to continue "playing" when you will have more fun when you are able to read sheet music.
(All tags in italic).
Btw. these key assignments are not accidentals. They are called the signature.
Edit:
I have looked up your other questions ... and there is really no better advice than the one you got  in a comment of your first question: **Please take lessons - or at the very least read some "teach yourself" books which cover fingering patterns in detail. If you start inventing your own, you will only develop bad habits which are very hard to break later. – Carl Witthoft **
acceptable to use same finger for 2 succeeding notes in this case?
If you can't afford the costs of piano lessons you can also try to play easy pieces that you can download  only from  pictures  when you google a song or one of this terms I told you should learn to know.
Comment: Thanks for the callout :-) .   I hope the OP takes your advice to heart.
Comment: If you follow his other questions you will see that "we" are struggling along. The next question of this kind will be the first that I might vote down.
Answer: I don't want to just give you a link and run. But I would look at http://musicnotation.org/ for an alternative way of looking at this. Basically, it is different sheet music notation that simply gives a space on the clef for each half step, does away with the sharp/flats notation, and makes it so that each clef is an octave apart (so no learning to read base, treble, alto etc as different).
It does not really solve being able to pick up a standard piece of sheet music and just sight read it.
But, it does make it, in my experience (especially with your relative way of reading notes), much easier to sight read in any key and much easier to transpose as you sight read. I have found that practicing reading notes from that system has majorly helped with developing my "ear" for music and really helped sight reading and playing by ear/how it sounds come much closer to meshing into one system for me.
Comment: Interesting. How would a chromatic staff deal with the need for double sharps and flats?
Comment: @BrianTHOMAS Can you give me more context? I would think it would work out just by going to the position two spaces away (one whole step). I think I'm not understanding your question because of how obvious the answer seems...
Comment: In conventional notation, if I notate a C# major triad, this contains the notes C# E# and G#. You mustn't write F natural - you have to write E#. On a chromatic staff, you'd lose this enharmonic information if you're forced to write an E# as F. They're the same heard pitch, but they're not the same note when you're analysing harmony. In the linked article I liked the Schoenberg quote which says lots of ingenious minds have tackled the problem of music notation!
Comment: @BrianTHOMAS Under a chromatic staff, the concepts of "flats" and "sharps would become completely unnecessary. One could easily give all 12 chromatic notes their own letter names defined without relation to any other notes, and then C♯ major mght just be "K major", spelled "D G J" or something.
Comment: @BrianTHOMAS So is the enharmonic about a very minuscule pitch shift to fit the chord (that an equal temperament instrument like a piano technically couldn't do)? If so, a chromatic notation should probably have something like a sharp-lite or flat-lite symbol that shows a small (maybe quantified/specified) amount of pitch shift?
Comment: @BrianTHOMAS Or, is the enharmonic about writing it different so you recognize/notice the pattern? If that is the case, maybe noticing C E G is wrong; instead notice the spaces between the notes, which should always look the same on a chromatic staff unlike our current staff. Or look for spaces of 4 and 3 steps.
Comment: Not understanding. CEG is either 3 consecutive lines or 3 consecutive spaces. What can be simpler?
Comment: +1 for the link (which may disappear at some future time). Fascinating stuff, mainly re-inventing the wheel. Possibly some of those ideas are better than what we have, possibly not. But I can't see how learning to read any of the alternative music helps reading basic staves. After so many hundreds of years entrenchment, it's nigh on impossible that any of the options would catch on - although it wouldn't be too difficult to programme a computer to re-interpret. It ain't broke, so why mend it?! Although it's never the easiest part of music.
Comment: @Tim It's the standard network effects "chicken and egg" problem with adopting better standards. Being defeatist about it is somewhat of a self fulfilling prophesy. I will say that in Denemo/Lilypond, you can add a few lines and reprint in the alternative format -- and that could probably be turned into a button in Denemo fairly easily a few people asked the developer for it. If we had OCR for music (I think some commercial engraving software does) and could import that into Denemo, then right there we have what you propose...


Qual a diferença entre o uso das constantes do enum StandardCopyOption?

Question: Estou implementando cópia de arquivos e decidi utilizar a classe Files, e uma das assinaturas do método copy() é receber 2 parâmetros do tipo Path e um terceiro do tipo CopyOption e é neste último que fiquei com dúvidas.
Para passar este terceiro parâmetro, utiliza-se o enum StandardCopyOption, e ele possui 3 constantes:

ATOMIC_MOVE
  Move the file as an atomic file system operation.
COPY_ATTRIBUTES
  Copy attributes to the new file.
REPLACE_EXISTING
  Replace an existing file if it exists.

A última eu até entendi que é sobre reescrita de arquivos, caso ele já exista no path de destino mas mesmo lendo a definição dos outros dois, me gerou algumas duvidas:
A cópia em si já não copia os atributos do arquivo de origem por padrão, já que estamos criando réplica do arquivo em outro local?
O que o ATOMIC_MOVE faz de diferente da cópia comum?
Answer: Como as flags são usadas
Todas as flags são passadas para a implementação de cópia de arquivos específica de cada sistema operacional.
Por exemplo, no caso de sistemas baseados no UNIX, a classe UnixCopyFile utiliza as opções para determinar se deve realizar determinadas operações adicionais.
Trecho relevante da classe UnixCopyFile:
static Flags fromMoveOptions(CopyOption... options) {
    Flags flags = new Flags();
    for (CopyOption option: options) {
        if (option == StandardCopyOption.ATOMIC_MOVE) {
            flags.atomicMove = true;
            continue;
        }
        if (option == StandardCopyOption.REPLACE_EXISTING) {
            flags.replaceExisting = true;
            continue;
        }
        if (option == LinkOption.NOFOLLOW_LINKS) {
            // ignore
            continue;
        }
        if (option == null)
            throw new NullPointerException();
        throw new UnsupportedOperationException("Unsupported copy option");
    }

    // a move requires that all attributes be copied but only fail if
    // the basic attributes cannot be copied
    flags.copyBasicAttributes = true;
    flags.copyPosixAttributes = true;
    flags.copyNonPosixAttributes = true;
    flags.failIfUnableToCopyBasic = true;
    return flags;
}

Cópia de atributos
Especificamente sobre COPY_ATTRIBUTES, geralmente copiar um arquivo significa criar um novo no local de destino e copiar o conteúdo.
Atributos do arquivo como data de último acesso, data de modificação e permissões geralmente recebem os valores padrão de um arquivo novo.
Portanto, tal flag faz com que o novo arquivo recebe os mesmos valores nesses atributos. Note que nem sempre é isto que queremos. Copiar poucas vezes tem o sentido completo de replicar na prática.
Trecho relevante da classe UnixCopyFile:
// copy owner/permissions
if (flags.copyPosixAttributes) {
    try {
        fchown(fo, attrs.uid(), attrs.gid());
        fchmod(fo, attrs.mode());
    } catch (UnixException x) {
        if (flags.failIfUnableToCopyPosix)
            x.rethrowAsIOException(target);
    }
}
// copy non POSIX attributes (depends on file system)
if (flags.copyNonPosixAttributes) {
    source.getFileSystem().copyNonPosixAttributes(fi, fo);
}
// copy time attributes
if (flags.copyBasicAttributes) {
    try {
        futimes(fo,
                attrs.lastAccessTime().to(TimeUnit.MICROSECONDS),
                attrs.lastModifiedTime().to(TimeUnit.MICROSECONDS));
    } catch (UnixException x) {
        if (flags.failIfUnableToCopyBasic)
            x.rethrowAsIOException(target);
    }
}

Operações atômicas
A flag ATOMIC_MOVE na verdade não se aplica nas operações de cópia, apesar do nome do enum, mas ao mover um arquivo.
No caso de sistemas baseados no UNIX, o Java usa o comando rename para mudar o arquivo do caminho de origem para o caminho de destino, pois este comando é atômico.
Além disso, o código Java não realiza outras operações adicionais, tal como verificar se o arquivo de destino existe, pois isto tornaria o processo sujeito a condições de corrida, isto é, não atômico.
Trecho relevante da classe UnixCopyFile:
// handle atomic rename case
if (flags.atomicMove) {
    try {
        rename(source, target);
    } catch (UnixException x) {
        if (x.errno() == EXDEV) {
            throw new AtomicMoveNotSupportedException(
                source.getPathForExecptionMessage(),
                target.getPathForExecptionMessage(),
                x.errorString());
        }
        x.rethrowAsIOException(source, target);
    }
    return;
}

Comment: Então operações de cópia não são atômicas? Isso explica alguns problemas que tive, como cópias incompletas e as vezes cópias com dados corrompidos.
Comment: @diegofm É um problema comum. Do ponto de vista de um programa *single-threaded*, as operações em disco são atômicas. Porém, outros processos ou *threads* conseguem enxergar um arquivo que acabou de ser criado enquanto você ainda está começando a gravar os dados nele.
Comment: Se você trabalha com integração de arquivos, onde um programa gera o arquivo e outro programa consome, vejo duas opções: ou você faz com que o programa de origem avise o programa de destino quando o arquivo estiver completo, ou, se usa monitoramento de diretórios, grave o conteúdo num arquivo temporário e, somente ao terminar, mova o arquivo para o diretório onde ele será lido.


UIPageViewController and UIScrollView

Question: I have a view controller that it part of a UIPageViewController. Within this view controller, there is a view called pdfView. This view has a UIScrollview.
-UIPageViewController
   -UIViewController
        -pdfView (UIView)
            -UIScrollView

I set the gesture recognizers of pdfView to be the UIPageViewController's gesture recognizers (for turning the page). The only problem is, if the user zooms into the scroll view by pinching, they are unable to move to the right or left of the scroll view because the page turns instead. What do you suggest I do to prevent this from happening? Thanks.
pdfView.gestureRecognizers = self.pageViewController.gestureRecognizers;

Comment: Setting the view controller's gestureRecognizers instead of the pdfView's somewhat solves this problem (can move throughout the UIScrollView), but the user is unable to swipe to turn the page (code: viewController.view.gestureRecognizers = ...)
Answer: I know my answer is the accepted, but I have tryed to change my UIView to a scrollView and all works better.
when I zoom a page, the pageview gestures of that page stop working, so I can zoom in and out, and pan the zoomed image withouth problem, and when I zoom to the initial scale, the page gestures start to work again automatically.
I have in my dataViewController the view, a full screen scrollerView, and a full screen imageView inside the scroller view.
-UIPageViewController
   -UIViewController
        -UIView
            -UIScrollView
                -UIImageView

So, if you want to change the page while it is zoomed, yo can, you have to choose between pan the zoomed page or change the page with the pan gesture.
It was the behabiour I was looking for, in my code I do it manually, but I'm goin to change to the UIScrollView because the UIScrollView pan and pinch gestures work much better than mine.
Comment: I have the exact same problem. Can you give an idea of how you achieved your solution, using the UIScrollView?
Comment: I just did what I said and it worked without any changes. But it's a scroller view for each page, so you zoom the pages individually if you are in 2 pages mode. Just put an UIScrollView inside the view of the viewController you use for each page.
Answer: Try this,
instead using a scrollview use a regural UIView
Add to this new UIView an UIPinchGestureRecognizer to zoom it and an UIPanGestureRecognizer to move the content. (you have to create the pinch and pan actions, but you can google them)
I did something similar and worked, the only problem is sometimes it detect the page swipe instead the view pan, you can solve is forcing the pan to require 2 touches.
If you have doubts let me know
Answer: I made this library that makes this setup work
-UIPageViewController
   -UIViewController
        -UIView
            -UIScrollView
                -UIImageView

https://github.com/holyman2k/WXPagedPhotoView
the only issue i have is when user zoom the photo, the pageviewcontroller pan gesture is disabled till user scroll the edge and restart panning.  you have this weird behaviour that user zoom in the photo, scroll to the very right hand, then scrolling stops, then user scroll again to move to the next page

UIPageViewController and UIScrollView


How to scale layout proportionally to screen's physical size?

Question: Need the whole layout width to fit exactly the same within the portrait physical width from the screen in any device, so that it doesn't matter the DPI, the screen size, the pixel portrait width, nor the width-height relation.
All I have managed to do right now is to override the font size from the user's Android configuration, by adding the next code to MainActivity.cs:
<code>public override Resources Resources
{
    get
    {
        Configuration config = base.Resources.Configuration;
        if (config == null)
        {
            config = new Configuration();
        }
        config.FontScale = 1f;
        return CreateConfigurationContext(config).Resources;
    }
}
</code>
That made a great improvement, but still see plenty of difference between different devices, those devices may have longer or shorter screens, greater or smaller DPI, and different sizes. For example device Pixel 2 from emulator, which has 1080x1920 resolution and 420 dpi, the layout fits perfectly (I made it that way), but when I try in physical device Redmi 9 1080x2340 resolution and 395 dpi (about 3 mm bigger portrait width), the layout becomes a little bigger, and elements don't fit in.
How to make the layout width to scale proportionally to the physical size, so that it can always fit within the width from portrait mode no matter the device?
Comment: https://learn.microsoft.com/en-us/xamarin/essentials/device-display?tabs=android
Comment: If your project is Xamarin.Android,at first, you can get the phone's size before you design the UI or create different xml for different size screen. In addition, use the wrap_content instead of specific dp. Furthermore, you can also use the ConstraintLayout which can make the view in the UI show acorrding to the scale of screen's width. If your project is Xamarin.Forms, you should get the scale of the device first by the Essential, and then set the width and height of the view.
Comment: You can try to use the weight to set the width and height of the layout.
Answer: You can try using percentage or ratio dimension attributes of ConstraintLayout.
ConstraintLayout : ConstraintLayout


Alinhar a coluna para direita pdfsharp

Question: Bom dia, estou utilizando a biblioteca pdfsharp, e estou querendo alinhar pela direita a coluna referente ao valor. Poderiam me ajudar, por gentileza? Segue abaixo o código.
            graphics.DrawString(f.ENT_DAELOC, font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna, vLinha, 100, 0));
            graphics.DrawString(f.ENT_MATRIC, font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 50, vLinha, 100, 0));
            graphics.DrawString(f.ENT_MED_ANO_OUT, font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 130, vLinha, 100, 0));
            graphics.DrawString(f.ENT_RIGEM, font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 190, vLinha, 100, 0));
            graphics.DrawString(f.ENT_VALOR.PadLeft(18, ' '), font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 220, vLinha, 100, 0));
            graphics.DrawString(f.ENT_VR_MEDIDO.PadLeft(18, ' '), font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 320, vLinha, 100, 0));
            graphics.DrawString(f.ENT_VR_DIFERENCA.PadLeft(18, ' '), font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 420, vLinha, 100, 0));
            graphics.DrawString(f.ENT_REMANEJ, font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 520, vLinha, 100, 0));
            graphics.DrawString(f.ENT_DEBAUT, font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 580, vLinha, 100, 0));
            graphics.DrawString(f.ENT_CORTE, font, PdfSharp.Drawing.XBrushes.Black, new RectangleF(vColuna + 640, vLinha, 100, 0));

Answer: O método DrawString tem um overload que aceita um StringFormat.
ex:
var format = new StringFormat
{
    Alignment = StringAlignment.Far,
};

graphics.DrawString("texto", font, Brushes.Black, new RectangleF(vColuna, vLinha, 100, 0), format);

Alinhar a coluna para direita pdfsharp


How to recursively filter sequential predictions of binary classifier?

Question: Problem
My goal is to estimate binary state using entire observation history. Observations are coming sequentially with fixed interval (~1 sec). I have xgboost model which predicts the state given a single observation; I treat this prediction directly as conditional probability $P(x_t = 1 | z_t)$.
Observations are noisy, so each prediction alone does not tell much about real situation. Important point is that state can change with time.
What is the best theoretical way to estimate $x_t$ knowing $P(x_t | z_t)$ and $z_{1:t}$? I tried discrete bayes filter, but it has some not obvious parameters: aprior distribution of states and probability of transition between states, is there a method not requiring knowledge of this?
Current work
I used discrete bayes filter algorithm from "Probabilistic robotics" book
Assume following notation

$x_t \in \{0, 1\}$ - state at time $t$
$z_t$ - observation at time $t$
$P_{k,t} = P(x_t = k | z_{1:t})$ - result of filter, $P_{k,0} = P(x_0 = k)$
$\hat{P}_{k,t} = P(x_t = k | z_{1:t-1})$
$P(x_t = 1 | z_t)$ - prediction of xgboost model
$$
\hat{P}_{0,t} = P(x_{t} = 0 | x_{t-1} = 0) P_{0,t-1} + P(x_{t} = 0 | x_{t-1} = 1) P_{1,t-1} \tag{1}
$$
$$
\hat{P}_{1,t} = P(x_{t} = 1 | x_{t-1} = 0) P_{0,t-1} + P(x_{t} = 1 | x_{t-1} = 1) P_{1,t-1} \tag{2}
$$
$$
P_{0,t} = \alpha P(z_t | x_t = 0) \hat{P}_{0,t} \tag{3}
$$
$$
P_{1,t} = \alpha P(z_t | x_t = 1) \hat{P}_{1,t} \tag{4}
$$
$$
\alpha \text{ is a normalization constant such that } P_{0,t} + P_{1,t} = 1
$$

To use this algorithm with $P(x_t = 1 | z_t)$ I need to modify it using bayes rule
$$
P(z_t | x_t = 1) = \frac{P(x_t = 1 | z_t)P(z_t)}{P(x_t = 1)} \tag{5}
$$
Now
$$
P_{0,t} = \alpha \frac{P(x_t = 0 | z_t)P(z_t)}{P(x_t = 0)} \hat{P}_{0,t} \tag{6}
$$
$$
P_{1,t} = \alpha \frac{P(x_t = 1 | z_t)P(z_t)}{P(x_t = 1)} \hat{P}_{1,t} \tag{7}
$$
To cancel $P(z_t)$
$$
\frac{P_{1,t}}{1 - P_{1,t}} = \frac{P(x_t = 1 | z_t) P(x_t = 0)  \hat{P}_{1,t}}{P(x_t = 0 | z_t) P(x_t = 1) \hat{P}_{0,t}} = K \tag{8}
$$
$$
P_{1,t} = \frac{K}{1 + K} \tag{9}
$$
Are my derivations correct? Seems strange that the bigger $P(x_t = 0)$ is, the bigger $P_{1,t}$ will be.
This algorithm is not very convenient as soon as it requires many parameters ($P(x_t)$, $P(x_t | x_{t-1})$) and also does not give any confidence estimate, are there better examples of such algorithms?
Comment: Some of your notation is ambiguous - what are the $z_{i}$, some latent state variables? It seems that $P_{0, t} = P(x_{t} = 0)$ and $P_{1, t} = P(x_{1} = 0)$, so it would be nice if you could clarify that they are synonyms. I believe either there is a typo in the text you are using or you have made an arithmetic error - in equation $(5)$, assuming $P_{0, t}$ and $P_{1, t}$ mean what I think they do, you should have $P_{0, t} + P_{1, t} = 1$ - these are after all complementary events for a binary outcome.
Comment: @SkanderH.-ReinstateMonica Letting $\alpha \neq 1$ is a way to allow improper distributions to be converted into true probabilities. It seems to me to be a common technique used in the more computer science / machine learning leaning practitioners.
Comment: Fixed arithmetical typo and made needed notation clarfications
Comment: So then I'm guessing $(4)$ should have a $(1-\alpha)$ instead of an $\alpha$ as the leading coefficient?
Comment: hmm, $\alpha$ is just a normalization constant $\alpha = \frac{1}{P(z_t | x_t = 0) \hat{P}_{0,t} + P(z_t | x_t = 1) \hat{P}_{1,t}}$ such that $(3)$ and $(4)$ sums up to 1
Comment: Ah, got it. That clarifies things.
Comment: @СтасЦепа I'm not following: Based on (6) and (7) shouldn't $\alpha =1 $ all the time (by setting $P(z_t)=1$)?
Answer: So it might be helpful to explain in words what is happening in equations $(1)$ and $(2)$ above. These two equations are essentially applying the Law of Total Probability to split up your probabilities into the two terms in each sum, and then applying the (probability) Chain Rule to expand each term into a product of conditional probabilities - essentially a chain of repeated applications of Bayes' Rule.
The recursive nature of $(1)$ and $(2)$ implies that the probability of the state $x_{T}$ at any time $T$ depends on all previous states $x_{t}$ for $t < T$ and observations $z_{t}$ for $t \leq T$. Your algebra substituting $(6)$ and $(7)$ into $(8)$ seems fine to me. $(8)$ clearly shows $P_{0, t}$ and $P_{1, t}$ are inversely proportional to each other for fixed $K$. In fact, if you find the equation for $P_{0, t}$ which corresponds to equation $(9)$ for $P_{1, t}$ by using $P_{0, t} + P_{1, t} = 1$, we have
$$
P_{0, t} = \frac{1}{1 + K} \tag{10}
$$
To address your confusion about $P(x_{t} = 0)$ seemingly counterintuitive effect on $P_{1, t}$, again it's helpful to think about what each term is quantifying. $P(x_{t} = 0)$ is the unconditional probability of observing the state $x_{t} = 0$ at time $t$, without any influence from observations $z_{1:t}$. If this probability is high, you wouldn't be surprised to find that in fact $x_{t} = 0$. What really matters is how $P(x_{t} = 0)$ relates to $P(x_{t} = 0 | z_{t})$. The conditional probabilty $P(x_{t} = 0 | z_{t})$ quantifies how informative observation $z_{t}$ is about the state $x_{t}$. If $P(x_{t} = 0 | z_{t}) \ll P(x_{t} = 0)$, then we have learned a lot of surprising information from $z_{t}$, so that we drastically change our opinion of the state $x_{t}$. If we instead have $P(x_{t} = 0) \approx P(x_{t}=0|z_{t})$, then $z_{t}$ doesn't really tell us much to change our minds about the state $x_{t}$. This idea of surprise/informativity can be seen if you look at $(5)$ and $(4)$. Increasing the magnitude of $P(x_{t} = 0)$ causes a corresponding decrease in $P(x_{t} = 1)$. Then the rarer state $x_{t} = 1$ is more informative than the mundane state $x_{t} = 0$. The denominator of $(5)$ decreases in this case, and the value of $P(z_{t} | x_{t} = 1)$ correspondingly increases - the rarity of $x_{t} = 1$ means that it carries more information than the more mundane $x_{t} = 0$ about the observation $z_{t}$, and we have a corresponding increase in $P_{1, t}$ as seen in $(4)$. To reiterate, $P(x_{t}=0) \approx 1$ means that any variation in $z_{t}$ is not tightly coupled to the state $x_{t} = 0$ - $x_{t} = 0$ likely occurs with equal frequency for all possible values of $z_{t}$. The fact that this forces $P(x_{t} = 1) \approx 0$ means that because the state $x_{t} = 1$ occurs so infrequently, it is by that very property highly likely to be unevenly co-occuring with different values of $z_{t}$, and thus is in a sense highly informative about $z_{t}$. If $z_{t}$ has $100$ possible values, and $x_{t} = 0$ occurs with $99.99\%$ probability, then any value of $z_{t}$ is likely to occur with $x_{t} = 0$. However, this means that on the rare occasion $x_{t} = 1$ does occur, it most likely only does so with some smaller subset of values of $z_{t}$.
As I mentioned above, your complaint about requiring many parameters is valid, and stems from the recursive nature of the system. There are alternative models that weaken this dependence on all previous times $t<T$ by imposing some kind of Markov property. Another alternative is to use something like a Kalman Filter, which basically lets you only keep track of a set of variables of fixed size at each time step, as opposed to a set of variables increasing in size with $t$. As for confidence bounds on your estimates, you're actually getting the whole probability distribution, so you actually already have those. The dependence on your prior diminishes with time as you gather more observations, so that shouldn't really be an issue.
Comment: About my confusion -- I meant that $P(x_t = 0)$ increasing causing $P_{1,t}$ to increase, not what you wrote in your answer. To clarify $P_{0,t} = P(x_t = 0 | z_{1:t}) \neq P(x_t = 0)$
Comment: @СтасЦепа I've edited my answer to hopefully directly address your point of confusion.


Help solving a tricky matrix PDE coupled system

Question: I am trying to a solve a matrix equation of the form$$\begin{equation}\label{jacobi_cond}
\frac{\partial \mathbf{P} (x_3)}{\partial x_3} = \mathbf{H}(x_3) \mathbf{P}(x_3).
\end{equation}$$
where
$$\frac{\partial}{\partial x_3}\begin{bmatrix} \chi_1(x_3) & \chi_2(x_3) \\ \chi_3(x_3) & \chi_4(x_3) \end{bmatrix} =\begin{bmatrix} \Delta_1(x_3) & \Delta_2(x_3)  \\ \Delta_3(x_3)  & \Delta_4(x_3) \end{bmatrix}  \begin{bmatrix} \chi_1(x_3) & \chi_2(x_3) \\ \chi_3(x_3) & \chi_4(x_3) \end{bmatrix}$$
with initial condition
$$\mathbf{P}(x_3=0) = \mathbf{I}$$
the identity matrix.
The $\chi(x_3)$ entries have real and imaginary parts. The $\Delta(x_3)$ functions are nontrivial. I should note also that $\text{Tr}[\mathbf{H}(x_3)] \neq 0.$
I am trying to get a handle on the determinant of the matrix $\mathbf{P}(x_3).$
$\textbf{So far I have tried}$ using Jacobi's formula. This is easy to implement if $\text{Tr}[{\mathbf{H}(x_3)}] = 0,$ meaning the initial condition becomes the determinant, however in my case it does not hold.
I have also tried solving this numerically, but the determinant blows up rapidly. So I am really stuck at this.
I would really appreciate any ideas or discussion. Thanks.
Comment: The determinant evolution is $\frac{d}{dx}\det(P(x))=trace(H(x))\det(P(x))$. Is that conform with your observed determinant growth?
Answer: This is actually a linear first-order differential system with variable coefficients, in terms of $x_3 = x$. The present system can be recast as
$
\boldsymbol{\chi}'(x) =  {\bf A}(x)\, \boldsymbol{\chi}(x)
$,
where $\boldsymbol{\chi} = (\chi_1, \chi_2, \chi_3, \chi_4)^\top$ and
$$
{\bf A} =
\begin{pmatrix}
\Delta_1 & 0 & \Delta_2 & 0\\
0 & \Delta_1 & 0 & \Delta_2\\
\Delta_3 & 0 & \Delta_4 & 0\\
0 & \Delta_3 & 0 & \Delta_4
\end{pmatrix} .
$$
The solutions are given by
$\boldsymbol{\chi}(x) = e^{{\bf B}(x)}\,  \boldsymbol{\chi}_0$,
where $\boldsymbol{\chi}_0 = (1,0,0,1)^\top$ and where $e^{{\bf B}(x)}$ denotes the matrix exponential of ${\bf B}(x) = \int_0^x {\bf A}(\xi)\, \text d \xi$, i.e. the matrix exponential of
$$
{\bf B} =
\begin{pmatrix}
d_1 & 0 & d_2 & 0\\
0 & d_1 & 0 & d_2\\
d_3 & 0 & d_4 & 0\\
0 & d_3 & 0 & d_4
\end{pmatrix},
\qquad
d_n(x) = \int_0^x \Delta_n(\xi)\,\text d \xi\, .
$$
Using symbolic calculus software, the following $x$-dependent coefficients $\chi_n$ are obtained:
$$
\boldsymbol{\chi} = \frac{e^{(d_1 + d_4)/2}}{2\sqrt{\mathcal{D}}} \begin{pmatrix}
(d_1-d_4+\sqrt{\mathcal{D}})e^{\sqrt{\mathcal{D}}/2} - (d_1-d_4-\sqrt{\mathcal{D}})e^{-\sqrt{\mathcal{D}}/2} \\
2\, (e^{\sqrt{\mathcal{D}}/2} - e^{-\sqrt{\mathcal{D}}/2})\, d_2 \\
2\, (e^{\sqrt{\mathcal{D}}/2} - e^{-\sqrt{\mathcal{D}}/2})\, d_3 \\
(d_1-d_4+\sqrt{\mathcal{D}})e^{-\sqrt{\mathcal{D}}/2} - (d_1-d_4-\sqrt{\mathcal{D}})e^{\sqrt{\mathcal{D}}/2}
\end{pmatrix}
$$
where $\mathcal{D} = (d_1 - d_4)^2 + 4d_2d_3$. The corresponding Maple code is given below:
<code>with(LinearAlgebra):
B := Matrix(<<d__1,0,d__3,0>|<0,d__1,0,d__3>|<d__2,0,d__4,0>|<0,d__2,0,d__4>>);
M := MatrixExponential(B):
chi := M . Vector(<1,0,0,1>);
</code>
Comment: @rodger_kicks I have included the Maple code. Apparently, it is `MatrixExp` with [Mathematica](https://reference.wolfram.com/language/ref/MatrixExp.html)
Comment: This implies then, that the solution is $\chi_{n}(x) = e^{\int_{0}^{x}\Delta_{n}(\phi) d\phi}$ where $n=1,2,3,4$?
Comment: Thanks for the clarification. Are you using mathematica?
Comment: Could I look at your code for this? Mathematica doesn't help itself with solving such equations...


Which Pentatonic "Box #" do you use to switch between Major and Minor?

Question: From m to M: Some guys switch to "Box 2",(from Box 1) others claim "Box 4" (from box 1). Your thoughts please? I've checked out this short John Meyer clip on the subject, you might want to also-

Thanks!
Comment: This strikes me as a matter of personal preference. Could you elaborate on the kind of answer you're looking for?
Comment: True...Clearly, Meyer is maintaining Am Pentatonic by shifting back and forth between Box 1 and Box 5. The only difference where utilizing a major sound is concerned, has to with which note you kick off on w/in "contiguous" shape 5...Many players however, think in terms of kicking off w/ the relative major [A] using a different box- often #2 or #4...it's often taught either box- was curious as to which one others are most comfortable with.
Answer: You use whichever box fits over the sweet spot for your solo. For the minor, you start with the root on the "1" in your diagram. For the major, you start with the root on the "b3" in your diagram.
Honestly though, the classic pentatonic boxes are terribly limiting. Learn the subset pattern shown for the EAD string set: 1 b3 4 5 b7 1 and learn where all the roots of your scale are on the fretboard, in this case where all the Cs are. Remember to shift your pattern up one fret when you cross from the G string to the B string. Now play that short pattern starting on all the Cs. When you have that down, learn to shift your pattern up and down the neck from the root, the 1. Now you can play pentatonics in any position on the neck while only memorizing one pattern.

Alternatively, you could learn the universal pentatonic patterns, remembering to shift up the neck one fret when you cross from the G to the B string.
Minor pentatonic pattern

Major pentatonic pattern


Is this statement about linear-activation neural network in the PRML in error?

Question: I found the following statement in "Pattern Recognition and Machine Learning" (C. M. Bishop, 2016) p.229.

If the activation functions of all the hidden units in a network are taken to be linear, then for any such network we can always find an equivalent network without hidden units. This follows from the fact that the composition of successive linear transformations is itself a linear transformation. However, if the number of hidden units is smaller than either the number of input or output units, then the transformations that the network can generate are not the most general possible linear transformations from inputs to outputs because information is lost in the dimensionality reduction at the hidden units.

However, I think that there are two exceptions: D < M < K, and D > M > K, where D, M, and K are the numbers of input, hidden, and output units respectively.
For example, in the former case, when the input and hidden units are connected by identity matrix (only D of M nodes are used, and others are zero), the neural network (without activation) can represent all possible linear transformation using linear transformation between M and K.
Is my understanding correct?
Answer: The easier way to think of this is as matrices: a two-layer linear-activation neural network (with bias units) can be written
$$
f(x) = W (V x + b) + c = (W V) x + (W b + c)
.$$
Using your notations, the first layer has its weights $V$ of shape $M \times D$ (and bias $b$ of shape $M$), and the second layer has weights $W$ of shape $K \times M$ (and bias of shape $K$).
This is equivalent to a single layer, with linear activations, whose weights are $W V$ of shape $K \times D$ and bias $W b + c$.
Because $c$ can be anything, we can ignore the effect of $W b$ there, and get any bias we want for the equivalent one-layer network.
$W V$ can be any $K \times D$ matrix whose rank is at most $\min(M, K, D)$. So, if $M = K$ or $M = D$, the one-layer network can be any possible matrix. If $M$ is smaller than both $K$ and $D$, then it limits the set of possibilities. So, in your example, if $D < M < K$ then $M$ doesn't actually limit the final outputs.
I don't think Bishop's intended meaning was wrong, but he wrote it in a slightly confusing way: "if the number of hidden units is smaller than either the number of input or output units" should mean "$M < \min(K, D)$", not the perhaps more natural reading of "$M < K$ or $M < D$."


onSaveInstanceState() does not work when the screen is rotated

Question: Possible, my code is correct, but method onSaveInstanceState() does not work when the screen is rotated. The data does not save after activity destroy (onDestroy() worked). However, the method works after methods onPause() and onStop(). There is one element on activity - textView, and I write text when the methods are worked. There is the error? Thank you in advance.
<code>    public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        textView = findViewById(R.id.textView);

        if (savedInstanceState != null)
        {
           textView.setText(savedInstanceState.getString("saveInstance"));
        }

        Log.i("lifecycle show", "onCreate() worked");
        textView.append("onCreate() worked\n");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("lifecycle show", "onStart() worked");
        textView.append("onStart() worked\n");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("lifecycle show", "onResume() worked");
        textView.append("onResume() worked\n");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i("lifecycle show", "onRestart() worked");
        textView.append("onRestart() worked\n");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("lifecycle show", "onPause() worked");
        textView.append("onPause() worked\n");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("lifecycle show", "onStop() worked");
        textView.append("onStop() worked\n");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("lifecycle show", "onDestroy() worked");
        textView.append("onDestroy() worked\n");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i("lifecycle show", "onSaveInstanceState() worked");
        textView.append("onSaveInstanceState() worked\n");
        outState.putString("savedInstance", textView.getText().toString());
    }
}
</code>
Answer: Wrong tag. You put string using "savedInstance" as tag, then get string by tag "saveInstance".
Comment: My God... Thank You so much. It is funny but I'm very ashamed. =)


Trying to unzip a zipfile, then within the folders that result, find and unzip any/all zipfiles

Question: I must use Python 2.6!
This is a task that I really want to automate, the situation is static and once I create this, I'll be golden (good).
I must create one, stand alone script (in Idle, I hope) that will:

Unzip a single original zipfile (in_Zip) to the contents of the folder that the zipfile currently resides.
Go to the unique (NON ZIPPED) folders (actually student usernames 'aforker', 'allisw99', 'btaylor7', etc) that result from step 1. (there may be anywhere from 1 to 40 of these unique student folders)
within each unique folder ('aforker', 'allisw99', 'btaylor7', etc) extract any and all (could be none, could be 3 or 4) .zip files within, to their relative aforementioned unique folders ('aforker', 'allisw99', 'btaylor7', etc), while 'navigating' i.e. not getting hung up on possible .pdf or docx files that may or may not reside in the unique folders ('aforker', 'allisw99', 'btaylor7', etc)

This is what I've got so far: (and it 'works') (I'll modify later so that I do not need to hard-code the original zipfile (in_Zip))
import os, os.path, zipfile
inZip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip'
outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1"

z = zipfile.ZipFile(in_Zip,'a')
z.extractall(outDir)
zipContents = z.namelist()

print zipContents
z.close

It works, I get the following in the Python Shell:
'>>> ================================ RESTART ================================'
'>>>'
['Lab_2/aforker/', 'Lab_2/aforker/aforker_Lab2.zip', 'Lab_2/allisw99/', 'Lab_2/allisw99/allisw99_Lab2.zip', 'Lab_2/allisw99/allisw99_Lab2_Bonus.pdf', 'Lab_2/allisw992/', 'Lab_2/allisw992/allisw99_Lab2_Bonus.pdf', 'Lab_2/btaylor7/', 'Lab_2/btaylor7/2nd_btaylor7_Lab2.zip', 'Lab_2/btaylor7/btaylor7_Lab2.zip', 'Lab_2/']
'>>> '

But, what I can't figure out is how to get 'into' each unique folder: aforker, allisw99, etc. and then extract any and all zips within 'aforker', 'allisw99', etc.
I've had some suggestions on other forums/list serves, but they all involve trashing my current code and doing things in the windows command window, etc.
a) I can't get them to work, and b) it doesn't really help me because I need ONE stand alone .py file to make this all work.
Why? you ask? I will be using this to create an ArcGIS 'tool' that requires one script (at least for me to comprehend it) :-)
Thank you in advance for any and all suggestions, tips etc.
For the record, I did try the following @ the bottom of the code above:
for item in zipContents:
     itemLoc = os.path.join(outDir,item)
     y = zipfile.ZipFile(itemLoc,'a')
     y.extractall(os.path.aplit(itemLoc)[0])
     y.close

but I get the following error:
Traceback (most recent call last):
  File "D:\D_Drive_Documents\Scripts\Unzip_a_zip_of_zips\Scripts\unzip_a_zip.py", line 50, in <module>
    y = zipfile.ZipFile(itemLoc,'a')
  File "C:\Python26\ArcGIS10.0\lib\zipfile.py", line 687, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 13] Permission denied: 'D:\\D_Drive_Documents\\Student_Work_Sample_usecopy1\\Lab_2/aforker/'

Answer: With the help of nnoenneo (the other answerer above or below) Peter Otten, & Oscar Benjamin (on a different (python.org) forum), I was able to come up with the following code that works.
import os, os.path, zipfile, arcpy

in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip'

outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1"

z = zipfile.ZipFile(in_Zip,'r')

z.extractall(outDir)

zipContents = z.namelist()
z.close()

for item in zipContents:
    if item.endswith('.zip'):
        fullpath = os.path.join(outDir, item)
        x = zipfile.ZipFile(fullpath,'r')
        dest_path = os.path.dirname(fullpath)
        x.extractall(dest_path)
        x.close()

If creating a tool in Esri's ArcGIS, one would have to replace the 'in_Zip' line with:
in_Zip = arcpy.GetParameterAsText(0)
and the 'outDir' line with:
outDir = os.getcwd()
and then in the properties of the tool in ArcGIS browse to the .py file that contains the code above.
Special Thanks to Peter Otten and Oscar Benjamin on python.org who have been helping me struggle through this since August 7th 2012!
Regards,
Greg
Comment: note: a maliciously created (or out of ignorance) zip archive can overwrite files outside `outDir`. Check that `item` is not an absolute path or there is no ".." in it.
Answer: That extra code almost works, but you'll want to make sure you're unzipping a zip file (and not, say, a directory):
for item in zipContents:
     if item.endswith('.zip'):
         itemLoc = os.path.join(outDir,item)
         y = zipfile.ZipFile(itemLoc,'a')
         y.extractall(os.path.split(itemLoc)[0]) # This is going to unzip to C:\\ -- you will want to change that
         y.close()


Largest singular values

Question: Given the positive semi-definite, symmetric matrix $A = bb^T + \sigma^2I$ where b is a column vector is it possible to find the singular values and singular vectors of the matrix analytically? I know that it has real eigenvalues since it's symmetric and positive semidefinite but not sure about solving directly for those values and their corresponding vectors.
Comment: What is $b$?  Would it be a column vector, a rectangular matrix, or a square matrix?  Since the singular values are well defined mathematically and loads of software exists to find them, please explain what you mean by "is it possible to find."
Comment: $b$ is a column vector and I mean an analytical solution
Answer: The singular values are the eigenvalues of $A.$ By definition, when there exists a nonzero vector $\mathbf x$ for which $A\mathbf{x}=\lambda \mathbf{x},$ $\lambda$ is an eigenvalue and $\mathbf{x}$ is a corresponding eigenvector.
Note, then, that
$$A\mathbf{b} = (\mathbf{b}\mathbf{b}^\prime + \sigma^2I)\mathbf{b} = \mathbf{b}(\mathbf{b}^\prime \mathbf{b}) + \sigma^2 \mathbf{b} = (|\mathbf{b}|^2+\sigma^2)\mathbf{b},$$
demonstrating that $\mathbf{b}$ is an eigenvector with eigenvalue $\lambda_1 = |\mathbf{b}|^2 + \sigma^2.$
Furthermore, whenever $\mathbf{x}$ is a vector orthogonal to $\mathbf{b}$ -- that is, when $\mathbf{b}^\prime \mathbf{x} = \pmatrix{0},$ we may similarly compute
$$A\mathbf{x} = (\mathbf{b}\mathbf{b}^\prime + \sigma^2I)\mathbf{x} = \mathbf{b}(\mathbf{b}^\prime \mathbf{x}) + \sigma^2 \mathbf{x} = (0+\sigma^2)\mathbf{x},$$
showing that all such vectors are eigenvectors with eigenvalue $\sigma^2.$
Provided these vectors are in a finite dimensional vector space of dimension $n$ (say), a straightforward induction establishes that the vectors $x$ for which $\mathbf{b}^\prime \mathbf{x}=0$ form a subspace $\mathbf{b}^\perp$ of dimension $n-1.$  Let $\mathbf{e}_2, \ldots, \mathbf{e}_n$ be an orthonormal basis for this subspace.  It extends to an orthonormal basis $\mathscr{E} = (\mathbf{\hat  b}, \mathbf{e}_2, \ldots, \mathbf{e}_n)$ of the whole space where $\mathbf{\hat b} = \mathbf{b}/|\mathbf{b}|$.  In terms of this basis the matrix of $A$ therefore is
$$\operatorname{Mat}(A, \mathscr{E}, \mathscr{E}) = \pmatrix{|\mathbf{b}|^2+\sigma^2 & 0 & 0 & \cdots & 0 \\
0 & \sigma^2 & 0  & \cdots & 0 \\
0 & 0 & \ddots & \vdots & \vdots \\
\vdots & \vdots & \cdots & \ddots & 0 \\
0 & 0 & \cdots & 0 & \sigma^2
}$$
Whether or not every step of this derivation was clear, you can verify the result by setting
$$Q = \left(\mathbf{b}; \mathbf{e}_2; \ldots; \mathbf{e}_n\right)$$
to be the matrix with the the given columns and computing
$$Q\,\operatorname{Mat}(A, \mathscr{E}, \mathscr{E})\,Q^\prime = \mathbf{b}^\prime + \sigma^2I = A.$$
This is explicitly a singular value decomposition of the form $U\Sigma V^\prime$ where $V=Q,$ $\Sigma= \operatorname{Mat}(A, \mathscr{E}, \mathscr{E}),$ and $U=Q^\prime.$
The Gram Schmidt process provides a general algorithm to find $\mathscr{E}$ (and therefore $Q$): its input is the series of vectors $\mathbf{\hat b}$, $(1,0,\ldots,0)^\prime,$ and so on through $(0,\ldots,0,1)^\prime.$  After $n-1$ steps it will produce an orthonormal basis including the starting vector $\mathbf b.$

As an example, let $\mathbf{b} = (3,4,0)^\prime.$ With $\sigma^2 = 1,$ compute
$$\mathbf{b}\mathbf{b}^\prime + \sigma^2 I = \pmatrix{10&12&0\\12&17&0\\0&0&1}$$
Here, $|\mathbf{b}|^2 = 3^2+4^2+0^2=5^2,$ so that $\mathbf{\hat b} = \mathbf{b}/5 = (3/5,4/5,0)^\prime.$  One way to extend this to an orthonormal basis is to pick $\mathbf{e}_2 = (-4/5,3/5,0)^\prime$ and $\mathbf{e}_3 = (0,0,1)^\prime.$  Thus
$$Q = \pmatrix{3/5&4/5&0\\-4/5&3/5&0\\0&0&1}$$
and we may confirm that
$$\begin{align}
Q\,\operatorname{Mat}(A, \mathscr{E}, \mathscr{E})\,Q^\prime &= \pmatrix{3/5&4/5&0\\-4/5&3/5&0\\0&0&1}\pmatrix{5^2+1^2&0&0\\0&1&0\\0&0&1}\pmatrix{3/5&-4/5&0\\4/5&3/5&0\\0&0&1}\\
&=\pmatrix{10&12&0\\12&17&0\\0&0&1}
\end{align}$$
as intended.

Largest singular values


Does the integral $\int_0^t \frac{x}{(b^2x^2+1)^2} \sin(ax)dx$ converge?

Question: I tried to compute this integral in Python, but it shows no results.
I used the integration by parts and it led to the following integral
$\displaystyle \int_0^t \frac{\cos(ax)}{b^2x^2+1} \,dx$, which is still complicated.
Comment: It converges since the integrand is continuous for all $x$.
Comment: Do you mean converges as $t\to\infty?$
Comment: Even if $t\to\infty$ as @ThomasAndrews suggested, it still converges because it's basically $\int_1^\infty 1/x^2$.
Answer: The integral exists, as commented, because the integrand is continuous on $[0,t]$.  However, it is not an elementary function, so your basic methods of integration won't evaluate it for you.
Maple says (if $a>0,b>0$) the value of the integral is
$$
\frac {1}{2\,b} \left( -i\cosh \left( {\frac {a}{b}} \right) {\it Ci}
 \left( -{\frac {a \left( -bt+i \right) }{b}} \right) +{\it Si}
 \left( {\frac {a \left( -bt+i \right) }{b}} \right) \sinh \left( {
\frac {a}{b}} \right)\\ +i\cosh \left( {\frac {a}{b}} \right) {\it Ci}
 \left( {\frac {a \left( bt+i \right) }{b}} \right) +\pi\,\cosh
 \left( {\frac {a}{b}} \right) -{\it Si} \left( {\frac {a \left( bt+i
 \right) }{b}} \right) \sinh \left( {\frac {a}{b}} \right)  \right)
$$
Here, $Si$ and $Ci$ are the
Sine Integral and Cosine Integral functions.
The limit as $t \to +\infty$ is
$$
-{\frac {\pi}{2\,b} \left( \sinh \left( {\frac {a}{b}} \right) -\cosh
 \left( {\frac {a}{b}} \right)  \right) }
=
{\frac {\pi}{2\,b}{{\rm e}^{-{a/b}}}}
$$
Comment: If we are in the real domain what would be the expresssion of the integral for all variables real positif
Answer: I don't see why do we have to evaluate the integral to prove convergence.
We just write $|\int_{0}^{t}\dfrac{xsinaxdx}{(b^{2}x^{2}+1)^{2}}|$ $\leq$
$\int_{0}^{t}|\dfrac{xsinaxdx}{(b^{2}x^{2}+1)^{2}}|$ $\leq$$\int_{0}^{t}\dfrac{x|sinax|dx}{(b^{2}x^{2}+1)^{2}}$
$\leq$$\int_{0}^{t}\dfrac{xdx}{(b^{2}x^{2}+1)^{2}}$=$\dfrac{1}{2}\int_{0}^{t}\dfrac{d(x^{2})}{(b^{2}x^{2}+1)^{2}}$=
$\dfrac{1}{2b^{2}}\int_{0}^{t}\dfrac{d(b^{2}x^{2}+1)}{(b^{2}x^{2}+1)^{2}}$
=$\dfrac{1}{2b^{2}}$$[-\dfrac{1}{(b^{2}x^{2}+1)}]_{0}^{t}$=$-\dfrac{1}{2b^{2}}(\dfrac{1}{b^{2}t^{2}+1}-1)$
which converges to $\dfrac{1}{2b^{2}}$ as $t\to +\infty$.
Now consider the case $b=0$. Then the integral for $a=0$ clearly converges since it is zero.
If $a\neq\,0$ then the integral is equal to:$\dfrac{sinat-atcosat}{a^{2}}$
which does not converge.