text:
Q: Can't Plot Graph from training Model in Multi classification Help me solve the problem/error the graph could not be plotted, i am a python beginner
ValueError: x and y must have same first dimension, but have shapes (100,) and (938,)
My code is below
#code

mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]))
mnist_testset = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()]))

mnist_valset, mnist_testset = torch.utils.data.random_split(mnist_testset, [int(0.9 * len(mnist_testset)), int(0.1 * len(mnist_testset))])

train_dataloader = torch.utils.data.DataLoader(mnist_trainset, batch_size=64, shuffle=True)
val_dataloader = torch.utils.data.DataLoader(mnist_valset, batch_size=32, shuffle=False)
test_dataloader = torch.utils.data.DataLoader(mnist_testset, batch_size=32, shuffle=False)

print("Training dataset size: ", len(mnist_trainset))
print("Validation dataset size: ", len(mnist_valset))
print("Testing dataset size: ", len(mnist_testset))

# visualize data
fig=plt.figure(figsize=(20, 10))
for i in range(1, 6):
  img = transforms.ToPILImage(mode='L')(mnist_trainset[i][0])
  fig.add_subplot(1, 6, i)
  plt.title(mnist_trainset[i][1])
  plt.imshow(img, cmap="gray")
plt.show()

#model = Model()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.1)

if (torch.cuda.is_available()):
  model.cuda()

no_epochs = 100
train_loss = list()
val_loss = list()
best_val_loss = 1
for epoch in range(no_epochs):
  total_train_loss = 0
  total_val_loss = 0

  model.train()

  # training
  for itr, (image, label) in enumerate(train_dataloader):

      if (torch.cuda.is_available()):
          image = image.cuda()
          label = label.cuda()

      optimizer.zero_grad()

      pred = model(image)

      loss = criterion(pred, label)
      total_train_loss += loss.item()

      loss.backward()
      optimizer.step()

  total_train_loss = total_train_loss / (itr + 1)
  train_loss.append(total_train_loss)

I searched all previous issues and could not get through about the solutions
I have posted the code


text:
Q: Electrical network of current sources - What happens if one source is defect? Suppose you have connected in a parallel circuit a pair of, say for the sake of concretness 5 sources of 300 mA and 0,5 V each, which are themselves connected together in series. Hence, in total one has 10 sources.
I am wondering what happens if one of these sources is defect, i.e. is formally replaced by a infinitely high resistor? More concretely, I'm interested in the change of the    open-circuit voltage.
After some thoughts about this problem I came to the conclusion that the voltage should decrease compared to a series of 5 sources, although more sources are involved. I expect that at each end of the parallel circuit one obtains the average of both potential values, where on the defect side only the sources right respectively left to the defect source are counted.
In particular, the open-circuit voltage should depend on the position of the defect source in the circuit.
Could you check my thoughts and give me a clear explanation?

A: As I understand your question, you have a set of 5 'good' sources in series.  You also have 4 'good' sources and 1 source that starts out 'good' but turns into an infinite resistor, which are in series.  You connect the two sets in parallel, and then measure the open-circuit voltage between the two ends.
The short answer is that nothing would happen to the voltage, though if you attached a load the current would change.
Potential difference is path-independent, so consider going from one end of the 'good' branch to the other end, through 5 sources.  Before and after the 'bad' branch was changed, the voltage through the 'good' branch is still due to the 5 sources, with 2.5 V total.
However, suppose we have these sources connected to a 5 Ohm resistor.  In your initial setup (all 10 sources are 'good'), the voltage across the resistor is 2.5 V, so the current through the resistor is 0.5 A.  The two branches of sources are identical, so 0.25 A flows through each side.
Now break one of the sources so it become an open circuit with infinite resistance.  The voltage across the network of sources is the same, so the voltage across the resistor is the same.  The current through the resistor is also the same, but now it's all coming from the 'good' branch, so the current through the 'good' branch has doubled to 0.5 A.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When is a vtable destroy in C++? Is calling a virtual function in the destructor of a base class is a good practice? And "Does vtable exist in destruction time? And is calling a virtual function in the destructor recommended?"

A:
Can I call a virtual function in the destructor of a base class?

Calling virtual functions from destructors or constructors is a bad practice. See the standard (emphasis mine):

12.7 Construction and destruction....
  Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2).
  When a virtual function is called directly or indirectly from a constructor or from a destructor, including
  during the construction or destruction of the class's non-static data members, and the object to which the
  call applies is the object (call it x) under construction or destruction, the function called is the final overrider
  in the constructor's or destructor's class and not one overriding it in a more-derived class. If the virtual
  function call uses an explicit class member access (5.2.5) and the object expression refers to the complete
  object of x or one of that object's base class subobjects but not x or one of its base class subobjects, the
  behavior is undefined.

You can find this recommendation in many sources, including Scott Meyers'
Effective C++: 55 Specific Ways to Improve Your Programs and Designs
(Item 9: Never call virtual functions during construction or destruction.)
or Herb Sutter's
C++ Coding Standards: 101 Rules, Guidelines, and Best Practices (49. Avoid calling virtual functions in constructors and destructors).

A: Yes, the object will have a pointer to its vtable when you call the destructor.
The standard explicitly says it is possible to call virtual functions in the destructor, and says what happens.  There is agreement that even though it is allowed it is a bad practice, because it is inherently brittle code that leads to surprises with apparently innocent changes.
If you have that DerDer inherits from Der, which inherits from Base, all of them override member function void member(), and you are in the destructor of Der, and call member(), you are calling Der::member(), not DerDer::member(), because the DerDer part of your object is GONE, DESTROYED already.  A base class can refer inadvertently to data in a derived class, for example:
struct Base {
    int *ip;
    Base(int *ip): ip(ip) {}
    virtual void useInt() { std::cout << *ip << std::endl; }
    ~Base() { useInt(); }
};
struct Der: Base {
    int theInt;
    Der(): Base(&theInt) {}
    void useIntPointer() override { std::cout << theInt << std::endl; }
};

When an object of type Der gets deleted, there is "undefined behavior":  First the implicit destructor of Der is called, then the explicit destructor of Base, Base::~Base.  At that point Base::ip is referring to a member of Der that has already been destroyed.


text:
Q: Can't upload a file with asp:FileUpload For some reason, I'm unable to upload a file with the <asp:FileUpload /> control. I know it's not just something completely pooched, because I created a new project with this code in it and that uploaded the file.
My code looks like this (some bits removed...):
<form id="querydata" runat="server" enctype="multipart/form-data">

        <asp:ScriptManager ID="queryscriptmanager" runat="server" />
        <asp:UpdatePanel runat="server" ID="querypanel" UpdateMode="Conditional">
        <ContentTemplate>

                    <asp:FileUpload runat="server" ID="Directory" Width="194" />

               <asp:Button runat="server" ID="Submit" Text="Update Database" onclick="checkForm"  />

        </ContentTemplate>
        </asp:UpdatePanel>

</form>

If I go select a file, then click the submit button, once the execution makes it to checkForm, Directory.FileName is "" and Directory.HasFile is False
Any clue why it won't send my file?

SOLVED:
All I had to do (per the blog post in the accepted answer) was add three lines:
</ContentTemplate>
<Triggers>
   <asp:PostBackTrigger ControlID="Submit" />
</Triggers>

</asp:UpdatePanel>

A: The problem is the UpdatePanel.  http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx#using_the_FileUpload_Control_with_the_UpdatePanel_control.
An excellent blog post that will help you fix it:
http://geekswithblogs.net/mmintoff/archive/2009/04/01/fileupload-within-updatepanel.aspx


text:
Q: Setting different compiler flags when "Running" and "Debugging" app I would like my native code to run -O3 optimisation whenever I hit "Run (Shift+F10)" in Android Studio and -O0 when I hit "Debug (Shift+F9)". How would I achieve this in CMakeLists or in build.gradle for my app?
I couldn't find what I am looking for through Google.
Any help is appretiated!


text:
Q: When using HtmlUnit, how can I configure the underlying NekoHtml parser? I'm using HtmlUnit to try and scrape a webpage because of it's Javascript support.  (I'd rather use Jsoup, but no JS support).
The issue relates to a feature of the underlying NekoHtml parser:
    "http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe"
See: http://nekohtml.sourceforge.net/settings.html
This can apparently be enabled in Neko, but I'm using HtmlUnit.  Is there a way to configure the underlying Neko parser that HTML unit is using to enable this feature?
When attempting to run this code:
final WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(url.toString());

I'm getting this error:
Caused by: com.gargoylesoftware.htmlunit.ObjectInstantiationException: unable to create HTML parser
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.<init>(HTMLParser.java:418)
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.<init>(HTMLParser.java:342)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:203)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:179)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:221)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:106)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:433)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:373)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:358)
    at
Caused by: org.xml.sax.SAXNotRecognizedException: Feature 'http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe' is not recognized.
    at org.apache.xerces.parsers.AbstractSAXParser.setFeature(Unknown Source)
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.<init>(HTMLParser.java:411)
    ... 41 more

A: try initializing the web client with FF behavior
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);

and activate javascript
webClient.setJavaScriptEnabled(true);

it should be ok then.

A: Solved...
    BrowserVersionFeatures[] bvf = new BrowserVersionFeatures[1];
    bvf[0] = BrowserVersionFeatures.HTMLIFRAME_IGNORE_SELFCLOSING;
    BrowserVersion bv = new BrowserVersion(
            BrowserVersion.NETSCAPE, "5.0 (Windows; en-US)",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8",
            (float) 3.6, bvf);

    WebClient webClient = new WebClient(bv);
    webClient.setJavaScriptEnabled(true);


text:
Q: Lunch TDCH to Load to load data from Hive parquet table to Teradata I need to load data from Hive tables which stored as parquet files to Teradata Database using TDCH(Teradata connector for Hadoop). I use TDCH 1.5.3 and CDH 5.8.3. and Hive 1.1.0
I try to start TDCH usign hadoop jar command and getting the Error:

java.lang.ClassNotFoundException:
  org.apache.parquet.hadoop.util.ContextUtil

Is anybody have any idea why it's happened?

A: When looking at your problem that you might not have all Hive Libraries needed to be able to upload to Teradata.
Here is a example of script that could be used for exporting from Hive to TD.
#!/bin/bash

## Declare Hive Source and Teradata Target
Source_Database="???"
Source_Table="???"
Target_Database="???"
Target_Table="???"
JDBC="???"

## Format
Format="???"

## Declare User used to Connect and Load Data
MYUSER="???"
MYPASSWORD="???"

## Display configuration libraries.
echo $USERLIBTDCH
echo $LIB_JARS

