text:
Q: Expo Cli React Native Geolocation Tracking App I want to create a react native expo cli geolocation tracking system, i have got the location coordinates via expo location(lib).I have stored these co-ordinates into a variable(text) as a string. Now i want to display these coordinates in a map view in real time. How should i proceed?
Here is the code:
     import React, { useState, useEffect } from 'react';     //hooks for using react features without class
    import { Platform, Text, View, StyleSheet } from 'react-native'; import Device from 'expo-device';
    import * as Location from 'expo-location';  //expo lib to get location coordinates
    export default function App() {   const [location, setLocation] = useState(null);
      const [errorMsg, setErrorMsg] = useState(null);
     useEffect(() => {
            (async () => {
              if (Platform.OS === 'android' && !Device.isDevice) {
                setErrorMsg(
                  'Try it on your device!'
                );
                return;
              }
              let { status } = await Location.requestForegroundPermissionsAsync();
              if (status !== 'granted') {
                setErrorMsg('Permission to access location was denied');
                return;
              }
              let location = await Location.getCurrentPositionAsync({});
              setLocation(location);
            })();   }, []);
     let text = 'Waiting..';
if (errorMsg) {
            text = errorMsg;   }
    else if (location) {
            text = JSON.stringify(location);   }
     return (
            <View style={styles.container}>
              <Text style={styles.paragraph}>{text}</Text>
            </View>   ); }
    const styles = StyleSheet.create({   container: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            padding: 20,   },   paragraph: {
            fontSize: 18,
            textAlign: 'center',   }, });

A: Thanks, i got it done by myself:
here is the code:
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import MapView from "react-native-maps";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";

const LOCATION_TASK_NAME = "background-location-task";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      region: null,
      error: '',
    };
  }

  _getLocationAsync = async () => {
    await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
      enableHighAccuracy: true,
      distanceInterval: 1,
      timeInterval: 5000
    });
    // watchPositionAsync Return Lat & Long on Position Change
    this.location = await Location.watchPositionAsync(
      {
        enableHighAccuracy: true,
        distanceInterval: 1,
        timeInterval: 10000
      },
      newLocation => {
        let { coords } = newLocation;
        // console.log(coords);
        let region = {
          latitude: coords.latitude,
          longitude: coords.longitude,
          latitudeDelta: 0.045,
          longitudeDelta: 0.045
        };
        this.setState({ region: region });
      },
      error => console.log(error)
    );
    return this.location;
  };

  async componentWillMount() {
    // Asking for device location permission
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if (status === "granted") {
      this._getLocationAsync();
    } else {
      this.setState({ error: "Locations services needed" });
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <MapView
          initialRegion={this.state.region}
          showsCompass={true}
          showsUserLocation={true}
          rotateEnabled={true}
          ref={map => {
            this.map = map;
          }}
          style={{ flex: 1 }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff"
  }
});


text:
Q: Regex syntax error with Sed command in Ubuntu 9.04 I have the sed command like this:
radius_clientsfile=clients.conf
iface_netsize="/64"
wireless_prefix=fd04:bd3:80e8:3::
sed -i "/client $wireless_prefix\\$iface_netsize/ {n s/\(\W*secret\W*=\W\).*/\1$key/}" $radius_clientsfile

clients.conf has the content like this:
client fd04:bd3:80e8:3::/64 {
  secret      = 00000000000000000000000000000001
}

which aim to replace value of secret by key in clients.conf file. For Example, if key is 00000000000000000000000000000002, the content of clients.conf should be changed as following:
client fd04:bd3:80e8:3::/64 {
      secret      = 00000000000000000000000000000002
    }

This script work on OpenWRT attitude adjustment r35400 for armv5tejl
However, it can not work in Ubuntu 9.04 with error:
 sed: -e expression #1, char 36: extra characters after command
Could anyone help me for this situation?

A: I think you need add a ; between command n and command s, like this
sed -i "/client $wireless_prefix\\$iface_netsize/ {n; s/\(\W*secret\W*=\W\).*/\1$key/}" $radius_clientsfile

This working in my cygwin environment.

A: You need to separate the commands in the command block with a semi-colon, so add a ; after the n command to separate it from the following command.
Like this:
{n;s/\(\W*secret\W*=\W\).*/\1$key/}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculate percentage of a False boolean in a column in Power BI I have a boolean column for my data and I need to calculate what percentage is False

A: FalsePercentage =
VAR totalRows = COUNTROWS('Table')
VAR falseRows =
  CALCULATE (
    COUNTROWS('Table'),
    'Table'[BoolColumn] = FALSE()
  )

RETURN DIVIDE(falseRows,totalRows)

Set the measure value type as percentage


text:
Q: Has mathoverflow yet led to mathematical breakthroughs? Some people ask questions here out of simple curiosity. But some ask them because they are working on a research project, come up with a question they need to know the answer to, and think that the answer is probably known. In the past, one had to search for the right person to tell you the answer or trawl through lots of books and articles, often not knowing quite where to look. Mathoverflow ought to be a far more efficient way of doing it.
So my question here (asked out of simple curiosity) is whether there are some good examples of people using mathoverflow in an essential way to solve a research problem. The best example would be a story such as this: you struggled to solve a problem, you identified a statement that you thought would be helpful, you asked about it on mathoverflow, you got an answer, and the answer was just what you needed to complete your research project.

A: My feeling is there have been a number of observations that could be expanded into short papers, such as  Kevin's example of a smooth proper scheme over Z with no section. I expect though that most of the time, people won't bother.

A: The answer to this question has saved me a lot of time and effort on my current research. Besides that, it helped me get a better understanding of the structures involved.

A: I have an example almost of the sort you are looking for, but not quite with the happiest ending (at least for me!). I was struggling to solve a problem. I identified a statement that would be helpful. I asked on mathoverflow. I got an answer. It turns out that both the statement and my intended application were about to appear in an article by some other authors.
In this instance mathoverflow has saved me a great deal of effort simply by allowing me to not work on the problem and read instead someone else's solution. Without mathoverflow it is very unlikely that I would have heard of the article before it was published. (It doesn't seem to be on the arxiv.)
In general, it seems to me that mathoverflow is an extremely efficient way of getting expert advice on research-level questions.

A: Hey Tim. I'm not so sure whether my model of how "proving a theorem" works is the same as yours. But let me give some kind of an example of something and you can take it or leave it. I'm writing a paper with Toby Gee at the minute, and we're both number theorists, and the arguments in the paper are "robust" but the details need checking. We're now at the point where we're writing up technical calculations and these technical calculations are mostly in the area of representation theory of reductive algebraic groups, an area which I think it's fair to say that neither Toby nor I would call ourselves experts in. So we have this overall "robust" argument, and a write-up that exists but occasionally says "lemma: (statement in representation theory); proof: TO BE ADDED". We 'know' these lemmas are true because they fit into our overall picture, but occasionally when I write one of these things up I can't go from my intuition to a rigorous proof. Here's an example of an occasion when I got stuck:
This question of mine.
Ben Webster made a crucial remark that enabled me to finish the argument, so that lemma went from "must be true but proof not yet written or even discovered by authors" to "lemma proved".
So if I were interpreting your question in a particularly anal way, one might argue that had this lemma been the last of the lemmas we need to write up the proof of, then Ben's contribution might be "just what I needed to complete my research project". Unfortuately there are several more to go :-).
Having said all that, it's not clear to me that MO was "crucial" to solving the problem. I could have worked more on the problem until I'd done it myself. I could have asked one of the representation theorists in my own department. I could have left it and hoped that my co-author sorted it out. All of these would have been viable approaches. Why did I ask at MO? Simply because I am sick of writing this paper and asking at MO was by no means the only way of solving the problem, but I had high hopes that it would be the quickest.
Kevin

A: John Pardon has solved the Hilbert-Smith conjecture for group actions on 3-manifolds.
Lemma 2.17 of the paper was based on the answer to this mathoverflow question. I was quite surprised to receive an e-mail a few months after answering the question with a preprint resolving the conjecture, especially since I did not know the identity of the MO user or for what purpose the question was intended.

A: My question about graph norms being cyclotomic received two inconclusive answers, but also resulted in another mathoverflow user contacting me and Noah Snyder about the problem. There's now an almost finished paper that completely answers the question.
I'm not sure if this exactly fits the mold of your question --- it's not that mathoverflow helped with a lemma, but rather that mathoverflow brought a difficult question to the attention of the right person.

