text:
Q: How to run async functions sequentially on a React-Native app, using Expo
UPDATE
Combining both solutions below, I wrote:
const startMusic = async () => {
    let currentSong
    let songPath
    const songArray = [
      { path: require("../assets/sounds/Katsu.mp3"), song: mainTheme },
      { path: require("../assets/sounds/MainTheme2.mp3"), song: mainTheme2 },
      { path: require("../assets/sounds/MainTheme3.mp3"), song: mainTheme3 },
    ]

    for (var i = 0; i < songArray.length; i++) {
      currentSong = songArray[i].song
      songPath = songArray[i].path
      try {
        await currentSong.loadAsync(songPath)
        await currentSong.playAsync()
        // setSoundObject(currentSong)
        console.log("Music will start")
        return new Promise(resolve => {
          currentSong.setOnPlaybackStatusUpdate(playbackStatus => {
            if (playbackStatus.didJustFinish) {
              console.log("Just finished playing")
              resolve()
            }
          })
        })
      } catch (error) {
        console.log(`Error: ${error}`)
        return
      }
    }
  }

This actually plays the song, and the console logs occur on time ("Just finished playing" happens exactly when the song ends)
I'm trying to figure out how to play the next song.. and how will it know when it has reached the final song?
return new Promise(resolve => {
  currentSong.setOnPlaybackStatusUpdate(playbackStatus => {
    if (playbackStatus.didJustFinish) {
      console.log("Just finished playing")
      resolve()
    }
  })
}).then(() => console.log("Next song?"))

Figured how where to put the .then to get it to console log right after "Just finished playing" I'm just trying to see how to actually put the next song there
(then of course, telling it when to go back to the first song in the array)

Original Post
Working on an assignment for a react native app using expo-av library for Sound files.
Right now, the app has a startMusic function set in a Context file that is responsible for playing the app's background music.  It only has one song for now:
const startMusic = async () => {
    try {
      await mainTheme.loadAsync(require("../assets/sounds/Katsu.mp3"))
      await mainTheme.playAsync()
      setSoundObject(mainTheme)
      console.log("The first song is playing! Enjoy!")
    } catch (error) {
      console.log(`Couldnt load main theme: ${error}`)
      return
    }
  }

It is used in the homescreen component's file like so:
const { startMusic } = useContext(MusicContext)

useEffect(() => {
  startMusic()
}, [])

For the second song, I wrote another const in the MusicContext file:
const secondSong = async () => {
    try {
      await mainTheme2.loadAsync(require("../assets/sounds/MainTheme2.mp3"))
      await mainTheme2.playAsync()
      setSoundObject(mainTheme2)
      console.log("Now playing the second track. Enjoy!")
    } catch (error) {
      console.log(`Could not play the second song: ${error}`)
      return
    }
  }

Annnnnd… here is where my trouble lies.  I know this wasn't gonna work but I wrote this in the component file to try to get the second song playing after the first song
useEffect(() => {
    startMusic()
      .then(secondSong())
  }, [])

I know there's more to it than that but I'm having trouble.