## Define the connection option
hadoop jar $USERLIBTDCH \
com.teradata.connector.common.tool.ConnectorExportTool \
-libjars $LIB_JARS \
-url jdbc:teradata://$JDBC/logmech=ldap,database=$Target_Database,charset=UTF16 \
-username $MYUSER \
-password  $MYPASSWORD \
-jobtype hive \
-fileformat $Format \
-sourcedatabase $Source_Database \
-sourcetable $Source_Table \
-targettable $Target_Table \
-method internal.fastload \
-nummappers 1`

Before using this script you need to check if the libraries that you put into hadoop jars are configured. This means that all Path variables are set and as follows by calling (use your variable name)
echo $USERLIBTDCH

Expected output of the PATH Variable (This is how it looks in Cloudera Enviroment)
/opt/cloudera/parcels/CDH/lib/avro/avro.jar,
/opt/cloudera/parcels/CDH/lib/avro/avro-mapred-hadoop2.jar,
/opt/cloudera/parcels/CDH/lib/hive/conf,
/opt/cloudera/parcels/CDH/lib/hive/lib/antlr-runtime-3.4.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/commons-dbcp-1.4.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/commons-pool-1.5.4.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/datanucleus-api-jdo-3.2.6.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/datanucleus-core-3.2.10.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/datanucleus-rdbms-3.2.9.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/hive-cli.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/hive-exec.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/hive-jdbc.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/hive-metastore.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/jdo-api-3.0.1.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/libfb303-0.9.2.jar,
/opt/cloudera/parcels/CDH/lib/hive/lib/libthrift-0.9.2.jar,
/opt/cloudera/parcels/CDH/lib/hive-hcatalog/share/hcatalog/hive-hcatalog-core.jar,
/opt/jars/parquet-hadoop-bundle.jar

I would probably expect that the Path Variable is not properly set. For this your could use the following command. To create all the necesseary paths.
PATH=$PATH:~/opt/bin
PATH=~/opt/bin:$PATH

If you look at the Teradata Connector Documentation you need to specify the following libraries.
  Hive Job(version 0.11.0 as example):
         a) hive-metastore-0.11.0.jar
         b) hive-exec-0.11.0.jar
         c) hive-cli-0.11.0.jar
         d) libthrift-0.9.0.jar
         e) libfb303-0.9.0.jar
         f) jdo2-api-2.3-ec.jar
         g) slf4j-api-1.6.1.jar
         h) datanucleus-core-3.0.9.jar
         i) datanucleus-rdbms-3.0.8.jar
         j) commons-dbcp-1.4.jar
         k) commons-pool-1.5.4.jar
         l) antlr-runtime-3.4.jar
         m) datanucleus-api-jdo-3.0.7.jar

    HCatalog Job:
         a) above Hive required jar files
         b) hcatalog-core-0.11.0.jar

Hope this helps.


text:
Q: "In case" vs "if"? I was taught that "in case" does not mean "if". As in:

*

*I will give you my card in case you need it. (Take it and use in case of need in the future)

*I will give you my card if you need it. (When you need it, I will give it to you.)

But then I do not understand the following:

In case you have seen this man...

Should it not be if?

A: I don't think it's inherently incorrect. Depending on the context you could use in case in a sentence in a past tense (e.g. Please check your phone's pictures in case you have seen this man but didn't notice).
I think it's just the sentence you chose makes it hard to find a fitting context.
With this I don't mean to imply that if and in case are interchangeable, just that you could use in case in that sentence without it being incorrect.


text:
Q: ShellCheck doesn't check files with .sh extension (or any custom ones) I have the following in my pre-commit:
---
repos:
- repo: local
  hooks:
  - id: shellcheck
    name: shellcheck
    entry: shellcheck
    language: system
    types: [file, bash]
    files: \.(sh\.j2|sh)$

For some reason it doesn't detect e.g. script.sh in the top directory of my git repo, or in any sub folder. However, when I remove the files: line, it is able to find Bash files. But only if there is no .sh extension. What am I doing wrong here? In theory I wouldn't even need the files: line, because my scripts do have the shebang (#!/bin/bash). But when the .sh is included, it doesn't recognize those files.
The software versions:
rpm -qa pre-commit ShellCheck
ShellCheck-0.7.2-5.fc36.x86_64
pre-commit-2.20.0-1.fc36.noarch

A: from the docs:

types, types_or, and files are evaluated together with AND when filtering

since types: [bash] anded with files: \.sh\.j2 is an empty set those files won't match

disclaimer: I wrote pre-commit


text:
Q: Docker for Desktop error during connect: Post A connection attempt failed because the connected party did not properly I have freshly installed Docker for Desktop Edge in Windows 10 Home and try to build an image using the docker build command. But unfortunately, it didn't work for me, and got the below error :
CMD -   docker build -t heet1996/post:0.0.1 .
error during connect: Post https://192.168.99.100:2376/v1.40/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&session=na8ugnpn6d8gnxl3z8ppx4gap&shmsize=0&t=heet1996%2Fpost%3A0.0.1&target=&ulimits=null&version=1: dial tcp 192.168.99.100:2376: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Earlier I was using a docker toolbox so I had to remove all the environment variables related to the Docker in my User variables before installing Docker for Desktop. After a lot of search on GitHub issues, I am still not getting the solution.
This is what I found in my service.txt file (C:\ProgramData\DockerDesktop\service.txt)
[18:27:22.232][LoggingMessageHandler][Info   ] [f9b6b957] <Server end> POST http://localhost/dns/refresh-hosts -> 204 NoContent (took 118ms)

A: I got this error when i un-installed the docker toolbox and installed the docker desktop.
System Configuration:
OS: Windows 10 Home
Version: 21H1
Steps I Followed:

*

*Un-installed the docker desktop.

*Removed the all dockers related environment variables from the user variables.
Navigation: This System-> Properties-> Advance System Settings-> Environment Variables-> User Variables.

*Re-installed the docker desktop and it's started working properly.

A: Try to run it on Docker CLI instead of CMD

A: Docker for windows must have:

*

*[✓] Updated Windows 10 version >=2004

*[✓] WSL 2 and Default Distro (i.e ubuntu)

The steps are well documented here. These are what to do after the installation:

*

*To confirm ubuntu's installation, open C:/Windows/System32/bash.exe aka bash.

*To test if docker is properly installed, run docker version on bash. This should print the docker client and server engine.

*After successfully tested and confirmed the installations, try entering your command

$ docker build -t heet1996/post:0.0.1 .

A: Open Powershell as Administrator and run the below commands
cd "C:\Program Files\Docker\Docker"
./DockerCli.exe -SwitchDaemon

A: here we are talking about using Docker with PowerShell and not with WSL. And also following the addition of variables in the environment variables of Windows.
Configuration when this response was made:

*

*Windows 10 Pro 20H2 (Build 19042.867)

*Docker 20.10.5

*Powershell 5.1.19041.610
I also had to configure docker in a dirty way too much, after several hours of research and a comparison of installation on a clean Windows 10 I understood where my error was.
In addition to the user environment variable also make sure that you do not have DOCKER variables in the Windows system environment variables either.
Here is where my error was, I think it was due to the installation of the Docker module

I had the DOCKER_HOST variable in my system variable environment, so i deleted it.
If you want to check all your environment variables with Powershell:
[System.Environment]::GetEnvironmentVariables()

If you really want a Docker fresh installation on Windows, you need to delete the following folders:
C:\ProgramData\Docker
C:\Program Files\Docker\Docker
$HOME\AppData\Local\Docker
$HOME\AppData\Roaming\Docker
$HOME\AppData\Roaming\Docker Desktop
$HOME\.docker

my error, therefore, produced this error:
ERROR ==> error during connect: Get http://docker.artofshell:2376/v1.24/version: dial tcp: lookup docker.artofshell: no such host

After a complete uninstall of all docker (Via chocolatey, official docker ...) and by properly installing Docker from the official executable here everything is back to normal
Then if you want to use docker via Powershell you have to change the configuration of DockerCLI as you can see on many answers

Conclusion

*

*It is possible to use docker with Powershell you must check if the
server daemon is used by Windows/amd64, you can modify the daemon with this command cd "C:\Program Files\Docker\Docker"; .\DockerCli.exe  -SwitchDeamon

*You can check the configuration of the daemon with the following command: docker version

*You must remove all traces of old Docker installations if you had any

*You must delete the environment variables from the old installation or from the docker toolbox

*You must also activate the experimental features: information here


text:
Q: Finding the indexes of an element of 9x9 array that is divided into nine 3x3 arrays In order to create an ultimate tic-tac-toe game, which includes a 9x9 array that is divided into nine 3x3 sub-arrays.
Each sub-array is numbered in the following manner:

And I want to create a function that if the user for example enters two parameters, it goes to the cell in the 9x9 matrix, (or gives back the indexes).
For example, if I enter 2,2: I go to the second 3x3 matrix, and there I go to the second cell, which means I end up in cell [0,4] in the 9x9 matrix.
I'm writing the code in the C language.
All I ended up with is making a big function with many loops that takes me directly to the wanted cell, but its too much I think, I would be happy for a simpler way to do that.
Any ideas?
The following code is just the start of what I did.
I divided the 9x9 matrix into three columns, and each time I deal with a column according to the number from 1-9 the user chosen for sub array, and from there I go to a series of functions for each sub array to find the proper place. It's too complicated and long, and that's the problem of my code. That's why I'm searching for an alternative.
int Insert_Move(char player, char GameBoard[Lines][Columns], int chosen_pos,
                int next_subboard)

{
    if(next_subboard == 3 || next_subboard == 6 || next_subboard == 9)
        return First_Column_9x9(player, GameBoard, chosen_pos, next_subboard);

    if(next_subboard == 2 || next_subboard == 5 || next_subboard == 8)
        return  Second_Column_9x9(player, GameBoard, chosen_pos, next_subboard);

    if(next_subboard == 1 || next_subboard == 4 || next_subboard == 7)
        return Third_Column_9x9(player, GameBoard, chosen_pos, next_subboard);

    return 1; /* Success */
}

A: In the two-dimensional array as:
X coordinate = ((p1-1)℅3)*3 + (p2-1)℅3;
Y coordinate = ((p1-1)/3)*3 + (p2-1)/3;

A: Here is a function that takes an array of two size_t values to store the indices of the cell, and the two position arguments given by the user. It finds the indices for the given positions in a zero-indexed 3X3 array, and then combines these results to produce the indices in the 9X9 array.
I put it in a little program to test a couple of inputs:
#include <stdio.h>

void get_index(size_t indices[2], int pos, int sub_board);

int main(void)
{
    size_t indices[2];
    int pos, sub_board;

    pos = 2;
    sub_board = 2;

    get_index(indices, pos, sub_board);

    printf("Cell indices are: [%zu][%zu]\n", indices[0], indices[1]);

    pos = 6;
    sub_board = 9;

    get_index(indices, pos, sub_board);

    printf("Cell indices are: [%zu][%zu]\n", indices[0], indices[1]);

    return 0;
}

void get_index(size_t indices[2], int pos, int sub_board)
{
    size_t row_pos, col_pos;
    size_t row_sub, col_sub;

    row_pos = (pos - 1) / 3;
    col_pos = (pos - 1) % 3;
    row_sub = (sub_board - 1) / 3;
    col_sub = (sub_board - 1) % 3;

    indices[0] = 3 * row_sub + row_pos;
    indices[1] = 3 * col_sub + col_pos;

}

Output:
Cell indices are: [0][4]
Cell indices are: [7][8]


text:
Q: JavaScript manipulate string problem var a
var a = "ACdA(a = %b, ccc= 2r2)";

var b
var b = "\ewfsd\ss.jpg"

Expected outputs:
var c = "ACdA(a = %b, ccc= 2r2, b_holder = \ewfsd\ss.jpg)"

It adds the string b to the end of string a, that's it! But be careful of the ")"
"b_holder " is hard coded string, it's absolutly same in all cases, won't be changed.
Thanks everyone!

A: You need to do two things:

*

*Concatenate ", b_holder = " to var b, and

*Replace ")" in var a with the result of the concatenation.

Since this is homework, I'll leave it to you to figure out which methods to use. Good luck!
Hint: you can either store the result of the concatenation in step (1) in another variable, or you can do it all in one line.
Edit: You also need to concatenate the ")" back onto the end. So maybe three things. :-)

A: You still don't show any code for what you're doing with a and b to produce c; you are just showing a simple assignment of the expected (desired) value.
You have a problem, however with the value you're assigning to var b -- because the backslash \ is an escape.  If you want a backslash in the actual string you need to double it, so your assignment would be
var b = "\\ewfsd\\ss.jpg";

A: var a = "ACdA(a = %b, ccc= 2r2)";
var b = "\\ewfsd\\ss.jpg"; // need to escape the backslash for RegExp replace
var re = /\)$/;
var c = a.replace(re, ", b_holder = "+b+"\)");


text:
Q: Matplotlib plotting data that doesnt exist I am trying to plot three lines on one figure. I have data for three years for three sites and i am simply trying to plot them with the same x axis and same y axis. The first two lines span all three years of data, while the third dataset is usually more sparse. Using the object-oriented axes matplotlib format, when i try to plot my third set of data, I get points at the end of the graph that are out of the range of my third set of data. my third dataset is structured as tuples of dates and values such as:
data=
[('2019-07-15', 30.6),
 ('2019-07-16', 20.88),
 ('2019-07-17', 16.94),
 ('2019-07-18', 11.99),
 ('2019-07-19', 13.76),
 ('2019-07-20', 16.97),
 ('2019-07-21', 19.9),
 ('2019-07-22', 25.56),
 ('2019-07-23', 18.59),
 ...
 ('2020-08-11', 8.33),
 ('2020-08-12', 10.06),
 ('2020-08-13', 12.21),
 ('2020-08-15', 6.94),
 ('2020-08-16', 5.51),
 ('2020-08-17', 6.98),
 ('2020-08-18', 6.17)]

where the data ends in August 2020, yet the graph includes points at the end of 2020. This is happening with all my sites, as the first two datasets stay constant knowndf['DATE'] and knowndf['Value'] below.
Here is the problematic graph.
And here is what I have for the plotting:
fig, ax=plt.subplots(1,1,figsize=(15,12))
fig.tight_layout(pad=6)

ax.plot(knowndf['DATE'], knowndf['Value1'],'b',alpha=0.7)
ax.plot(knowndf['DATE'], knowndf['Value2'],color='red',alpha=0.7)
ax.plot(*zip(*data), 'g*', markersize=8) #when i plot this set of data i get nonexistent points
ax.tick_params(axis='x', rotation=45) #rotating for aesthetic
ax.set_xticks(ax.get_xticks()[::30]) #only want every 30th tick instead of every daily tick

I've tried ax.twinx() and that gives me two y axis that doesn't help me since i want to use the same x-axis and y-axis for all three sites. I've tried not using the axes approach, but there are things that come with axes that i need to plot with. Please please help!


text:
Q: Fabric : pipe task's output as another task input I'd like to chain two tasks :

*

*the first one creates an archive (create_archive) with an arbitrary name

*the second one uploads an archive to a FTP server (upload_archive)

I'd like to invoke them like this : fab create_archive upload_archive
Is there a way/syntax to automatically pass the create_archive's output to the upload_archive's output like the bash | character does ?
Thanks in advance

A: Doesn't seem like it. I don't see any mentions in the fabric docs either at http://docs.fabfile.org/en/1.10/.
The closest thing I can think of is managing state with an outside variable, say something attached to env or a global variable in the module.
i.e.:
from fabric.api import run, env, task

@task
def setup():
    env.hosts = ['localhost']

env.counter = 1
env.lines = ""

@task
def task1():
    env.counter += 1
    result = run("seq {}".format(env.counter))
    env.lines += "#task1\n{}".format(result)

@task
def task2():
    env.counter += 1
    result = run("seq {}".format(env.counter))
    env.lines += "#task2\n{}".format(result)

@task
def task3():
    print repr(env.lines)

# fab setup task1 task2 task3

Then in the shell:
$ fab setup task1 task2


text:
Q: MySqli Inserting mass data I am working on a PHP script that will be mass inserting data into a table.
I am using a prepared statement like this:
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
            VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement

$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);

After that I have a while loop that will be executing a lot of queries(hundreds of thousands or even a couple of million!) and the data in them is quite big! The playerjson is a huge json array.
The data will be received from a JSON response from a website API.
I looked at transactions but they ended up with a 502 Bad Gateway which I assume is because of too much data in memory. It isn't timeout problems because I handled them in nginx and ini_set
So what is the quickest way to mass insert large amounts of data?

A: The quickest way is LOAD DATA INFILE.  Consider creating a file !
But in your case create a tempory table
create table clans_temp like clans;

and insert into that. THEN update the original in one query and delete the temporary table.
As far a i know that is the quickest way given the restrictions of the question.


text:
Q: Is it possible to use Jquery AJAX with PHP using MVC architecture?
The problem is that I have recently found out about MVC, and I want to port my current project to use the MVC architecture. My current project uses Jquery AJAX to handle most of the calls and I dont want to just scrap my js code. I'm pretty much a beginner so I was wondering if there was anyway to use Jquery AJAX with PHP if I'm following the MVC architecture. If there is how would I go about handling it. Also I am aware of prewritten frameworks, but I find the concepts easier to understand if I write my own code for the 1st project.

A: Of course that's possible.
I usually create folders in my project such as: Model, View, Static and two PHP files index.php and Controller.php. Also I found out recently that it's better to create one controller for each class but I think that for small learning projects one controller is enough and even for bigger projects it doesn't go against MVC philosophy.
So imagine you have html form, from where you want to register new Note.
notes.html
<form method="POST" action="Controller.php">
    <input type="text" class="form-control" name="title"/>
    <input type="text" class="form-control" name="description"/>
    <input type="Button" value="Add" onclick="addNote();"/>
</form>

ajax.js
function addNote()
{
    var formElements = document.querySelectorAll(".form-control");
    var formData = new FormData();
        formData.append("Code", "1");
        formData.append("Sequence", "1");
    for(var i = 0; i < formElements.length; i++)
        formData.append(formElements[i].name, formElements[i].value);
    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {
                //doSomething
            }
        }
        xmlHttp.open("POST", "Controller.php");
        xmlHttp.send(formData);
}

Controller.php
<?php
    if(!empty($_POST["Code"] && !empty($_POST["Sequence"]))
    {
        if($_POST["Code"] == "1")
        {
            switch($_POST["Sequence"])
            {
                case 1:
                    $noteObj = new Note();
                        $noteObj->create($_POST);
                    break;
            }
        }
    }
?>

Then you will create Note class, with private fields, accessors and so on. Main idea is to divide your code and make it manageable which means that you can change User-Interface without changing back-end side as you have controller and classes which will return result to all requests, even if you send requests from command line tools such as curl.
MVC is as simple as it's main goal and idea. It improves code re-usability and also flexibility in terms of helping you better monitor and upgrade it sequentially.


text:
Q: Determine if there are duplicates in vector I would like to determine if there are duplicates in a vector. What is the best option here?
sort(arrLinkToClients.begin(), arrLinkToClients.end(), [&](const type1& lhs,const type1& rhs)
{
    lhs.nTypeOfLink < rhs.nTypeOfLink;
});

auto it = unique(arrLinkToClients.begin(), arrLinkToClients.end(), [&](const type1& lhs, const type1& rhs)
{
    lhs.nTypeOfLink == rhs.nTypeOfLink;
});

//how to check the iterator if there are duplicates ?
if (it)
{
  //
}

A: The "best" option does not exist. It depends on how you define "best".
Here are some solutions, each with their own advantages and disadvantages:
Using map
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    std::unordered_map<T, int> m;

    for (const auto& e : v)
    {
        ++m[e];

        if (m[e] > 1)
            return true;
    }
    return false;
}

Using set
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    std::unordered_set<int> s;
    std::copy(v.begin(), v.end(), std::inserter(s, s.begin());

    return v.size() != s.size();
}

Using sort and adjacent_find (mutating range)
template <class T>
auto has_duplicates(std::vector<T>& v) -> bool
{
    std::sort(v.begin(), v.end());

    return std::adjacent_find(v.begin(), v.end()) != v.last();
}

Manual iteration with std::find
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    for (auto it = v.begin(); it != v.end(); ++it)
        if (std::find(it + 1, v.end(), *it) != v.end())
            return true;

    return false;
}

Manual iteration
template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    for (auto i1 = v.begin(); i1 != v.end(); ++i1)
        for (auto i2 = i1 + 1; i2 != v.end(); ++i2)
            if (*i1 == *i2)
                return true;

    return false;
}

A: If there are no duplicates, the iterator returned from unique is the end iterator. So:
if (it != arrLinkToClients.end())
    cout << "Some duplicates found!";


text:
Q: What is the name of spectrally defined Sobolev spaces? Consider a compact domain $\Omega \subset \mathbb{R}^n$, and a self-adjoint positive compact operator $T: L^2(\Omega) \to L^2(\Omega)$ (e.g. $\Delta^{-1}$ with Dirichlet boundary conditions). Then $T$ has eigenfunctions $v_j$ with eigenvalues $\lambda_j \searrow 0$ that form an orthonormal eigenbasis of $L^2(\Omega)$.
For $s \geq 0$, we can define the space
$$
\mathcal{H}^s = \left\{\sum_{j \in \mathbb{N}} f_j v_j: \sum_{j \in \mathbb{N}} f_j^2 \lambda_j^{-2s} < \infty\right\}.
$$
This has a close connection to the space $H^{s}$ consisting of $s$-times weakly differentiable functions that have finite $L^2$-norm.
I was wondering if there is a general name for $\mathcal{H}^s$, and if there is literature about its properties. One can find some results for when $T = \Delta^{-1}$, for example, Partial Differential Equations I, Basic Theory by M. Taylor (c.f. Chapter 5.A). It seems that there must be more known about these spaces, but I can't find anything about them.
Cross-post Math Overflow


text:
Q: Convert code from es6 to es5? See example for the es6 code I have the following code in es6 and I want to convert it to es5.
class PowerArray extends Array {
  isEmpty() {
    return this.length === 0;
  }
}

let arr = new PowerArray(1, 2, 5, 10, 50);
console.log(arr.isEmpty()); // -> empty
console.log(arr.filter(item => item >= 10)); // -> 10, 50

I tried using Array.prototype.filter.call(context, callback), but I can't figure out what to pass in the first argument. Is it even possible to accomplish this?
I know I can use Babel, but this question is for learning purposes.


text:
Q: Template c++ compiler differences VC++ different output I had written some c++ code in Visual Studio and was trying to run it on my c++ code on a linux server. When I tried to compile it with G++ however, it failed to compile with tons of errors. I looked through the error and was able to simplify the problem to this:
template<int x>
struct Struct
{
    template<int y>
    static void F()
    {
        //Struct<x>::F<0>(); // compiles
        //Struct<y>::G(); // compiles
        Struct<y>::F<0>(); // does not compile?
    }

    static void G()
    {
    }
};

int main ()
{
    Struct<0>::F<0>();
}

On Visual Studio this code compiles just fine but on G++ or Clang++, it fails to compile. Errors on G++ 8.3.0:
test.cpp: In static member function 'static void Struct<x>::F()':
test.cpp:9:19: error: expected primary-expression before ')' token
   Struct<y>::F<0>(); // does not compile?
                   ^
test.cpp: In instantiation of 'static void Struct<x>::F() [with int y = 0; int x = 0]':
test.cpp:19:18:   required from here
test.cpp:9:15: error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'
   Struct<y>::F<0>(); // does not compile?

Errors on Clang++:
5691311/source.cpp:9:19: error: expected expression
            Struct<y>::F<0>(); // does not compile?
                            ^

See it live: https://rextester.com/AAL19278
You can change the compiler and copy the code to see the different errors.
Is there anyway I could get around this problem so that my code will compile on G++ or Clang++?
Original Code:
template<int x, int y>
ThisType add()
{
    return ThisType::Create(this->x() + x, this->y() + y);
}

ResultPos to = p.add<0, 1>();

A: template<int x>
struct Struct
{
    template<int y>
    static void F()
    {
        Struct<y>::F<0>(); // does not compile?
    }
};

should not compile. You need to specify for the compiler that F in fact requires a template list, since F is a dependent template type. Otherwise the compiler will assume that the next < is a smaller than.
template<int x>
struct Struct
{
    template<int y>
    static void F()
    {
        Struct<y>::template F<0>();
    }
};

I assume Struct<x>::F<0> works, since the compiler already knows that the current type is Struct<x>, but it cannot know that y is the same as xin this case.


text:
Q: What is the difference between `HTMLImports.whenReady` and `window.addEventListener('WebComponentsReady', function(e) {` What is the difference between HTMLImports.whenReady  and window.addEventListener('WebComponentsReady', function(e) {?
Polymer's official documentation says:

"To define an element in your main HTML document, define the element from HTMLImports.whenReady(callback). callback is invoked when all imports in the document have finished loading."

Webcomponents.org's official documentation on imports says:

Under native imports,  tags in the main document block the loading of imports. This is to ensure the imports have loaded and any registered elements in them have been upgraded. This native behavior is difficult to polyfill so the HTML Imports polyfill doesn't try. Instead the WebComponentsReady event is a stand in for this behavior:

What is the difference between the two?

A: They are almost * the same: both are triggered at the same time.
So you can choose your favourite flavor between callback and Event.
Nota Bene: if, for some reasons, you reference the CustomElement.js polyfill alone (i.e. without the HTMLImports.js feature), only the WebComponentsReady event will be thrown.
(I prefer to use the Event Handler because in the first case you need to be sure the HTMLImports is defined, and because it is the only documented API here)

*: Of course they are different! The difference is stated in the quoted definitions.

*

*The latter is waiting for the Custom Elements to be instanciated. It is triggered by CustomElement.js polyfill.

*The first is waiting only for the Imports to be loaded and parsed. It is called by HTMLImports.js polyfill, just after {HTMLImportsLoaded} has been sent.

However in normal situation, because Custom Elements are instanciated as soon as they are registered, the 2 events will happen one after the other.
Chronological order

*

*<link rel=import>.onload(),

*{HTMLImportsLoaded} event,

*HTMLImports.whenReady()

*{WebComponentsReady} event

More here.


text:
Q: Bootstrap navbar not loading properly I am new to bootstrap and I recently used one of their templates,all works well, but my navbar is not loading properly, it SHOULD look like this:
What i Should be getting
But it looks like this in both chrome and firefox:
What I get
and this is my html (only the nav part)

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
              Toggle navigation

            </button>
            Project name

Home

About

Contact

Can you please help?

A: It looks to me like your CSS isn't loading correctly.  Try adding this to your page  from http://getbootstrap.com/docs/3.3/getting-started/#download:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

It's just a copy of Bootstrap.  If that works, then you know the problem is with your local copy (if you're using one, or your CDN), if it doesn't then the problem lies elsewhere.
EDIT: I should edit to say that I've tested the code you provided on another website, and it seems to work fine.

A: Works fine on jsfiddle:
https://jsfiddle.net/ajrvrtz6/

I used:
butstrap v3.3

<link rel="stylesheet" href="maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/…; integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


text:
Q: PHP7.2.7-fpm/Docker ini_set(): Headers already sent. You cannot change the session module's ini settings at this time I'm trying to have a secure login page, which was working fine, whilst working with XAMPP, but now that i have switched to Docker, i am getting this error:
Warning: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time in /var/www/inc/cUser.php on line 30

I'm not sure, if there is some settings i need to do on the container itself and i haven't found a solution so far
I get $_POST Data from a form and pass it on to my process.php:
require_once(dirname($_SERVER['DOCUMENT_ROOT']) . '/inc/autoloader.php');
  $user = new cUser();

  $user -> sec_session_start();

cUser.php:
protected function sec_session() {
    define("SECURE", true);
    $session_name = 'sec_session_id';
    $secure = SECURE;
    $httponly = true;
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
    //header("Location: /error.php?err=Could not initiate a safe session (ini_set)");
// here i got the same error twice, so i commented it out and used the code below
        echo("<script>location.href = /error.php?err=Could not initiate a safe session (ini_set);</script>");
            exit();
        }
        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams["lifetime"],
            $cookieParams["path"],
            $cookieParams["domain"],
            $secure,
            $httponly);
        session_name($session_name);
        session_start();
        session_regenerate_id();
    }

The above works fine and i come back to my process.php:
if ($login) {
              // Login successful
              exit(header('Location: /index.php'));
          } else {
              // Login not successful
              exit(header('Location: /error.php?error=1'));
          }

and i get successfully redirected to index.php. In my index.php i call the same method again, to make sure i have the correct user and is authorized to view the page:
require_once(dirname($_SERVER['DOCUMENT_ROOT']) . '/inc/autoloader.php');
  $user = new cUser();

  $user -> sec_session_start();

and now i stumble onto the error. This is the line:
if (ini_set('session.use_only_cookies', 1) === FALSE) {

I'm not sure what can be wrong here, can someone help me please?

A: I think it's key to understand what causes Headers already sent errors in order to ghet to the bottom of what your error is.
When someone requests a webpage, the first bit of the page before any form of HTML is sent is a set of headers. These are key value pairs that contain key information about a page like it's status code (200 for success, 404 for not found etc).
It also contains cookie information which is key to how PHP sessions work (this, I suspect you may know given the commands you're executing).
As headers are sent at the beginning of a request, if you have put any output to the page which isn't header related (even a newline that is outside the <?php tags) this will prevent any additional headers being send and throw the error that you're seeing.
Given the symptoms that you're seeing (this previously worked, not working in Docker), the most likely cause is that there is either a configuration difference in terms of error reporting (the error reporting in the Docker container is set to be higher than it was in XAMPP) or PHP version (potentially using a newer version of PHP in your Docker container than you were on XAMPP).
None of the code you've posted looks like it should error, so I would assume this potential error is occurring in your autoloader.php file.


text:
Q: Windows make a default program for pattern of file extensions How to make a default program for pattern of file extensions in Windows?
Specifically, I SSH into a Linux cluster to run job scripts and there is information in a file of the form
JobName.o####
where #### is a counter of the number of jobs since the system was last reset, so it can be any length.
Doing some poking around it seems like the method described in this question for extensionless files could be used. However, how do I handle the numbers at the end?


text:
Q: Interpolation of an array of points I have the following data points that represent the boundaries of a constellation.
let boundaries = [
    {
      ra: 344.46530375,
      dec: 35.1682358
    },
    {
      ra: 344.34285125,
      dec: 53.1680298
    },
    {
      ra: 351.45289375,
      dec: 53.1870041
    },
    ...
]

Irrelevant, but these have been extracted from IAU quoted values.
However. Between each of these points I need what is known as the "great circle distance" - or the orthodromic distance, between point i and point i+1. To do that, we can interpolate between point i and point i+1 at a given precision, x.
I have written the following function which can perform this operation (it's worth noting that is done in Equatorial Coordinates - not Cartesian - so the Mathematics is slightly more complex, but not massively so).
The function for interpolate between two points is as follows (written in Typescript ES6 for prosperity and safety):
/**
 * getInterpolatedEquatorialCoordinates()
 *
 * @description This function takes in a start and end
 * @param start EquatorialCoordinate
 * @param end EquatorialCoordinate
 * @param precision number
 * @output returns the interpolated array of []EquatorialCoordinate points:
 */
export const getInterpolatedEquatorialCoordinates = (
  start: EquatorialCoordinate,
  end: EquatorialCoordinate,
  precision: number
): Array<EquatorialCoordinate> => {
  // The interpolated points array to return:
  const points: Array<EquatorialCoordinate> = []

  // Obtain the difference between the end coordinate's Right Ascension, RA, and the start coordinate's RA:
  let nra = ((end.ra - start.ra)) % 360

  if (nra > 180) nra = nra - 360
  if (nra < -180) nra = nra + 360

  // Obtain the "gradient" rate of change of RA:
  const dra: number = nra / precision

  // Obtain the difference between the end coordinate's Declination, dec, and the start coordinate's dec:
  const ndec = ((end.dec - start.dec))

  // Obtain the "gradient" rate of change of dec:
  const ddec: number = ndec / precision

  let i = 0

  // Obtain the interpolated EquatorialCoordinate points for each step:
  while (i < precision) {
    i++
    points.push({
      ra: start.ra + (dra * i),
      dec: start.dec + (ddec * i)
    })
  }

  return points
}

I have run this through a test suit, between the first two points of the above boundaries, to obtain it's validity Mathematically:
test('getInterpolatedEquatorialCoordinates', function () {
  const start = {
    ra: 344.46530375,
    dec: 35.1682358
  }

  const end = {
    ra: 344.34285125,
    dec: 53.1680298
  }

  const minRA = Math.min(start.ra, end.ra)
  const minDec = Math.min(start.dec, end.dec)

  const maxRA = Math.max(start.ra, end.ra)
  const maxDec = Math.max(start.ra, end.ra)

  const precision = 10

  const points = getInterpolatedEquatorialCoordinates(start, end, precision)

  const isRAAboveLowerThreshold = (
    p: EquatorialCoordinate
  ) => p.ra >= minRA

  const isRABelowUpperThreshold = (
    p: EquatorialCoordinate
  ) => p.ra <= maxRA

  const isDecAboveLowerThreshold = (
    p: EquatorialCoordinate
  ) => p.dec >= minDec

  const isDecBelowUpperThreshold = (
    p: EquatorialCoordinate
  ) => p.dec <= maxDec

  expect(points.length).toBeGreaterThan(0)
  expect(points.length).toBe(precision)
  expect(points.every(isRAAboveLowerThreshold)).toBe(true)
  expect(points.every(isRABelowUpperThreshold)).toBe(true)
  expect(points.every(isDecAboveLowerThreshold)).toBe(true)
  expect(points.every(isDecBelowUpperThreshold)).toBe(true)
})

The interpolated outputted points are as follows:
[
      { ra: 344.4530585, dec: 36.968215199999996 },
      { ra: 344.44081324999996, dec: 38.7681946 },
      { ra: 344.428568, dec: 40.568174 },
      { ra: 344.41632275, dec: 42.3681534 },
      { ra: 344.40407749999997, dec: 44.168132799999995 },
      { ra: 344.39183225, dec: 45.9681122 },
      { ra: 344.379587, dec: 47.7680916 },
      { ra: 344.36734175000004, dec: 49.568071 },
      { ra: 344.3550965, dec: 51.3680504 },
      { ra: 344.34285125, dec: 53.1680298 }
]

This seems to work for any precision to a good degree of accuracy that I am happy with, it also works regardless of which "direction" we're going.

Question:
What I want to do now is to apply this to the above boundaries array, for every point, returning a new array of all of the points combined as one ...
What would be the best way to achieve this? I've tried using the Array.prototype.map method, but to zero success ...
The desired output is as follows for the following "boundaries":
let boundaries = [
    {
      ra: 344.46530375,
      dec: 35.1682358
    },
    {
      ra: 344.34285125,
      dec: 53.1680298
    },
    ...
]

let desiredOutput = [
  {
    ra: 344.46530375,
    dec: 35.1682358
  }, // Original Index 0
  // Start Interpolated Intermediary Values
  {
    ra: 344.4530585,
    dec: 36.968215199999996
  },
  {
    ra: 344.44081324999996,
    dec: 38.7681946
  },
  {
    ra: 344.428568,
    dec: 40.568174
  },
  {
    ra: 344.41632275,
    dec: 42.3681534
  },
  {
    ra: 344.40407749999997,
    dec: 44.168132799999995
  },
  {
    ra: 344.39183225,
    dec: 45.9681122
  },
  {
    ra: 344.379587,
    dec: 47.7680916
  },
  {
    ra: 344.36734175000004,
    dec: 49.568071
  },
  {
    ra: 344.3550965,
    dec: 51.3680504
  },
  {
    ra: 344.34285125,
    dec: 53.1680298
  },
  // End Interpolated Intermediary Values
  {
    ra: 344.34285125,
    dec: 53.1680298
  }, // Original Index 1
  ...
]

A: You could use the map but, the reduce is a more natural fit for this scenario
boundaries.reduce((a,p,i,arr) => {
  if ( i > 0 ) {
    a.push(getInterpolatedEquatorialCoordinates(arr[i-1], p, precision))
  }
  return a;
}, [])

NOTE:
If you are using the map case instead of looking up the previous value you have to lookahead but, you will end up with an undefined at the end which you need to slice off

A: I think Array.reduce() is the best tool to use here.
You could write a function that takes an array of boundaries and a preceistion and outputs your desired array of EquatorialCoordinate:
const fillInBoundryPoints = (boundaries: EquatorialCoordinate[], precision: number) => {
  return boundaries.reduce((acc, cur, i, arr) => {
    if (i < arr.length - 1) {
      acc.push(cur)
      acc.push(...getInterpolatedEquatorialCoordinates(cur, arr[i + 1], precision))
    }
    return acc
  }, [] as EquatorialCoordinate[])
}

Which you would use as so:
const precision = 10

const boundaries: EquatorialCoordinate[] = [
  {
    ra: 344.46530375,
    dec: 35.1682358
  },
  {
    ra: 344.34285125,
    dec: 53.1680298
  }
]

const desiredOutput = fillInBoundryPoints(boundaries, precision)

Outputs:
[
  { ra: 344.46530375, dec: 35.1682358 },
  { ra: 344.4530585, dec: 36.968215199999996 },
  { ra: 344.44081324999996, dec: 38.7681946 },
  { ra: 344.428568, dec: 40.568174 },
  { ra: 344.41632275, dec: 42.3681534 },
  { ra: 344.40407749999997, dec: 44.168132799999995 },
  { ra: 344.39183225, dec: 45.9681122 },
  { ra: 344.379587, dec: 47.7680916 },
  { ra: 344.36734175000004, dec: 49.568071 },
  { ra: 344.3550965, dec: 51.3680504 },
  { ra: 344.34285125, dec: 53.1680298 }
]


text:
Q: "Multichannel" development using git I'm developing an App for Windows Phone, using SDK version 7.1 (for WP7) and hosting it in a git repo. In order to make it available on Windows Phone 8 devices with higher resolutions, I created a branch WP8 where I converted the Visual Studio project and made some necessary code adjustments.
Now that I continue developing on master, I would like to update functionality-related changes to the WP8 branch. My first thought is to merge those branches, but I fear two possible problems:

*

*When using merge, one branch will disappear. (Not true)

*Firmware-related changes (WP7 → WP8) might be overridden.

Is there a proper way in git to develop for several different (but similar) target SDKs that depend on a big amount of identical code?

A:
When using merge, one branch will disappear.

No, no branch will disappear

Firmware-related changes (WP7 → WP8) might be overridden

First, try rather to rebase WP8 on top of master.
That is, try to apply WP8 on top of master (see merge vs. rebase).
As Gary Fixler comments below, this makes sense for branches with a short history (otherwise, re-applying very old commits on top of recent work can be troublesome, and the history wouldn't make sense).

I only bring up rebase, because it is considered bad practice to merge master to any other branch (this is called "back merge", and makes Adam Dymitruk angry;)).
You should use Feature branches, which you can then merge to master, and to WP8 branch.
That takes advantage of the ease of branching offered by git, and leave master with only a stable state of the code: any further evolution to master should be done in a feature branch (and then merged to master), instead of being done in master (resulting in "back merge" from master to another branch, which is bad practice)
See more on Adam's article "Branch Per Feature".

Regarding configuration files, you can also store the values in separates files, and use template file to build the right config file with the right values, depending on the branch you are.
See "What's the easiest way to deal with project configuration files?".
That way, you want have any merge issue for those files with different content in different branches, because their values are stored in different files.

A: You can get away with this with branches or folders, but it's a prime candidate IMO for submodules. I use them for such things. Here's an example set of 3 repos:
common/ (bare repo of common files)
    .git/

wp7/ (regular repo of wp7 specifics)
    .git/
    common/ (submodule)

wp8/ (same as wp7, but for wp8)
    .git/
    common/ (submodule)

To make the common one you would just take a regular repo and git clone --bare repo optional_bare_repo_name. If you don't give it a name, it'll clone common into a folder called common.git, which is the bare version. Now you can from within either wp repo do git subdmodule add path/to/common optional_folder_name (it uses the repo folder name if you don't specify one). This effectively clones the common repo into a folder inside each wp repo. These can also be branches of a single repo; you'd just do the submodule add while on each branch.
Submodules are slightly more maintenance than branches, but they do something branches can't. They give you a parallel line of development inside your repo. When you make a change in the common repo inside either wp repo, you commit it there, and you can push it back to the external, bare version of common, and pull it down in the other wp repo's common repo. It's just a regular repo, but its clones live inside the wp repos. In your wp repos you would tell it which version you want right now by first checking out the correct commit inside the common repo, then outside in the wp repo doing git add common and git commit -m'Update common for feature X'. This creates a commit in the wp repo that just stores the hash of the commit in the common submodule.
When you checkout this commit in the wp repo later, it'll checkout the wp code, and also the appropriate commit in the common repo. Basically you're able to track which version of the common repo to be at at particular times. This is nice for a couple of reasons. For one, you don't have to get latest in common in a particular wp repo if you don't want or need it. It also means you can actually checkout an older commit in either common repo, add it, and commit it in that wp repo, and then work against that older one for as long as you need to. It is a little more work, though, and you have to remember to work in the wp and common repos together. I do it every day, but I've heard many people say it's too much bother.
You can also add and commit a particular version of common along with files in a wp repo, so for example you could go in and refactor things in common, hop out and fix changes against that refactoring in wp7, then add common and the wp7 changes together in wp7 and commit them to track both changes. Now if you roll back 1 commit the common repo will also roll back to before the refactoring, so you can have properly functioning code at every commit.

A:
Firmware-related changes (WP7 → WP8) might be overridden.

Branches are meant to be versions of the same thing in different stages of development.  If you merge a branch, git will try to move all changes from one to the other.  There is no easy way to move only architecture-independent changes from one branch to another.
The best situation is when you can get one branch to build for both.  Share the files that can be shared, and store the project specific things in separate directories, like arch/wp7 and arch/wp8.


text:
Q: Filtering a list of Objects with lists- Javascript What would be the most effective to filter a list that has objects with lists in them. I have been looking at underscore's _.filter function but this takes takes arrays and returns arrays.
I want to take an object and filter the it by a certain word.
For example, how would I filter:
    [
{level: "Title 1", details: [
    {real: "There we go", fake: "THERE_WE_GO"},
    {real: "Where is it", fake: "WHERE_IS_IT"},
    {real: "The dog jumped", fake: "THE_DOG_JUMPED"},
] },
{level: "Title 2", details: [
    {real: "There it is", fake: "THERE_IT_IS"},
    {real: "Car is flying", fake: "CAR_IS_FLYING"},
    {real: "Driving is fun", fake: "DRIVING_IS_FUN"}
] },
{level: "Title 2", details: [
    {real: "There he is", fake: "THERE_WE_GO"},
    {real: "Where is the dog", fake: "WHERE_IS_THE_DOG"},
    {real: "The dog died", fake: "THE_DOG_DIED"},
    {real: "I am tired", fake: "I_AM_TIRED"},

]}
];

by the word "the"
such that it returns
    [
{level: "Title 1", details: [
    {real: "There we go", fake: "THERE_WE_GO"},
    {real: "The dog jumped", fake: "THE_DOG_JUMPED"},
] },
{level: "Title 2", details: [
    {real: "There it is", fake: "THERE_IT_IS"},
] },
{level: "Title 2", details: [
    {real: "There he is", fake: "THERE_WE_GO"},
    {real: "Where is the dog", fake: "WHERE_IS_THE_DOG"},
    {real: "The dog died", fake: "THE_DOG_DIED"},
]}
];

Notice that when filter by the word "the" I also want to keep anything that has the word "the" as a part of it, such "There"...and I only went to check if the word "the" is in the "real" index of the objects inside the detail's array.

A: You can use filter, but you will have to apply it once on each of the inner lists and once on the outer list:
var phrase = "the".toUpperCase();
return _.filter(_.map(data, function(item) {
    return {
        level: item.level,
        details: _.filter(item.details, function(detail) {
            return detail.fake.indexOf(phrase) > -1;
        })
    };
}), function(item) {
    return item.details.length > 0;
});

From your example I cannot infer whether you need the outer filter at all, or whether you would not want to drop items with an empty details list.

A: This is a solution with plain javascript:
    var arr = [
    {level: "Title 1", details: [
        {real: "There we go", fake: "THERE_WE_GO"},
        {real: "Where is it", fake: "WHERE_IS_IT"},
        {real: "The dog jumped", fake: "THE_DOG_JUMPED"},
    ] },
    {level: "Title 2", details: [
        {real: "There it is", fake: "THERE_IT_IS"},
        {real: "Car is flying", fake: "CAR_IS_FLYING"},
        {real: "Driving is fun", fake: "DRIVING_IS_FUN"}
    ] },
    {level: "Title 3", details: [
        {real: "There he is", fake: "THERE_WE_GO"},
        {real: "Where is the dog", fake: "WHERE_IS_THE_DOG"},
        {real: "The dog died", fake: "THE_DOG_DIED"},
        {real: "I am tired", fake: "I_AM_TIRED"},

    ]}
];
function filterArr(arr, str) {
    var ret = new Array();
    for (var i = 0; arr[i]; i++) {
        var obj = arr[i].details;
        ret[i] = new Object();
        ret[i]['level'] = arr[i].level;
        ret[i]['details'] = [];

        for (var j = 0; obj[j]; j++) {
            if (obj[j].real.toLowerCase().indexOf(str.toLowerCase()) != -1) {

                ret[i].details.push(obj[j]);
            }

        }
    }
    return ret;
}
console.log( filterArr(arr, 'the'));

A: Here is another "plain" javascript solution. It tries to minimse hard coded properties, but likely that's not really necessary.
You can do it in less code using filter, forEach, map, etc. but generally plain loops run faster than nested iterators:
  function filterOn(data, value) {
    var re = new RegExp(value,'i');
    var result = [];
    var details, keys, obj, temp;

    for (var i=0, iLen=data.length; i<iLen; i++) {
      temp = {level: data[i].level, details:[]};
      details = data[i].details;

      for (var j=0, jLen=details.length; j<jLen; j++) {
        obj = details[j];

        for (var p in obj) {

          if (obj.hasOwnProperty(p) && re.test(obj[p])) {
            temp.details.push(details[j]);
            break;
          }
        }
      }
      if (temp.details.length) result.push(temp);
    }
    return result;
  }


text:
Q: Use select in angular to pass multiple arguments In Angular Js is there a way to use a select element the same way you can with a list of links?
For example if I have some links like this:
One
Two
...

Is there a way I can do the same thing with a select element?
<select>
    <option value="argument1,argument2">One</option>
    <option value="argument3,argument4">Two</option>
    ...
</select>

A: you can pass the variables and model through ng-change , hope below code helps you,
template

        <select ng-model="item" ng-options="i.name for i in items" ng-change="changed('hello','world',item)">
            <option value="">choose items</option>
        </select>

controller
function myCtrl($scope) {

    $scope.items = [{

            "name": "first",
            "type" : "type1"

    }, {

            "name": "second",
            "type" : "type2"

    }, {

            "name": "third",
            "type" : "type3"

    }];

    $scope.changed = function (hello,world,item) {
        alert(hello); // argument1
        alert(world); //argument2
        alert(item.type); //model argument based on the selection
    }

}

A: do u mean this? use controller value instead of scope value if u wish

<select ng-options="['a,b','c,d']" ng-model="selected" ng-change="ctrl.change(selected)">


text:
Q: How to convert regular expression when we are using localization in iphone app? When we are using localization and regular expression in our iphone application. And when we are not using the english language.
Then how to convert that regular expression in relative language.
If i am using below regular expression:
+ (BOOL) isAlphabetsOnly:(NSString *) candidate {
    if (![self isEmpty:candidate]) {
        NSString *alphaRegex = @"^\\s*([A-Za-z ]*)\\s*$";
        NSPredicate *alphaTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", alphaRegex];

        return [alphaTest evaluateWithObject:candidate];
    }
    return NO;
}

It's work fine for the english. But not for other language. Then how can we convert it into other language. So it will work in different language to.
Please help me.
Thanks,

A: You could put your regular expression as a String in the Localizable.strings file.
You could then get it by doing the following:

NSString
  *myRegularExpression=NSLocalizedString(@"my_regular_expression",nil);

A: I have never worked on the iOS but according to here if you use something like so: ^\\s*([\\s]*)\\s*$ should work across different locales.

\w     Match a word character. Word characters are
  [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}].

Edit: Yes you are correct, my bad. As stated in here you should be able to do what you need using the \p{L} you should be able to match any letter:
^\\s*([\\p{L}\\s]*)\\s*$


text:
Q: Timer counting faster on second run I am working on a simple game right now. its almost done except for the timer has a glitch in it and I can't figure out whats doing it. when you push a button, an HTML5 text on the canvas starts to count down from 35 to 0. On the first run it's fine. But if you choose to play again with out refresh the timer starts to countdown faster. here is the code.
var timer = 35;

ctx.fillText("Countdown: " + timer, 320, 32);

function resetReggie(){
    reggie.x = canvasWidth / 2;
    reggie.y = canvasHeight / 2;
}

//Starts Timer for Timed Game
function timedMsg()
{
    resetReggie();
    ballsCaught = 0;
    timer = 35;
    alert('Pick up as many as you can in ' + timer + ' seconds');
    countDown();
        var t=setTimeout(function() {
        var again = confirm("TIMES UP! You Gathered " + ballsCaught + " Balls! Play Again?");
            if (again === true){
                timedMsg();
                resetReggie();
            }
                if (again === false){
                resetReggie();
                ballsCaught = 0;
                timer = 35;
                }
        }, timer * 1000);

}

function countDown() {
    if (timer != 0){
        timer-=1;
        setTimeout('countDown()', 1000);
    }
}

A: I think the problem is in the line
    }, timer * 1000);

where you have a value that is at most 34 at the time 'timer' is evaluated to set the timeout.  Because you initialize it to 35 but then call countDown() which decreases it to 34, then you have a call to confirm() which might let 'timer' decrease even more.  As a result the subsequent call to timedMsg() happens a little too soon causing countDown() to be called twice as often.   Try the following (I ran it in node) and then change the 4 to 6.
function countDown() {
    console.log("Countdown: " + timer, 320, 32);
    if (timer != 0) {
        timer -= 1;
        setTimeout(countDown, 1000);
    }
}
function timedMsg() {
    timer = 5;
    countDown();
    var t=setTimeout(function() {
        timedMsg();
    }, 4 * 1000);
}
timedMsg();

A: As mentioned in my comment, each time you start a new game, it appears you are decreasing the timeout value. As a result, this reduces the time each time.
Try this:
var timeout = currentTime = 5;
var int = setInterval(function() {
    console.log(currentTime);
    currentTime--;
    if(currentTime < 0) {
    var again = confirm('Play again?');
    if(again) {
        currentTime = timeout;
    }
    else {
        clearInterval(int);
    }
    }
}, 1000);

http://jsfiddle.net/gRoberts/CsyYx/
Look at your console (F12 in Chrome), or update the code to write to the browser to see it working ;)


text:
Q: Could not find chunky_png-1.3.3 in any of the sources When I try to run a new Foundation Projekt over the Terminal, this line above seems to make my projekt not running correctly. The whole answer here:
xxxxxMacBookAir:htdocs xxxxx$ foundation new _lutz2015
Creating ./_lutz2015
      create  _lutz2015
Cloning into '_lutz2015'...
remote: Counting objects: 117, done.
remote: Total 117 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (117/117), 40.07 KiB | 0 bytes/s, done.
Resolving deltas: 100% (46/46), done.
Checking connectivity... done.
Installing dependencies with bower...
         run  compass compile from "./_lutz2015"
/Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find chunky_png-1.3.3 in any of the sources (Bundler::GemNotFound)
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler/spec_set.rb:85:in `map!'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler/spec_set.rb:85:in `materialize'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler/definition.rb:132:in `specs'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler/definition.rb:177:in `specs_for'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler/runtime.rb:13:in `setup'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler.rb:128:in `setup'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/bundler-1.7.2/lib/bundler.rb:133:in `require'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/gems/compass-1.0.1/bin/compass:26:in `<top (required)>'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/bin/compass:23:in `load'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/bin/compass:23:in `<main>'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `eval'
    from /Users/xxxxx/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `<main>'
./_lutz2015 was created
xxxxxMacBookAir:htdocs xxxxx$

A: I had the same problem. But you should just cd into '_lutz2015' and run bundle (only once per project). This will resolve all dependencies and is much easier. Basically, the following will be installed ( you will need to have installed bundler, of course) :
chunky_png x.x.x
multi_json x.x.x
sass x.x.x
compass-core x.x.x
compass-import-once x.x.x
rb-fsevent x.x.x
ffi x.x.x
rb-inotify x.x.x


text:
Q: export { default as x } does not infer type Typescript does not infer the type of Activity when i export it from another file. I have activity defined as a constant, with inferred typing from mongoose:
models.ts:
import mongoose from "mongoose";

const activitySchema = new mongoose.Schema({
    name: String
})

export const Activity = mongoose.model("Activity", activitySchema);

This file sits in a folder with other (mongoose) related Typescript files.
Another TS file that sits in the same folder, index.ts, exports this variable:
index.ts:
export { default as Activity } from "./models";
export { default as configureMongoose } from "./configureMongoose";

However, in index.ts, the type of Activity cannot be inferred. The type of the variable from the "./configureMongoose" reference however, is automatically inferred. This prevents me from being able to make use of the type related functions and properties.
How come the type is not automatically inferred?


text:
Q: Is FSharp.Data.DesignTime .NET 4.5 only? I'm using FSharp.Data.1.1.10 in a .NET 4.0 project, and when I add FSharp.Data with Nuget, it creates a packages\FSharp.Data.1.1.10\lib\net40 directory where it puts FSharp.Data.dll and FSharp.Data.DesignTime.dll. According to Telerik JustDecompile, FSharp.Data.dll is a .NET 4.0 dll, but FSharp.Data.DesignTime.dll is a .NET 4.5 dll even though it resides in the net40 subdirectory.
So, is FSharp.Data.DesignTime .NET 4.5 only, or is this a bug?

A: Yes, FSharp.Data.DesignTime is .NET 4.5, but that doesn't mean your projects have to be .NET 4.5 also, it's just a design time component, and you shouldn't even reference it, only FSharp.Data.dll
EDIT:
In FSharp.Data 1.1.x the DesignTime dll was being added by mistake when referencing the nuget package, in 2.x that is now fixed


text:
Q: TIdHttpServer freezing when Active set to False after Windows Update We have a Indy (version 10.6.1.5235) TIdHttpServer "service" that has worked well for years with Delphi 2007.  After the most recent Windows Update (KB4338815 and KB4338830) we noticed the service freezes when TIdHttpServer is set to false.
I have included source code where TIdHttpServer is created.  In our service "Stop" handler we set IdHttpServer1.Active to False and this is where it freezes.  It seems Indy hangs when it is trying to close the http connections.  Is there a work around?
Update One Per Remy Lebeau, I have created a Minimal, Complete, and Verifiable example.  Here it is:
procedure TMainForm.Button1Click(Sender: TObject);
begin
  memo1.clear;
  iCall := 0;
  IdHTTPServer1 := TIdHTTPServer.Create;
  IdHTTPServer1.MaxConnections := 10;
  IdHTTPServer1.AutoStartSession := True;
  IdHTTPServer1.SessionState := True;
  IdHTTPServer1.OnCommandGet := IdHTTPServer1CommandGet;
  IdHTTPServer1.KeepAlive := False;
  idHttpServer1.DefaultPort := 80;
  if ReuseSocket.checked then
    IDHTTPSERVER1.ReuseSocket :=  rsTrue;
  IdHTTPServer1.Active := True;
end;

procedure TMainForm.IdHTTPServer1CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  iCall := iCall + 1;
  if iCall mod 100 = 0 then
    memo1.lines.add(inttostr(iCall)+ ' calls made');
  AResponseInfo.ContentText := '<html><body>Hello There</body></html';
end;

procedure TMainForm.StopClick(Sender: TObject);
begin
  try
    IdHTTPServer1.Active := False;
    memo1.lines.add('IdHTTPServer1.Active := False;');
  except
    on e: exception do
      memo1.lines.add('Exception on IdHTTPServer1.Active := False; Message:'+e.message);
  end;

end;

Application will run fine but once you click the "Stop" button which sets the IdHttpServer Active property to False it hangs.

A: You might have encountered this similar issue:
Windows 2012 R2 closesocket() hangs on listening socket

The issue was brought by patch from Microsoft KB4338815, which caused closesocket tо hang forever on Intel Xeon processors

That issue was fixed by uninstalling KB4338815, which you do have installed.  So try uninstalling that KB on your system and see if it solves your issue.


text:
Q: KivyMD MDFileManager shows only image files, how to list all file types? I am developing a KivyMD text file explorer for Android. Following is the code snippet:
def __init__(self, **kwargs):
self.file_manager = MDFileManager(
            exit_manager=self.exit_manager,
            select_path=self.select_path,
            previous=False,
        )
request_permissions([Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE,Permission.INTERNET])
self.ROOT_PATH = primary_external_storage_path()

Above initialization works flawlessly, also the following code statement launches the file manager/explorer.
self.file_manager.show(self.ROOT_PATH)

But the resulting contents are only either folder names or image files(.jpg, .jpeg, .png). No other file types are shown.
I tried following before invoking self.file_manager.show(self.ROOT_PATH), but no change in response.
self.file_manager.use_access = True
self.file_manager.previous=False
self.file_manager.preview=False

When I tried self.file_manager.ext = ['txt'] extension filtering technique, even the image files listing disappeared, only folder names were listed/shown.
Hence, I write this request seeking expert response.
Thanks in advance.

A: If the above case won't work, please try:
self.file_manager = MDFileManager(exit_manager=self.exit_manager,
                                     select_path=self.select_path,)
   self.file_manager.ext = [".py",".kv"]

A: *

*Update library from master branch - https://github.com/kivymd/KivyMD, not from pip.

*

self.file_manager = MDFileManager(
    exit_manager=self.exit_manager,
    select_path=self.select_path,
    preview=True,
    # preview=True - deprecated
 )

*If you set the "preview" parameter, then only images will be displayed in the file manager. If you want the file manager to display all file types do not use the "preview" paramete

*

self.file_manager = MDFileManager(
    exit_manager=self.exit_manager,
    select_path=self.select_path,
    ext=[".py", "kv"],
)

A: I had the same issue like you.
Found out on android.developers that actually for "All files" is needed the permission MANAGE_EXTERNAL_STORAGE.
Just put in buildozer.spec file MANAGE_EXTERNAL_STORAGE also:
(list) Permissions
android.permissions = INTERNET,WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE,MANAGE_EXTERNAL_STORAGE
No need to put it in the py code as you mnetioned for the other other permissions.
they are ok in the code to avoit asking for the permission every time the app is launched.
But, after the app is installed you'll have to go on the app permission to all the management of all files allow permission
Worked for me, hope it helps.


text:
Q: Directly vs indirectly nested structs In the Go documentation for xml:Unmarshal there is an example that unmarshals this xml
    <Person>
        <FullName>Grace R. Emlin</FullName>
        <Company>Example Inc.</Company>
        <Email where="home">
            <Addr>gre@example.com</Addr>
        </Email>
        <Email where='work'>
            <Addr>gre@work.com</Addr>
        </Email>
        <Group>
            <Value>Friends</Value>
            <Value>Squash</Value>
        </Group>
        <City>Hanga Roa</City>
        <State>Easter Island</State>
    </Person>

using these structs
    type Address struct {
        City, State string
    }
    type Result struct {
        XMLName xml.Name `xml:"Person"`
        Name    string   `xml:"FullName"`
        Phone   string
        Email   []Email
        Groups  []string `xml:"Group>Value"`
        Address
    }

Note that Result contains a reference to the separately defined Address. Obviously, this code works.

When I try to unmarshal this xml
<C>
  <D>
    <E>Fred</E>
    <F>42</F>
  </D>
</C>

using these structs
type D struct {
  E string
  F int
}
type C struct {   // Compiles OK but result empty.
  D
}

I get empty results {{ 0}}. However the struct below works OK producing {{Fred 42}}
type C struct {   // This works.
  D struct {
    E string
    F int
  }
}

See Playground example.
Am I missing some subtle point about structs?

A: When you do this:
type C struct {
    D
}

This is called embedding (D is an anonymous field or embedded field). You may think of this as if the fields (and methods) of the embedded type become part of the embedder type (they get promoted). So in this case it's "legal" to write C.E and C.F.
When you do:
type C struct {
    D struct {
      E string
      F int
    }
}

This is not embedding (or "nesting"). Here D is a "regular", named field of the C type. D is the name of the field, which is followed by an anonymous type literal, the type of the field. Here it is not legal to write C.E nor C.F, only C.D.E and C.D.F. And this is the proper mapping of the XML structure you try to unmarshal, hence this works (try it on the Go Playground).
Note that if you change the embedding to a regular field, it will also work (try it on the Go Playground):
type C struct {
    D D
}

Also note that you can skip the whole D wrapper struct if you specify the XML element paths in the field tags:
type C struct {
    E string `xml:"D>E"`
    F int    `xml:"D>F"`
}

Try it on the Go Playground.


text:
Q: using google analytics to log ajax errors I have the following code which is supposed to send a notification on ajax error to the user, and as a snap-solution, I decided to use google analytics to log those errors, however it doesn't work, does anyone have an idea/lead or must I implement a different solution?
showNotification(title, message) is a custom dialog box invoker.
$(document).ajaxError(function(e, xhr, settings) {
    $(".modal").modal('hide');
    showNotification('Something went wrong...', 'Whoa there! Something happened which we didn\'t predict, we sent ourselves a notification. ');
    _gaq.push(['_trackEvent', 'AjaxError', xhr.status, settings.url]);
});

it works in the sense that it shows the notification, but it doesn't send an event to analytics.
any leads?

A: The problem is that xhr.status is an integer, and typically 0.  The second argument to trackEvent is supposed to be a string, and apparently if it's integer 0, Google ignores the call.  So using statusText fixes it:
$(document).ajaxError(function(e, xhr, settings) {
    // Generic Google error logging
    _gaq.push(['_trackEvent', 'AjaxError', xhr.statusText, settings.url]);

    // Application-specific UI code
    $(".modal").modal('hide');
    showNotification('Something went wrong...', 'Whoa there! Something happened which we didn\'t predict, we sent ourselves a notification. ');
});

Also, I'd recommend putting the GA call before your code since (no offense) Google's code is less likely to error out.
Great idea, BTW!

A: You may have another error happening somewhere else in your code.  I have mocked up a sample of this functionality here, and it works:
http://jsbin.com/emocah/edit#preview
Did you just start tracking this?  Sometimes new events take a few days to propagate in GA.  Also, are there any other JS errors that occur on your page?


text:
Q: Tensorflow serving grpc client error 12 I am currently trying to serve a simple model via tensorflow serving and then I want to call into it via gRRC using node.js. I felt the easiest way to learn/understand this would be to break it down to the simplest model possible.  Please forgive the naming as I originally started doing this with a Mnist tutorial but I wasn't successful there either. So the name still says mnist, but it is just a simple calculation implementation.
I created and exported the model with the below code:
-- Simple Model --
x = tf.placeholder(tf.float32, shape=(None))
y = tf.placeholder(tf.float32, shape=(None))
three = tf.Variable(3, dtype=tf.float32)
z = tf.scalar_mul(three, x) + y

-- Export --
model_version = 1
path = os.path.join("mnist_test", str(model_version))
builder = tf.python.saved_model.builder.SavedModelBuilder(path)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    builder.add_meta_graph_and_variables(
    sess,
    [tf.python.saved_model.tag_constants.SERVING],
    signature_def_map = {
        "test_mnist_model": tf.saved_model.signature_def_utils.predict_signature_def(
            inputs={"xval": x, "yval":y},
            outputs={"spam":z})
    })
    builder.save()

The message in the end when I ran this seems to be successful:

INFO:tensorflow:No assets to save. INFO:tensorflow:No assets to write.
  INFO:tensorflow:SavedModel written to: b'mnist_test/3/saved_model.pb'

So I then run tensorflow server and point it to my model via the below line and the server states it is runnign at 0.0.0.0:9000:
../../bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server --model_base_path=mnist_test --model_name=calctest --port=9000

I then proceeded to setup the .proto file and it contains this:
syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.mnisttest";
option java_outer_classname = "MnistTestProto";
option objc_class_prefix = "MNT";

package mnisttest;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc test_mnist_model (InputRequest) returns (OutputReply) {}

}

// The request message containing the user's name.
message InputRequest {
  float xval = 1;
  float yval = 2;
}

// The response message containing the greetings
message OutputReply {
  float spam = 1;
}

Finally I setup a mnistclient.js file which I run under node.js and it contains the below code:
var grpc = require('grpc')
var PROTO_PATH = __dirname + '/../../protos/mnisttest.proto';

module.exports = (connection) => {
    var tensorflow_serving = grpc.load(PROTO_PATH).mnisttest;//.serving;
    console.log(tensorflow_serving);

    var client = new tensorflow_serving.Greeter(
        connection, grpc.credentials.createInsecure()
    );

    return {
        test: () => {
            console.log(client);
            return client.testMnistModel({xval:5.0,yval:6.0}, function(err, response){
                if(err){
                    console.log("Error: ",JSON.stringify(err));
                    return {Err: JSON.stringify(err)};
                }
                console.log('Got message ', response);
            });
        }
    }
};

function main() {
    var cli = module.exports('localhost:9000')
    cli.test();
}

if( require.main === module){
    main();
}

With the Model running on tf server, when I run the client under node.js I get the below error.  I am also printing out the info under client, but when I looked up what the error code 12 meant, it stated the following: Operation is not implemented or not supported/enabled in this service
I have been at this for quite some time and I am assuming that there is just some piece of this that I am blatantly missing.  Is anyone able to provide any insight as to why I can't get this simple call into the model working?
I have not ever been able to get a TF model served up yet and thought taking this simple approach would work best, however I can't even get this to work.  Any help on this would be a great help!  Thanks in advance!
{ InputRequest:
   { [Function: Message]
     encode: [Function],
     decode: [Function],
     decodeDelimited: [Function],
     decode64: [Function],
     decodeHex: [Function],
     decodeJSON: [Function] },
  OutputReply:
   { [Function: Message]
     encode: [Function],
     decode: [Function],
     decodeDelimited: [Function],
     decode64: [Function],
     decodeHex: [Function],
     decodeJSON: [Function] },
  Greeter: { [Function: Client] service: { testMnistModel: [Object] } } }
Client { '$channel': Channel {} }
Error:  {"code":12,"metadata":{"_internal_repr":{}}}

A: It looks like you have defined a service interface proto (mnisttest.proto), which can be useful when creating a custom server. However, the TensorFlow Serving Model Server supports a service with defined endpoints. In other words, you are speaking to a custom service "Greeter" that does not exist on the Model Server.
Please take a look at the Model Server's API/Service: apis/prediction_service.proto. You most likely want the Predict API: apis/predict.proto.
The Predict API uses the model signature you defined at export time, so you will need to pass in tensors for "xval" and "yval", and fetch the "spam" tensor.
Hope this helps!
  Thanks,
  Noah


text:
Q: Q-pigeon hole: a group of 52 sequences, each 9 long from the group {0,1} let A be a group of sequences, each sequence length is 9 and each od its elements is from the group {0,1}
we know that |A| =52.
show that there exsits at least 2 sequence a1 and a2 such that you can switch at most 2 elemnts in a1 and get a2

A: I'll assume that you meant "switch at most $2$ elements", since the statement is false as written.
Around each sequence is a ball of $10$ sequences that differ from it in at most $1$ element. If there were no two sequences at distance at most $2$, these balls could not overlap. There would be $10\cdot52=520$ different sequences in these balls, but there are only $2^9=512$ different binary sequences of length $9$.


text:
Q: Determining nature of complex singularities using Taylor and Laurent series I'm facing the following function:
$$f(z) = \frac{z}{\sin z}$$
I know there are singularities at $z_k=k\pi$ with $k \in \mathbb{Z}$. Using the basical properties of the $\sin(z)$ function, I found:
$$\sin(z-k\pi) = (-1)^k \sin(z)$$
And as $\sin(z)$ can be developped with a Taylor series:
$$\sin(z) = \sum_{n=0}^{+\infty} \frac{(-1)^n}{(2n+1)!} z^{2n+1}$$
I turn my initial equation into:
$$\frac{z}{\sin z} = \frac{(z-k\pi) + k\pi}{(-1)^k \sin (z-k\pi)} = \sum_{n=0}^{+\infty}\frac{(2n+1)!}{(-1)^n(-1)^k}(z-k\pi)^{-2n} + \dots$$
I conclude thus that all those poles are essential, meaning the Laurent development of this series has infinite terms different from zero.
Yet, my book claims that they are all... simple poles !

*

*Where is my mistake ?

*How to prove these are single poles ?


text:
Q: Couldn't find Boot disk error while Installing Windows 7 using USB I am getting problem while installing windows 7 on my single partition hard disk. I am using bootable USB drive for the installation. The error I get is "Setup was unable to create new system partition or locate an existing system partition. See the setup log files for more information". When I opened the setup log file(setuperr.log), it shows the error "Couldn't find boot disk on the BIOS based computer". Have anyone got this error before. Please help!!
More Info:
Boot Sequence:USB, Harddisk
System: Dell Inspiron 1545

A: Try setting the Hard Disk as boot order 1 and USB as order 2. While the PC is booting hit F12 during the POST and select the USB drive.

A: I got this same error, setting the hard disk as 1st (and even removing the USB stick from the boot order) did not help. As far as I can tell, this is some interaction in the BIOS that prevents the win10 installer from thinking that the installation target drive is bootable, perhaps due to the particular USB key I was using (a USB 3.0 Kingston DataTraveler). I solved it by creating an "install partition" on the target disk using diskpart from the command line (shift+F10 in the installer):
> diskpart
diskpart> list disk
diskpart> select disk 0   # Choose the disk you want to install to
diskpart> clean           # will delete everything, hope you have backups!
diskpart> create partition primary size=100000 # size in MB
diskpart> create partition primary size=5000 # temporary install partition
diskpart> format fs=ntfs quick
diskpart> assign          # assigns a drive letter, it was D: for me
diskpart> active          # makes the install partition bootable
diskpart> exit

then copy the installer files from the USB key to the temporary partition:
c:\> xcopy c: d: /e /h    # /e for recursive with empty, /h for system files

and reboot, remove the USB key, and boot from the temporary install partition. The win10 installer will detect that the disk is bootable this time through & will let you install. When you're done with the installer you can remove the temporary partition and resize your main partition to take up the whole disk.


text:
Q: How to write a subroutine for initial condition in Nonlinear Schrodinger Equation that depends on x I am solving Nonlinear Schrodinger equation by split-step Fourier method:
i df/dz+1/2* d^2f/dX^2+|f|^2*f=0
using an initial condition:
f=q*exp(-(X/X0)^24).
But I have to use the condition that q=1 for |x|<1, otherwise, q=0.
So I write the following subroutine (excerpt of the code involving transverse variable) for transverse variable x:
   fs=120;
   N_fx=2^11; %number of points in frequency domain
   dX=1/fs;
   N_X=N_fx;
   X=(-(N_X-1)/2:(N_X-1)/2)*dX;
   X0=1;
   Xn=length(X);

   for m=1:Xn
   Xnn=Xn/8;
   pp=m;
   if pp>3*Xnn && pp<5*Xnn
   q=1.0;
   f=q*exp(-(X/X0).^24);
   else
   f=0;
   end
   end

But it seems that 'f' is getting wrong and it is a 1 by 2048 vector with all entries zero. I'm not getting the expected result. If my initial condition is only f=q*exp(-(X/X0).^24), q=1, it is straightforward, but with the above condition (q=1 for |x|<1, otherwise, q=0) what I need to do?
Any help will be much appreciated.
Thanks in advance.

A: A MWE, this has 0 < [f(867) : f(1162)] <= 1:
fs=120;
N_fx=2^11; %number of points in frequency domain
dX=1/fs;
N_X=N_fx;
X=(-(N_X-1)/2:(N_X-1)/2)*dX;
X0=1;
Xn=length(X);
f = zeros(1,Xn);  % new: preallocate f size and initialise it to 0

for m=1:Xn
    Xnn=Xn/8;
    if m>3*Xnn && m<5*Xnn
   %if abs(X(m)) < 1   %alternative to line above
        q=1.0;
        % error was here below: you overwrote a 1x1 f at each iteration
        f(m)=q*exp(-(X(m)/X0).^24);
    else
        f(m)=0;
    end
end


text:
Q: matplotlib bar plot adjust bar direction I want to start the bars from the bottom. How can I change the starting point from zero to e.g. -2 ?
My code:
import matplotlib.pyplot as plt
import numpy as np

N=1000
sample=np.random.random_integers(1,10,N)
hist,bins=np.histogram(sample)

plt.bar(bins[:-1],np.log10(1.*hist/N),np.diff(bins))

plt.show()

Output:

A: Try This:
plt.bar(bins[:-1],abs(np.log10(1.*hist/N)),np.diff(bins))


text:
Q: Extracting and transforming a list of tuples to plain columns.[Python] I have the bellow list of tuples in python:
[(('A', 'B'), 4), (('B', 'C'), 4), (('C', 'D'), 4)]

And I want to extract the Information as shown bellow:
[('A', 'B', 4), ('B', 'C', 4), ('C', 'D', 4)]

How can I bring it to this form by extracting the inner tuple?

A: You can use the unpack operator (prefix *) to spread out an iterable:
tuples = [(('A', 'B'), 4), (('B', 'C'), 4), (('C', 'D'), 4)]
result = [(*t[0], t[1]) for t in tuples]
result # [('A', 'B', 4), ('B', 'C', 4), ('C', 'D', 4)]


text:
Q: codeigniter query builder and active record sql injection since my last question in SO, I've been reading a bit about how to prevent sql injection and many people mentioned active records class. but when I google it, it only exists in codeigniter 2.
so my questions are:

*

*is Query Builder Class in codeigniter 3 the upgraded version of Active Record Class or do they serve different purposes?

*is it enough (in general) to use Query Builder Class methods like $this->where('field', $foo); instead of $this->where("field = '$foo'"); to prevent sql injection?
P.S. I'm using codeigniter 3 and mysql

A: 1- ActiveRecord was in Codeigniter 2, but in Codeigniter 3 you have QueryBuilder instead. The both classes do same work for you, maybe QueryBuilder is improved version of ActiveRecord. In other frameworks like Yii2, ActiveRecord is an ORM not only query string builder but in CI was simple query builder.
2- Codeigniter will escape all passed parameters automatically but I suggest you validate your inputs before running queries. For example, the value of a numeric id field should be a number, not a string so the rule of ID input should be INTEGER.
You can see Validation in Codeigniter 3 at official documentation: https://www.codeigniter.com/userguide3/libraries/form_validation.html
All works that you should do is pass your field value as a function parameter, not as a string (field and value together). If you want to run your query without QueryBuilder, you must escape your parameters manually. You can get more information about it in Codeigniter documentation:
https://www.codeigniter.com/userguide3/database/queries.html#escaping-queries


text:
Q: Excess of array dimension in Fortran 90/95 I am very curious about how printing of the 3rd row in the following is possible or at least why it is not a trash value:
PROGRAM b
    INTEGER:: A(2,2) = reshape((/1,2,3,4/),(/2,2/))

    PRINT*, A(1,:)
    PRINT*, A(2,:)
    PRINT*, A(3,:)
END PROGRAM b

My result is:
       1           3
       2           4
       3       66825

I would really appreciate your help. Thanks in advance.

A: Your 66825 is a trash value! Even if you got just 0, it is still an undefined behavior that can cause bad result or crash your program (or even start WWIII). Do not do this. Use features provided by the compiler to check the array bounds and other similar stuff:
gfortran -fcheck=all

ifort -check

and so on.
You can also use valgrind on Linux to see undefined values and invalid reads and writes in memory.