A: This MO question
Walsh Fourier Transform of the Möbius function
was  aimed toward a certain conjecture (which was offered a few days earlier on my blog and Dick Lipton's blog) extending the prime number theorem (the constant one function is asymptotically orthogonal to the Mobius function) to certain class of low-complexity functions.  (Relpacing the constant one function.)
A few days after being posted Ben Green indicated a solution to the conjecture and a few days later the complete details appeared in a lovely short paper that Ben wrote. (Ben also indicated a method that may lead to a complete solution of the MO question, but this may require more work.)  This is a substantial advance.
In this case, this was not a question Dick and I struggled with but rather a question we hoped to attract an expert who may find it interesting.

A: See this very similar discussion on meta.MO.

A: Chris's answer to my first question definitely cleaned up some statements in my current project.

A: There was a question which could be interpreted as a question about Latin squares.  I presented at a problem session at our research group meeting at Monash, where it was completely resolved (at least, the part I'm directly interested in).
PS: Although, this is hardly a breakthrough.

A: David Speyer's answer to my question has helped me to finish my Senior Project paper. But it is more at the level of graduate level homework exercise or student research than serious breakthrough. In case anyone wishes to look at it, I proved David's basis really works as well as provided computational proof for some other small rank examples.


text:
Q: Is 'access to' redundant here? In a blog, I read the following line:

In its report, the Board has also asked the Special Investigation Team to investigate whether someone with access to either "insulin or hypoglycemic agent" was present near the Leela Palace hotel, where Sunanda died, on January 17, 2014.

To my mind, there is no need to put 'access to' here as the sentence looks ok without putting it:

In its report, the Board has also asked the Special Investigation Team to investigate whether someone with either "insulin or hypoglycemic agent" was present near the Leela Palace hotel, where Sunanda died, on January 17, 2014.

Is 'access to' redundant here? If no, then what does it signify in the sentence?

A:
I have access to insulin: I have an insulin pen on a bookshelf in my apartment.

Thus, I am a person who has access to insulin. However, then I go shopping or riding a bicycle, I don't take the insulin pen with me.
From the investigator's standpoint, I might have the insulin pen with me at any time, because I have access to it. It is the investigator's job to be suspicious of everyone.
So if someone is found dead and with an injection mark on his body, and I was nearby when this death occured, the investigator might suspect me of involvement in the crime.
However, the investigation will have to prove that I actually had some insulin with me during that time, because "having access" does not equal "having the insulin pen with you at the time of the crime".

A: access is not redundant here.
When you have something, you have it.
When you have an access to something, you don't have it, but you can have it whenever you require it.
Let's create a scene:

A terrorist has a gun and he entered into the hotel.

Here, the terrorist has it. You see a gun in his hand.
But then...

A terrorist has an access to a gun

may mean that you don't see a gun in his hands. But if he wants, he can have it. So, either he may have gun in his pocket from where he can have access to the weapon or in the hotel itself, he has hide the gun somewhere. He has access to it.

A: Of course if the someone died from an overdose of insulin, somebody would have had to have insulin on their person at the scene, However...
The reason for using the phrase has access to might be a technical one.
Insulin is a controlled substance so anyone one with normal access to it would either have to be of a certain rank or status, or a user.  They may be asking if either a medical person or a diabetic was at the scene of the crime thereby establishing how the medication was available.
As a corollary, usage of controlled substances are logged and there may be a record of where it came from.


text:
Q: Minimal polynomial of $e^{\frac{2 \pi i}{p^2}}$ (p is prime number) $X^{p^2}-1 = (X-1)(X^{p-1}+X^{p-2}+..+X+1)(X^{p(p-1)}+X^{p(p-2)}+..X^{p}+1)$
Then, $e^{\frac{2 \pi i}{p^2}}$ is a root of $f(X)=X^{p(p-1)}+X^{p(p-2)}+..X^{p}+1$
Hence, $g(X)=\frac{X^{p^2}-1}{X-1}$ for $X\neq 1$
thus, for $X \neq 0$ we have
$$g(X+1)=\frac{(X+1)^{p^2}-1}{X}=\sum_{i=1}^{p^2} \binom{p^2}{i}X^{i-1}$$
But $g(X)$ isn't irreducible and minimal polynomial
So, How can I prove it by Eisenstein Criteria?

A: The polynomial $$\frac{(x+1)^{p^2}-1}{(x+1)^p-1}$$ is Eisenstein at $p$.


text:
Q: Can I automatically 'Generate Scripts' in a SQL Server 2005 task? I'd like to automatically generate database scripts on a regular basis. Is this possible.

A: To generate script for an object you have to pass up to six parameters:
exec proc_genscript
    @ServerName = 'Server Name',
    @DBName = 'Database Name',
    @ObjectName = 'Object Name to generate script for',
    @ObjectType = 'Object Type',
    @TableName = 'Parent table name for index and trigger',
    @ScriptFile = 'File name to save the script'

http://www.databasejournal.com/features/mssql/article.php/2205291

A: You might want to look at the SQL Server Management Objects (SMO).  There are objects for scripting that will assist in generating T-SQL scripts from database objects.  A good reference for this is "Programming SQL Server 2005" by Bill Hamilton.  Chapter 12 in particular references the SMO utility classes.


text:
Q: Instance returning undefined (JS) I am currently learning JavaScript from MDN and have run into a weird issue that I can't quite figure out. When I type newSquare.sideLength, it returns undefined, despite the instance having a number passed through it. What I need is for it to return the number 4 like I have passed through when creating the instance.
I've tried the same thing with a previous class and it worked perfectly fine but I don't quite understand what is wrong here.
Here's my code:
// OOJS 1
class Shape {
    name;
    sides;
    sideLength;
    constructor(name, sides, sideLength) {
        this.name = name;
        this.sides = sides;
        this.sideLength = sideLength;
    }

    calcPerimeter() {
        console.log(this.sides * this.sideLength);
    }
}

class Square extends Shape {
    constructor(sideLength) {
        super(sideLength);
        this.name = 'Square';
        this.sides = 4;
    }

    calcArea() {
        console.log(Math.pow(this.sideLength, 2));
    }
}

const newSquare = new Square(4);
console.log(newSquare.sideLength);

p.s. Sorry if this has a really simple solution, I've hit a block and I'm really trying to figure it out.

A: Construction is just like another function and sequence of arguments should be same. when you pass super(sideLength); It sets name = 4 and other two arguments sets to undefined
You have to pass correct sequence of parameters in super function
super('Square', 4, sideLength);

A: The Shape Class constructor, receive 3 properties, but in the square class, you only call the super constructor with 1 parameter, in this case, the name.
So when you call newSquare.sideLength this property has not been initialized and its value is undefined.
In Javascript, you need to respect the order of parameters in a constructor or function.


text:
Q: Daemon in python generates defunct/zombie linux process I'm trying to spawn long processes from a flask application. So I have a main process that handles incoming web requests and from which I start daemons using the python-daemon library. Here is a minimal working example:
import os
import time
import daemon
import lockfile

def daemon_function():
    return True

working_directory = os.path.dirname(os.path.abspath(__file__))
pid_file = os.path.join(working_directory,"my_daemon.pid")

daemon_context = daemon.DaemonContext(
        working_directory=working_directory,
        pidfile=lockfile.FileLock(pid_file),
    )

pid = os.fork()
if pid == 0:
    with daemon_context:
        daemon_function()

time.sleep(10)

When I use the linux command ps -ef while the main process is still running, after the daemon process has terminated, I see this output:
user     2484     1  0 09:38 ?        00:00:01 /lib/systemd/systemd --user
user    11269  6061  0 12:07 pts/2    00:00:00 bash
user    28817 11269  1 15:43 pts/2    00:00:00 python test_daemon.py
user    28818 28817  0 15:43 pts/2    00:00:00 [python] <defunct>

The reason why I use the fork function before the with daemon_context: statement is that I need the main process to continue.
Should I worry about the created defunct process (I might spawn a lot of them) ? How could I avoid this zombie to appear?

A: If you don't want to create zombie processes you should wait for them to finish i.e. execute wait system call instead of sleep:
import os
import time
import daemon
import lockfile

def daemon_function():
    return True

working_directory = os.path.dirname(os.path.abspath(__file__))
pid_file = os.path.join(working_directory,"my_daemon.pid")

daemon_context = daemon.DaemonContext(
        working_directory=working_directory,
        pidfile=lockfile.FileLock(pid_file),
    )

pid = os.fork()
if pid == 0:
    with daemon_context:
        daemon_function()

os.waitpid(pid, 0)


text:
Q: How to use or expand environment variables in a command instantiated by CreateProcess? The following code utilizes CreateProcess to run commands with environmental variables. Here, it tries to run notepad %APPDATA%\test.txt.
If I run notepad %APPDATA%\test.txt directly within Windows' CMD, %APPDATA% will be expanded. However, the environmental variable can not be expanded when executed by CreateProcess. Could you help to comment on the reason and the workaround? Any comment will be appreciated!

    program TestConsole2;

    {$APPTYPE CONSOLE}

    uses
      Windows, SysUtils;

    var
      I: Integer;
      ProgramName: String;
      StartInfo  : TStartupInfo;
      ProcInfo   : TProcessInformation;
      CreateOK   : Boolean;
    begin
      try

        FillChar(StartInfo, SizeOf(StartInfo), #0);
        FillChar(ProcInfo, SizeOf(ProcInfo), #0);
        StartInfo.cb := SizeOf(StartInfo);

        ProgramName := 'NOTEPAD %APPDATA%\test.txt';
        CreateOK := CreateProcess(
          nil, PChar(ProgramName), nil, nil, True, 0, nil, nil, StartInfo, ProcInfo);
        if CreateOK then WaitForSingleObject(ProcInfo.hProcess, INFINITE);

        Readln(ProgramName);

      except
        on E: Exception do
          Writeln(E.ClassName, ': ', E.Message);
      end;
    end.

A: Call ExpandEnvironmentStrings to expand environment variables.
When you use cmd.exe, it performs the expansion for you. CreateProcess does not so you will need to do it before calling CreateProcess. Alternatively you could use ShellExecute which will expand environment strings.
Your current code does not meet the contract of CreateProcess. The second parameter must be a pointer to modifiable memory. You can get away with this if you are using the ANSI API but when targetting Unicode you code is liable to fail. Pass a pointer to modifiable memory rather than a pointer to a literal. If you added a call to expand the environment variables then you would end up with a modifiable string.
Finally, it looks like you are just trying to open a text file. Why force the user to view it in Notepad? My default editor for text files is not Notepad. I'd loath any program that forced Notepad on me. Instead let the shell open the file in the user's preferred editor. Call ShellExecute, use 'open' as the verb and pass the text file name as the file name parameter. On the other hand, perhaps you know all this and this is just example code. If so, please just ignore this advice.


text:
Q: Returning two object from a function without an ArrayList I'm not sure how to word this correctly, but I'm told to write a method that would return the largest course object (the course with the most students). If there are two courses that have the same number of students, it would return both.
The second part of the problem is what troubles me, because I'm not allowed to make another ArrayList other than the ones he specified (which is already used). Is there a way to keep track of two+ objects without using an list/hash?
This is what I've done so far, but it only returns one course object.
public Course largestEnrollment(){
    int size = 0;
    Course p = null;
    for (Integer c : courseList.keySet()){
        if (courseList.get(c).getClassList().size() > size){
            p = courseList.get(c);
            size = courseList.get(c).getClassList().size();
        }
        return p;
    }
    return null;
}

A: Return an array of Course objects:
public Course[] largestEnrollment(){

You'll need to decide how to manipulate the array inside your for loop.

A: Sort the ArrayList based on size. Then you can return a sub-list of the largest courses.

A: If you don't have so many Course (e.g. <1k), you could implement Comparable or write a Comparator for your Course object. So that you could just from the map get all Values(Course) in collection, then sort the collection, just from the end of the sorted collection take those elements with same values(size).
I mentioned the size of the collection because sort make the O(n) problem into O(nlogn). But if the size is small, it is a convenient way to go.
Anyway, you have to change the method return type to a collection or an array.

A: Sort then return a sublist:
public List<Course> largestEnrollment(List<Course> courses) {
    Collections.sort(courses, new Comparator<Course>() {
        @Override
        public int compare(Course o1, Course o2) {
            return o1.getClassList().size() - o2.getClassList().size();
        }
    });
    for (int indexOfLargest = 1; indexOfLargest < courses.size(); indexOfLargest ++) {
        if (courses.get(indexOfLargest - 1).getClassList().size() > courses.get(indexOfLargest).getClassList().size())
            return courses.subList(0, indexOfLargest);
    }
    return courses;
}


text:
Q: How to copy a row from one google spreadsheet to another google spreadsheet using google apps script? I wanted to copy a particular row from one spreadsheet to another spreadsheet using google apps script.
Can anyone please help me to get the answer for this.

A: NOTE: This solution works for copying rows from one sheet to another sheet in the SAME spreadsheet, and does NOT work for copying a row from a sheet to a DIFFERENT spreadsheet.
Check out the documentation here:
http://code.google.com/googleapps/appsscript/service_spreadsheet.html
Let's assume you're working in the spreadsheet where you're copying from.
You'd have to get a handle to the current spreadsheet and the target spreadsheet. You'll need to get the ID for the target spreadsheet. Details are in the link up there.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.openById("abc1234567");

Next we need to pick the particular sheets within those spreadsheets. Let's say your row is on the sheet named "New Stuff", and you have a sheet in the target spreadsheet named "Archive".
var source_sheet = ss.getSheetByName("New Stuff");
var target_sheet = target.getSheetByName("Archive");

Now, the concept that google apps spreadsheets use are ranges. A range is just a chunk of cells. So we need to determine the from-range and the to-range. Let's say your sheet has 7 columns and you want the 10th row.
var source_range = source_sheet.getRange("A10:G10");
var target_range = target_sheet.getRange("A1:G1");

So we're going to take that row and put it on the first row of the target sheet. Now for the actual copy:
source_range.copyTo(target_range);

And you're done!
Now, this will always clobber the first row of the target sheet. There's plenty you can do to stop that. Instead of always using the first line, you could use the sheet object methods to find the last row, add one after, and then use it as your range.
var last_row = target_sheet.getLastRow();
target_sheet.insertRowAfter(last_row);
var target_range = target_sheet.getRange("A"+(last_row+1)+":G"+(last_row+1));

That way each time you copy a row over, it just gets added to the bottom of the sheet.

A: The copyTo method is poorly documented, because it does not allow you to copy contents to a sheet in another spreadsheet.
You may want to use the getValues ans setValues like below:
function CopyDataToNewFile() {
  var sss = SpreadsheetApp.openById('0AjN7uZG....'); // sss = source spreadsheet
  var ss = sss.getSheetByName('Monthly'); // ss = source sheet
  //Get full range of data
  var SRange = ss.getDataRange();
  //get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();
  //get the data values in range
  var SData = SRange.getValues();

  var tss = SpreadsheetApp.openById('8AjN7u....'); // tss = target spreadsheet
  var ts = tss.getSheetByName('RAWData'); // ts = target sheet
  //set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);

}

A: I ran into this as well.  I managed to figure out a nice workaround that copies everything from one sheet to another (except for images, graphs, scripts and stuff). It copies formulas, values, formating for sure.
Basically the solution is to

*

*copy the source sheet to the target spreadsheet as a temp source sheet

*copy the data from the temp source sheet to the target sheet

*remove the temp source sheet

Code:
var sss = SpreadsheetApp.openById(spreadsheet); // sss = source spreadsheet
var ss = sss.getSheetByName(sheet); // ss = source sheet
var ss_temp = ss.copyTo(targetsheet);
var tss = SpreadsheetApp.openById(spreadsheet); // tss = target spreadsheet
var ts = tss.getSheetByName(sheet); // ts = target sheet
var range2Copy = ss_temp.getRange(range);
range2Copy.copyTo(ts.getRange(range));
bss.setActiveSheet(ss_temp);
bss.deleteActiveSheet()

Based on the above I created a spreadsheet that allows me to update many copies from a master spreadsheet. With about 15 copies, it saves a lot of copy-paste actions.

A: Another way of doing it would be to import the row (or any range) from the source into the target spreadsheet.
Assuming that you want to import row 3 from source spreadsheet's sheet called "source-spreadsheet-sheet-name", put in the first column of the target location the following formula:
=IMPORTRANGE("source-spreadsheet-key","source-spreadsheet-sheet-name!3:3")

where "source-spreadsheet-key" is the unque ID of the source spreadsheet that you extract from its URL.
If you do it first time, the security message will appear:

Just confirm and the whole row will be filled in automatically.
Please remember that sometimes it takes couple of minutes to update the imported cells after changes have been made in the source area. However you can speed it up by pressing ctrl-E, or ctrl-shift-E, while beeing in the target spreadsheet, whichever works.

A: This does not work - returns an error "Target range and source range must be on the same spreadsheet."  Looks like we need to do something similar to this:
function copyRow_ (origSheetName, destSheetName, origRowNumber, destRowNumber)
{
  var origSheetObject = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(origSheetName);
  var destSheetObject = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(destSheetName);
  var origLastCol = origSheetObject.getLastColumn();
  var arrOrigData = origSheetObject.getRange(origRowNumber, 1, 1, origLastCol).getValues();
  var destlastRow = destSheetObject.getLastRow() + 1;
  if (destRowNumber)
    destlastRow = destRowNumber;
  var cont;
  for (cont = 0; cont < origLastCol; cont++)
       destSheetObject.getRange(destlastRow, 1+cont).setValue(arrOrigData[0][cont]);
}

(blatantly stolen from here)

A: Use range.setValues, is the best choice.
Works for any range in any sheet, as far as the origin and destination range are similar.
Here's a sample code:
function openCSV() {

  //Buscamos el archivo
  var files = DriveApp.getFilesByName("ts.csv");

  //Cada nombre de archivo es unico, por eso next() lo devuelve.
  var file = files.next();

  fileID = file.getId();

  //Abrimos la spreadsheet, seleccionamos la hoja
  var spreadsheet = SpreadsheetApp.openById(fileID);
  var sheet = spreadsheet.getSheets()[0];

  //Seleccionamos el rango
  var range = sheet.getRange("A1:F1");
  values = range.getValues();

  //Guardamos un log del rango
  //Logger.log(values);

  //Seleccionamos la hoja de destino, que es la activeSheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var SSsheet = ss.getSheets()[0];

  //Seleccionamos el mismo rango y le asignamos los valores
  var ssRange = SSsheet.getRange("A1:F1");
  ssRange.setValues(values);

}


text:
Q: How to display arrays declared as vbox/hbox into main window? I was creating a function that was supposed to display elements into the Main window after a certain function is performed in IUP for Lua.
The problem was that whenever I run the function without arrays for vbox/hbox, the program displays the GUI elements as normal (in this test case, a textbox). I also tested this by having this display on a new window, which also worked. This is the normal code that I used:
function wa()
    local txt = {}
    txt[1] = iup.text{
      multiline = "NO",
      padding = "5x5",
      size="100x15",
      scrollbar="Horizontal",
    }
    iup.Append(hrbox, txt[1])
    iup.Map(txt[1])
    iup.Refresh(hrbox)
end

But when I ran the code by declaring an array variable as a hbox/vbox into the function, suddenly, the program just won't display the element into the main window, nor at the new window, at all:
function wa()
    local txt = {}
    local a = {}
    a[1] = iup.vbox{}
    txt[1] = iup.text{
      multiline = "NO",
      padding = "5x5",
      size="100x15",
      scrollbar="Horizontal",
    }
    iup.Append(a[1], txt[1])
    iup.Map(txt[1])
    iup.Refresh(a[1])
    iup.Append(hrbox, a[1])
    iup.Refresh(hrbox)
end

And then the strangest thing is that when I made the hrbox (the box I used to display elements into the main window) into a separate variable altogether, it does not display it in the main window, but it does display in the new window. Here's the code that came afterwards:
function wa()
    local txt = {}
    hrbox = iup.hbox{}
    a = {}
    a[1] = iup.vbox{}
    txt[1] = iup.text{
      multiline = "NO",
      padding = "5x5",
      size="100x15",
      scrollbar="Horizontal",
    }
    iup.Append(a[1], txt[1])
    iup.Map(txt[1])
    iup.Refresh(a[1])
    iup.Append(hrbox, a[1])
    iup.Refresh(hrbox)
end

How can I make an array variable that is declared as a hbox/vbox element  work so that it can displayed into the main window? I have no idea how to do it, and after going through all the research, I'm essentially stuck.
Any answers and suggestions is appreciated.
Thanks in advance!

A: I tried to create a minimal reproducible example:
local iup = require("iuplua")

local Button = iup.button{TITLE="Add"}
local hrbox  = iup.vbox{Button}
local Frame  = iup.dialog{hrbox,SIZE="THIRDxTHIRD"}

function wa()
    local txt = {}
    txt[1] = iup.text{
      multiline = "NO",
      padding = "5x5",
      size="100x15",
      scrollbar="Horizontal",
    }
    iup.Append(hrbox, txt[1])
    iup.Map(txt[1])
    iup.Refresh(hrbox)
end

Button.action = function (Ih)
  wa()
end

Frame:show()
iup.MainLoop()

So, basically, your code is working properly. Please make sure you declare hrbox above the wa.
EDIT: I just understand your question finally
You have an issue in this piece of code:
function wa()
    local txt = {}
    local a = {}
    a[1] = iup.vbox{}
    txt[1] = iup.text{
      multiline = "NO",
      padding = "5x5",
      size="100x15",
      scrollbar="Horizontal",
    }
    iup.Append(a[1], txt[1])
    iup.Map(txt[1])
    iup.Refresh(a[1])
    iup.Append(hrbox, a[1])
    iup.Refresh(hrbox)
end

You actually need to map the newly created hbox. The children will be automatically mapped in the same time. Calling refresh one time is enough.
local iup = require("iuplua")

local Button = iup.button{TITLE="Add"}
local hrbox  = iup.vbox{Button}
local Frame  = iup.dialog{hrbox,SIZE="THIRDxTHIRD"}

function wa()
    local txt = {}
    local a = {}
    a[1] = iup.vbox{}
    txt[1] = iup.text{
      multiline = "NO",
      padding = "5x5",
      size="100x15",
      scrollbar="Horizontal",
    }
    iup.Append(a[1], txt[1]) -- Append the text to the new-box
    iup.Append(hrbox, a[1])  -- Append the new-box to the main box
    iup.Map(a[1])            -- Map the new-box and its children
    iup.Refresh(hrbox)       -- Re-calculate the layout
end

Button.action = function (Ih)
  wa()
end

Frame:show()
iup.MainLoop()


text:
Q: Should I use != or <> for not equal in T-SQL? I have seen SQL that uses both != and <> for not equal. What is the preferred syntax and why?
I like !=, because <> reminds me of Visual Basic.

A: Most databases support != (popular programming languages) and <> (ANSI).
Databases that support both != and <>:

*

*Apache Derby 10.6: != and <>

*IBM Informix Dynamic Server 10: != and <>

*InterBase/Firebird: != and <>

*Microsoft SQL Server 2000/2005/2008/2012/2016: != and <>

*Mimer SQL 11.0: != and <>

*MySQL 5.1: != and <>

*Oracle 10g: != and <>

*PostgreSQL 8.3: != and <>

*Sybase Adaptive Server Enterprise 11.0: != and <>
Databases that support the ANSI standard operator, exclusively:

*

*IBM DB2 UDB 9.5: <>

*Microsoft Access 2010: <>

A: One alternative would be to use the NULLIF operator other than <> or != which returns NULL if the two arguments are equal NULLIF in Microsoft Docs. So I believe WHERE clause can be modified for <> and != as follows:
NULLIF(arg1, arg2) IS NOT NULL

As I found that, using <> and != doesn't work for date in some cases. Hence using the above expression does the needful.

A: Technically they function the same if you're using SQL Server AKA T-SQL.  If you're using it in stored procedures there is no performance reason to use one over the other. It then comes down to personal preference. I prefer to use <> as it is ANSI compliant.
You can find links to the various ANSI standards at...
http://en.wikipedia.org/wiki/SQL

A: The ANSI SQL Standard defines <> as the "not equal to" operator,
http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt (5.2 <token> and <separator>)
There is no != operator according to the ANSI/SQL 92 standard.

A: <> is the valid SQL according to the SQL-92 standard.
http://msdn.microsoft.com/en-us/library/aa276846(SQL.80).aspx

A: I preferred using != instead of <> because sometimes I use the <s></s> syntax to write SQL commands. Using != is more handy to avoid syntax errors in this case.

A: It seems that Microsoft themselves prefer <> to != as evidenced in their table constraints.  I personally prefer using != because I clearly read that as "not equal", but if you enter [field1 != field2] and save it as a constrait, the next time you query it, it will show up as [field1 <> field2].  This says to me that the correct way to do it is <>.

A: They're both valid and the same with respect to SQL Server,
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/not-equal-to-transact-sql-exclamation

A: !=, despite being non-ANSI, is more in the true spirit of SQL as a readable language. It screams not equal.
<> says it's to me (less than, greater than) which is just weird. I know the intention is that it's either less than or greater than hence not equal, but that's a really complicated way of saying something really simple.
I've just had to take some long SQL queries and place them lovingly into an XML file for a whole bunch of stupid reasons I won't go into.
Suffice to say XML is not down with <> at all and I had to change them to != and check myself before I riggedy wrecked myself.

A: You can use whichever you like in T-SQL. The documentation says they both function the same way. I prefer !=, because it reads "not equal" to my (C/C++/C# based) mind, but database gurus seem to prefer <>.

A: '<>' is from the SQL-92 standard and '!=' is a proprietary T-SQL operator. It's available in other databases as well, but since it isn't standard you have to take it on a case-by-case basis.
In most cases, you'll know what database you're connecting to so this isn't really an issue. At worst you might have to do a search and replace in your SQL.

A: I understand that the C syntax != is in SQL Server due to its Unix heritage (back in the Sybase SQL Server days, pre Microsoft SQL Server 6.5).

A: Both works and I think any difference would be very negligible!
Just focus on productivity guys!
What is the value of your script? What does it do? How will it contribute to the business? Will it make more money?
Focus on these goals instead of these programmer prefered preferences.
This is like which is better C# or Visual Basic languages.
As if the end user cares what was used to write the App?
What the end user cares about is what your App could do.
How could it help him with what he is doing.

A: They are both accepted in T-SQL. However, it seems that using <> works a lot faster than !=. I just ran a complex query that was using !=, and it took about 16 seconds on average to run. I changed those to <> and the query now takes about 4 seconds on average to run. That's a huge improvement!


text:
Q: Adding an element to the end of an array in VBA Q&A:
How can one add an element to a the end of a (dynamic) array in VBA?
This same question was for a list in stead of an array:
Adding an element to variant list/array in VBA
This same question was about redimensioning arrays with 2 dimensions:
ReDiming an array in VBA
This same question did not ask for the general simple case:  https://superuser.com/questions/808798/adding-an-element-to-the-end-of-an-array

A: This is a short VBA code to:

*

*Create a dynamic array.

*Redimension a dynamic array to 3 elements.

*Fill the newly added element with a value.
Sub ChangingArrayLengthShort()
    ' First create array:
    Dim arr() As Variant
    Dim u As Integer
    u = 3

    ReDim arr(1 To u + 1) ' Redimension:
    arr(UBound(arr)) = "SomeValue" ' Fill last element
End Sub

This is that code explained:
Sub ChangingArrayLength()
    Dim arr() As Variant ' One can only redimension a dynamic array, so:
    'Dim arr(43 to 65) As Variant ' Will yield an error since it is not a dynamic- but a static array.

    Dim NrOfElements As Integer

    NrOfElements = 3
    ReDim arr(1 To NrOfElements) ' Re-dimension array length
    MsgBox (UBound(arr)) ' Show what the last element index is in array arr.

    NrOfElements = NrOfElements + 1 ' Increase the variable that is used to increase the nr of elements in array arr.
    ReDim arr(1 To NrOfElements) ' Re-dimension array length
    MsgBox (UBound(arr)) ' Show what the last element index is in array arr. (And that it increased by 1)

    ' Add value at element to the end of an array:
    arr(UBound(arr)) = "This string is added as last element of array named arr"
End Sub

A: I've already encountered this problem and I solved this way
 aArray(Array.IndexOf(aArray, aArray.Last)) 'this same reDim action for resize

It also solves the error of the reDim


text:
Q: is it possible to check in html that internet is connected? I am creating a webview. My apps displaying my folder link when internet connection is off.
Is it possible to check in html that internet is connected/not connected and displayed manual messages ? i want to hidden error in mobile browser like as.
The webpage at http://www.example.com could not be loaded as :
net:: ERR_NAME_NOT_RESOLVED

A: HTML is a markup language, So no, You can't. I also don't really get what you are trying to ask. people can't connect to your website without internet.


text:
Q: Python - is it better practice to use global var or pass to function when variable will only be used on error I have a aws python lambda with 7 functions. 1 of them is using a variable that is extracted from the payload called file_id. I now need that in another function that is called directly from this function but will only use it on the rare occasion of throwing an error.
eg.
def execute(event, context):
    body = get_body(event)
    file_id = get_file_id(body)
    # do some stuff here that generates service_header abd service_payload variable
    call_external_service(service_header, service_payload)
    # do some more stuff here that is irrelevant

def call_external_service(header, payload)
     # do some irrelevant stuff
     try:
        response = requests.put(
            url, data=payload, headers=headers
        )
    except Exception as e:
         LOGGER.info(
            "Failed request for file_id "
            + str(file_id) # obviously this isn't available wondering is it better to pass in or make global, it will rarely be used.
        )
        send_file_id_to_database(file_id);

Is it better practice to send it into the method by adding an extra parameter or is it better to  make it global. It will only be used rarely when another service is down.

A: Passing it in as a parameter is often considered better coding practice for several reasons, one of which being that it's easier to test the function that takes file_id as a parameter than if it accessed it as a global.


text:
Q: Add a new class into the css style with javascript how can i insert a new class into the current css?
var myStyle = $("head > style:eq(2)");

if( document.styleSheets[2].cssRules ) {
    myStyle.insertRule('#test { display:block; }', 0);
} else {
    if ( document.styleSheets[2].rules ) {
        myStyle.addRule('#test', 'display:block;');
    }
}

dd

A: You appear to be switching between a styleSheet object and the result of a framework's selector function (possibly jQuery).  Stick with document.styleSheets for the whole thing:
var myStyle = document.styleSheets[2];

if( myStyle.cssRules ) {
    myStyle.insertRule('#test { display:block; }', 0);
} else if ( myStyle.rules ) {
    myStyle.addRule('#test', 'display:block;');
}

nb: I did away with the redundant if block, switching to an else if instead.  You could do away with the else if condition and just leave it as else, if you wanted.


text:
Q: Moments in Java OpenCV 3.0 According to old documentation, there is
org.opencv.imgproc.Moments
but I am not able to load it for OpenCV 3.0.
Was this functionality moved?

A: yes, it seems to be gone.
maybe make an issue ?


text:
Q: I need a 802.11 caputure of the full wpa authentcation process I cant seem to get wireshark to work with my NIC to capture the raw 802.11 packets. I need just a screenshot, showing this exchange.

A: Which platform are you using? In general there is very limited support for any packet capture with wireless adaptors, especially on windows. See the following:
http://wiki.wireshark.org/CaptureSetup/WLAN#Windows


text:
Q: After upgrade to Mountain Lion, Flex apps won't load on phone I've developed two air for android apps that are on the market using Adobe Air/ Flash Builder..
I just purchased a new mac laptop with Mountain Lion which is a big upgrade over my old machine.
The problem is, when I loaded my old project folders into Flash Builder 4.6 on my new machine, they compile fine with no errors.
When I hit run, it begins to export the app to the Android device like normal, it then tuns the device's screen black as if the app is starting... then crashes.
If I hit debug, it starts the connection countdown and never connects to the debugger. Then it turns black and crashes just as before.
It doesn't give me any errors at all. I can't run it in the simulator because it has extensions that break it.
Just as a test, I started a new project and ran that on my phone, and it worked perfectly. So it's only the old projects that won't work..
What's crazy is the same exact project folder, if i put it on a USB drive, put it on my old copmuter, or my friends Macbook with Lion, export it to android to the same Android device...it works!...
I've already tried the following:

*

*Re-installed flashbuilder 4.6, installed 4.7 and test with that

*Downloaded the projects off of svn, and directly from an external hardrive to see if it was svn error

*Deleted all hidden filed within the project folders that may have had machine specific information in them

*Started a new project under the same name, manually recreated all the folders and pasted each individual file into them

*Tested it on multiple devices to see if it was just my phone

Any help would be greatly appreciated, I'm at a total loss, because the projects work on my old computer with Snow Leopard, my friend's computer with Lion, but won't work on mine at all!

A: Generally when an application is tested locally, it will attempt to cross one or more sandboxes especially in the area of security. Loading local assets vs. networked URL assets, etc.
As far as I know it still holds true today, but if you place your development folder in the 'trusted' space, you're apps are allowed a lot more freedom. I'm assuming the mac world is either the same or has a very close equivalent, but the PC route is to R-Click a running flash app > global settings > security manager > and add your workspace to the trusted space.
This might get you there a little quicker:
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html
If it's working on an equivalent cpu from your friend, what player version are you running vs. what he/she is running?

A:
Tested it on multiple devices to see if it was just my phone

What was the outcome of this?
Have you ensured you have the correct USB Drivers installed to remotely debug on the android device?


text:
Q: Keeping track of references in Java In Java, is there any way to tell whether or not references are being maintained to an object in other threads (or generally)?
Consider the following class:
public class ResourcePool<TYPE>
{
    private final Queue<Object> emptyLocks = new LinkedBlockingQueue<>();

    private final Queue<TYPE> available = new LinkedBlockingQueue<>();
    private final Queue<TYPE> claimed = new LinkedBlockingQueue<>();

    public void add(TYPE resource)
    {
        available.add(resource);
    }

    public TYPE claim() throws InterruptedException
    {
        if (available.isEmpty())
        {
            Object lock = new Object();
            synchronized (lock)
            {
                emptyLocks.add(lock);
                lock.wait();
            }
        }

        TYPE resource = available.poll();
        claimed.add(resource);
        return resource;
    }

    public void release(TYPE resource)
    {
        if (!claimed.remove(resource)) return;
        available.add(resource);

        Object lock = emptyLocks.poll();
        if (lock != null) synchronized (lock) {lock.notify();}
    }
}

The idea here is that multiple threads can claim/release resources such that two threads can never own the same resource at any given moment. But what happens if a thread forgets to release() a resource? Worse yet, what if the thread calls release() and then keeps doing stuff with the resource?
Using the WeakReference class, it's possible to tell when there exist no more strong references to a given object. However, when that happens, the object is garbage-collected and it's gone. SoftReference might work, but then there's still a chance that our resource will be GC'd before we can put it back in the "available" list.
So here's the question: Is there any way to keep track of whether these resources are still actually being used?
Ideally, threads could claim() resources, use them as long as they want, and those resources would be freed up automatically as soon as no more references are maintained. I think that would be very elegant, and useful in other situations too.

A: The answer is simple: No
GC works at VM global level and in current implementation (at least in Hotspot) it doesn't use reference counting, much less reference tracking. That means even the VM doesn't always know what is referenced at arbitrary points in time.
The GC is also generally the wrong tool for tracking things that need to be released in a timely manner; the GC may run only very infrequently (in extreme cases the GC may be tuned to run once every few hours). You probably want your resources to be available to other threads as soon as the owning block scope ends; a requirement vastly different from the lax handling by the GC.
What you want is immediate detection for things going out of scope per thread. While a nice feature, the question is if that would ever be worth  the performance impact it costs.
The example of your resources and a thread "forgetting" to release / retaining the resource after release is a something that can be dealt with by convention: use try-finally or maybe abuse try-with-resources blocks to make sure the life cycle is properly maintained.
To catch accidental leaking of a resource, you can abuse finalize; but again its not predicatble when resources get finalized (and you can only do cleanup, resurrecting the resource should not be done; see the JLS about finalize for that).
Edit: You can easily defend against rouge threads using a resource after release by stroing the owner in the resource. The resource can then do runtime checking that the calling thread is indeed the current owner.

A: You're searching for the finalize() method. You have to override this method to clean up when an object is not reachable any more.
Please note that creating a finalize() method is not as easy as it looks like (as explained in these answers).


text:
Q: VirtualBox and Vagrant stops working after Docker desktop instalation on Win10 pro On win 10 pro I got VM, Vagrant and Homestead.
After installation Docker Desktop VM, Vagrant stops working.
Message from console:
 $ vagrant up --provision
Bringing machine 'homestead' up with 'virtualbox' provider...
==> homestead: Checking if box 'laravel/homestead' version '10.1.0' is up to date...
==> homestead: A newer version of the box 'laravel/homestead' is available and already
==> homestead: installed, but your Vagrant machine is running against
==> homestead: version '10.1.0'. To update to version '10.1.1',
==> homestead: destroy and recreate your machine.
==> homestead: Clearing any previously set forwarded ports...
==> homestead: Clearing any previously set network interfaces...
==> homestead: Preparing network interfaces based on configuration...
    homestead: Adapter 1: nat
    homestead: Adapter 2: hostonly
==> homestead: Forwarding ports...
    homestead: 80 (guest) => 8000 (host) (adapter 1)
    homestead: 443 (guest) => 44300 (host) (adapter 1)
    homestead: 3306 (guest) => 33060 (host) (adapter 1)
    homestead: 4040 (guest) => 4040 (host) (adapter 1)
    homestead: 5432 (guest) => 54320 (host) (adapter 1)
    homestead: 8025 (guest) => 8025 (host) (adapter 1)
    homestead: 9600 (guest) => 9600 (host) (adapter 1)
    homestead: 27017 (guest) => 27017 (host) (adapter 1)
    homestead: 22 (guest) => 2222 (host) (adapter 1)
==> homestead: Running 'pre-boot' VM customizations...
==> homestead: Booting VM...
==> homestead: Waiting for machine to boot. This may take a few minutes...
    homestead: SSH address: 127.0.0.1:2222
    homestead: SSH username: vagrant
    homestead: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.

If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

I know there is problem with sharing
Hyper-V,
or windows subsystem for Linux.
Please give the solution how you can work with them on same windows 10.

A: This thread here: https://github.com/hashicorp/vagrant/issues/11987 outlines the same problem. When WSL2 is enabled as part of the Docker install, the vagrant up command hangs.
The commenter here: https://github.com/hashicorp/vagrant/issues/11987#issuecomment-758089840 mentions that by disabling the VirtualMachinePlatform and restarting the machine, vagrant will work as normal again.
Of course, it's not an ideal solution especially if you need to use Docker but it does offer a temporary solution.

A: Answer https://github.com/hashicorp/vagrant/issues/11987#issuecomment-777256616 by johollmann works for me and others (according to likes):
"My current workaround is to open VirtualBox Manager and select the virtual maschine, my vagrant is boooting up. It seems wiered but having the vm just in focus in VirtualBox GUI during vagrant up solves the problem"

A: WSL2 does not play well with VirtualBox.
Since you are Win 10 Pro, why not using Hyper-V?
You can see this benchmark, using Hyper-V is A LOT FASTER...
You can follow this step-by-step guide to setup.
If you want to try out Docker+WSL2, you can use Official Laravel Sail.
You can follow this tutorial to setup.


text:
Q: `Error: MLIR Pass Manager Failed': TensorFlow on MacBook Pro M1 Max I'm running Python 3.9.7 and TensorFlow 2.5 on my MacBook Pro with M1 Max chip, in a virtual environment managed through MiniForge. (Setup due to Jeff Heaton).
I have a custom loss function in the model. This code runs fine on my other machine, which is Ubuntu-based Pop!OS.
When I run model.fit from Keras, I occasionally get the following errors. Sometimes it runs just fine. Any idea what's causing it, why it only happens sometimes, and how to fix it?
In addition, it only produces this error from my custom loss function. Not from any Keras-native.
Thanks!
:5:10: error: invalid length (0) for size 20                                                                                | 0.00/1.00 [00:00<?, ?batch/s]
-:5:10: error: 'mps.slice' op failed to fold or infer return types
-:5:10: note: see current operation: %2 = "mps.slice"(%arg0) {axis = 0 : si32, length = 999 : i32, start = 1 : i32} : (tensor<20xf32>) -> tensor<*xf32>
/System/Volumes/Data/SWE/macOS/BuildRoots/5b2e67f8af/Library/Caches/com.apple.xbs/Sources/MetalPerformanceShadersGraph/MetalPerformanceShadersGraph-2.2.1/mpsgraph/MetalPerformanceShadersGraph/Core/Files/MPSGraphExecutable.mm:1179: failed assertion `Error: MLIR pass manager failed'
model.fit(tf.convert_to_tensor(Σ),tf.zeros((T,output)),batch_size=T,epochs=1,verbose=0,callbacks=[TqdmCallback()])#,tbc])
zsh: abort      python3
(tensorflow) kpmott@kevins-mbp-7 tf.olg % model.fit(tf.convert_to_tensor(Σ),tf.zeros((T,output)),batch_size=T,epochs=1,verbose=0,callbacks=[TqdmCallback()])#,tbc])
zsh: parse error near `)'
(tensorflow) kpmott@kevins-mbp-7 tf.olg % /opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/lib/python3.9/multiprocessing/resource_tracker.py:216: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown
  warnings.warn('resource_tracker: There appear to be %d '
model.fit(tf.convert_to_tensor(Σ),tf.zeros((T,output)),batch_size=T,epochs=1,verbose=0,callbacks=[TqdmCallback()])#,tbc])
zsh: parse error near `)'


text:
Q: Duplicate checking two very big tables I'm currently trying to check for duplicates across two tables, but these tables are huge I have two tables, one with about 60 million numbers and one with about 16 million numbers.
The server is a 16 Core Xeon, 32GB DDR3 RAM 14900, 2x 15K SAS.
I tried to run this command SELECT number FROM numbers,newData WHERE newData.number = numbers.number so that I can find out how many duplicates we have, but I left it for 24 hours with no such luck.
I've now written a php script that loops through 20 at a time and write to the newData table yes if it exists, but this is taking 6 seconds per number.
How can I speed this up? I have done all the optimizations possible for mysql including the inno_db_buffer_pool.

A: Your query seems ok, but you should be sure that your number columns are indexed in both tables.
If they are not create an index over each of them, which could take a while and take some disk. But if this is something you want to run multiple times it will be worth it.

A: Try:
SELECT number
  FROM numbers
WHERE exists (
     select 1
       From newData
      where numbers.number = newData.number
)

OR
SELECT numbers.number
  FROM numbers
  JOIN newData
  ON numbers.number = newData.number

If you could as well post the explain from both queries and from your query would be good.


text:
Q: Using webpack to add customizer live preview functionality - wp.customize is not a function So I'm using webpack to bundle my files. And I want to add a script that will enable me to change settings in the customizer on the fly.
I created a class which will hold all my customizer functionality
<?php
/**
 * The Customizer specific functionality.
 *
 * @since   1.0.0
 * @package mytheme
 */

namespace MyTheme\Customizer;

use MyTheme\Helpers as Helpers;

/**
 * Class Customizer
 */
class Customizer {

  /**
   * Global theme name
   *
   * @var string
   *
   * @since 1.0.0
   */
  protected $theme_name;

  /**
   * Global theme version
   *
   * @var string
   *
   * @since 1.0.0
   */
  protected $theme_version;

  /**
   * Initialize class
   *
   * @param array                  $theme_info Load global theme info.
   * @param Helpers\General_Helper $helpers Instance of the General Helpers object.
   *
   * @since 1.0.0
   */
  public function __construct( $theme_info = null, Helpers\General_Helper $helpers ) {
    $this->theme_name    = $theme_info['theme_name'];
    $this->theme_version = $theme_info['theme_version'];

    $this->helpers = $helpers;

  }

  /**
   * Register customizer settings
   *
   * @see add_action('customize_register',$func)
   * @param  \WP_Customize_Manager $wp_customize WP Customize object.
   * @since 1.0.0
   */
  public function register_customizer_settings( \WP_Customize_Manager $wp_customize ) {
    // Abort if selective refresh is not available.
    if ( ! isset( $wp_customize->selective_refresh ) ) {
      return;
    }

    /**
     * Footer section
     */
    $wp_customize->add_section( 'footer_section', array(
        'title'    => esc_html__( 'Footer', 'mytheme' ),
        'priority' => 100,
    ) );

    /**
     * Copyright notice
     */
    $wp_customize->add_setting( 'footer_copyright', array(
        'default'           => '',
        'type'              => 'theme_mod',
        'transport'         => 'postMessage',
        'sanitize_callback' => 'wp_kses_post',
    ) );

    $wp_customize->add_control( 'footer_copyright', array(
        'label'       => esc_html__( 'Footer Copyright Text', 'mytheme' ),
        'section'     => 'footer_section',
        'type'        => 'text',
    ) );
  }

  /**
   * Enqueue live preview script
   *
   * @since 1.0.0
   */
  public function live_preview_enqueue() {
    $customizer_script = '/skin/public/scripts/customizer.js';

    wp_register_script( $this->theme_name . '-customizer', get_template_directory_uri() . $customizer_script, array(), $this->helpers->get_assets_version( $customizer_script ) );
    wp_enqueue_script( $this->theme_name . '-customizer', array( 'jquery', 'customize-preview' ), false );
  }
}

In another class where I load my actions I have
private function define_customizer_hooks() {
  $customizer = new Customizer\Customizer( $this->get_theme_info(), new Helpers\General_Helper() );

  $this->loader->add_action( 'customize_register', $customizer, 'register_customizer_settings', 11 );
  $this->loader->add_action( 'customize_preview_init', $customizer, 'live_preview_enqueue' );
}

Now, I can see my settings just fine. The Footer section is showing. But I get an error in my console

jQuery.Deferred exception: wp.customize is not a function TypeError: wp.customize is not a function

The customizer.js looks like this
/* global wp */
$(function() {
  wp.customize('footer_copyright', (value) => {
    value.bind((newval) => {
      if ($('.footer__copyright').length) {
        if (newval !== '') {
          if ($('.footer__copyright').hasClass('hide')) {
            $('.footer__copyright').removeClass('hide').text(newval);
          } else {
            $('.footer__copyright').text(newval);
          }
        } else {
          $('.footer__copyright').addClass('hide');
        }
      } else {
        $('.footer__container').append(`<div class="footer__copyright">${newval}</div>`);
      }
    });
  });
});

And my webpack.config.js looks like this:
/* global process __dirname */

const DEV = process.env.NODE_ENV !== 'production';

const path = require('path');
const webpack = require('webpack');

const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

const appPath = `${path.resolve(__dirname)}`;

// Dev Server
const proxyUrl = 'mytheme.test';

// Theme
const themeName = 'mytheme';
const themePath = `/wp-content/themes/${themeName}/skin`;
const themeFullPath = `${appPath}${themePath}`;
const themePublicPath = `${themePath}/public/`;
const themeEntry = `${themeFullPath}/assets/application.js`;
const themeAdminEntry = `${themeFullPath}/assets/application-admin.js`;
const themeGutenbergEntry = `${themeFullPath}/assets/application-gutenberg.js`;
const themeCustomizerEntry = `${themeFullPath}/assets/customizer.js`;
const themeOutput = `${themeFullPath}/public`;

// Outputs
const outputJs = 'scripts/[name].js';
const outputCss = 'styles/[name].css';
const outputFile = '[name].[ext]';
const outputImages = `images/${outputFile}`;
const outputFonts = `fonts/${outputFile}`;

const allModules = {
  rules: [
    {
      test: /\.(js|jsx)$/,
      use: 'babel-loader',
      exclude: /node_modules/,
    },
    {
      test: /\.json$/,
      exclude: /node_modules/,
      use: 'file-loader',
    },
    {
      test: /\.(png|svg|jpg|jpeg|gif|ico)$/,
      exclude: [/fonts/, /node_modules/],
      use: `file-loader?name=${outputImages}`,
    },
    {
      test: /\.(eot|otf|ttf|woff|woff2|svg)$/,
      exclude: [/images/, /node_modules/],
      use: `file-loader?name=${outputFonts}`,
    },
    {
      test: /\.scss$/,
      exclude: /node_modules/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader', 'postcss-loader', 'sass-loader',
      ],
    },
  ],
};

const allPlugins = [
  new MiniCssExtractPlugin({
    filename: outputCss,
  }),

  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
  }),

  // Use BrowserSync For assets
  new BrowserSyncPlugin({
    host: 'localhost',
    port: 3000,
    proxy: proxyUrl,
    files: [
      {
        match: ['wp-content/themes/**/*.php', 'wp-content/plugins/**/*.php'],
      },
    ],
  }),

  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
    },
  }),

  new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
];