A: Problem with your code is not just running one function after another (that would be as simple as startMusic().then(() => secondSong()) but still won't solve the problem), but the fact that your functions actually don't wait for a song to finish playing before resolving
You expect this line await mainTheme.playAsync() to pause function execution until the song has finished, but what it in fact does according to docs https://docs.expo.io/versions/latest/sdk/av/ is exactly only starting the playback (without waiting for it to finish)
With that being said, you need to determine the moment your playback finishes, then create a Promise that will only resolve after the playback is finished so that your second song can only start after the first
In the simplest form without error handling and such, it can look like this
const startAndWaitForCompletion = async () => {
  try {
    await mainTheme.loadAsync(require('../assets/sounds/Katsu.mp3'))
    await mainTheme.playAsync()
    console.log('will start playing soon')
    return new Promise((resolve) => {
      mainTheme.setOnPlaybackStatusUpdate(playbackStatus => {
        if (playbackStatus.didJustFinish) {
          console.log('finished playing')
          resolve()
        }
      }
    })
  } catch (error) {
    console.log('error', error)
  }
}

the trick is of course the .setOnPlaybackStatusUpdate listener that will be called every so often with playback status, and by analyzing the status you can tell the song has finished playing. If you scroll to the bottom of the page I linked you will find other examples with status update

updated
const startAndWaitForCompletion = async (playbackObject, file) => {
  try {
    await playbackObject.loadAsync(file)
    await playbackObject.playAsync()
    console.log('will start playing soon')
    return new Promise((resolve) => {
      playbackObject.setOnPlaybackStatusUpdate(playbackStatus => {
        if (playbackStatus.didJustFinish) {
          console.log('finished playing')
          resolve()
        }
      }
    })
  } catch (error) {
    console.log('error', error)
  }
}

////

const songs = [
  { path: require('../assets/sounds/Katsu.mp3'), song: mainTheme },
  { path: require('../assets/sounds/MainTheme2.mp3'), song: mainTheme2 },
  { path: require('../assets/sounds/MainTheme3.mp3'), song: mainTheme3 },
]

useEffect(() => {
  (async () => {
    for (let i = 0; i < songs.length; i++) {
      await startAndWaitForCompletion(songs[i].song, songs[i].path)
    }
  })()
}, [])

A: .then() accepts a function but you've provided the result of function execution by calling secondSong.
Do:
useEffect(() => {
    startMusic()
      .then(() => secondSong())
  }, [])

Or just get rid of () after secondSong:
useEffect(() => {
    startMusic()
      .then(secondSong)
  }, [])

A: I think you need to rethink this problem/solution to be more abstract.
Instead of making a new const and promise for every single song you want to play (which, as you said, isn't workable, and isn't scalable, like say if you wanted 10 songs instead of 2), make "startMusic" a function that plays an array of songs (each array index being a filepath to an MP3, like in your example), and
then resolve/reject the promise as needed.
A quick "startMusic" rewrite:
const startMusic(songArray) = async () => {
    for (var songIndex in songArray) {
      try {
        await mainTheme.loadAsync(require(songArray[songIndex]))
        await mainTheme.playAsync()
        setSoundObject(mainTheme)
        console.log("Song #", songIndex, "of ", songArray.length " is playing. Enjoy!")
    } catch (error) {
      console.log(`Couldnt load song: ${error}`)
      return
    }
  }
}

A "Promise.all" chain could be useful here, too, if the above for-try-catch structure doesn't work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Not familiar with the expo-av library, so there might be some specific quirks to look out for there, but I think re-writing "startMusic" to be an abstract function that plays an array of "N" songs is a much more optimal approach, and will minimize/eliminate your problems.


text:
Q: Please advise me about this Computer Vision task I have some magnets with images on it. There is only a small set of different images (lets say 20 images), and they will be aligned in fixed chess boar (still not shown in the picture).

I have already an algorithm to extract each single magnet card from the board, applying a perspective transformation to the original image to prevent perspective distortion.
I would like to hear your advices in order to detect each single image on the board, I mean, detect if the magnet is: a panda, a rabbit, a dog, a carrot... since my main objective is to analyze the image and extract a matrix containing all the board elements.
My first attempt was very basic: guess the image according to the average color. It was not very robust since there are several images with similar average colors (specially those frozen cards), and light tinting can change color a lot.
Would you be so kind to point me in the right direction to extract a matrix containing all the images on the board? I don't need a specific implementation, but instead the concept of the steps that I should follow or techniques to be aplied to the main image in order to obtain a robust (and not too complex) algorithm.
I'm gonna implement it using OpenCV, but I guess that it would be the same using any other computer vision libraries.
Thanks a lot for your time!

A: While SIFT or other feature detectors work well and are widely applicable, I would always start with the simplest thing that could work: In your case, that's probably template matching. After all, you've already done the hard work of removing perspective distortion, rotation and different scale.
The basic idea is to take each of your 20 template images, and compare it to every possible position in the search image. Thanks to the convolution theorem, this is a relatively inexpensive operation.

A: Here is some example code:
void KeypointMatcher::computeMatches(cv::Mat image1, cv::Mat image2) {
        cv::initModule_nonfree();
        //Vector of keypoints
        std::vector<cv::KeyPoint> keypoints1;
        std::vector<cv::KeyPoint> keypoints2;
        //Detect features
        cv::SiftFeatureDetector detector;
        detector.detect(image1, keypoints1);
        detector.detect(image2, keypoints2);

        //Compute descriptors
        cv::Mat descriptors1, descriptors2;
        cv::SiftDescriptorExtractor extractor;
        extractor.compute(image1, keypoints1, descriptors1);
        extractor.compute(image2, keypoints2, descriptors2);

        //Find matches
        cv::BFMatcher matcher(4, true);
        std::vector<cv::DMatch> matches;
        matcher.match(descriptors1, descriptors2, matches);

        //Find good points for a homography
        std::vector<cv::Point2d> matchingPoints1, matchingPoints2;
        for (cv::DMatch& match : matches) {
            matchingPoints1.push_back(keypoints1[match.queryIdx].pt);
            matchingPoints2.push_back(keypoints2[match.trainIdx].pt);
        }
        cv::Mat mask;
        cv::findHomography(matchingPoints1, matchingPoints2, CV_RANSAC, 3, mask);

        //Just visualisation
        std::vector<char> vectorMask;
        mask.col(0).copyTo(vectorMask);
        cv::Mat result;
        cv::drawMatches(image1, keypoints1, image2, keypoints2, matches, result, cv::Scalar::all(-1), cv::Scalar::all(-1), vectorMask);
        //cv::drawMatches(image1, keypoints1, image2, keypoints2, matches, result);
        cv::imshow("Matches", result);
        cv::waitKey();
    }

It does the following: It extracts feature points from both images using SIFT. Then it finds matches between the features of both images. However, this will still contain a lot of rubbish matches. But we know that the transformation between the two images we're comparing is a perspective one, thus it must be possible to compute a homography between them. To find the "good" matches it now computes a homography with the RANSAC outlier filtering method. Which ones RANSAC considers outliers and which ones inlieres is saved inside the matrix mask (a 0 for outlier and a 1 for inlier). You could now e.g. count the ones inside this matrix to obtain the number of good matches. Then you could do this for the images of all the cards and compare the match count (e.g. pick the one with the most matches).
The last part of the code visualizes the good matches that were found.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python global variable with no import or global declaration I'm trying to add a couple of miscellaneous development helpers to my python project in such a way that I don't need to either import them or declare them global at the call site, just to save myself some typing.
Example usage would be something like:
# Somewhere, maybe src/__init__.py?
from pprint import pprint
superduperglobaleasyusenamespace.p = pprint

# A different file somewhere in my project
def whatever():
    p('hello')

I looked at builtin but wasn't able to get it to work. If that's the correct solution, provide example code that works in python3.

A: Add this as very first line in your program:
__builtins__.p = pprint

In general, it is not recommend to modify the builtin name space. An import is just one line after all.
Example
# mod1.py

from pprint import pprint

__builtins__.p = pprint

import mod2

and
# mod2.p

print(p)

Now:
python mod1.py
<function pprint at 0x10df28e18>


text:
Q: Deduce parameter type of pointer to member function template parameter I'm trying to write a C++ function template f with one template parameter of type void (Foo::*FUNC)(T const *) where Foo is some class type. Furthermore, I would like to deduce T from the concrete member function pointer specified for FUNC. So one idea would be:
template<typename T, void(Foo::*FUNC)(T const *)>
void f()
{ /* use T in here, e.g. if constexpr (std::is_same_v<T, int>) */ }

But then I have to specify T explicitly when instantiating f and can't just write e.g. f<&Foo::bar>. I know there are ways to deduce the type of the first parameter of a function but they are all overly complicated (without using Boost). Is there a smarter way to do what i want?

A: Here's a trait to extract an argument from a member function pointer that looks like you expect it to look:
namespace detail {
    template<typename M> struct extract_arg;
    template<typename R, class C, typename A>
    struct extract_arg<R (C::*)(A const*)> { using type = A; }
}

And here's a C++17 function template with a non-type template parameter whose type is deduced from a placeholder:
template<auto FUNC>
void f()
{
    static_assert(std::is_member_function_pointer_v<decltype(FUNC)>);
    using T = typename detail::extract_arg<decltype(FUNC)>::type;
    T t{};
}

It uses std::is_member_function_pointer to check its indeed of the correct type (well, family of types), and our helper trait to then extract T.
See it live.


text:
Q: how to stop re-rendering image I have a component which has  as one of the children. When I watch the network tab, the source of the image is being pulled twice on each re-render of the parent component. I have 2 questions:

*

*why does image loads twice, and

*how do I stop a component that contains  tag from re-rendering. Every time something happens in the parent component, the network tab shows the image being pulled twice, while I don't need it be re-pulled at all

I have tried creating a separate component which all that it has is  tag. I tried it as a function and a Class and as a memoized function:
const MyImage = React.memo(props => {
    console.log('render image')// logged once per render, but source pulled twice
    return
})

and like this:
class MyImage extends React.Component {
    shouldComponentUpdate(nextProps, nextState, nextContext) {
        console.log(nextProps, this.props)// never logged
        return nextProps.src === this.props.src;
    }

    render() {
        console.log('render img')//logged once per render, but source pulled twice
        return
    }
}

and like this:
function MyImage(props) {
    const {src, onLoad} = props;
    const [source, setSource] = useState(src);

    useEffect(() => {
        console.log('use effect')
        setSource(src);
    }, []); // React Hook useEffect has a missing dependency: 'src'. But shouldn't it be empty for initial loads?

    return
}

It seems like the onLoad event might be causing the source to be pulled twice (if I remove it, the network tab shows only one request). But why? All that the onLoad is doing is setting classes that are used by parent component


text:
Q: How to restrict Azure management portal access to corporate network(IP range) only Is there any way we can restrict sign in to azure portal to Company network only. We dont want to give access over public internet

A: There's nothing you can do to block / allow IP addresses to the Azure portal - you don't own the portal; Microsoft does. And it's a multi-tenant portal.
Not sure why you want to block the portal, but I guess that doesn't matter...
You can block access to the apps you deploy, via inbound network rules, access control lists, etc.
The only thing you can do with the portal is grant specific user permissions (via role-based access control) on specific resources.


text:
Q: deploying app using ClientDataSet I am currently in the process of doing a re-write on a large app of mine from BCB6 using paradox tables, and have started on several of my forms that use DBGrids.  I have already done a conversion of the data from paradox to SQLite 3.
The data in the grids are fine on my development machine (Windows 8 32bit), but when I want to put the app on to a secondary machine (being a WinXP 32bit system) it doesn't want to work when I try and open those forms that have grids on them.  I have isolated the problem to my ClientDataSet not allowing to become Active.  I am building a self contained EXE file for this app, and I have also tried putting several files that I think I may need in to the same fold as my application.  Yes I do have a dbxconnections.ini & a dbxdrivers.ini file in the folder as well.  I am using XE4.
The AV error that I am getting is Access violation at address 007EFA8F in module 'AC.exe'. Read of address 00000000
I am doing a test when I am opening the ClientDataSet
try
{
    cdsLots->Avtive = true;  // cdsLots being the ClientDataSet
}
catch (Exception &exception)
{
   ShowMessage("Failing to Open cdsLots");
   Application->ShowException(&exception);
}


text:
Q: Interpretation of compiler-generated assembly I'm trying to understand how simple C code is translated into assembly MIPS.
int main(){
int a;
a = 9;
return 0;
}

is being translated into
main:
    .frame  $fp,16,$31      # vars= 8, regs= 1/0, args= 0, gp= 0
    .mask   0x40000000,-4
    .fmask  0x00000000,0
    .set    noreorder
    .set    nomacro
    addiu   $sp,$sp,-16
    sw  $fp,12($sp)
    move    $fp,$sp
    li  $2,9            # 0x2
    sw  $2,0($fp)
    move    $2,$0
    move    $sp,$fp
    lw  $fp,12($sp)
    addiu   $sp,$sp,16
    jr  $31
    nop

I find a bit weird the use of $fp and $sp: it seems to me that there are unnecessary backups and restore. Probably it is just the way the compiler translates to assembly.
But I just can't understand why it reserves 16 bytes on the stack: 4 for the local variable, 4 for the $fp backup ... and the other 8 bytes?
I'm talking about MIPS, I'm using gcc with toolchain mips-mti-elf.

I modified the code, now the variable is global. Guess what? Stack size is 8 bytes (4 for $fp, but the other 4 bytes?).


text:
Q: How to populate a Google Chart from an HTML table? I have a question, is it possible to populate a Google Chart from an HTML table?
I have successfully initialized the Google Chart in Wordpress like this:

Table is filled dynamically unfortunately

   Name
   Kg

   [85-dynamic value]
   [86-dynamic value]

`

Thanks for any help


text:
Q: In JavaFX how do I determine if the node gaining focus is a child node of myself? I'm working with a TableView in JavaFX. What I'd like to do is keep track of edits made to the table. When the user navigates away from the table, I want to check if there have been any edits, and if so, prompt the user to ask if they want to save their changes.
I have the TableView working, and I can track edits, and I can determine when the TableView loses focus (using a focusedProperty change listener).
However, the problem is that when a cell is clicked to edit, the focusedProperty change listener for the table fires (the editing cell gains focus, the table itself loses it). What I really want is a way to tell if, when focus changes, is it changing to a child node of the table (such as a column or cell) or something outside of the table (selecting a different tab on the parent GUI). But I don't want to have to add listeners to every other possible node one could click.
If I knew how to get the currently-focused item (haven't seen how to do that), I could call getParent() recursively and check if the TableView is in that list, and if so, I'd know it's a child. But I haven't seen a generic way to just get the currently focused node within an app.
There's no good generic way to iterate through children of the table, because getChildrenUnmodifiable() returns me Node() types (I suppose I could cast each to determine if they each had more children), or I'd have to go to TableColumns then cells from there (and check graphic for each cell).
I'd probably go with iterating through children recursively, casting as needed, and checking isFocused() at this point, barring a better solution. But I'm hoping someone here might have a better solution to this problem, and preferably a more generic solution.

A: You can get the currently focused node through the scene's getFocusOwner() or focusOwnerProperty(). As you say, traversing from the focused node up to the TableView is better.
    public void createTable() {
        TableView tableView = new TableView();
        tableView.focusedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
            if (oldValue && !newValue) {
                if (!isParent(tableView, tableView.getScene().getFocusOwner())) {
                    System.out.println("Saving changes.");
                }
            }
        });
    }

    public boolean isParent(Parent parent, Node child) {
        if (child == null) {
            return false;
        }
        Parent curr = child.getParent();
        while (curr != null) {
            if (curr == parent) {
                return true;
            }
            curr = curr.getParent();
        }
        return false;
    }

A: I went with the search from a Node, casting to children and checking if the focused node was a child. It's not elegant - it certainly feels like there should be a better way. But here's the method I used to do so:
private boolean isChildFocused(javafx.scene.Parent parent)
{
    for (Node node : parent.getChildrenUnmodifiable())
    {
        if (node.isFocused())
        {
            return true;
        }
        else if (node instanceof javafx.scene.Parent)
        {
            if (isChildFocused((javafx.scene.Parent)node))
            {
                return true;
            }
        }
    }
    return false;
}

It seems to work fine (at least using a TableView as the root level parent), calling this when the focusedProperty() of the parent changes to false (via property change listener).


text:
Q: Selecting multiple sections and rows at a time in Tableview In my tableview I have different number of sections and different number of rows in each section.

*

*I want to select one section, for eg. if I select first section it should select all rows from that section. If I uncheck that section, it should uncheck all rows.

*If I select all rows in a section, it should check the section header also, if I uncheck atleast one row in that section, it should uncheck section header.

I can select all rows if I select one section, its working but If I check all rows section header is not getting selected.
Its completely vice versa among sections and rows.
Please Can I get any help for this.

A: case 1: when select on section header
run for loop to set the property of object (like strSelect=@"1"). set the checkmark image on that section and cell of that section.
case 2: selecting the cells.
on selecting any cell check that all object of that cell are selected or not.
if selected then then set the checkmark image on section and cells of that section
case 3 on deselecting the section header
run for loop to set the property of object (like strSelect=@"0"). set the uncheckmark image on that section and cell of that section.
for case 2 example
NSInteger sectionArrayCount= sectionArray.count;
NSInteger totalSelectedObject=0;
for (Item *obj in sectionArray)
{

    if ([obj.strSelectedQuantity isEqualToString:@"1"])
    {
        totalSelectedObject+=1;
    }
}

if (totalSelectedObject == sectionArrayCount)
{
    NSLog(@"all cells of that section are selected");
}


text:
Q: Libraries neccessary to install lua not installing I am running Debian Jessie and i was trying to learn how to embed Lua as a scripting language into a c++ program, but when i use apt to install lua i do not get the libraries "lua.h", "luaxlib.h", or "lualib.h" and i haven't found any answers when going through forums and such. I have done both
sudo apt-get install lua50
sudo apt-get install lua5.2

and they say i already have them up to date and upgraded, but i do not get the lua C API which is what i need at this point. I also do not know the difference between those two packages so any explanation over that would be greatly appreciated

A: lua.h, lauxlib.h, and lualib.h are not "libraries" they are header files and they would be contained in the -devel versions of the packages.
You aren't missing "the lua C api" you are missing the header files you need to compile your own C code against the lua api (because you lack the definitions of the api functions, etc.).
The difference between those packages is the version of lua involved.
lua50 is likely lua 5.0. lua5.2 is going to be lua 5.2. They are (very) different versions of the language.


text:
Q: Is validating fields in both constructor and setter considered bad redundant code? I have the following class :
public class Project {

    private int id;
    private String name;

    public Project(int id, String name) {
        if(name == null ){
            throw new NullPointerException("Name can't be null");
        }

        if(id == 0 ){
            throw new IllegalArgumentException("id can't be zero");
        }

            this.name = name;
            this.id = id;

    }

    private Project(){}

    public int getId() {
        return id;
    }

    public void setId(int id) {
        if(id == 0 ){
            throw new IllegalArgumentException("id can't be zero");
        }
        this.id = id;
    }

    public String getName()
        return name;
    }

    public void setName(String name) {
        if(name == null ){
            throw new NullPointerException("Name can't be null");
        }
        this.name = name;
    }

}

If you noticed that setName and setId share the same validation for its fields with the constructor. Is this redundant code that could cause issues in the future ( for example if somebody edit the the setter to allow 0 for the id and prevent -1 instead but didn't change the constructor) ? . Should I use a private method to do the check and share it between the constructor and the setter which seems too much if there's a lot of fields.
Note: This is why im not using the setters in the constructor. https://stackoverflow.com/a/4893604/302707

A: Here is the revised code:
public class Project {

    private int id;
    private String name;

    public Project(int id, String name, Date creationDate, int fps, List<String> frames) {

        checkId(id);
            checkName(name);
            //Insted of lines above you can call setters too.

            this.name = name;
            this.id = id;

    }

    private Project(){}

    public int getId() {
        return id;
    }

    public void setId(int id) {
        checkId(id);
        this.id = id;
    }

    public String getName()
        return name;
    }

    public void setName(String name) {
            checkName(name);
        this.name = name;
    }

    private void checkId(int id){
       if(id == 0 ){
            throw new IllegalArgumentException("id can't be zero");
        }
    }

    private void checkName(String name){
            if(name == null ){
            throw new NullPointerException("Name can't be null");
        }
    }

}

A: I recommend that you should define one method per field as isValid() and then call the same method in you setter as well as Constructor.

A: I would say yes. Rather than that, just call the setters from your constructor:
public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
    setName(name);
    setId(id);
    // other stuff with creationDate, fps and frames?
}

Also, you shouldn't check for a null name in getName -- do it in setName. Otherwise, bugs are going to be hard to track down -- you want to catch the invalid name as soon as it comes in, not when it's used (which may be much later).

A: if you make Project immutable, it will eliminate the redundant code. but for now, i think explicitly throwing exceptions in both the constructor and mutator methods is fine.
and i would not call the mutator methods within the constructor for many reasons, including this. also, i would remove the validation code in the accessor method...it's not necessary.


text:
Q: Validation Controller inside CMS in Silverstripe At the moment i have a LeftAndMain section named 'Applications' which contains a form with a password field:

The code for this is:
class Applications extends LeftAndMain {
    static $url_segment = 'applications';
    static $menu_title = 'Applications';
    static $url_rule = '$Action/$ID';

    public function init(){
        parent::init();
    }

    public function getEditForm($id = null, $fields = null) {
        $fields = new FieldList(
            TextField::create('Password', ' Password')
        );
        $actions = new FieldList(new FormAction('applicationPassword'));
        return new Form($this, "EditForm", $fields, $actions);
    }

    public function applicationPassword($data, Form $form){
        $form->sessionMessage('Correct password. I will redirect you to manage your model', 'success');
        return $this->redirectBack();
    }
}

When submiting this form, the action function should validate if it's equaly with something (in my case, it's a key to decrypt data from a database) and then redirect/show the Gridfield.
The second point is a ModelAdmin, where i can manage the data (that are comming from that database) through GridField.

The code for this is:
class Applications2 extends ModelAdmin {
    static $url_segment = 'applications2';
    static $menu_title = 'Applications2';

    private static $managed_models = array(
        'SecureFormInput'
    );
}

And here is my question: is it possible to do this ? Any suggestions/help becouse i tried for while and no result.

A: I'm finding it really hard to figure out what you're really trying to do.
Here are a few things that I can see that might still help you though:

*

*You wouldn't usually extend LeftAndMain directly. 99% of the time, developers are building admin-screens or areas, in which a single or multiple model(s) (DataObject subclasses) are managed.

*In your Applications class you have no $allowed_actions static. You need this to have at least a single value: 'applicationPassword' in order to tell SilverStripe which are the legitimate actions this controller can perform.

*Again, depending on what you're trying to do, you would usually password protect a CMS admin area using the SilverStripe CMS' standard permissions system (See the "Security" menu item). Notice you can authorise users or groups on some admin screens.
If this is what you're trying to do for your various custom controllers, you should ensure your controller declares a canView() method. Again see LeftAndMain.php for examples.

*Validation is usually done at a model level. E.g. you have a DataObject subclass which you want to manage from within a ModelAdmin. In which case you define a method called validate() on your DataObject subclass. When editing / creating new instances of this model
from within your ModelAdmin, the CMS knows to run your validate() method, if it finds one on your model.

*When you say "It isn't working" we really need to know "in what way?" e.g. Do you see an error message, do you not see something you should, if so what etc etc

If none of these points help, what would really help others help you, is if you re-wrote your question something like this:
"I am trying to password protect a custom CMS administration screen. I have a model MyModel with the following class definition (screenshot or code), and a ModelAdmin (screenshot or code). The code should show an error message of the password is bad (a bad password is one that doesn't match one in the database, or doesn't follow a specific format etc etc) or a success message of the password matched a DB entry or did follow a specific pattern or format."
Good luck :-)


text:
Q: geom_density with alpha vector I'd like to plot several distributions with geom_density, and have all but one of them faded out.  How can I do this, as the following doesn't change the alpha as expected.
require("ggplot2")

data = rbind(
  data.frame(generation=1, samples=rnorm(90)),
  data.frame(generation=2, samples=rnorm(100)),
  data.frame(generation=3, samples=rnorm(110)),
  data.frame(generation=4, samples=rnorm(120)),
  data.frame(generation=5, samples=rnorm(130)),
  data.frame(generation=6, samples=rnorm(140))
)

maxGen = max(data$generation)

ggplot(data) +
  geom_density(
    aes(
      colour= factor(generation),
      x=samples,
      alpha=ifelse(data$generation == maxGen, 0.3, 1.0)
    )
  )

In case it makes a difference, the real thing adds a facet wrap across another variable.

A: Switched to geom_line and it seems to work:
require("ggplot2")

data = rbind(
  data.frame(generation=1, samples=rnorm(100)),
  data.frame(generation=2, samples=rnorm(100)),
  data.frame(generation=3, samples=rnorm(100)),
  data.frame(generation=4, samples=rnorm(100)),
  data.frame(generation=5, samples=rnorm(100)),
  data.frame(generation=6, samples=rnorm(100))
)

maxGen = max(data$generation)

ggplot(data) +
  geom_line(
    aes(
      colour= factor(generation),
      x=samples,
      alpha=I(ifelse(data$generation == maxGen, 1, 0.3))
    ),
    stat="density",
    size=1.5
  )

I have no idea what the I in the I(ifelse(... is doing, but it seems to stop extra stuff from showing up in the legend.

A: If you want the transparency parameter to take an effect, you need to specify the fill parameter instead of color, which only affects the line of the plot:
ggplot(data) + geom_density(aes(fill= factor(generation), x=samples, alpha=generation == maxGen)) +
    scale_alpha_manual(labels = c("TRUE" = "Max", "FALSE" = "NoMax"), values = c(0.1, 0.8)) +
    theme(legend.title = element_blank())

A: One other option that works with geom_density is to specify colors with an alpha parameter directly in the scales_color_manual but in that case, it will take some more work to "scale" your plot for more colors.
cols <- scales::hue_pal()(6)
cols.alpha <- c(cols[1:5], grDevices::adjustcolor(cols[6], alpha.f = 0.3))

ggplot(data) +
  geom_density(
    aes(
      colour = factor(generation),
      x = samples,
    ), size = 1.5
  ) +
  scale_colour_manual(values = cols.alpha)


text:
Q: Cronjob fails to run a bash script giving an error "aws : command not found" I have a script to invalidate Amazon CloudFront in a .sh file and it works fine when I run it with bash (bash /../filename.sh). I need to invalidate my distribution every thursday, so I wrote a cron job, but it is giving the error "aws: command not found".
This is my cron job
      45 10 * * 2 /usr/bin/bash /var/www/cms/file.sh
What I am missing? Why the cron job is failing when bash could run the script?

A: This is because your system depends on an environment variable for places where to search for executable files and that variable is not set in the cron sessions. This variable is named $PATH. You can see it's contents in your current session by just typing echo $PATH in your terminal.
When a cron session is started for a job to be executed, this variable is not set.
To solve this issue, there are a few ways:
Method 1:
Use full path names in your shell script and do not depend on the PATH variable for finding executables.

Method 2:
Add the following at the beginning in your script (adjust if needed):
PATH=/sbin:/bin:/usr/sbin:/usr/bin

Method 3:
(This method is generally discouraged)
Add the following line in your crontab (adjust if needed):
PATH=/sbin:/bin:/usr/sbin:/usr/bin

You can do echo $PATH in your terminal and copy the output in the above variable in the crontab.

A: Thank you Sakis your answer worked perfectly for me.
I was baffled why my scripts would run just fine from the command line but error out when run from cron. The reason was i was trying to use an executable from within bash that was not a recognized command due to lack of reference to a path. Now it's clear.
Did exactly this - no root or other sudo required.
From your own shell, echo $PATH. Copy this line and enter in your own cron (affects all jobs in that cron) or at the top of your script.
PATH=/home/myuser/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

And voila !


text:
Q: How to use front tablet's webcam with HTML GetUserMedia? I am trying to use WebcamJS in Chrome on Windows tablet which has 2 webcams. However, it is working only with back webcam.
Any idea how to make it work with front webcam ?
Thanks for any hints.

A: There's a fork of that project that allows that very feature (the ability to choose the camera device): https://github.com/carvilsi/webcamjs
Hope this helps.


text:
Q: Python 3.9.6 virtual environment: different packages shown in two different machines I am a bit confused about the python Virtual environment. I thought you use them so you can make sure that the same packages and setting can run in two different machines. Here's my problem. I have installed and activate a python VENV in a Virtual machine running Centos 7. I have created a git repository that contains a django app called CTR and a python VENV:

CTR  python39-RIGS-venv  README.md

when activated:
source python39-RIGS-venv/bin/activate

pip3 list
Package            Version
------------------ ---------
asgiref            3.4.1
certifi            2021.10.8
charset-normalizer 2.0.7
Django             3.2.9
idna               3.3
pip                21.3.1
pytz               2021.3
requests           2.26.0
setuptools         56.0.0
sqlparse           0.4.2
urllib3            1.26.7

I have then downloaded the same repo in my mac, activated the python VENV and this is the result:
source python39-RIGS-venv/bin/activate

pip3 list
Package    Version
---------- -------
pip        21.1.3
setuptools 56.0.0

Why not all packages installed are visible in the mac VENV? I thought that was the purpose of python VENV. Make sure you can run same configuration in different machine. What am I missing here? Thank you for your help

A: After a more accurate search I have found out the question has been already answered here:
How to use python virtual environment in another computer
I will leave the link here to help other people with my same dilemma.


text:
Q: GreenDao query with LIKE clause in related object How to use green dao query to query objects, that has LIKE sting in related object?
      QueryBuilder qb = mainDao.queryBuilder();
  qb.where(
      mainDao.Properties.Date.between(filter.getFrom().getTime(), filter.getTo().getTime()),
      qb.or(mainDao.Properties.Details.like("%"+ string + "%"),
          infoDao.Properties.Display_name.like("%" + string + "%"),
          infoDao.Properties.Email.like("%" + string + "%"),
          infoDao.Properties.Phone.like("%" + string + "%"),
          infoDao.Properties.Code.like("%" + string + "%")));

This kind of query constructed by me will not work? Any suggestions how I could managed a query that checks related field properties for occurrences?
MainDao has foregin key of InfoDao
I think I want to do something like this:
    SELECT *
    FROM Main
    INNER JOIN Info
    ON Main.InfoID=Info.InfoID;
    WHERE Info.SomeField LIKE "%string%"

A: I don't know if it's the best solution but, since greendao doesn't support JOIN, it could do the trick. Also, you could simply use a SQLite query for this particular case.
Here I'm assuming that you have a relation between Main and Info. If you don't, you could do it with a few more steps.
List<Info> infoArray = infoDao.queyBuilder()
    .whereOr(infoDao.Properties.Display_name.like("%" + string + "%"),
        infoDao.Properties.Email.like("%" + string + "%"),
        infoDao.Properties.Phone.like("%" + string + "%"),
        infoDao.Properties.Code.like("%" + string + "%"))
    .list();

List<Main> mainArray = Collections.emptyList();
for (Info info : infoArray) {
    if(!mainArray.contains(info.getMain()) {
        mainArray.add(info.getMain());
    }
}

[UPDATED]
If you don't have a relation from Info to Main, there's another version:
List<Info> infoArray = infoDao.queryBuilder()
    .whereOr(infoDao.Properties.Display_name.like("%" + string + "%"),
        infoDao.Properties.Email.like("%" + string + "%"),
        infoDao.Properties.Phone.like("%" + string + "%"),
        infoDao.Properties.Code.like("%" + string + "%"))
    .list();

List<Long> infoIds= Collections.emptyList();
for (Info info : infoArray) {
    infoIds.add(info.getId());
}

List<Main> mainArray = mainDao.queryBuilder()
    .whereOr(mainDao.Properties.id.in(infoIds),
        mainDao.Properties.Details.like("%"+ string + "%"))
    .list();


text:
Q: Why is the curl command doesn't work in golang I am in the trouble when I use golang to run the command curl. My version of the golang is 1.15.7. The purposed is to call a API by using POST method. This is the whole command that I want to use:
curl -X POST -H "Content-Type:application/json" -d '{"DNS_ID":"DNS_1","Domain_ID":"Domain_1","Cell_ID":"Cell_1","Device_ID":"IOT1","IMEI":"ims-208930000000003","IPv4":"60.60.0.1","IPv6":":::60.60.0.1","Slice_ID":"121312","FQDN":"test.free5gc"}' "http://192.168.1.233:5534/current" -v

And this is my code so far. I used module os/exec in golang to run the command curl.
    var body string
    var FQDN string
    var content string
    var url string

    content = "\"Content-Type:application/json\""
    url ="\"http://192.168.1.233:5534/current\""
    DomainName := "test"
    IPAddress := "60.60.0.1"

    FQDN = DomainName + ".free5gc"
    body = `"DNS_ID":"DNS_1","Domain_ID":"Domain_1","Cell_ID":"Cell_1","Device_ID":"IOT1","IMEI":"ims-208930000000003","IPv4":"`+ IPAddress +`","IPv6":":::`+ IPAddress +`","Slice_ID":"121312","FQDN":"`+FQDN  +`"`

    fmt.Println(body)

    c := exec.Command("curl","-X","POST","-H",content,"-d","'{"+ body +"}'",url,"-v")

    fmt.Println(c)
    c.Stdout = os.Stdout
    c.Stderr = os.Stderr
    err := c.Run()
    if err != nil {
        fmt.Println("Error: ", err)
    }

After I build the code and run it. The whole command is correct but seems it has some problem in the part of the url. The error message is like below:
/usr/bin/curl -X POST -H "Content-Type:application/json" -d '{"DNS_ID":"DNS_1","Domain_ID":"Domain_1","Cell_ID":"Cell_1","Device_ID":"IOT1","IMEI":"ims-208930000000003","IPv4":"60.60.0.1","IPv6":":::60.60.0.1","Slice_ID":"121312","FQDN":"test.free5gc"}' "http://192.168.1.233:5534/current" -v
* Could not resolve host: "http
* Closing connection 0
curl: (6) Could not resolve host: "http
Error:  exit status 6

Also I have tried the command which is same as the above one in my VM. And the command curl can work. So I was wondering if it is the write way of the golang or not.
I have no idea where the error occur. Maybe it is the "",` or ""content"" I thought. The error message seems can't recognize the whole URL. This is just mu guess.
Hope guys can help me to deal with this problem.
Thanks a lot

A: This is happening because quotes are a way for bash to organise arguments, and since you are using Golang's os/exec package, there's no need to escape arguments prior to the command's execution (unless you are using bash in between go and the program you're trying to run):
var body string
var FQDN string
var content string
var url string

content = "Content-Type: application/json"
url = "http://192.168.1.233:5534/current"
DomainName := "test"
IPAddress := "60.60.0.1"

FQDN = DomainName + ".free5gc"
body = `"DNS_ID":"DNS_1","Domain_ID":"Domain_1","Cell_ID":"Cell_1","Device_ID":"IOT1","IMEI":"ims-208930000000003","IPv4":"`+ IPAddress +`","IPv6":":::`+ IPAddress +`","Slice_ID":"121312","FQDN":"`+FQDN  +`"`

fmt.Println(body)

c := exec.Command("curl","-X","POST","-H",content,"-d","{"+ body +"}",url,"-v")

fmt.Println(c)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
err := c.Run()
if err != nil {
    fmt.Println("Error: ", err)
}

tl;dr: drop the quotes, everything should start working :)


text: Q: How to change Echo output font size including EchoLabel within an entire Notebook? I am creating a notebook template. I have Input and Output font size set at 10 but the Echo font size is 12. How do I change Echo to font size of 10? I cannot find a setting for this in Option Inspector.


text:
Q: Why can't MikTex find all of my style files? I was wondering if you could help me please.  I'm using MiKTeX 2.9 and WinEdt on Windows 7 and I've tried to add the style files that I need to use for a particular project to the search path for MiKTeX.
I created a folder called Local within My Documents and then within that another folder called Tex and then added the folder containing all of my style files to the Tex folder.
Next I added C:/../MyDocuments/Local as a root directory with MiKTeX.  When I try to build a LaTeX document, however, it seems that MiKTeX can find some but not all of my style files.  I've double checked and they are all in there, so I'm not sure as to why it can't find some of them.
Does anyone have any suggestions?
Thanks in advance for your help!

A: Don't forget to press FNDB after making a new root. And your TeX input file (that uses the style) must not be in the root directory you just created.


text:
Q: Help with Joins please - Where on a CASE field? tblSource  - has ActionID, SourceName, and SourceID
tblX - has ActionCode and SourceName
lkuActionCode - has both.
I also need the CASE, because ActionCodes in tblX are different from ActionCodes in lkuActionCode....
I am trying ti display SourceID, ActionID, and everything else from tblX in one query...
right now i'm getting an error: Invalid column name 'newAction2'. on the last line... please help
select  t2.Sourceid, t1.actionCode , t3.ActionID
CASE
WHEN  t1.actionCode  = 'R' THEN 'N' END AS newAction2
from tblSource t2
right join  tblX t1 on t1.SourceName= t2.SourceName
right join lkuActionCode t3 on t3.actioncode = newAction2

A: select  t2.Sourceid, t1.actionCode , t3.ActionID,

CASE WHEN  t1.actionCode  = 'R' THEN 'N' END AS newAction2

from tblSource t2
right join  tblX t1 on t1.SourceName= t2.SourceName
right join lkuActionCode t3
       on t3.actioncode = CASE WHEN t1.actionCode  = 'R' THEN 'N' END

However, LEFT JOINs are usually preferable to avoid confusion later. Or you even need OUTER JOINs?
select
    t2.Sourceid, t1.actionCode , t3.ActionID,
    CASE WHEN t1.actionCode  = 'R' THEN 'N' END AS newAction2
from
    lkuActionCode t3
    LEFT JOIN
    tblX t1 on t3.actioncode = CASE WHEN 1.actionCode  = 'R' THEN 'N' END
    LEFT JOIN
    tblSource t2 t1.SourceName= t2.SourceName

A: You can't reference newAction2 in the join statement. Try repeating the case in the join, like this:
select
   t2.Sourceid
  ,t1.actionCode
  ,t3.ActionID
  CASE
    WHEN t1.actionCode = 'R' THEN 'N'
  END AS newAction2
from tblSource t2
right join tblX t1
  on t1.SourceName= t2.SourceName
right join lkuActionCode t3
  on t3.actioncode = CASE
    WHEN t1.actionCode = 'R' THEN 'N'
  END

Do you want the actionCodes that aren't R to come through unmodified? If so:
select
   t2.Sourceid
  ,t1.actionCode
  ,t3.ActionID
  CASE
    WHEN t1.actionCode = 'R' THEN 'N'
    ELSE t1.actionCode
  END AS newAction2
from tblSource t2
right join tblX t1
  on t1.SourceName= t2.SourceName
right join lkuActionCode t3
  on t3.actioncode = CASE
    WHEN t1.actionCode = 'R' THEN 'N'
    ELSE t1.actionCode
  END

You could also use a subquery to only make the case statement once:
 select
   t2.Sourceid
  ,t1.actionCode
  ,t3.ActionID
  ,fixedActionCode.actionCode
from tblSource t2
right join tblX t1
  on t1.SourceName= t2.SourceName
right join (
  SELECT
     CASE
       WHEN t1.actionCode = 'R' THEN 'N'
       ELSE t1.actionCode
     END as actionCode
    ,otherField1
    ,otherField2
  FROM lkuActionCode
) as fixedActionCode
  on t3.actioncode = fixedActionCode.actionCode

A: If you're just Mapping the one value you could make the join expression
  ON t3.actioncode = 'N'
   AND t1.actionCode = 'R'


text:
Q: Showing $L(1,\chi)$ is positive given that it's nonzero Let me first provide context for this question.
There is a series of four exercises in Ireland & Rosen's book (in second edition it's exercises 14-17 in chaprer 16), aim of which is (although this is not relevant to my question) to establish that in the interval $0<x<\frac{p}{2}$ there are more quadratic residues than nonresidues $\mod p$ for $p\equiv 3\pmod 4$.
The content of exercise 17, when restated, is essentially the following:

Let $\chi$ be the Dirichlet character $\mod 2p$ such that $\chi(n)=\left(\frac{n}{p}\right)$ for odd $n$. Given that $L(1,\chi)\neq 0$, show $L(1,\chi)>0$.

Since I am asking this question in the context of mentioned book, let me briefly go through what was established in the chapter (for the same of people who don't own the book and want to give an answer at the adequate level):

*

*Definitions of: zeta function, Dirichlet characters and L-functions was given and their basic properties were established

*Nonvanishing of L-functions has been proven by standard method for complex characters and for real characters using Landau's lemma (concerning Dirichlet series with nonnegative coefficients)

*I suppose these aren't related to my question, but just in case I mention these: Dirichlet's theorem was proven, it was shown that L-functions can be continued to the whole (punctured) complex plane, and L-functions have been evaluated at negative integers with help of generalized Bernoulli numbers.

The exercise so restated seems to be quite difficult, since sign of L-function value was at no point dealt with in the chapter. At this point you can guess what my question:

How to solve this exercise without using tools outside the ones provided by Ireland & Rosen in their book?

I know from other places that the value of $L(1,\chi)$ for real $\chi$ is always positive. So, extending my question:

Is there an easy way to show, for general real Dirichlet character $\chi$, that $L(1,\chi)>0$, given that we know it's not zero?

Let me also note that I am aware of a proof of nonvanishing of L-functions which at the same time proves that the value is positive, but this wouldn't be a valid answer to my question - as far as I can recall, the proof was by itself pretty nontrivial, and I'm looking for something that, in theory, could've been figured out by a reader of the book who, say, has not encountered analytic number theory before.
Thanks in advance.

A: The Euler product for $L(s,\chi)$ will tell you that $L(\sigma,\chi)>0$ for real $\sigma>1$. Moreover, $L(s,\chi)$ is continuous....


text:
Q: Adobe AEM package manager - how to show Activity log using curl I am using curl to automate AEM package manager, but I would like to see the actual progress. What I am seeing in /crx/packmgr/index.jsp in the window on the lower right.
So for example if I build or install a large package, curls progress only shows me that it's still busy/waiting, but not what is actually going on.
I would like to see the log output like
Building package
A META-INF
A META-INF/MANIFEST.MF
A META-INF/vault
A META-INF/vault/config.xml
A META-INF/vault/filter.xml
A META-INF/vault/nodetypes.cnd
A META-INF/vault/properties.xml
A /.content.xml
A /content
A /content/.content.xml
...
Package built in 407377ms.

If there a way to get this info for the POST request
curl -u admin:admin -X POST
'http://localhost:4502/crx/packmgr/service/.json/etc/packages/my_packages
 /allmycontent-1.0.zip?cmd=build'

or can I get some other url to see the activity log?

A: There is an easy way to do this using the following way:
curl -ku admin:admin -F file=@"package-1.0.zip" -F force=true -F install=true http://localhost:4502/crx/packmgr/service.jsp

This will print the output like expected.

A: please have a look at this post: https://stackoverflow.com/a/50325299/1514647
when adding a logger for the org.apache.jackrabbit.vault.packaging.impl.ActivityLog it will create entries:
05.05.2022 09:00:00.024 *INFO* [OsgiInstallerImpl] org.apache.jackrabbit.vault.packaging.impl.ActivityLog group:packagname:1.0.0: CREATE
05.05.2022 09:00:00.024 *INFO* [OsgiInstallerImpl] org.apache.jackrabbit.vault.packaging.impl.ActivityLog group:packagname:1.0.0: UPLOAD
05.05.2022 09:00:00.105 *INFO* [OsgiInstallerImpl] org.apache.jackrabbit.vault.packaging.impl.ActivityLog group:packagname:1.0.0: EXTRACT_SUB_PACKAGES ()

Local access of logs:
After that you can do a tail -f error.log in the crx-quickstart/logs folder
Remote access of logs:
http://host:port/system/console/slinglog/tailer.txt?tail=10000&grep=*&name=%2Flogs%2Ferror.log


text:
Q: Google speech recognition API not listening I was trying the below speech recognition code using Google Speech API.
#!/usr/bin/env python3
# Requires PyAudio and PySpeech.

import speech_recognition as sr

# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
    print("Say something!")
    audio = r.listen(source)

# Speech recognition using Google Speech Recognition
try:
    # for testing purposes, we're just using the default API key
    # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
    # instead of `r.recognize_google(audio)`
    print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

But I am getting only this.
jobin@jobin-Satellite-A665:~/scr$ python3 scr.py
Say something!

Even though I say something, nothing happens.
I don't have an external microphone. I think this script will work with my laptop's in-built microphone.
I have tested my laptop's microphone  here. It is working fine.
Am I missing anything?

A: You could test that pyAudio is finding your microphone by running the following:
"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

And playing the resulting output.wav file.
Once you are confident that you are getting some audio I would add a couple of print statements to the original code to locate how far you are getting, i.e.:
print("Audio captured!") # before trying to recognise see if you have something

and
print('Recognition Ended')  # at the end of the script

This will let you see how far you are getting.
Next you may need to find out which is the default audio device with:
import pyaudio
print(pyaudio.pa.get_default_input_device())

Which should tell you the default input device, this was one on my machine so used this:
with sr.Microphone(1) as source: # Specify which input device to use
    r.adjust_for_ambient_noise(source, 1) # Adjust for ambient
    print("Say something!")
    audio = r.listen(source, 2)  # 2 Second time out
print('Done Listening sample size =', len(audio.frame_data))


text:
Q: Check if an excel sheet is protected and find the password (using apache poi) I need to do the following:
User downloads excel file (which is a template) with some columns read only and other editable;(read only columns were made by protecting entire sheet

//protect entire sheet
sheet.protectSheet("password");
//create style for editable cells
XSSFCellStyle editableStyle = workbook.createCellStyle();
editableStyle.setLocked(false);
//for editable cells apply this style
cell.setCellStyle(editableStyle);

User modifies the template file, filling only editable cells
User upload the template
During uploading the template I need to check if the uploaded file is the one downloaded before, protected with exactly the same "password".
I have the possibility to get the password but it is encoded and I don't know how to decode it.
byte[] password = sheet.getCTWorksheet().getSheetProtection().getPassword();

Can you please help me?

A: If you want to check if the file is have the same password, then you can use validateSheetPassword method to check it.
Example:
if (sheet.validateSheetPassword("password"))
    print("It same password");

Or you can see the documentation here: https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFSheet.html#validateSheetPassword(java.lang.String)


text:
Q: What types of error estimates could I do for calculation of percent significantly increasing/decreasing/etc? For a research project I'm working on, I'd like to present the percent significantly increasing (or decreasing, etc.) in a table for different treatments. I realize this is pretty minimal information to present, but for my study, adding a confidence interval or similar for fold change doesn't make a lot of sense (since whether there was a significant change matters much more than the magnitude of the change).
While trying to get my research published, I've gotten a comment from one reviewer asking for an error estimate for this percent significantly increased (my p-values are already corrected for multiple testing, so I don't think this is what they mean). How could I generate this? If it's not possible, can anyone think of another way to present this data that would satisfy the reviewer.
Thanks in advance!


text:
Q: How to upload multiple pictures at once in itunesconnect? How can I upload multiple pictures at once to my app details in itunesconnect? I remember that at some time it was possible via Safari and drag/dropping multiple pictures onto the 'choose picture'-button. Now (Mountain Lion, Safari 6.0.1) it isn´t anymore.
Any ideas on how to solve this? It´s really annoying to upload 15 pictures (iPhone, iPhone5, iPad) one after another.

A: I not sure if it was ever possible to upload multiple pictures at once. However, drag & drop (for single files) is still possible - it's just broken in Safari, which opens/displays the dragged file. In Firefox and Chrome, dropping an image file (e.g. some .png) on the "Choose File" button results in an upload.

A: You can't do that as i have tried up to 2 images

A: Seems like apple removed this feature, for whatever reason.
Best you make a suggestion on iTunes Connect.
Just log in and click on "Contact Us" in the footer.
(I can't provide a link, because it varies)


text:
Q: UTF8 with PHP and MySQL error I got a form that allow user to submit data. I set the collation of the whole table in the database as utf8mb4_unicode_ci.
However when I tried to input non-English characters, what I get in the field is something like ä½ ç‡!!å&curren.....
When I later echo the data out with php, similar illegible characters appers.
Is it the problem with my form submission? Or is PHP capable of output the correct data from the strang strings in mysql?

A: Looks like you are inserting html encoded strings into your sql server. Somewhere you are missing to html_entity_decode()

A: For database(in the php file), if you are pulling data from query
$db->set_charset('utf8');  or mysql_set_charset('utf8',$db);

Also I would suggest using utf8 general-ci for all languages.


text:
Q: prepared parameterized query with PDO New to this new and secure way of handling SQL's in PHP and MySql driven web based application, to secure the code from SQL injections. I am planning to start using mysqli with PDO. Can anyone please outline how should i get started and proceed.
Any reference to any article will also be helpful.
Thanks in advance.

A: To create the connection
try {
    $db = new PDO("mysql:dbname=".DB_NAME.";host=".DB_HOST,DB_USER,DB_PWD);
} catch (PDOException $e) {
    die("Database Connection Failed: " . $e->getMessage());
}

Then to prepare a statement
$prep = $db->prepare("SELECT * FROM `users` WHERE userid = ':id'");

As you can see, you label each parameter you'd like by prefixing any string with ':'. Then all you do is pass an array mapping the parameter (:id) to the value when you execute.
if (!$prep->execute(array(":id" => $userinput))) {
   $error = $prep->errorInfo();
   echo "Error: {$error[2]}"; // element 2 has the string text of the error
} else {
   while ($row = $prep->fetch(PDO::FETCH_ASSOC)) { // check the documentation for the other options here
        // do stuff, $row is an associative array, the keys are the field names
   }
}

Instead of PDO::FETCH_ASSOC with the "fetch" function, there are various other ways to get your data. You can use fetchAll to get an array of ALL the results at once instead of just going row by row. Or you can get the array of information as a 0-indexed array, or you can even fetch the results directly into a class instance (if the field names line up with the properties of the class.)
All the documentation of PDO can be found here: PHP.net PDO Manual


text:
Q: MFE ModuleFederationPlugin failing with TypeError: container.init is not a function MFE1 will expose some functionality including some html using createCustomElement angular/elements
MFE2, which is expected to use this remote MFE html as it is. it will embedded and create from calling multiple domain specific mfes.
Following are some details about approach:
MFE1 web pack config
    const singleSpaAngularWebpack =
      require('single-spa-angular/lib/webpack').default;
     const { merge } = require('webpack-merge');
     const { EnvironmentPlugin } = require('webpack');
     const { ModuleFederationPlugin } = require('webpack').container;

     require('dotenv').config();

    module.exports = (config, options) => {
       const singleSpaWebpackConfig = singleSpaAngularWebpack(config, options);
       return merge(singleSpaWebpackConfig, {
       output: {
          scriptType: 'text/javascript'
        },
        plugins: [new ModuleFederationPlugin({
        name: 'mfe1',
        filename: 'remoteEntry.js',
        exposes: {
             './Module': 'src/app/app.module.ts',
        }
      }),
      new EnvironmentPlugin(['ENVIRONMENT'])],
        })
       }

main.ts file MF2 - calling remote MFE1
import { loadRemoteEntry } from '@angular-architects/module-federation';

Promise.all([
  loadRemoteEntry({
    type: 'module',
    remoteEntry: 'http://localhost:4206/remoteEntry.js',
  }),
])
  .catch((err) => console.error('Error loading remote entries', err))
  .then(() => import('./bootstrap'))
  .catch((err) => console.error(err));

And my MFE2 routing file is
import { APP_BASE_HREF } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { EmptyRouteComponent } from './core/components/empty-route/empty-route.component';
import { loadRemoteModule } from '@angular-architects/module-federation';

const routes: Routes = [
 {
  path: 'test',
  loadChildren: () =>
      loadRemoteModule({
          type: 'module',
          remoteEntry: 'http://localhost:4206/remoteEntry.js',
          exposedModule: './Module'
      })
      .then(m => m.MyModule)
},
 { path: '**', component: EmptyRouteComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [{ provide: APP_BASE_HREF, useValue: '/' }],
})
export class AppRoutingModule {}

Problem:
ngx-logger.mjs:607 2023-02-19T14:59:44.358Z ERROR [main.js:575:21] Error from global error handler in order Error: Uncaught (in promise): TypeError: container.init is not a function
TypeError: container.init is not a function
at angular-architects-module-federation-runtime.mjs:27:1
ngx-logger.mjs:607 2023-02-19T14:59:44.363Z ERROR [main.js:575:21] Error from global error handler in order Error: Uncaught (in promise): TypeError: container.get is not a function
TypeError: container.get is not a function
at angular-architects-module-federation-runtime.mjs:10:1
What would it be missing?


text:
Q: How to generate a File Tree in Java Swing directly by providing a absolute path? My requirement is that there is a browse button on my UI.When I select a directory and press Open,then using the selected path a tree structure should appear.The parent/root directory will start from the folder that I selected.
Eg: If I select c:/mydocuments/myfiles,then the root for the tree will be myfiles and then it should show all its children in the tree.
Presently in swings JTree can be used to generate a tree structure but for doing this we need to make a list and then supply it to the JTree.
In my scenario,it becomes difficult as everytime I need to generate a list the moment path changes.
So i want to know that in java do we have anything like jqueryfiletree which takes the absolute path and generates the tree automatically.

A: You do not need to make a list. You should just have code that can generate a TreeModel based on a file path.
And that code is available on a lot of locations on the internet. For example in this Sun JTree article
Another nice example is the 'File Browser GUI' from Andrew Thompson who is also active on this site

A: Here is a minimal working code sample:
public class FileTree extends JTree
{
   public FileTree(String path)
   {
      super(scan(new File(path)));
   }

   private static MutableTreeNode scan(File node)
   {
      DefaultMutableTreeNode ret = new DefaultMutableTreeNode(node.getName());
      if (node.isDirectory())
         for (File child: node.listFiles())
            ret.add(scan(child));
      return ret;
   }
}


text:
Q: How can quantum wavefunctions be smooth/continuous when particles are created/destroyed/changed? My (admittedly limited) understanding of the Schrodinger equation tells me that the vector differential operators are only meaningful over a differentiable phase space.
For example, if the dimensions of my phase space are the Euclidean coordinates of $N$ featureless point particles, then it makes sense that you can construct a $3N$ary field of some (algebraically) vector quantity, associate it with these coordinates, and apply differential operators. If the quantum wavefunction only governed these positions then the interpretation would be very direct.
But if the wavefunction allows particles to be created, then we might now have a future state in a $3(N+1)$ary field. In the finite case the interpretation breaks down.
Now, I know the wavefunction operates on an infinite-dimensional phase space, and if I strain my imagination I can just about conceive an association between this object and the particles in the universe (if I take it for granted that all particles are everywhere and the particle field is the sum of these, okay)...
...but I cannot conceive of a way this wavefunction can be continuous when particles are created or destroyed...
...and if it isn't continuous, how can we apply differential operators?

A: First, you are not talking about a phase space, but configuration space.
Now, the space of wavefunctions of a single particle in 3D space is the space of Lebesgue square-integrable functions $L^2(\mathbb{R}^3)$ on the configuration space $\mathbb{R}^3$. So already for a single particle, there is no generic requirement for the wavefunction to be smooth, differentiable or even continuous.
However, in practice, you may deal with Hamiltonians that are differential operators, and hence one needs to require the existence of derivatives of the wavefunction, i.e. pass to the Sobolev space $W^{2,2}(\mathbb{R}^3)$ for which weak second derivatives exist. Still the wavefunction itself is an equivalence class of square-integrable functions, and the representants need not be differentiable in the strong sense.
Therefore, the wavefunction is already not necessarily smooth, differentiable or even continuous in the case of a single particle.
Introducing many particles and the possibility of their creation and annihilation, quantum mechanics deals with this by defining the one particle-space $H_1 := L^2(\mathbb{R}^3)$ and the $i$-th particle space as the $i$-th symmetrized tensor product
$$ H_i = S^i (H_1)$$
for bosons or the antisymmetrized product for fermions. The total space of states then becomes the Fock space $\bigoplus_{i=0}^\infty H_i$. However, the proper framework for the annihilation of creation of arbitrary particles is quantum field theory, not quantum mechanics.

A: Continuity of a wave-function is not a necessary condition, as already pointed out by @ACuriousMind.
For instance, consider a linearly dispersing particle in the presence of a $\delta$-function potential. The time-independent Schrödinger equation in this case is
$-i \frac{\partial}{\partial x} \psi(x) + V \delta(x) \psi(x) = E \psi(x)$
Typically, you have quadratically dispersing particles, in which case you can indeed find a continuous wave-function (See https://en.wikipedia.org/wiki/Delta_potential).
However, owing to the linear dispersion, for any $V\neq 0$, the wave-function must necessarily have a discontinuity at $x = 0$.

A:
How can quantum wavefunctions be smooth/continuous when particles are created/destroyed/changed?

Because particle creation etc merely involves a change of configuration. There is no magic. In gamma-gamma pair production you start with two photons, and you end up with an electron and a positron. Each has a wave nature, as evidenced by things like electron diffraction. When you annihilate an electron and a positron you get two gamma photons, and they have a wave nature too. Note that in atomic orbitals electrons "exist as standing waves". It's like you change the wave configuration from an open path to a closed path.

My (admittedly limited) understanding of the Schrodinger equation tells me that the vector differential operators are only meaningful over a differentiable phase space.

All you need to understand is that the Schrödinger equation equation is a wave equation.

For example, if the dimensions of my phase space are the Euclidean coordinates of N  featureless point particles

There are no point particles. The E=hf photon has a wave nature, and so does the E=mc² electron. It's field is what it is. It isn't some speck that has a field, it is field. Think standing wave standing field, and there ain't no billiard ball in the middle. And if anybody objects to that, tell them it's quantum field theory, not quantum point-particle theory.

then it makes sense that you can construct a 3Nary field of some (algebraically) vector quantity

Yes, you can construct a standing field from a dynamical wave. That's what gamma-gamma pair production does. Then we talk about vector fields:

Public domain image by Fibonacci, see Wikipedia.

But if the wavefunction allows particles to be created, then we might now have a future state in a 3(N+1)ary field. In the finite case the interpretation breaks down.

Sorry, I don't know what you mean by this. But can I offer that the electron's electromagnetic field is dynamical, hence its magnetic moment. And its helical motion through a magnetic field. And the Einstein-de Haas effect which "demonstrates that spin angular momentum is indeed of the same nature as the angular momentum of rotating bodies as conceived in classical mechanics."

Now, I know the wavefunction operates on an infinite-dimensional phase space, and if I strain my imagination I can just about conceive an association between this object and the particles in the universe (if I take it for granted that all particles are everywhere and the particle field is the sum of these, okay)...

You should read up on weak measurement and stuff like this by Jeff Lundeen:
"With weak measurements, it's possible to learn something about the wavefunction without completely destroying it. As the measurement becomes very weak, you learn very little about the wavefunction, but leave it largely unchanged. This is the technique that we've used in our experiment. We have developed a methodology for measuring the wavefunction directly, by repeating many weak measurements on a group of systems that have been prepared with identical wavefunctions. By repeating the measurements, the knowledge of the wavefunction accumulates to the point where high precision can be restored. So what does this mean? We hope that the scientific community can now improve upon the Copenhagen Interpretation, and redefine the wavefunction so that it is no longer just a mathematical tool, but rather something that can be directly measured in the laboratory."

but I cannot conceive of a way this wavefunction can be continuous when particles are created or destroyed.

Conceive of it changing direction. From straight to curved, or vice versa.

...and if it isn't continuous, how can we apply differential operators?

It's continuous.


text:
Q: How to assign value of a formula (that contains a variable) to another variable I've to assign an algebraic formula that contains a variable (i for example) to another variable (say a).
I'm probably not using the right syntax. I've searched but couldn't find relevant answers.
Dim i As Long, a As Long
For i = 1 To 30
    a = SIN(RADIANS(i))
    With ActiveSheet.Shapes("sketch_1").Duplicate
        .IncrementTop i
        .IncrementRotation a
    End With
Next i

Is there also a way to directly enter the formula next to .IncrementRotation as opposed to having seperate variable "a" to do this job?

A: You can use Excel formulas in VBA using WorksheetFunction
a = Sin(WorksheetFunction.Radians(i))


text:
Q: Can liquibase use github as source of changeLog files? Consider project with different language modules that use same database. Database is controlled by liquibase. Liquibase changeLog files placed in special github repository. So every developer could download it and run locally to keep local instance of database in actual state.
Often developers use inmemory database like H2 for testing and liquibase rebuilds database structure every test run. To keep testing database in actual state every developer need to download changeLogs and put in their modules manually. But sometimes he could miss that somebody else changed database structure, so his tests should fail, but will pass. This is more actual for testing in CI.
Could liquibase download changelogs automatically from internet source? Could it use private github repositories? Could it use some property like changeLogFile for this?

A: May I confirm some assumptions?  It sounds you have a team of developers all commiting liquibase database changes and you want to be able to automatically deploy in a CI/CD process?
Thanks,
Ronak
Liquibase Developer Evangelist

A: Liquibase can't run changelogs placed into some remote git repo. But in your CI you can setup such thing: if there is a pull-request from branch 'feature' to branch 'master' automatically:

*

*Before tests are executed checkout branch 'feature'
and merge 'master' there

*Apply all changelogs

*Run tests after it

So if another developer change DB structure and commit it into master tests in 'feature' branch will be executed with latest DB structure.


text:
Q: Where should I set UINavigationController's delegate property? I'm working with some custom controller transitions, which make use of UINavigationController's delegate property. If I set it in viewDidLoad(), self.navigationController?.delegate gets deallocated at some point after the push. Setting it in viewWillAppear() works, but I'm wondering why that property gets deallocated in the first place, and where people typically set this property.
    // The first time you push, it will work correctly, and the delegate function below is called. After you pop back to this controller, delegate is nil (has been deallocated)
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.delegate = self
    }

    // Brute force works
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationControllerOperation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        if operation == .push {
            return WTPPushAnimator()
        }
        if operation == .pop {
            return WTPPopAnimator()
        }
        return nil;
    }

A: If the ViewController you are pushing also sets navigationController?.delegate = self, then when that ViewController is popped, that ViewController will be deallocated and the weak var delegate will be set to nil.  viewDidLoad() only runs when the ViewController is first created, so when returning to the first ViewController, viewDidLoad() will not run again. viewWillAppear() is always called when a ViewController is pushed or when it is returned to on a pop, so viewWillAppear() is the right place to set this delegate.


text:
Q: C# How to split string based on 2 parameters? I have three string called This_is string1 and This is string2 There_is string3
How to split these 3 strings after "This_", "This " "There_) in one condition? basically, i want to split based on first "_" or " " in a string in one condition.

A: The answer is simple, you can use the String.Split method, specifying the multiple delimiters (in your case the underscore and whitespace):
str.Split(new char[]{'_',' '})

LinQPad result:

If you want to split only the first part, you can use the 2nd overload of String.Split:
str.Split(new char[]{'_',' '}, 2);

and this is the result in LinQPad:

A: So you want to split only the first part? You can use the overload of String.Split that allows to specify the count and multiple delimiters:
str.Split(new[]{' ', '_'}, 2);

So on the first string you get: "This" + "is string1", similar on the others.


text:
Q: Command to find user who runs the server(IIS)? I hosted my django project in IIS on windows,Is there any python function to find the user who runs IIS?
Thanks in advance.

A: If you mean the user account in which IIS is executed you can try:
>>> import getpass
>>> getpass.getuser()
"salem" # my username account


text:
Q: Upgrading Nginx 1.1.9 to 1.4.x I have a production server running Nginx 1.1.9 (on Ubuntu 12.04). I would like to upgrade it to The latest stable version of Nginx. I'm having some trouble finding out how and if upgrading will have some backwards compatibility issues. I have multiple sites running and altered config files etc.
What should I expect when upgrading?

A: Nginx allows very graceful upgrade procedure. You should read the article: http://nginx.org/en/docs/control.html#upgrade
As for the guide about API changes, you can find all of them in change log under the Change: keyword: http://nginx.org/en/CHANGES


text:
Q: Pong Game From Python for absolute beginners i am running into two error going two routes the ball is find works great but the score text wont work, every time i implement it it throws the two errors.
from superwires import games, color
from random import *

"""Main application file"""

#the screen width and height
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
points = 0
score = 0

"""Paddle object that is controlled by the player. Moves up and down. Collides with the ball. Points are added when ball is collided with"""
class Paddle(games.Sprite):
    HEIGHT = 480/20
    paddle_image = games.load_image('paddle.png', transparent=True)
    def __init__(self):
        super(Paddle, self).__init__(image = Paddle.paddle_image,
                                  x = 40,
                                  y = 50,
                                  is_collideable=True)
        self.score = games.Text(value = 0,
                           size = 30,
                           color = color.green,
                           x = SCREEN_WIDTH - 25,
                           y = SCREEN_HEIGHT - 431)
        games.screen.add(self.score)
        games.screen.mainloop()

    """ updates Position based on mouse Position"""
    def update(self):
     self.y = games.mouse.y
     self.Check_Collision()

    def Check_Collision(self):
        for PongBall in self.overlapping_sprites:
             PongBall.handle_collide()

"""actual ball in play """
class PongBall(games.Sprite):

   #velocity variables
    vel_x = 5
    vel_y = 0

    #pos of boundry to ball pos
    lower_bounds_check = 0
    upper_bounds_check = 0

    #checks if paddle gets collided with
    def handle_collide(self):
        if((SCREEN_WIDTH/2) < self.x):
            PongBall.vel_x = randint(-10,-5)
            PongBall.vel_y = randint(-10,-5)
        elif((SCREEN_WIDTH/2) > self.x):
            PongBall.vel_x = randint(5,10)
            PongBall.vel_y = randint(5,10)

    #checks if it hit the bottom; bool function
    def check_boundry_lower(self):
        PongBall.lower_bounds_check = (SCREEN_HEIGHT/2)
        return ((self.y - PongBall.upper_bounds_check) > PongBall.lower_bounds_check)

   #checks if it hits the top; bool function
    def check_boundry_upper(self):
        PongBall.upper_bounds_check = (SCREEN_HEIGHT/2)
        return ((self.y + PongBall.upper_bounds_check) < PongBall.upper_bounds_check)

    #Resets the velocity based on boundry collision
    def boundry_update(self):
        if(self.check_boundry_upper()):
            PongBall.vel_y = randint(5,10)
            return
        elif(self.check_boundry_lower()):
            PongBall.vel_y = randint(-10,-5)
            return

    def update(self):
        self.boundry_update()
        self.x += PongBall.vel_x
        self.y += PongBall.vel_y

"""
Entry point Function
"""

# Create background, paddle, and ball. Then call the game mainloop.

# crate the window
games.init(SCREEN_WIDTH, SCREEN_HEIGHT, 50, virtual = False)

#sets/loads background
background = games.load_image(f"background.png", transparent=True)
games.screen.background = background

# paddle image
paddle_image = games.load_image(f"paddle.png", transparent = True)

#PingPong ball
PingPongBall = games.load_image(f"Ball.png", transparent = True)

#paddle Right and left
paddle_1 = Paddle()
paddle_2 = Paddle()

#pingball ball instance
ball = PongBall(image = PingPongBall, x = 150, y = 250, is_collideable=True)

#adding all three sprites to screen
games.screen.add(ball)
games.screen.add(paddle_1)
games.screen.add(paddle_2)

#each instance update function
ball.update()
paddle_1.update()
paddle_2.update()

#adding text

#main loop
games.screen.mainloop()

i get this error;
 Traceback (most recent call last):
  File "C:\Users\gamer\Desktop\PingPong\main.py", line 15, in <module>
    class Paddle(games.Sprite):
  File "C:\Users\gamer\Desktop\PingPong\main.py", line 17, in Paddle
    paddle_image = games.load_image('paddle.png', transparent=True)
  File "C:\Users\gamer\AppData\Local\Programs\Python\Python310\lib\site-packages\superwires\games.py", line 836, in load_image
    if not screen.virtual:
AttributeError: 'NoneType' object has no attribute 'virtual'

Please help i cant seem to escape the error even if i dont pass through the constructor i get text object doesnt not have handle_collide() attribute
-Thanks guys
new error:
Traceback (most recent call last):
  File "C:\Users\gamer\Desktop\PingPong\main.py", line 153, in <module>
    games.screen.mainloop()
  File "C:\Users\gamer\AppData\Local\Programs\Python\Python310\lib\site-packages\superwires\games.py", line 783, in mainloop
    sprite._process_sprite()
  File "C:\Users\gamer\AppData\Local\Programs\Python\Python310\lib\site-packages\superwires\games.py", line 440, in _process_sprite
    self.update()
  File "C:\Users\gamer\Desktop\PingPong\main.py", line 40, in update
    self.Check_Collision()
  File "C:\Users\gamer\Desktop\PingPong\main.py", line 36, in Check_Collision
    PongBall.handle_collide()
AttributeError: 'Text' object has no attribute 'handle_collide'

A: You need to have the games.load in the __init__ function so as not to call it before the environment is set up.
Replace this:
class Paddle(games.Sprite):
    HEIGHT = 480/20
    paddle_image = games.load_image('paddle.png', transparent=True)

    def __init__(self):
        super(Paddle, self).__init__(image = Paddle.paddle_image,
                                  x = 40,
                                  y = 50,
                                  is_collideable=True)

with this:
class Paddle(games.Sprite):
        HEIGHT = 480/20

        def __init__(self):
            self.paddle_image = games.load_image('paddle.png', transparent=True)

            super(Paddle, self).__init__(image = self.paddle_image,
                                      x = 40,
                                      y = 50,
                                      is_collideable=True)


text:
Q: Load Image while page is loading in JSP I have been trying to display an image in while my page is loading. But as you can see in the screenshot that page is loading before the image. Probably because of sequence.

    <meta http-equiv="X-UA-Compatible" content="IE=EDGE"/>

And at the bottom of the page I have used this script
window.onload = function(){ document.getElementById('loading').style.display='none';}

But my page is not loading before the content. So, in a nut shell I can't see loading image on page load.


text:
Q: EFv1 mapping 1 to many Relationship to POCOs I'm trying to work through a problem where I'm mapping EF Entities to POCO which serve as DTO.
I have two tables within my database, say Products and Categories. A Product belongs to one category and one category may contain many Products. My EF entities are named efProduct and efCategory.  Within each entity there is the proper Navigation Property between efProduct and efCategory.
My Poco objects are simple
public class Product
{
    public string Name { get; set; }
    public int ID { get; set; }
    public double Price { get; set; }
    public Category ProductType { get; set; }
}

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Product> products { get; set; }
}

To get a list of products I am able to do something like
    public IQueryable<Product> GetProducts()
    {
        return from p in ctx.Products
               select new Product
               {
                   ID = p.ID,
                   Name = p.Name,
                   Price = p.Price
                   ProductType = p.Category
               };
    }

However there is a type mismatch error because p.Category is of type efCategory. How can I resolve this? That is, how can I convert p.Category to type Category?
Likewise when I do
        return from c in ctx.Categories
                where c.ID == id
                select new Category
                {
                    ID = c.ID,
                    Name = c.Name,
                    ProductList = c.Products;
                };

I get a mismatch because ProductList is of type Product, where c.Products is an EntityCollection
I know in .NET EF has added support for POCO, but I'm forced to use .NET 3.5 SP1.

A:     return from p in ctx.Products
           select new Product
           {
               ID = p.ID,
               Name = p.Name,
               Price = p.Price
               ProductType = new Category
               {
                   ID = p.Category.ID,
                   Name = p.Category.Name // etc.
               }
           };

For Category you do:
    return from c in ctx.Categories
            where c.ID == id
            select new Category
            {
                ID = c.ID,
                Name = c.Name,
                ProductList = from p in c.Products
                              select new Product
                              {
                                  ID = p.ID,
                                  Name = p.Name,
                                  Price = p.Price
                              }
            };