const allOptimizations = {
  runtimeChunk: false,
  splitChunks: {
    cacheGroups: {
      commons: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendors',
        chunks: 'all',
      },
    },
  },
};

// Use only for production build
if (!DEV) {
  allOptimizations.minimizer = [
    new UglifyJsPlugin({
      cache: true,
      parallel: true,
      sourceMap: true,
      uglifyOptions: {
        output: {
          comments: false,
        },
        compress: {
          warnings: false,
          drop_console: true, // eslint-disable-line camelcase
        },
      },
    }),
  ];
  allPlugins.push(new CleanWebpackPlugin([themeOutput]));
}

module.exports = [

  // Theme Skin
  {
    context: path.join(__dirname),
    entry: {
      application: [themeEntry],
      applicationAdmin: [themeAdminEntry],
      themeGutenberg: [themeGutenbergEntry],
      customizer: [themeCustomizerEntry],
    },
    output: {
      path: themeOutput,
      publicPath: themePublicPath,
      filename: outputJs,
    },

    optimization: allOptimizations,

    mode: 'production',

    module: allModules,

    plugins: allPlugins,

    devtool: DEV ? '#inline-source-map' : '',
  },
];

and package.json is
{
  "name": "mytheme",
  "version": "1.0.0",
  "author": "dingo_d",
  "private": true,
  "main": "",
  "scripts": {
    "__sassUnusedTheme": "sass-unused \"wp-content/themes/init_theme_name/**/*.scss\"",
    "__eslintTheme": "eslint wp-content/themes/init_theme_name/skin/assets/",
    "__stylelintTheme": "stylelint \"wp-content/themes/init_theme_name/**/*.scss\" --syntax scss",
    "precommitCss": "npm run __stylelintTheme",
    "precommitCssUnused": "npm run __sassUnusedTheme",
    "precommitJs": "npm run __eslintTheme",
    "precommit": "npm run precommitJs && npm run precommitCss && npm run precommitCssUnused",
    "start": "webpack --progress --watch --display-error-details --display-reasons",
    "build": "NODE_ENV=production webpack --progress"
  },
  "devDependencies": {
    "@infinumjs/eslint-config": "^1.1.0",
    "@infinumjs/stylelint-config": "^1.0.0",
    "babel-core": "^6.26.3",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-syntax-dynamic-import": "^6.18.0",
    "babel-preset-env": "^1.6.1",
    "browser-sync": "^2.24.1",
    "browser-sync-webpack-plugin": "^2.2.2",
    "clean-webpack-plugin": "^0.1.19",
    "copy-webpack-plugin": "^4.5.1",
    "css-loader": "^0.28.11",
    "eslint": "^4.19.1",
    "eslint-plugin-import": "^2.11.0",
    "expose-loader": "^0.7.5",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.11",
    "imports-loader": "^0.8.0",
    "mini-css-extract-plugin": "^0.4.0",
    "node-sass": "^4.9.0",
    "postcss-cssnext": "^3.1.0",
    "postcss-loader": "^2.1.4",
    "precss": "^3.1.2",
    "sass-loader": "^7.0.1",
    "style-loader": "^0.21.0",
    "stylelint": "^9.2.0",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.1.2"
  },
  "dependencies": {
    "autoprefixer": "^8.4.1",
    "babel-polyfill": "^6.26.0",
    "bugsnag-js": "^4.6.0",
    "css-mqpacker": "^6.0.2",
    "cssnano": "^3.10.0",
    "jquery": "^3.3.1",
    "jquery-match-height": "^0.7.2",
    "layzr.js": "^2.2.2",
    "media-blender": "^2.1.0",
    "normalize.css": "^8.0.0",
    "npm": "^6.0.0",
    "postcss-font-magician": "^2.1.1",
    "slick-carousel": "^1.8.1",
    "whatwg-fetch": "^2.0.4"
  },
  "browserslist": [
    "android >= 4.2",
    "not ie < 11",
    "last 2 versions",
    "Safari >= 8"
  ]
}

The thing that bothers me is that I basically used (and modified) my code that works in the theme that is built without all the fancy build tools (https://themes.svn.wordpress.org/expire/1.0.9/inc/customizer/js/customizer.js)
I tried with
/* global wp */
(function(api) {
  api('footer_copyright', (value) => {
    value.bind((newval) => {
      if ($('.footer__copyright').length) {
        if (newval !== '') {
          if ($('.footer__copyright').hasClass('hide')) {
            $('.footer__copyright').removeClass('hide').text(newval);
          } else {
            $('.footer__copyright').text(newval);
          }
        } else {
          $('.footer__copyright').addClass('hide');
        }
      } else {
        $('.footer__container').append(`<div class="footer__copyright">${newval}</div>`);
      }
    });
  });
})(wp.customize);

But again, I got

Uncaught ReferenceError: wp is not defined

And in the inspector wp.customize is available.
What am I doing wrong?


text:
Q: How might a resonant antenna and black body radiation interact? How does an antenna behave when it is cooled so that its black-body radiation is emitting energy at its resonant frequency?
Edit: To clarify, its not how they're related in general, but how might thermal radiation and resonance interact with each other when their spectra are aligned well?
Edit: Also, I'm sure that the thermal radiation spectra that have a significant peaks are associated with incredibly high temperatures, and peak at incredibly small wavelengths, rendering such an antenna completely impractical to build. Still, I'm still interested in the theoretical concept.

A: OK, the simple answer:
When there is  a resonance in the antenna  you have a coherent phenomenon. All the bands of electrons of the antenna are marching in tune.
The black body radiation is an incoherent phenomenon coming from the individual atoms of the antenna. Even if the peak of the black body radiation were sitting on the resonance of the antenna it is still an incoherent phenomenon that cannot couple to the coherent behavior of the electrons in the current that resonate.
Think of a single violin tune and a crowd of people talking. The noise of the people does not cover the clarity of the violin even in high volumes.

A: They're not related. The black-body radiation as well as the resonance curve may look like "bumps" but they are very different bumps mathematically. The black body radiation gets emitted at all frequencies, and the "uncertainty of the frequency" is maximized, in some sense. On the other hand, resonances are peaked around a particular frequency.
Resonance curves are about matrix elements between pure states; thermal curves are traces over the whole Hilbert spaces so they arise from mixed stated. That's why the exponentials only appear in the thermal curves.
So the only thing they share is that they produce intensities as a function of frequency - but many other things in physics do the same thing - and in both cases, complex numbers are useful ($E_0-i\Gamma/2$ for resonances and imaginary time $i\beta$ in the thermal case) - but complex numbers are useful across physics.


text:
Q: Código JavaScript me ejecuta correctamente en mi IDE pero al pasarlo a la página de evaluación me da error Debo encontrar en una matriz un valor par si los demás son impares e impar si los demás son pares. Me corre en mi IDE pero en la página de evaluación me da error, resalto que sólo uno de los valores debe ser par o impar y el resto debe ser contrario a ese único valor.
    var integers = [0, 1, 2];
    //var integers = [2, 4, 0, 100, 4, 11, 2602, 36];
    //var integers = [160, 3, 1719, 19, 11, 13, -21];

    findOutlier(integers);

    function findOutlier(integers){
      var impar = 0;
      var par = 0;
      var contaPar = 0;
      var contaImpar = 0;

        for (let i = 0; i < integers.length; i++){

            divi = parseInt((integers[i] % 2));

            if(divi == 0){
                contaPar +=1;
                par = parseInt(integers[i]);

            }else{
                contaImpar +=1;
                impar = parseInt(integers[i]);

            }
        }

        if(contaPar > contaImpar){
            return console.log('El número diferente es impar: ' + impar);
        }else{
            return console.log('El número diferente es par: ' + par);
        }

    }

Les paso un pantallazo de la página de evaluación.

A: El fallo es que tu función no devuelve nada:
return console.log('El número diferente es impar: ' + impar);

debería ser:
console.log('El número diferente es impar: ' + impar);
return impar;

porque la llamada a console.log no devuelve nada


text:
Q: Robust Javascript Exception Handling I am developing a DHTML/Javascript application which relies on some advanced features (DOM manipulation, AJAX, Flash communication, and more). I'm very concerned about functionality -- if problems occur, even after the application is deployed, I want to make sure I know why and how to fix them -- and also, I want to make sure the user is able to continue using the application, possibly with reduced functionality if the exception was severe.
I currently have a logging and exception handling system built whereby functions can generate logs, and if an exception is caught, all logs are emailed to me. The system works well but I'd like to make it more robust. I'm looking for suggestions.
One idea I have is to wrap the body of every javascript function in a try/catch block and upon catching an exception, log the name of the function and then throw the error to the global handler. But that's a lot of code just to track down the function the exception occurred in.
Any ideas to make runtime exceptions easier to find and reproduce?

A: Rather than dealing with adding N try/catch blocks to N functions, it might be easier to use the window.onerror event.
JavaScript Kit has a series of examples you could use. Especially the 3rd:
window.onerror = function (msg, url, line) {
  alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + line);
  return true;
}