text:
Q: How Can I speed up my load data query I have a table with 33 million unique record. New records inserted in it twice in a week. when I import data its take about 8 to 9hrs. The new file which used to load has 6 to 7 million record  s. How can i optimize this?
Table engine is MYISAM.

A: Indexing = overhead
Any index including unique indexes are a bit of extra work to be done when inserting the row (aka overhead). It's not necessarily a lot of work when take individually -- especially since compensate by helping speed things up when reading information but -- it does add up.
When inserting a new row into a table with indexes, every column which is included in an index must be registered into the index file; every unique constraint must be checked before insertion to make sure no duplicates are saved.
Imagine having to check 33 million rows of unique values once for every inserted row. If you're inserting 1 million extra rows that's 33 billion checks.
Drop uniqueness in favor of PK:
If you drop the uniqueness constraint you will be able to insert rows much faster. Unfortunately if you can't guarantee that the newly imported values are unique without checking then you kinda need the uniqueness constraint.
Also dropping the uniqueness constraint means that when you query that table searching for a particular item filtering based on the column that used to be unique the query will be slower (much slower in 33 million rows).
If you can guarantee that they are unique or can leave the checking for a later stage (clean of duplicates) then you can just setup a primary key with auto_increment or UUID and do the duplicate cleanup afterwards.
If you don't need to query that table using the unique column (if you can change the application to query by primary key) things will move much faster.