If you'd prefer a stack trace, you might check out Eric Wendelin's (or Luke Smith's update). It's one of the few I know of that attempts to work cross-browser.


text:
Q: Moving documents from SOLR to elasticsearch I'm working on moving all documents in SOLR to elasticsearch using Python code with Pysolr.
With pysolr i'm able to access only 499 documents, it there a way to access the entire set of documents.

A: The documents could be accessed in sets of 499 using the offset and size parameter in pysolr API, i found this after checking the Pysolr api more in detail. The sample code is attached below :
limit = 499
offset = 0
while True:
    kwargs = {'sort':'id DESC'}
    response = source.search(q='projectid:774 AND source:FACEBOOK', start=offset, rows=limit, **kwargs  )
    print(len(response.docs))

    offset = offset + limit

    if len(response.docs) == 0:
        break

    # Do neccessary Operations
    pass


text:
Q: Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new service: ChromeDriverService I am getting this error while running Selenium grid for the first time:

Exception in thread "main"
  org.openqa.selenium.SessionNotCreatedException: Unable to create new
  service: ChromeDriverService.

Please help and suggest!
Below is the code:
WebDriver driver;
ChromeOptions options = new ChromeOptions();
String URL = "http://www.google.com";
String Node = "http://192.168.22.139:5555/wd/hub";
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY,options);
cap.setPlatform(org.openqa.selenium.Platform.HIGH_SIERRA);
WebDriver remoteWebDriver = new RemoteWebDriver(new URL(Node),cap);
remoteWebDriver.get(URL);
Thread.sleep(5000);
remoteWebDriver.quit();
}


text:
Q: How to forward fill NaN values in pandas data frame? I have the following pandas dataframe:
        S.No.           Name                  DOB Gender  Profile/work Order-History
    0     1.0      Sam Smith  1989-01-05 00:00:00   Male         abc     A
    1     NaN            NaN                  NaN    NaN         NaN     B
    2     NaN            NaN                  NaN    NaN         NaN     C
    3     NaN            NaN                  NaN    NaN         NaN     D
    4     NaN            NaN                  NaN    NaN         NaN     E
    5     NaN            NaN                  NaN    NaN         NaN     F
    6     NaN            NaN                  NaN    NaN         NaN     G
    7     NaN            NaN                  NaN    NaN         NaN     H
    8     NaN            NaN                  NaN    NaN         NaN     I

How may I forward fill the NaN values to achieve the desired output as below?
    S.No.           Name                  DOB Gender  Profile/work  Order-History
0     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         A
1     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         B
2     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         C
3     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         D
4     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         E
5     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         F
6     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         G
7     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         H
8     1.0      Sam Smith  1983-12-29 00:00:00   Male  abc         I

A: For me working forward filling missing values, if all data are in second row (in first row is header):
df = pd.read_excel('file.xlsx').ffill()


text:
Q: ANOVA model for two groups with a fixed model for a third variable I have two continouos group of values that belong to the same variable measured at different times.
There's also a third variable that corresponds to the location where those measures where done.
So I would have something like:
Var1Time1      Var1Time2        Location
23             34               Madrid
34             36               Madrid
12             11               Roma
26             45               Roma