text:
Q: After using dir() on a object, i only get some of the list of valid attributes from the object, the rest are displayed as [...] After using dir() on a object, i only get some of the list of valid attributes from the object, the rest are displayed with [...] at the end
Is there a way to get all of them to show?
And example of output would be [ '__class__', '__something__', '__something__', ...]
But the output i want would be [ '__class__', '__something__', '__something__', '__something__' 'names', 'numbers']


text:
Q: Making non-bootstrap nav bar expand after menu click I am having a bit of trouble making my nav menu appear from clicking the nav menu icon.
HTML
nav role="navigation" class="navbar">

        Testy Testy Web

About

Services

Pricing

Contact

CSS
nav {width: 100%; position: fixed; text-align: left; background-color: #404040; z-index: 999;}
nav ul li {display: inline;}
nav a {text-decoration: none; float: left; color: white; padding: 1em; line-height: 100%;}
nav a:hover {background-color: #1AA2D4;}
.nav-header a {display: inline-block;}
#toggle {float: right; display: none;}

@media (max-width: 592px) {
    .splash p {font-size: 1em;}
    .splash h1 {font-size: 8em;}
    nav {width: 100%; position: fixed; top: 0; text-align: left; background-color: #404040; z-index: 999;}
    nav ul li {display: block; float: left; clear: left; width: 100%; clear: bottom;}
    nav ul {width: 100%;}
    nav a {text-decoration: none; float: left; color: white; padding: 1em; line-height: 100%;}
    #toggle {float: right; display: block;}
    #menu {display: none;}

JavaScript/jQuery
$(document).ready(function(){

$('#toggle').click(function(){
        $('#menu').css('display', 'visible');
    });

});

Basically, I have it so that the nav links are hidden when displayed on smaller screens, however I am struggling to figure out how to get jQuery to make it visible when you click the toggle icon. I know this is a standard thing in Bootstrap, but the website I am building is not using a framework.
Is anyone able to let me know what I am doing wrong.
Thanks

A: display property gets block, inline, inline-block and none values. To show menu, you should change this line:
$('#menu').css('display', 'visible');

To :
$('#menu').css('display', 'block');

Also you can use toggle in order to hide and show menu on each click :
$('#menu').toggle();

More info on using toggle :
http://api.jquery.com/toggle/

A: You can use toggle class. Defined a new class "menu" which can be switched to show/ hide your menu. Cooked your code, you can replace your existing code with this.

$(document).ready(function(){

   $("#toggle").click(function(){
        $("#menu").toggleClass("menu");
    });

});
nav {width: 100%; position: fixed; text-align: left; background-color: #404040; z-index: 999;}
nav ul li {display: inline;}
nav a {text-decoration: none; float: left; color: white; padding: 1em; line-height: 100%;}
nav a:hover {background-color: #1AA2D4;}
.nav-header a {display: inline-block;}
#toggle {float: right; display: none;}

@media (max-width: 592px) {
    .splash p {font-size: 1em;}
    .splash h1 {font-size: 8em;}
    nav {width: 100%; position: fixed; top: 0; text-align: left; background-color: #404040; z-index: 999;}
    nav ul li {display: block; float: left; clear: left; width: 100%; clear: bottom;}
    nav ul {width: 100%;}
    nav a {text-decoration: none; float: left; color: white; padding: 1em; line-height: 100%;}
    #toggle {float: right; display: block;}
 #menu {display:none;}

    .menu {display:block!important;}
  }

            Testy Testy Web
            Menu

About

Services

Pricing

Contact


text:
Q: How to solve gesture that cause error (caused by java.lang.NullpointerException)? public class GusterActivity extends Activity implements OnGesturePerformedListener
 {
  TextView txtmsg;
  TextView txtwrt;
  private GestureLibrary gesturelib;
  /** Called when the activity is first created. */
  @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GestureOverlayView gestureoverlayview=new GestureOverlayView(this);
    View inflate=getLayoutInflater().inflate(R.layout.main,null);
    gestureoverlayview.addView(inflate);
    gestureoverlayview.addOnGesturePerformedListener(this);
    gesturelib= GestureLibraries.fromRawResource(this,R.raw.gestures);
    if(gesturelib.load()){
        finish();
    }
    setContentView(gestureoverlayview);
}

public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
    ArrayList<Prediction> predictions = gesturelib.recognize(gesture);
    for(Prediction prediction : predictions){
        if(prediction.score>1.0){

                Toast.makeText(this,prediction.name,Toast.LENGTH_SHORT);

        }
    }
}

A: May be you are getting nullpointer because your gesturelib is null in line( gesturelib= GestureLibraries.fromRawResource(this,R.raw.gestures);)


text:
Q: What does pclean do? I have looked everywhere for information on this... what does pclean do?

The program 'pclean' is currently not installed. You can install it by
  typing: apt install pbuilder-scripts

A: pclean is just a wrapper for pbuilder --clean, and from the manpage of pbuilder:
--clean
      Cleans   up   the   directory  specified  by  the  configuration
      BUILDPLACE and APTCACHE specified in /etc/pbuilderrc


text:
Q: How to call a webservice from windows phone 6.5? I have the following problem, I try to call an web service from
an Windows phone 6.5 while its connected to active sync to my desktop computer,
in development debug environment.
So I dont have wlan connected on the phone, maybe that is the problem?
But when its connected to my desktop pc, by USB (Windows Mobile Device Center) i can
browse the web and I can acess the ?wsdl meta data on the phone - to the web service.
The webservice is running on my computer as an windows service.
I use an simple web reference to my local webservice:
private void button2_Click(object sender, EventArgs e)
{
    var method = new MobileCashier.TestReference.YvesTransfer();

    method.Timeout = 30000;
    bool bResult, bResultSpec;
    method.TestConnection(out bResult,out bResultSpec);

    MessageBox.Show(bResult.ToString());
    MessageBox.Show(bResultSpec.ToString());

    method.Dispose();
}

But when I run it on the phone in debug mode (or not debug) I get this error:
"No connection could be made because the target machine actively refused it"

If I run the windows exe app on my desktop computer(the same as I deploy on the phone), or from another desktop computer then there is no problem.
Maybe I need wlan to make it accept the calls?
Can some one help me please?

A: Yes you do need Wlan activated on your cell to access a local webservice, you should essentially be in the same network of your desktop machine.
I would rather use any other wlan connected machine to test my webservice on another machine, and be sure of it, may be write a small testbed app to check the webservice.
you can also open your webservice wsdl page on your phone, and see if it opens well, now your code must be able to call your webservice from your desktop's hosted webservice.


text:
Q: What is the difference between evict() and clear() methods in Hibernate? I want to detach object from session so I written code like is shown below. But it is not detaching from session, instead it is saving to the database.
How evict() and clear() methods work, can anybody answer please?
session.evict(student);
session.save(student);

A: I think you should call session.save(student); and then session.evict(student); or session.clear(); as it will not make sense vice versa.
Answering your original question session.evict(student); will remove the object from the session while session.clear(); will completely clear the session.

clear() Completely clear the session.
evict(Object object)
            Remove this instance from the session cache.

You could refer the official documentation at https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html.
Hope that helps