I want to perform an ANOVA for the two variables (time1 and time2) including a fixed effect for the location,
in order to assess whether there are differences between the groups independently of where the measures were taken.
What is the best way to do this with R?


text:
Q: (Num (b -> b), Num b) in Haskell I noticed a pattern in Haskell. Usually when I do something wrong
[(+3),(-3)] <*> pure 4 :: (Num (b -> b), Num b) => [b]

I know the issue is the (-3), which should be (subtract 3), but however the type signature seems to imply at first, that you get a valid value, with some constraints.
Num b is logical, there are mathematical operations are involved.
But what does this Num (b -> b) mean? The operation b -> b is supposed to be a number?
Usually when I notice this, I can imply further arguments to the statement and I get well-typed statements:
[(+ 3),(- 3)] <*>  pure 4 4 4 :: (Num (t -> [b]), Num (b -> b), Num t, Num b) => [b]

What is happening here?


text:
Q: Symfony: Editing entities with form I'm having trouble getting my edit form fields of an entity to place the entity values in each fields. In my controller I was able to have a search for to first search for that one particular row by its first entity identifier. In this case it is a search for a DA number (dano) from a form, which goes to an action that displays the row. That row will have an edit action that will go to an edit page where the form will have input fields that display the entities to edit. Except however, I keep getting this error message when trying to plug it all together:
Catchable Fatal Error: Argument 1 passed to
...Bundle\Controller\EditController::createEditForm() must be an instance of
...\Bundle\Entity\SumitomoMain, array given, called in
...\Bundle\Controller\EditController.php on line 83 and defined in
...\Bundle\Controller\EditController.php line 99

I definitely don't know where to begin checking the problem.
Here are the actions in my controller:
/**
 * @return \Symfony\Component\HttpFoundation\Response
 * @Route("/", name="edit_home")
 * @Template()
 * @Method("GET")
 */
public function indexAction(Request $request)
{
    $form = $this->createDAForm();
    $form->handleRequest($request);

    if($form->isValid()) {

        return $this->redirect($this->generateUrl('edit_showda', array(
                'dano' => $form->get('dano')->getData()
                )));
    }

    return array(
            'searchdaform'      => $form->createView(),
        );
}

/**
 * @param Request $request
 * @return Response
 * @Route("/{dano}", name="edit_showda")
 * @Method("GET")
 * @Template()
 */
public function showDAAction($dano) {

    $getda = $this->getDoctrine()
        ->getRepository('CIRBundle:SumitomoMain')
        ->findByDano($dano);
    if (!$getda) {
        throw $this->createNotFoundException('Unable to find DA #');
    }

    return $this->render('CIRBundle:Edit:showda.html.twig', array(
            'dano' => $getda
        ));
}

/**
 * @param Request $request
 * @param $dano
 * @Route("/{dano}/edit", name="edit_editeda")
 * @Method("GET")
 * @Template()
 */
public function editDAAction($dano) {
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('CIRBundle:SumitomoMain')->findByDano($dano);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find DA');
    }

    $editform = $this->createEditForm($entity);

    return array(
        'entity'      => $entity,
        'editform'    => $editform->createView()
     );

}

/**
 * @param Request $request
 * @param $dano
 * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
 * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
 * @Route("/{dano}", name="edit_update")
 * @Method("PUT")
 * @Template("CIRBundle:Edit:editda.html.twig")
 */
public function updateDAAction(Request $request, $dano) {
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('CIRBundle:SumitomoMain')->find($dano);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find SumitomoMain entity.');
    }

    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {
        $em->flush();

        return $this->redirect($this->generateUrl('edit_editeda', array('dano' => $dano)));
    }

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
    );
}

/**
 * Creates a form to edit a SumitomoMain entity.
 *
 * @param SumitomoMain $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createEditForm(SumitomoMain $entity)
{
    $form = $this->createForm(new SumitomoMainType(), $entity, array(
            'action' => $this->generateUrl('edit_update', array('dano' => $entity->getDano())),
            'method' => 'PUT',
        ));

    $form->add('submit', 'submit', array('label' => 'Update'));

    return $form;
}

  public function createDAForm() {
    $form = $this->createFormBuilder()
        ->setMethod('GET')
        ->add('dano', 'text', array(
                'label' => 'DA #',
            ))
        ->add('submit','submit')
        ->getForm();

    return $form;
}

I've checked my Form Type and it all looks fine:
class SumitomoMainType extends AbstractType
{
 /**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('dano','text', array(
                'label' => 'DA'
            ))
        ->add('partno','text', array(
                'label' => 'Part'
            ))
        ->add('batchno','text', array(
                'label' => 'Batch'
            ))
        ->add('indate','date', array(
                'label' => 'Date',
                'widget' => 'single_text'
            ))
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'CIR\Bundle\Entity\SumitomoMain'
    ));
}

/**
 * @return string
 */
public function getName()
{
    return 'cir_bundle_sumitomomain';
}
}

Entity SumitomoMain.php:
/**
* SumitomoMain
*
* @ORM\Table(name="sumitomo_main", indexes={@ORM\Index(name="dano", columns={"dano"})})
* @ORM\Entity(repositoryClass="CIR\Bundle\Entity\SumitomoMainRepository")
*/
class SumitomoMain
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="indate", type="date", nullable=true)
 */
private $indate;

/**
 * @var string
 *
 * @ORM\Column(name="dano", type="string", length=50, nullable=false)
 */
private $dano;

/**
 * @var string
 *
 * @ORM\Column(name="partno", type="string", length=50, nullable=false)
 */
private $partno;

/**
 * @var integer
 *
 * @ORM\Column(name="batchno", type="integer", nullable=true)
 */
private $batchno;

/**
 * @var integer
 * @ORM\OneToMany(targetEntity="SumitomoSub", mappedBy="mainId")
 */
protected $sub;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set indate
 *
 * @param \DateTime $indate
 * @return SumitomoMain
 */
public function setIndate($indate)
{
    $this->indate = $indate;

    return $this;
}

/**
 * Get indate
 *
 * @return \DateTime
 */
public function getIndate()
{
    return $this->indate;
}

/**
 * Set dano
 *
 * @param string $dano
 * @return SumitomoMain
 */
public function setDano($dano)
{
    $this->dano = $dano;

    return $this;
}

/**
 * Get dano
 *
 * @return string
 */
public function getDano()
{
    return $this->dano;
}

/**
 * Set partno
 *
 * @param string $partno
 * @return SumitomoMain
 */
public function setPartno($partno)
{
    $this->partno = $partno;

    return $this;
}

/**
 * Get partno
 *
 * @return string
 */
public function getPartno()
{
    return $this->partno;
}

/**
 * Set batchno
 *
 * @param integer $batchno
 * @return SumitomoMain
 */
public function setBatchno($batchno)
{
    $this->batchno = $batchno;

    return $this;
}

/**
 * Get batchno
 *
 * @return integer
 */
public function getBatchno()
{
    return $this->batchno;
}

/**
 * Set sub
 *
 * @param string $sub
 * @return SumitomoMain
 */
public function setSub($sub)
{
    $this->sub = $sub;

    return $this;
}

/**
 * Get sub
 *
 * @return string
 */
public function getSub()
{
    return $this->sub;
}
/**
 * Constructor
 */
public function __construct()
{
    $this->sub = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Add sub
 *
 * @param \CIR\Bundle\Entity\SumitomoSub $sub
 * @return SumitomoMain
 */
public function addSub(\CIR\Bundle\Entity\SumitomoSub $sub)
{
    $this->sub[] = $sub;

    return $this;
}

/**
 * Remove sub
 *
 * @param \CIR\Bundle\Entity\SumitomoSub $sub
 */
public function removeSub(\CIR\Bundle\Entity\SumitomoSub $sub)
{
    $this->sub->removeElement($sub);
}
}

Any help would be appreciated!

A: $em->getRepository('CIRBundle:SumitomoMain')->findByDano($dano) returns an array of matching items. You pass that result to createEditForm, which expects only one entity and not an array.
You have to use findOneByDano instead, to only get one result.


text:
Q: Commenting JavaScript functions á la Python Docstrings It is valid JavaScript to write something like this:
function example(x) {
    "Here is a short doc what I do.";
    // code of the function
}

The string actually does nothing. Is there any reason, why one shouldn't comment his/her functions in JavaScript in this way?
Two points I could think of during wiriting the question:

*

*The string literal must be initiated, which could be costly in the long run

*The string literal will not be recognized as removable by JS minifiers
Any other points?
Edit: Why I brought up this topic: I found something like this on John Resig's Blog, where the new ECMA 5 standard uses a not assigned string literal to enable "strict mode". Now it was my interest to just evaluate, if there could be uses or dangers in doing such documentation.

A: There's really no point in doing this in Javascript.  In Python, the string is made available as the __doc__ member of the function, class, or module.  So these docstrings are available for introspection, etc.
If you create strings like this in Javascript, you get no benefit over using a comment, plus you get some disadvantages, like the string always being present.

A: I was looking for a way to add multi-line strings to my code without littering it with \n's. It looks like this module fits the bill:
https://github.com/monolithed/doc
Unfortunately, the comments won't survive minification, but I suppose you could write a compile task to convert docstrings to "\n" format.


text:
Q: Read epub file path There are two files in my project,one is pdf and other is epub.
            NSString *str1 = [[NSBundle mainBundle] pathForResource:@"delhi" ofType:@"pdf"];
NSString *str = [[NSBundle mainBundle] pathForResource:@"jackson" ofType:@"epub"];

my problem is str1 is giving path correctly,but str is giving nil.So is it any way to find the path of type "epub".

A: *

*Make sure both of the files are included in Xcode's copy phase.

*Make sure the case of the file and extensions is ok, it can work on simulator but won't on real device.

A: The nil result means that there is no jackson.epub at the top level of your app bundle. Either you forgot to include it in the Copy Files build phase or you've gotten the name wrong (capitalization counts).

A: Some times we will drag files in our projects to add but they are not loaded in "NSBundle" so we will get nil path. To conform click on main project file icon  and then switch to tab "Build Phases" Click to "Add" sign to add your required file if not available here.


text:
Q: Passing fullstops (periods) and forward slashes in a GET request? I have built a form that submits values to Wufoo as a GET request in the URL. I cannot get it to work if any of the values (in a textarea) contain a line-break or a forward slash. Is there a way to encode these in a URL?
This is being done in Rails.

A: I thought Rails would do that for you.  But if you need to do it manually, you can use CGI::escape, e.g.
 > require 'cgi'
 ...
 > CGI.escape("hello%there\nworld")
 => "hello%25there%0Aworld"

EDIT:
Actually, CGI does not seem to escape a dot.  URI can be used instead, it takes an extra parameter that lets you list extra characters you want escaped:
URI.escape("hello.there%world", ".")

A: http://en.wikipedia.org/wiki/Percent-encoding


text:
Q: DRF Newbie - Stuck in small mistake kindly assist I created 1 API its all working fine from all ends.
I created 2nd API the DRF headings title showing the headings of old api where i am doing mistake kindly assist.
serializers.py
from rest_framework import serializers
from .models import Brand, Category

class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = (
            'id',
            'name',
            'slug',
            'icon',
            'featured_image',
            'url'
        )

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = (
            'id',
            'name',
            'slug',
            'featured_image',
        )

products.url
router = routers.DefaultRouter()
router.register(r'', BrandViewSet)
router.register(r'', CategoryViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

product.view
class CategoryViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
    """
    API endpoint that allows sites to be viewed or edited
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

There is no error but in brower when i run the API url it shows brand list instead of category list,

A: The problem is that you have the views registered  to the same endpoint. So it resolves the first one it finds.
So do the register to different endpoints like this:
router = routers.DefaultRouter()
router.register(r'brands', BrandViewSet)
router.register(r'categories', CategoryViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

So you can access brands via 127.0.0.1:8000/brands and categories via 127.0.0.1:8000/categories


text:
Q: Can a program be coded which searches written solutions for math problems in a specific database? I want to make a project for helping students to find answers to specific problems. Assume that we have a student book full of 100 math questions. I will write the questions and their solutions and create a database for that.
Is it possible for students to find the exact solution to their question by the help of a program if they write the question as an input into a web page?


text:
Q: How to move object in the direction of rotation in flash? I have a "car" which has to be moved in the direction which it is rotated.
Now it just rotates in a direction and keeps on going up and down.Please help me.
I am using adobe flash pro cs6 and actionscript3.
My code is :
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;

car.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_MoveInDirectionOfKey(event:Event)
{
    if (upPressed)
    {
        car.y += 5;
    }
    if (downPressed)
    {
        car.y -= 5;
    }
    if (rightPressed)
    {
        car.rotation += 5;
    }
    if (leftPressed)
    {
        car.rotation -= 5;
    }
}

function fl_SetKeyPressed(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:
        {
            upPressed = true;
            break;
        }
        case Keyboard.DOWN:
        {
            downPressed = true;
            break;
        }
        case Keyboard.LEFT:
        {
            leftPressed = true;
            break;
        }
        case Keyboard.RIGHT:
        {
            rightPressed = true;
            break;
        }
    }
}

function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:
        {
            upPressed = false;
            break;
        }
        case Keyboard.DOWN:
        {
            downPressed = false;
            break;
        }
        case Keyboard.LEFT:
        {
            leftPressed = false;
            break;
        }
        case Keyboard.RIGHT:
        {
            rightPressed = false;
            break;
        }
    }
}

A: You need to use vector math to move the car's x,y based on an angle and a distance.
For example, you could move your car based on an angle and speed like this:
function move(degrees:Number, speed:Number):void {
    var radians:Number = degrees * (Math.PI / 180);
    car.x += Math.cos(radians) * speed;
    car.y += Math.sin(radians) * speed;
}

Then you can use the car's rotation as the angle and 5 or -5 as the speed:
if (upPressed) {
    move(car.rotation, 5);
}
if (downPressed) {
    move(car.rotation, -5);
}

Note that this assumes rotation=0 means your car is facing right-ward. If you've draw your car facing a different direction you'll need to compensate for the angle you've drawn the car, for example if the car is facing upward you need to use move(car.rotation - 90, 5).


text:
Q: image and CSS color in ie 8 problem I m converting a template and everything is fine in ff. Problem is when i open converted template into internet explorer. I am using an image to make curve in navigation. That image's color matches with div's background color in ff but does not match in ie. another problem with ie is that back ground image of top navigation appears for a while and then disappears. I even tried a 1px image as background of div without any luck.
{note: problem1 is solved. it was because of ddroundies script that i m using to roundify divs.}

A: It's because your image is a png, use a gif instead and see if it works. IE uses different png color profiles.
You can read more about the 'issue' here: http://hsivonen.iki.fi/png-gamma/