text:
Q: How do I easily edit the style of the selected text in a JTextPane? How do I easily edit the style of the selected text in a JTextPane? There doesn't seem to be many resources on this. Even if you can direct me to a good resource on this, I'd greatly appreciate it.
Also, how do I get the current style of the selected text? I tried styledDoc.getLogicalStyle(textPane.getSelectionStart()); but it doesn't seem to be working.

A: Here's a code snippet to insert a formatted "Hello World!" string in a JEditorPane:
Document doc = yourEditorPane.getDocument();

StyleContext sc = new StyleContext();
Style style = sc.addStyle("yourStyle", null);

Font font = new Font("Arial", Font.BOLD, 18);

StyleConstants.setForeground(style, Color.RED);
StyleConstants.setFontFamily(style, font.getFamily());
StyleConstants.setBold(style, true);

doc.insertString(doc.getLength(), "Hello World!", style);

A: Take a look at the following code in this pastebin:
http://pbin.oogly.co.uk/listings/viewlistingdetail/d6fe483a52c52aa951ca15762ed3d3
The example is from here:
http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneStylesExample3.htm
It looks like you can change the style using the following in an action listener:
final Style boldStyle = sc.addStyle("MainStyle", defaultStyle);
StyleConstants.setBold(boldStyle, true);

doc.setCharacterAttributes(0, 10, boldStyle, true);

It sets the style of the text between the given offset and length to a specific style.
See the full pastebin for more details.  That should fix your problem though.

A: The easiest way to manipulate text panels is using editor kits and their associated actions. You can find a demo of this in the JDK samples (under jdk\demo\jfc\Stylepad).
Sample code that installs a StyledEditorKit and uses a FontSizeAction to manipulate the text:
  public static void main(String[] args) {
    // create a rich text pane
    JTextPane textPane = new JTextPane();
    JScrollPane scrollPane = new JScrollPane(textPane,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    // install the editor kit
    StyledEditorKit editorKit = new StyledEditorKit();
    textPane.setEditorKit(editorKit);
    // build the menu
    JMenu fontMenu = new JMenu("Font Size");
    for (int i = 48; i >= 8; i -= 10) {
      JMenuItem menuItem = new JMenuItem("" + i);
      // add an action
      menuItem
          .addActionListener(new StyledEditorKit.FontSizeAction(
              "myaction-" + i, i));
      fontMenu.add(menuItem);
    }
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fontMenu);
    // show in a frame
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 400);
    frame.setJMenuBar(menuBar);
    frame.setContentPane(scrollPane);
    frame.setVisible(true);
  }

(Tip: if you want to use a FontFamilyAction, have a look at GraphicsEnvironment.getAvailableFontFamilyNames() and logical font family names.)

A: I'd recommend taking a look at Sun's Java Tutorial about editor panes.

A: Ok, wow. Hard question. So I have not found a way to get the style of a given character. You can, however, get the MutableAttributeSet for a given character and then test to see if the style is in that attribute set.
   Style s; //your style
   Element run = styledDocument.getCharacterElement(
       textPane.getSelectionStart() );
   MutableAttributeSet curAttr =
       ( MutableAttributeSet )run.getAttributes();
   boolean containsIt = curAttr.containsAttributes( s );

One problem with getting the Style for a range of characters is that there may be more than one style applied to that range (example: you may select text where some is bold and some is not).
To update the selected text you can:
  Style s; //your style
  JTextPane textPane; //your textpane
  textPane.setCharacterAttributes( s, false );

Oh, and it appears that the function getLogicalStyle doesn't work because it's returning the default style (or maybe just the style) for the paragraph that contains p, rather than the the style of the character at p.


text:
Q: How to click on dropdown list items through Selenium in VBA macro? I am trying to create a macro to download a file from a web page. I have coded the login and navigating to main download page however, unable to get codes to click on a drop-down menu on a web page. I need to click on 3 dots then click on Download xlsx to start downloading the file. I can not proceed to rest of the codes until file is downloaded. Here is the link to HTML properties of this dropdownlist
obj.FindElementsByClass("ant-dropdown-menu-item").Click

A: I had figured out the solution. I had to click on the blank space to get that drop down buttons appear. Then clicked as usually. I got the element path form Chropath chrome add on  and used xpath.
Obj.FindElementByClass("insight__header").Click         '-----------This clicks on blank space to show 3 dots.
Obj.FindElementByXPath("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/header[1]/span[2]/div[1]/button[1]/i[1]/*").Click   '---------This cicks on 3 dots and displays the menu.
Obj.FindElementByXPath("/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/ul[1]/li[4]/span[1]").Click    '---------This clicks on Download xlxs button to start downloading the file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: kivymd OneLineIconListItem change to new screen when you click i need to change to new screen when i click on OneLineIconListItem pls help me
MDNavigationDrawer:
id:nav_drawer
BoxLayout:
orientation: 'vertical'
spancing: '8dp'
padding: '8dp'
Image:
source: 'image.png'
            ScrollView:
                MDList:

                    OneLineIconListItem:
                        text: "Home"
                        IconLeftWidget:
                            icon : 'home-circle'

                    OneLineIconListItem:
                        text: "Contact Us Here"
                        IconLeftWidget:
                            icon : 'email'
                    OneLineIconListItem:
                        text: "Help"
                        IconLeftWidget:
                            icon : 'help-circle'
                    OneLineIconListItem:
                        text: "Setting"
                        IconLeftWidget:
                            icon : 'cog'
                    OneLineIconListItem:
                        text: "Search"
                        IconLeftWidget:
                            icon : 'magnify'

A: ScrollView:
MDList:
    OneLineIconListItem:
        text: "Home"
        IconLeftWidget:
            icon : 'home-circle'
        on_press:root.funation name()

    OneLineIconListItem:
        text: "Contact Us Here"
        IconLeftWidget:
            icon : 'email'
        on_press:root.function name()

    OneLineIconListItem:
        text: "Help"
        IconLeftWidget:
            icon : 'help-circle'
        on_press:root.function name()

    OneLineIconListItem:
        text: "Setting"
        IconLeftWidget:
            icon : 'cog'
        on_press:root.function name()

    OneLineIconListItem:
        text: "Search"
        IconLeftWidget:
            icon : 'magnify'
        on_press:root.function name()


text:
Q: how to close this file to rename and delete a file("Stream closed") Hi I am having trouble deleting and renaming my file this is because my file is still open but when I try to close my file I then get a stream closed  which means my file is closed, my question how do I get my code to delete and rename my file even though my file stream is closed, all my txt files are in the correct folder
public static void updateRecord(int recordID, int recordColumnIndex, String newValue,String fileName) throws IOException {
        java.io.PrintWriter writer;
        try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(fileName))) {
            writer = new java.io.PrintWriter("temp.txt");
            String line;
            // Read file line by line...
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) {
                    writer.println(line);
                    continue;
                }
                // Split each read line to separate data.
                String[] lineParts = line.split("\\s*,\\s*");

            /* If the record ID value matches the supplied ID value
               then make the desired changes to that line.    */
                if (Integer.parseInt(lineParts[0]) == recordID) {
                    lineParts[recordColumnIndex] = newValue;
                    // Rebuild the data line...
                    StringBuilder sb = new StringBuilder(String.valueOf(recordID));
                    for (int i = 1; i < lineParts.length; i++) {
                        sb.append(",").append(lineParts[i]);
                    }
                    line = sb.toString();
                }
                writer.println(line);  // write line to `temp.tmp` file.
                writer.flush();        // Immediate write.
                reader.close();
            }
        }
        writer.close();

        File inputFile = new File("tasks.txt");
        File outFile = new File("temp.txt");

        if (inputFile.exists()) {
            Files.delete(Path.of("tasks.txt"));
            outFile.renameTo(inputFile);
            System.out.println("test");
        }else{
            System.out.println("error");
        }

    }

A: Your problem most likely is caused elsewhere - check all file I/O operations. I suggest you tidy your code so that the file handling is clearer, consistently using NIO Path and Files, not repeating filename definitions, and that all streams are closed using try-with-resources handling:
public static void updateRecord(int recordID, int recordColumnIndex, String newValue, Path fileName) throws IOException {

    Path tempOutFile = Path.of("temp.txt");
    Path mainInputFile = Path.of("tasks.txt");

    try (BufferedReader reader = Files.newBufferedReader(fileName);
         PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempOutFile))) {

        ...
    }
    // Replace main file:
    Files.deleteIfExists(mainInputFile);
    Files.move(tempOutFile, mainInputFile);
}


text:
Q: Does level scaling stop at level 81? I am nearing level 81 (the max level without legendary skills), and want to know whether I after that no longer have to worry about level scaling or what. If level scaling doesn't stop then does it slow down or stop at some other point?

A: Different things in Skyrim scale differently.
Creatures and un-named NPCs generally always pull from Leveled Lists, and have fixed stats and levels. So, for weaker animals like Wolves, the strongest version are level 6, beyond which they stop scaling altogether. For Dragons, however, depending on the DLC you have, there are options up to a player of level 78.
Named NPCs work differently, however. Because they aren't spawned into the game when needed, they can't pull from a leveled list. Instead, their level is scaled to yours, within a range. Each NPC scales differently, too. So Jarl Balgruuf, for example, will always have 1.5 levels for every level the player has, except that he cannot go below level 10, nor above level 30. Thus, he stops scaling once the player hits level 20.
Some NPCs don't even have a maximum level. J'Zargo, for example, will always be the same level as the Player, with a minimum of level 6. The Followers page can be useful for finding NPCs with no, or high level cap.
As a named NPC gains levels, their Health, Magicka, and/or Stamina will increase by a fixed amount per level, and their skills also increase according to their class. So, at a certain point, a given named NPC will max out their various skills, meaning that they are getting less benefit per level.

A: It really depends on what you're looking at.
Most of the apparent level scaling (i.e., Master Conjurer instead of Novice Conjurer) is simply the game looking at the player's level, comparing it to the Conjurer-Type Enemy List, and pulling out the appropriate mob.
So in that sense, there is a cap on the leveling, since once you level past a certain point, the game will always pull from the highest box (i.e., Master Conjurerers everywhere).
However, this is different for different lists, with Dragons, notably, maxing out at level 78 (when Legendary Dragons begin to appear).
But that said, if you're already approaching level 81, I think it's likely you've hit the cap on most of these, and they will get no stronger.
While I haven't been able to verify for sure, I think there might be a few quest mobs (non-radiant) that have strict level-based scaling, but these would only be a minor fraction of any fights you might get into -- the exception, not the rule.
You should be able to consider the scaling to have stopped around level 50 for most things, though.


text:
Q: Install code from Github with setup.py file I am trying to use the OpenDutchWordnet from https://github.com/stephantul/OpenDutchWordnet.
I have cloned the directory to my machine and think that I should now execute the setup.py file.
In the Anaconda Prompt (from the directory in which setup.py is located) I ran both:
python setup.py
and
python3 setup.py
However, both return:

What do I need to do set up the code properly?

A: Installing Packages With setup.py
$ python setup.py install

or
$ setup.py install

You can find more information about installing packages in Python
resources

References:

*

*Installing Python Modules


text:
Q: Firebase CLI: database:set keeps complaining about 'Path must begin with /' According to the CLI docs and its own help command, I just need to pass it the path (which I assume is the path on the project), my json file, and any options. So this is what I do (while I'm in the folder containing the json data):
firebase database:set --project MyProject / myJsonData.json
where I want / to be the root of my project, I want to wipe out existing data and replace it with the data in myJsonData.json. However whenever I run this, even with changing parameter order, or putting the / in quotes, it tells me Error: Path must begin with /. The path is /, so I don't know what it's complaining about. There's no examples of this command in use, so I don't know what it's expecting...

A: Turns out the answer is to put // as the path. Now I get an Unexpected error while setting data, but that's another issue.


text:
Q: AWS SDK generates wrong presigned url for reading an object I am using S3 to store videos.
And now, I am using presigned urls to restrict access to them.
I am using these functions to generate the presigned url:
var getVideoReadSignedUrl = async function (url) {
  const key = awsS3Helpers.parseVideoKeyFromVideoUrl(url);
  return new Promise((resolve, reject) => {
    s3.getSignedUrl(
      "getObject",
      {
        Bucket: AWS_BUCKET_NAME,
        Key: key,
        Expires: 300,
      },
      (err, url) => {
        console.log(
          " ~ file: s3-config.js ~ line 77 ~ returnnewPromise ~ err",
          err
        );
        console.log(
          " ~ file: s3-config.js ~ line 77 ~ returnnewPromise ~ url",
          url
        );
        if (err) {
          reject(err);
        } else {
          resolve(url);
        }
      }
    );
  });
};

And this:
const parseVideoKeyFromVideoUrl = (object_url) => {
  const string_to_remove =
    "https://" + AWS_BUCKET_NAME + ".s3." + REGION + ".amazonaws.com/";
  const object_key = object_url.replace(string_to_remove, "");
  return object_key;
};

This is an example of a video url:

https://BUCKET_NAME.s3.REGION.amazonaws.com/videos%2F60e589xxxxxxxxx463c.mp4

So I call getVideoReadSignedUrl to get the signed url to give access to it:
getVideoReadSignedUrl(
  "https://BUCKET_NAME.s3.REGION.amazonaws.com/videos%2F60e589xxxxxxxxx463c.mp4"
);

parseVideoKeyFromVideoUrl correctly parses the key from the url:
videos%2F60e589xxxxxxxxx463c.mp4

BUT, this is what getVideoReadSignedUrl generates:

https://BUCKET_NAME.s3.REGION.amazonaws.com/videos%252F60e589xxxxxxxxx463c.mp4?X-Amz-Algorithm=AWS4-xxx-xxxxx&X-Amz-Credential=AKIARxxxxxMVEWKUW%2F20221120%2Feu-xxxx-3%2Fs3%2Faws4_request&X-Amz-Date=20221120xxxx19Z&X-Amz-Expires=300&X-Amz-Signature=0203efcfaxxxxxxc53815746f75a357ff9d53fe581491d&X-Amz-SignedHeaders=host

When I open that url in the browser it tells me that the key does not exist:
NoSuchKey
<Message>The specified key does not exist.</Message>
<Key>videos%2F60e589xxxxxxxxx463c.mp4</Key>

Even though in the error message the key is the same as in the original url.
But, I noticed a slight difference in the key between the original url and the presigned url:
Key in original url:

videos% |2F60| e589xxxxxxxxx463c.mp4

Key in signed url:

videos% |252F60| e589xxxxxxxxx463c.mp4

Not sure if this is causing the issue.

NOTE:
For the upload, I am using multipart upload and the reason the video url is structured like that is because of file_name here:
const completeMultiPartUpload = async (user_id, parts, upload_id) => {
  let file_name;
  file_name = `videos/${user_id}.mp4`;
  let params = {
    Bucket: AWS_BUCKET_NAME,
    Key: file_name,
    MultipartUpload: {
      Parts: parts,
    },
    UploadId: upload_id,
  };

  return data;
};

However, it should be stored like this:

/videos/e589xxxxxxxxx463c.mp4

and not like this:

/videos%2F60e589xxxxxxxxx463c.mp4

I am not sure why it replaces / with %2F60 and this may be what's causing the whole issue.

After more investigation, I found that completeMultiPartUpload returns this:
{
          Location:
            "https://BUCKET_NAME.s3.REGION.amazonaws.com/videos%2Fxxxxxxxxxxxxxxxxx.mp4",
          Bucket: "lodeep-storage-3",
          Key: "videos/xxxxxxxxxxxxxxxxx.mp4",
          ETag: '"ee6xxxxxxxxxxxxf11-1"',
        }

And so the actualy object key is saved like this in S3:
"videos/xxxxxxxxxxxxxxxxx.mp4"

And this is the object url if I get it from AWS console:

https://BUCKET_NAME.s3.REGION.amazonaws.com/videos/xxxxxxxxxxxxxxxxx.mp4

But, in the database, this url gets saved like this since it's what completeMultiPartUpload function finally returns:

https://BUCKET_NAME.s3.REGION.amazonaws.com/videos%2Fxxxxxxxxxxxxxxxxx.mp4

Notice how / is replaced with %2F.
So, when I am generating the signed url to read the video, the function that parses the key from the url parseVideoKeyFromVideoUrl, instead of getting the correct url in the S3:

https://BUCKET_NAME.s3.REGION.amazonaws.com/videos/xxxxxxxxxxxxxxxxx.mp4
It gets the one stored in the database:
https://BUCKET_NAME.s3.REGION.amazonaws.com/videos%2Fxxxxxxxxxxxxxxxxx.mp4

And so instead of returning this as a key:

/videos/xxxxxxxxxxxxxxxxx.mp4

It returns this:

/videos%2Fxxxxxxxxxxxxxxxxx.mp4

Which is an incorrect key. And so the signed url to read the video is incorrect. And I get this key doesn't exist error.


text:
Q: How can I force the compiler-generated copy constructor of a class to *not* be inlined by the compiler? Alternate question title would be:
How to explicitly have the compiler generate code for the compiler-generated constructors in a specific translation unit?
The problem we face is that for one code path the resulting -- thoroughly measured -- performance is better (by about 5%) if the copy-ctor calls of one object are not inlined, that is if this constructor is implemented manually. (We noticed this because during code-cleanup the superfluous explicitly implemented copy ctor of this class (17 members) was removed.)
Edit: Note that we have checked the generated assembly code and have made sure that the inlining and code generation is happening as I describe for the two different code versions.
We face now the choice of just dropping the manual copy-ctor code back in (it does exactly the same as the compiler generated one) or finding any other means of not inlining the copy ctor of this class.
Is there any means (for Microsoft Visual C++) to explicitly instantiate the compiler generated class functions in a specific translation unit or will  they always be inlined in each translation unit where they are used? (Comments for gcc or other compilers are also welcome to get a better picture of the situation.)

Since the first 2 answers show some misunderstanding: The compiler generated class functions are only generated by the compiler itself if they are neither declared nor defined by the user. Therefore no modifiers whatsoever can be applied to them, since these function do not exist in the sourcecode.
struct A {
  std::string member;
};

A has a default and copy ctor, a dtor and a copy operator. Neither of these function can be modified via some declspec because they do not exist in the code.
struct B {
  std::string member;
  B(B const& rhs);
};

B now has a user supplied copy ctor and the user has to implement it. The compiler will not generate code for it.

Some more background for the doubters :-) ...
This code is compiled using MS Visual C++, but it is linked for an embedded(-like) (realtime) system. Performance was measured by taking timings on this system and I therefore think the guys who took the timings will have some decent numbers.
The test was performed by comparing two code versions where the only difference was the inline vs. the not-inline copy ctor of this one class. Timings with the inlined code were worse by about 5%.

Further checking has revealed that I was mistaken in one point: The compiler will generate separate functions for complex copy constructors. It will do this on its own discretion and it also depends on the optimization settings. So in our case the compiler is doing the wrong thing in our specific circumstances. From the answers so far it does not appear we can tell the compiler otherwise. :-(

A:
$12.1/5- "An implicitly-declared
  default constructor is an inline
  public member of its class.".

So there is nothing much we can do. The implcit constructor has to be an inline. Any other behavior in this regards would probably be an extension
Having said that,
It is likely that your manual copy constructor (which you removed during code cleanup) was doing the right thing. As an example, if one of the members (out of 17) in your class is a pointer member, it is likely that the manual copy constructor took care of deep copy(and hence took a performance hit).
So, unless you carefully review your manual copy constructor, don't even think of removing it and relying on the (potentially buggy) implicit copy constructor (in your context)

A: I highly doubt inlining has anything to do with it. If the compiler inlines the compiler-generated copy ctor, why wouldn't it also inline the explicitly defined one? (It is also unusual that the compiler's optimization heuristics fail so badly as to make inlined code 5% slower)
Before jumping to conclusions,

*

*check the generated assembly to verify that the two versions actually do the exact same thing (and in the same order, using the same assembly and so on, since otherwise that might be the source of your performance difference)

*check that the compiler-generated one actually is being inlined, and the manually defined one is not.

If that is the case, could you update your question with this information?
There is no way in C++ to indicate if a compiler-generated function should or shouldn't be inlined. Not even vendor-specific extensions such as __declspec(noinline) will help you there, since you're explicitly handing over all responsibility for the function to the compiler. So the compiler chooses what to do with it, how to implement it and whether or not to inline it. You can't both say "please implement this function for me", and at the same time "please let me control how the function is implemented". If you want control over the function, you have to implement it. ;)
In C++0x, it may be possible (depending on how these vendor-specific extensions interact with functions declared as = default).
But again, I'm not convinced that inlining is the issue. Most likely, the two functions just result in different assembly code being generated.

A: __declspec(noinline).
The documentation says that it applies only to member functions, but in fact it works with free functions as well.

A: it's often best to isolate it to a few core types which you know are problematic. example a:
class t_std_string {
    std::string d_string;
public:
    /* ... */

    /* defined explicitly, and out of line -- you know what to do here */
    t_std_string();
    t_std_string(const std::string& other);
    t_std_string(const t_std_string& other);
    ~t_std_string();

    inline std::string& get() { return this->d_string; }
    inline const std::string& get() const { return this->d_string; }
    /* ... */
};

struct B {
    t_std_string member;
    /* 16 more */
    /* ... */
};

or you can take some of it for free. example b:
/* B.hpp */

struct B {
private:

    /* class types */
    struct t_data {
        std::string member;

        /* 16 more ... */
    public:
        /* declare + implement the ctor B needs */

        /* since it is otherwise inaccessible, it will only hurt build times to make default ctor/dtor implicit (or by implementing them in the header, of course), so define these explicitly in the cpp file */
        t_data();
        ~t_data();

        /* allow implicit copy ctor and assign -- this could hurt your build times, however. it depends on the complexity/visibility of the implementation of the data and the number of TUs in which this interface is visible. since only one object needs this... it's wasteful in large systems */
    };
private:

    /* class data */
    t_data d_data;
public:
    /* you'll often want the next 4 out of line
       -- it depends on how this is created/copied/destroyed in the wild
     */
    B();
    B(const B& other);
    ~B();
    B& operator=(const B&);
};

/* B.cpp */

/* assuming these have been implemented properly for t_data */
B::B() : d_data() {
}

B::B(const B& other) : d_data(other) {
}

B::~B() {
}

B& B::operator=(const B&) {
    /* assuming the default behaviour is correct...*/
    this->d_data = other.d_data;
    return *this;
}
/* continue to B::t_data definitions */

A: You could use some sort of nested object. In this way the nested object's copy constructor can be left as the maintenance-free default, but you still have an explicitly created copy constructor that you can declare noinline.
class some_object_wrapper {
    original_object obj;
    __declspec(noinline) some_object_wrapper(const some_object_wrapper& ref)
        : obj(ref) {}
    // Other function accesses and such here
};

If you're desperate, you could compile the class in question separately in a .lib and link to it. Changing it to a different translation unit will not stop VC++ from inlining it. Also, I have to question as to whether they're actually doing the same thing. Why did you implement a manual copy constructor if it does the same as the default copy constructor?

A: To add my own conclusion and to answer the exact question without going into details:

*

*You cannot force the compiler, specifically VC++, to inline or not inline a compiler-generated ctor/dtor/etc. -- but

*The optimizer will choose - on its discretion - if it inlines the code for a compiler generated function (ctor) or if it generates a "real" function for this code. AFAIK there is no way to influence the decision of the optimizer in this regard.


text:
Q: How to publish SharePoint Framework application to the Marketplace? I have created SharePoint Framework application. I need to publish that application to the SharePoint Marketplace.
I have refereed below link for the same,
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/publish-to-marketplace-checklist
Can anyone share me the steps or share the demo application which published into the Marketplace?
Thanks in Advance


text:
Q: SonarQube MSBuild version warning I am running a C# build within teamcity which includes a step to analyze my code with Sonar.
However, I always get the warning within the sonar build logs.
INFO  - SonarAnalyzer.Scanner needs to be executed: true
        ***********************************************************************************
WARN  - *                 Use MSBuild 14 to get the best analysis results                 *
WARN  - * The use of MSBuild 12 or the sonar-scanner to analyze C# projects is DEPRECATED *
WARN  - ***********************************************************************************

Now i know that the project does not use MSBuild 12, and the first line in the snippet suggests that the issue is because sonar-scanner is been used.
How do I avoid the use of sonar scanner, and use MSBuild 14?
The following are the versions of my software:
Teamcity version 10.0.4
SonarQube version 6.2
Sonar C# plugin version 5.5.2.537
sonar-plugin for teamcity compiled from source as of 4th Jan 2017

Does the TeamCity Sonar plugin only use sonar-scanner or is it something else i can change?

A: The SonarQube TeamCity plugin is a community one, which seem to use the SonarScanner directly. This is not ideal, because .NET projects can have complex build setups and the SonarScanner in itself is not able to process the various msbuild targets. .NET projects should be analyzed by the SonarQube Scanner for MsBuild, which delegates the project structure processing to MsBuild itself.
We don't have native integration with TeamCity, but that shouldn't stop you from using the Scanner for MsBuild. It's a simple command line application, so you can call the begin and end steps in a TeamCity Command Line build step.
BTW, you see the msbuild12 warning, because the SonarScanner only runs a file by file analysis contrary to the Scanner for MsBuild, which uses whichever msbuild you specify. In case of MsBuild14 you benefit from all the goodies of Roslyn, and in case of MsBuild12 we fall back to the file by file analysis.


text:
Q: Fullscreen mode for ActiveX control I tried to implement a switch-to-fullscreen mode for an ActiveX control. This currently works by removing and hiding the parent window and changing my control's placement and position.
However, I have a problem with switching between applications while the control is in fullscreen mode. If I switch to another application and then click on my window area (not in the taskbar), it seems to not be activated. You can see in the taskbar, that another application still has the highlight and on the main screen, my window is partly hidden behind the taskbar unless it has the focus.
I process the WM_LBUTTONDOWN window message to detect if my window is clicked. And I already tried to call the following WINAPI functions:
::ShowWindow(m_hWnd, SW_RESTORE);
::SwitchToThisWindow(m_hWnd, FALSE);
::SetForegroundWindow(m_hWnd);
::SetActiveWindow(m_hWnd);
::SetFocus(m_hWnd);
::BringWindowToTop(m_hWnd);
::SetWindowPos(m_hWnd, HWND_TOP, m_monitorInfo.rcMonitor.left, m_monitorInfo.rcMonitor.top, m_monitorInfo.rcMonitor.right, m_monitorInfo.rcMonitor.bottom, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW); // SWP_NOACTIVATE, SWP_NOOWNERZORDER

I also tried to use ::SetWindowLongW(m_hWnd, GWL_STYLE, WS_VISIBLE); which surprisingly gave my window the focus back. But it then suddenly disappeared when trying to switch back from fullscreen mode again.
I have no idea why there are so many different functions that for me seem all to do roughly the same. But it doesn't matter as none of them worked anyway.
What is the/one correct way to behave my control correctly?

A: Windows might be getting a bit confused because you're filling the screen with a child window, but you want it to behave like a top-level (overlapped) window.  The host application is probably not getting activated because you've hidden its window.
You might do better to create a new top-level full-screen window for full-screen mode.  If this is owned by the top-level window that (ultimately) hosts your control then your new window will always be above it, so you don't need to hide the existing window.  Activation should just work.  In short, you want your window to behave like a pop-up modal dialog.
Adobe's flash player seems to do something similar.  Full-screen playback is in a window of class ShockwaveFlashFullScreen.


text:
Q: Postgres insert adds empty values as ' ' - how to show blank instead I'm assigning a value from a flask-WTForms form to insert into postgres.I'm using this code to assign value's to the fields
fabric_spool_number = form.fabric_spool_number.data

I'm then running a standard insert command to insert the data into a postgres table. However, when I view the table in pgAdmin, if a field was left blank, rather than showing an empty field, it shows a double apostrophe  instead i.e. '' .
EDIT:
This is the insert command:
def insert(form):
        cur.execute("INSERT INTO radio_archive_index_gui.radio_archive_index_gui_out (rai_number, carrier_format, physical_location, brand_title, recording_artist, producer, session, tx_date, network, programme_sub_category, programme_number, start_time_1, end_time_1, start_time_2, end_time_2, duration, part_number, number_of_parts, disc_number, number_of_discs, additional_info, notes, fabric_spool_number, username, edited_timestamp) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                (form.rai_number.data, form.carrier_format.data, form.physical_location.data, form.brand_title.data, form.recording_artist.data, form.producer.data, form.session.data, form.tx_date.data, form.network.data, form.programme_sub_category.data, form.programme_number.data, form.start_time_1.data, form.end_time_1.data, form.start_time_2.data, form.end_time_2.data, form.duration.data, form.part_number.data, form.number_of_parts.data, form.disc_number.data, form.number_of_discs.data, form.additional_info.data, form.notes.data, form.fabric_spool_number.data, form.username.data, dt))
        con.commit()

Here is the views form- just to say i've tried replacing the apostrophes in the request.args.get commands with blank spaces and None and this doesn't resolve the issue:
@app.route('/results', methods=['GET', 'POST'])
def results():
        form=SendForm()
        ranumber = request.args.get('ranumber', '')
        rai_number = request.args.get('rai_number', '')
        brand_title = request.args.get('brand_title', "")
        carrier_format = request.args.get('carrier_format', '')
        recording_artist = request.args.get('recording_artist', '')
        producer = request.args.get('producer', '')
        session = request.args.get('session', '')
        tx_date = request.args.get('tx_date', '')
        network = request.args.get('network', '')
        programme_number = request.args.get('programme_number', '')
        start_time_1 = request.args.get('start_time_1', '')
        end_time_1 = request.args.get('end_time_1', '')
        start_time_2 = request.args.get('start_time_2', '')
        end_time_2 = request.args.get('end_time_2', '')
        duration = request.args.get('duration', '')
        part_number = request.args.get('part_number', '')
        number_of_parts = request.args.get('number_of_parts', '')
        disc_number = request.args.get('disc_number', '')
        number_of_discs = request.args.get('number_of_discs', '')
        additional_info = request.args.get('additional_info', '')
        notes = StringField = request.args.get('notes', '')
        fabric_spool_number = form.fabric_spool_number.data
        username = request.args.get('username', '')
        if request.method == 'POST':
                if form.validate_on_submit():
                        try:
                                models.insert(form)
                        except:
                                print ("hasn't worked")
                        else:
                                return redirect(url_for('success'))
                else:
                        number_of_discs = form.number_of_discs.data
                        number_of_parts = form.number_of_parts.data
                        disc_number = form.disc_number.data

        return render_template(
        'results.html', title='Results', ranumber=ranumber, rai_number=rai_number,brand_title=brand_title,carrier_format=carrier_format,recording_artist=recording_artist,producer=producer,session=session,tx_date=tx_date,network=network,programme_number=programme_number,start_time_1=start_time_1,end_time_1=end_time_1,start_time_2=start_time_2,end_time_2=end_time_2,duration=duration,part_number=part_number,number_of_parts=number_of_parts,disc_number=disc_number,number_of_discs=number_of_discs,additional_info=additional_info,notes=notes,fabric_spool_number=fabric_spool_number,username=username,form=form

)

Is this normal behavior? If not, what could be causing it?
Thanks


text:
Q: Em Python, verificar se o conteúdo de uma coluna está presente em outra coluna? estou no Jupyter Notebook trabalhando com Python.
Meu dataframe atual está com o seguinte formato - data.columns['nome', 'nome_arquivo', 'texto'].

Todoas as colunas são do tipo string, desejo, pegar a coluna 'nome' e verificar se todo o conteúdo dela é encontrado exatamente em alguma parte na string da coluna 'texto'. Desejo ter como resultado todos os registros verificados se encontrou ou não, conforme figura abaixo.

Posteriormente desejo ter este resultado exportado para csv.

A: Não tenho sua base então criei uma própria. Veja abaixo:
>>> import pandas as pd

>>> df = pd.DataFrame({"nome": ["teste 1", "teste 2", "teste 3"], "nome_arquivo": ["um arquivo", "dois arquivos", "tres adivinha"], "texto": ["Aqui vc encontra um arquivo", "Aqui nao tem o texto", "tres adivinha está aqui"]})

>>> df
      nome   nome_arquivo                        texto
0  teste 1     um arquivo  Aqui vc encontra um arquivo
1  teste 2  dois arquivos         Aqui nao tem o texto
2  teste 3  tres adivinha      tres adivinha está aqui

>>> df["encontrado"] = df.apply(lambda x: x.nome_arquivo in x.texto, axis=1)

>>> df
      nome   nome_arquivo                        texto  encontrado
0  teste 1     um arquivo  Aqui vc encontra um arquivo        True
1  teste 2  dois arquivos         Aqui nao tem o texto       False
2  teste 3  tres adivinha      tres adivinha está aqui        True

Espero que ajude


text:
Q: Are there any internal MySQL protocol other than SQL queries in text? I was wondering what happens after MySQL received SQL texts? Hows does it process them across differents nodes?
Is it possible to create a driver which use binary MySQL protocols, rather than plain text SQL queries?
For example, direct access to tables data before JOIN or any other transformations.
Just a bit curious, not real-world problem.

A: now MySQL 5.6 has memcached protocol, you can write data in memcached protocol, and analye them in SQL. It's kinda cool.
http://dev.mysql.com/doc/refman/5.6/en/news-5-6-6.html


text:
Q: Elasticbeanstalk - Static IP Address with new VPC I want to create new Elasticbeanstalk environment with static IP Address.
For this, I've created new VPC firstly. And it has 2 subnets. One of them is public, the other one is private.
I've created new Nat Gateway, and I've define it to private subnet.
And I've created new EBS, with more option. And define it to this VPC with both Private&Public subnets.
So, I can not reach to the environment (because I guess, my definitions are wrong)
what should I do step-by-step for this operation?
Whats wrong with my process.


text:
Q: Google chrome color patches around transparent images. I am using Ubuntu 18.04 LTS version. The PNG images are not displaying correctly in my Google Chrome Version 68.0.3440.84 (Official Build) (64-bit).
See the facebook icons

Google Logo

A: solution:
in chrome://flags/ find Force color profile and set on sRGB


text:
Q: How to pass query parameters to a Facebook Page tab app is it possible to add ?variable=value to the end of a facebook application url ?
for example:
facebook.com/pagename/app_abcdefghij/phppage.php?variable=value
then use a _Get to query a mysql database ?

A: To pass data to a page tab app, use the app_data parameter.
The value you supply for this will be present in the signed_request which is POSTed to your app. Other parameters are not passed.
There's more information about this in the page tab documentation under the header Integrating with Facebook APIs


text:
Q: How do I change tkinter default title in OS bar? I am writing a python app using Tkinter and I cannot find a way to change the default title Tk in OS top bar (Gnome top bar and dock too).
I can set the main window title but it does not change the string in the top bar where it stays Tk. Honestly I am surprised I cannot find anyone asking this same question.
I am developing on Ubuntu 18.04 using Python 3.6
This is a sample code to replicate the problem:
import tkinter as tk

if __name__ == "__main__":
    mainWindow = tk.Tk()
    mainWindow.title("TEST")
    mainWindow.geometry("1024x600")
    mainWindow.mainloop()

I would expect to read the string TEST in the main window frame title, in the OS top bar and in the OS application dock, but I get it only in the windows frame title. The rest display Tk

A: Use className
mainWindow = tk.Tk(className='Ghanshyam')

According to python Docs on tkinter:

The Tk class is instantiated without arguments. This creates a toplevel widget of Tk which usually is the main window of an application. Each instance has its own associated Tcl interpreter.

A: The top bar title in Ubuntu is not set by the application running, it is set by the desktop entry for the app. I'm not sure why it works the way it does when there is no desktop entry present, but you can create a file like this and import it into Ubuntu for it to work properly.
[Desktop Entry]
Type=Application
Terminal=false
Icon=/path/to/icon/icon.png
Name=TITLE (this is what handles the top bar title)
Exec=/path/to/file/executable
Categories=Utility;

See this question on AskUbuntu.


text:
Q: How can I center a div inside a div within a container? I'm using the Materialize CSS front end framework and using margin: 0 auto; as I always have, and having a nightmare getting this div centered within its parent. What gives?

.outer {
  border: 1px solid red;
  height:100px;
}

.inner{
  border: 1px solid black;
  height:50px;
  margin: 0px auto;
}

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">

http://codepen.io/kinsdotnet/pen/mEYJVg

A: Materialise uses a grid system that floats elements. You can't use margin: auto on a floated element.
You'll need to either use offset classes form the grid, or  rearrange the grid and that child element...
(http://codepen.io/jmsherry/pen/OXYVRL <-- like that)
Also, don't listen to the really bad advice of !important and Absolute positioning. There are better ways to do this...

A: Absolute inside Relative
Set the position of the outer div to relative, the inner to absolute.
To make margin: 0px auto work, add left: 0; right:0;
Also you must specify width to the inner div.
if you want to center vertically,
just replace:
margin: 0px auto

with:
margin: auto

Result:

.outer {
  border: 1px solid red;
  height:100px;
  position:relative;
}

.inner{
  border: 1px solid black;
  height:50px;
  margin: 0px auto;

  width:100px;
  position:absolute;
  left:0;
  right:0;
}

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">

A: Try adding this to your inner class:
float:none !important;

it looks like the class col applies a float left, and that's why it doesn't center


text:
Q: JavaScript scope, break for cycle from function callback I need to break cycle if proccess = true, but it's undefined.
        var mapFound;
        var locations = {$addressTest};
        for (var i = 0; i < locations.length; ++i) {
            getCoordinates(
                    locations[i],
                    function(proccess) {
                    }
            )
            if(proccess) { break; }
        }

A: The problem seems to be basically that getCoordinates() makes an asynchronous call.
By the time the loop is over you haven't received even the first response, based on your question text, so you need to use another solution.
I mean by this that you won't be able to break the cycle, because by the time the cycle is over you still don't know if process is true.
Depending on your implementation you might want to take a look at promises. Although it might be easier to wrap the whole thing in a function that executes a callback:
function getCoords(locations, name, callback){
    for (var i = 0; i < locations.length; i++) {
        getCoordinates( locations[i], name,
            function(proccess) {
                if(process){
                    console.log("Map found in "+locations[i]);
                    callback.call();
                }
            }
        );
    }
}

getCoords({$addressTest}, {$name}, function(){
    // Place here whatever you want to do once the map is found.
    // you can get the map location by passing it as an argument for the callback.
});


text:
Q: will look out over a capital city Does "will look out over a capital city" mean "will keep watch on a capital city"?  The prepositional word "over" has given me a hard time to figure out what it means. Because a phrase like "look over one's shoulders" is very different in meaning with "look on one's shoulders."

Stay home, Americans were exhorted, to prevent further spread of a surging virus that has claimed 400,000 American lives. Biden will look out over a capital city dotted with empty storefronts that attest to the pandemic's deep economic toll and where summer protests laid bare the nation's renewed reckoning on racial justice.

Source:  The Associated Press

A: Look out over means 'look from a high viewpoint at [the scene below]'. The writer envisages Mr Biden standing at a White House upper window looking out over Washington. (I've never been to Washington, but I imagine he would not literally be able to see details of the streets from there.)


text:
Q: SCOM 2019 not generating and not sending any e-mail notifications New SCOM 2019 Installation. Notifications (channel, subscription and subscribers) has been configured to send all alerts via email. Alerts are visible in SCOM "Active Alerts" window every day, but no notification has been sent via email.
Port TCP 25 to SMTP mail server is open. Server has been configured to accept anonymous traffic from SCOM Server. Connecting and sending a test message by using Telnet from SCOM 2019 Management Server works well - email has been delivered. Management Server is a part of Notification Resource Pool (dynamic). Wireshark monitoring on TCP 25 shows that SCOM 2019 generates no notification at all. Looks like a serious bug in SCOM 2019 on Win Srv 2019 Datacenter. Maybe similar to SCOM 2012 R2 (when enabling SNMP service on OS level disabled email notifications). I tried to disable SNMP Trap service or enable it but it hasn't change anything. No email notifications has been sent. Wireshark shows that SCOM 2019 has not generated any email. Maybe something is broken in SCOM 2019, email notifications needs to be enabled somewhere (in SCOM Console or from PowerShell) or some OS service needs to be enabled or disabled as email notifications depends on it ?
No errors in Event Logs. Wireshark monitoring shows no activity on TCP 25 on SCOM 2019 Management Server.
Any ideas are more than welcome.

A: A solution has been found:
Looks like there may be some bug with "Windows Cluster Management Library" Management Pack (Target: Windows Cluster Service, Cluster Service Discovery)
It was not able to properly discover our cluster based on Windows Server 2012R2 and due to this fact SCOM 2019 entered a rows containing NULLs into OperationsManager.dbo.MT_HealthService table. In the Health Explorer for Management Configuration Service Group we've found out that "Delta Syncronization Proces" failed with XML form notification -> Specified Cast is not valid.
To solve the issue we've deleted such rows manually and disable/override Object Discovery for a specific object of class: Windows CLuster Service (selecting both cluster nodes).
In a few seconds email notifications started instantly
Next step is to create a ticket to Microsoft to troubleshoot that "Windows Cluster Management Library" Management Pack.


text:
Q: Return top 'X' records within multiple groups in one query I have a list of records across multiple months i.e. September, October, November etc. and I need to return the top 10 results by count for each month within the same query. I have the below so far:
SELECT [Financial Year] & "Resolved" & [Text Month] & [SegmentDescriptionST] AS [Key], "FY" & IIf(Month([MinOfResolvedDate])<10,Year([MinOfResolvedDate]),Year([MinOfResolvedDate])+1) AS [Financial Year], "Resolved" AS Metric, Format([MinOfResolvedDate],"mmm-yy") AS [Resolved Month], Format([MinOfResolvedDate],"mmm") AS [Text Month], Content_Accuracy_q.SegmentDescriptionST, Count(Content_Accuracy_q.SegmentDescriptionST) AS Amount

FROM Content_Accuracy_q

WHERE (((([Content_Accuracy_q].[MinOfResolvedDate]) Between #9/1/2018# And (DateSerial(Year(Date()),Month(Date()),0))) In
    (SELECT TOP 10 Content_Accuracy_q.SegmentDescriptionST

    FROM Content_Accuracy_q

    Where ((Content_Accuracy_q.[Level 3 - Issue ST])="Inaccurate Information" Or (Content_Accuracy_q.[Level 3 - Issue ST])="Change of accommodation") AND ((Content_Accuracy_q.[Level 4 - Reason ST])<>"Cost"))))
    GROUP BY "FY" & IIf(Month([MinOfResolvedDate])<10,Year([MinOfResolvedDate]),Year([MinOfResolvedDate])+1), "Resolved", Format([MinOfResolvedDate],"mmm-yy"), Format([MinOfResolvedDate],"mmm"), Content_Accuracy_q.SegmentDescriptionST

    HAVING (((Content_Accuracy_q.SegmentDescriptionST)<>""))

    ORDER BY Format([MinOfResolvedDate],"mmm-yy") DESC , Count(Content_Accuracy_q.SegmentDescriptionST) DESC)

ORDER BY Format([MinOfResolvedDate],"mmm-yy") DESC , Count(Content_Accuracy_q.SegmentDescriptionST) DESC;

However, I continuously get the 'Syntax error in ORDER BY clause' and can't get past this point. Has anyone been able to successfully run a query similar to this and return the top 'X' results by count within the months needed?

A: On formatting your SQL with indentation, there are a few oddities in your code:
SELECT
    [Financial Year] & "Resolved" & [Text Month] & [SegmentDescriptionST] AS [Key],
    "FY" & IIf(Month([MinOfResolvedDate])<10,Year([MinOfResolvedDate]),Year([MinOfResolvedDate])+1) AS [Financial Year],
    "Resolved" AS Metric,
    Format([MinOfResolvedDate],"mmm-yy") AS [Resolved Month],
    Format([MinOfResolvedDate],"mmm") AS [Text Month],
    Content_Accuracy_q.SegmentDescriptionST,
    Count(Content_Accuracy_q.SegmentDescriptionST) AS Amount
FROM
    Content_Accuracy_q
WHERE
    (
        (
            (
                [Content_Accuracy_q].[MinOfResolvedDate] BETWEEN #9/1/2018# AND DateSerial(Year(Date()),Month(Date()),0)
            )
            IN
            (
                SELECT TOP 10 Content_Accuracy_q.SegmentDescriptionST
                FROM Content_Accuracy_q
                WHERE
                (
                    Content_Accuracy_q.[Level 3 - Issue ST] = "Inaccurate Information" OR
                    Content_Accuracy_q.[Level 3 - Issue ST] = "Change of accommodation"
                )
                AND
                Content_Accuracy_q.[Level 4 - Reason ST] <> "Cost"
            )
        )
    )
GROUP BY
    "FY" & IIf(Month([MinOfResolvedDate])<10,Year([MinOfResolvedDate]),Year([MinOfResolvedDate])+1),
    "Resolved",
    Format([MinOfResolvedDate],"mmm-yy"),
    Format([MinOfResolvedDate],"mmm"),
    Content_Accuracy_q.SegmentDescriptionST
HAVING
    Content_Accuracy_q.SegmentDescriptionST <> ""
ORDER BY
    Format([MinOfResolvedDate],"mmm-yy") DESC,
    Count(Content_Accuracy_q.SegmentDescriptionST) DESC)
ORDER BY
    Format([MinOfResolvedDate],"mmm-yy") DESC,
    Count(Content_Accuracy_q.SegmentDescriptionST) DESC;

First, the obvious error is that you have an unbalanced parenthesis in your first order by clause:
ORDER BY
    Format([MinOfResolvedDate],"mmm-yy") DESC,
    Count(Content_Accuracy_q.SegmentDescriptionST) DESC)
                                                       ^------- here

But then you also have two order by clauses, which is invalid syntax:
ORDER BY
    Format([MinOfResolvedDate],"mmm-yy") DESC,
    Count(Content_Accuracy_q.SegmentDescriptionST) DESC)
ORDER BY
    Format([MinOfResolvedDate],"mmm-yy") DESC,
    Count(Content_Accuracy_q.SegmentDescriptionST) DESC;

The having clause also seems redundant, as the criteria is not referencing a field which is the result of the aggregation:
HAVING
    Content_Accuracy_q.SegmentDescriptionST <> ""

As such, this criteria could instead be included as part of the where clause:
FROM
    Content_Accuracy_q
WHERE
    Content_Accuracy_q.SegmentDescriptionST <> "" AND

However, looking at your where clause, this statement doesn't make sense to me:
(
    [Content_Accuracy_q].[MinOfResolvedDate] BETWEEN #9/1/2018# AND DateSerial(Year(Date()),Month(Date()),0)
)
IN
(
    SELECT TOP 10 Content_Accuracy_q.SegmentDescriptionST
    FROM Content_Accuracy_q
    WHERE
    (
        Content_Accuracy_q.[Level 3 - Issue ST] = "Inaccurate Information" OR
        Content_Accuracy_q.[Level 3 - Issue ST] = "Change of accommodation"
    )
    AND
    Content_Accuracy_q.[Level 4 - Reason ST] <> "Cost"
)

Here, the code is saying:
"Select records where the result of [Content_Accuracy_q].[MinOfResolvedDate] BETWEEN #9/1/2018# AND DateSerial(Year(Date()),Month(Date()),0) is one of the results returned by SELECT TOP 10 Content_Accuracy_q.SegmentDescriptionST ..."
But the expression:
[Content_Accuracy_q].[MinOfResolvedDate] BETWEEN #9/1/2018# AND DateSerial(Year(Date()),Month(Date()),0)

Will return a boolean value (i.e. True/False -1/0); and I'm guessing that it is not your intention to check whether a boolean value is a member of the results returned by the subquery.


text:
Q: Give an example of a homomorphism $f : R\to S$ such that $R$ has an identity but $S$ does not Does this contradict part 4 of theorem 3.10 (if $R$ is a ring with identity, and $f$ is surjective, then $S$ is a ring with identity $f(1_R).$
I believe I have an answer to this, $R=\mathbb Z$ and $S$ being the subset of $2\times2$ matrices of the form $\begin{pmatrix} a & 0 \\ a & 0 \end{pmatrix}$, and $f$ being the zero homomorphism. Clearly $R$ has identity and $S$ doesn't, but this doesn't contradict the theorem because the zero homomorphism is not surjective. However, what if we have the function $f(x) = \begin{pmatrix} x & 0 \\ x & 0 \end{pmatrix}$. $f$ seems to be surjective, as every element of $S$ is mapped to by some element of $R$, and also seems to contradict the theorem, since $f(1) \ne \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}$. Am I misunderstanding something?

A: The identity for your $S$ is $\left(\begin{array}{cc} 1 & 0\\ 1 & 0\end{array}\right)$.
The theorem is ok and your example is not a counter example. The mentioned thheorem says that the identity of
$R$ is mapped into identity of the image of $f$.


text:
Q: generate a number of independent splits of dataset when using sklearn split function, is it possible to produce k independent splits, namely, k splits that have at least one element not in common? If not, is there any other library that can be used?

A: Have a look at the cross_validation module.
For what you want, KFold should do the trick.


text:
Q: Validating an unknown set of items with WTForms I have a form that looks something like this:
<form method="post">
    <input id="1" name="people" type="checkbox" value="1"/>
    Paul

    <input id="2" name="people" type="checkbox" value="2"/>
    Elizabeth

    <input type="submit"/>
</form>

When submitting this form, I want to validate that the user has checked at least one person. Note that I don't want to use name"person-0" and name="person-1", I actually want to use name="people" as the name of my objects.
I'll create my form using something like this...
class MyForm(Form):
    some_field = fields.TextField(u'Some Field', [validators.required()])
    some_option = fields.BooleanField(u'Some Option')
    people = # What to put here?

So, what type of field can I use for the 'people' field?
I don't think I can use FieldList, since that will expect the names to be person-0 and person-1 rather than people, which I don't want. I can't use SelectMultipleField because that seems to expect a list of choices, and I don't know the list of choices (it is dynamically given to me by a 3rd party).
I'm only using the form for validation of the resulting HTML post data, not rendering the HTML, so no worries there.
I'm going to post what I've done as an answer, which is to use a custom field. But I was wondering if there was some way to do this in wtforms using the built-in fields.
Thanks

A: Here is what I have so far ended up doing:
I create my own field called "ListField"...
class ListField(Field):
    def process_formdata(self, valuelist):
        self.data = valuelist

Then I can use it like the following:
class MyForm(Form):
    some_field = fields.TextField(u'Some Field', [validators.required()])
    some_option = fields.BooleanField(u'Some Option')
    people = ListField()

    def validate_people(self, field):
        if len(field.data) == 0:
            raise ValidationError('Must select at least one person')

This works for now, but I'm not sure if there is a way to do this with the built-in fields and validators.


text:
Q: Serializable transaction deadlock Documentation says, serializable transactions execute one after one.
But in practic it seems not to be truth. Here's two almost equal transactions, the difference is delay for 15 seconds only.
#1:
set transaction isolation level serializable
go
begin transaction
if not exists (select * from articles where title like 'qwe')
begin
waitfor delay '00:00:15'
insert into articles (title) values ('qwe')
end
commit transaction go

#2:
set transaction isolation level serializable
go
begin transaction
if not exists (select * from articles where title like 'qwe')
begin
insert into articles (title) values ('asd')
end
commit transaction go

The second transaction has been run after couple of seconds since the start of first one.
The result is deadlock. The first transaction dies with
Transaction (Process ID 58) was deadlocked on
lock resources with another process and has been chosen as the deadlock victim.
Rerun the transaction.

reason.
The conclusion, serializable transactions are not serial?

A: I got into a similar problem and i found that:
From MSDN:
SERIALIZABLE
Specifies the following:

*

*Statements cannot read data that has been modified but not yet
committed by other transactions.

*No other transactions can modify data that has been read by the
current transaction until the current transaction completes.

*Other transactions cannot insert new rows with key values that would
fall in the range of keys read by any statements in the current
transaction until the current transaction completes.

The second point does not state that both sessions can't take the shared lock that will result in deadlock. We solved it with a hint on SELECT.
select * from articles WITH (UPDLOCK, ROWLOCK) where title like 'qwe'

Have not tried if it would work in this case but i think you would have to lock on the table part since the row is not yet created.

A: serializable transactions don't necessarily execute serially.
The promise is just that transactions can only commit if the result would be as if they had executed serially (in any order).
The locking requirements to meet this guarantee can frequently lead to deadlock where one of the transactions needs to be rolled back. You would need to code your own retry logic to resubmit the failed query.
See The Serializable Isolation Level for more about the differences between the logical description and implementation.

A: What happens here:
Because transactions 1 runs in serializable isolation level, it keeps a share lock it obtains on table articles while it wait. This way, it is guaranteed that the non exists condition remains true until the transaction terminates.
Transaction 2 gets a share lock as well that allows it to do the exist check condition. Then, with the insert statement, Transaction 2 requires to convert the share lock to a exclusive lock but has to wait as Transaction 1 holds a shared lock.
When Transaction 1 finishes to wait, it also requests a conversion to exclusive mode => deadlock situation, 1 of the transaction has to be terminated.


text:
Q: how to insert data into std::map and show data from std::map in vc6 i am using vc6. what is wrong in code below, i cant find out:
std::map<int, std::vector<int> > myTemplate;

//append data to map
int temp=0;
for (int i=0;i<=5;i++)
{
    std::vector<int> tempVector;
    temp+=111;
    tempVector.push_back(temp);
    std::pair<int, std::vector<int> > myPair;
    myPair=std::make_pair(i,tempVector);
    myTemplate.insert(myPair);
}

//show data from map
std::map<int, std::vector<int> >::iterator iter;
iter=myTemplate.begin();
while(iter!=myTemplate.end());
{
    std::vector<int> tempVector;
    std::vector<int>::iterator sencondIter=iter->second.begin();
    int myValue=*sencondIter;
    CString cstrTemp;
    cstrTemp.Format("%d is the int type value in vector<int>",myValue);
    AfxMessageBox(cstrTemp);

    iter++;
}

A: Semicolon after while results in an infinite loop
while(iter!=myTemplate.end()); // <-----------------------

Remove it.

A: I recommend you check out Microsoft Visual Studio Express here:  http://en.wikipedia.org/wiki/Microsoft_Visual_Studio_Express
For updated versions of MS Visual Studio IDEs


text:
Q: Создание и удаление динамических массивов Как правильно создать динамический массив на 100 элементов? Как удалить потом значение каждого его элемента? Как удалить весь динамический массив?

A: Если Вы не создавали каждый элемент по отдельности, то и удалять нужно все вместе. В случае с массивами это delete[] имя_массива; - парная функция к new[]
A: На мой взгляд, в C++ правильным путём является использование std::vector.
Создание массива просто:
std::vector v(100);

Удалять его не надо: vector самоудалится, когда выйдет из окружающего блока видимости. Чтобы контролировать время жизни массива, либо заведите его в нужном блоке, либо положите в какой-нибудь класс, либо положите в динамическую память — вариантов множество, описаны в книге по C++, которую вы, надеюсь, сейчас читаете.


text:
Q: Multiples of length division algorithm c++ question Problem Statement
You are given an array a of n integers.
You want to make all elements of a equal to zero by doing the following operation exactly three times:
Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different).
It can be proven that it is always possible to make all elements of a equal to zero.
Input
The first line contains one integer n (1 ≤ n ≤ 100000): the number of elements of the array.
The second line contains n elements of an array a separated by spaces: a1,a2,…,an (−10^9 ≤ ai ≤ 10^9).
Output
The output should contain six lines representing three operations.
For each operation, print two lines:
The first line contains two integers l, r (1 ≤ l ≤ r ≤ n): the bounds of the selected segment.
The second line contains r−l+1 integers bl,bl+1,…,br (−10^18 ≤ bi ≤ 10^18): the numbers to add to al,al+1,…,ar, respectively; bi should be divisible by r−l+1.
Example
input
4
1 3 2 4
output
1 1
-1
3 4
4 2
2 4
-3 -6 -6
Code Solution
#include<bits/stdc++.h>

int64_t minv(int64_t a, int64_t m) {
    assert(0 < a && a < m);
    if (a == 1) return 1;
    return m - minv(m % a, a) * m / a;
}

int main() {
    using namespace std;
    ios_base::sync_with_stdio(false), cin.tie(nullptr);

    int N; cin >> N;
    vector<int64_t> A(N);
    for (int i = 0; i < N; i++) {
        cin >> A[i];
    }

    if (N == 1) {
        cout << 1 << ' ' << 1 << '\n' << -A[0] << '\n';
        cout << 1 << ' ' << 1 << '\n' << 0 << '\n';
        cout << 1 << ' ' << 1 << '\n' << 0 << '\n';
        exit(0);
    }

    int64_t invNm1 = minv(N-1, N);
    assert(invNm1 * (N-1) % N == 1);

    vector<int64_t> op1(N);
    vector<int64_t> op2(N-1);
    for (int i = 0; i < N-1; i++) {
        op2[i] = -A[i] % N * invNm1 % N;
        assert((A[i] + (op2[i] * (N-1))) % N == 0);
        op1[i] = -(A[i] + (op2[i] * (N-1))) / N;
        assert(A[i] + (op1[i] * N) + (op2[i] * (N-1)) == 0);
    }

    cout << 1 << ' ' << N << '\n';
    for (int i = 0; i < N; i++) {
        cout << op1[i] * N << " \n"[i+1==N];
    }
    cout << 1 << ' ' << N-1 << '\n';
    for (int i = 0; i < N-1; i++) {
        cout << op2[i] * (N-1) << " \n"[i+1==N-1];
    }

    cout << N << ' ' << N << '\n';
    cout << -A[N-1] << '\n';

    return 0;
}

Question
I believe the code is using an extended euclidean algorithm for minv, and I really need help to visualize what's going on with the minv part. Also, I'm having trouble following the logic inside the for loop with the op2 and op1 equations and how the code produces the output from the input provided. Would anyone please share explanations to the code with the equations and logic here?

A: minv function finds modular multiplicative inverse. Meaning, for a given number a, its inverse modulo N is a number b which satisfies a*b % N = 1.
Extended Euclidian algorithm can be used to find such inverse.
As for:
cout << op1[i] * N << " \n"[i+1==N];

This is just index trickery with bools. "<space>\n" has a type char[2] char[3], thus indices can be used to select between a space and a newline. Bool can be used to index such array since bools are implicitly convertible to ints - true->1, false->0.


text:
Q: Can you apply one property in a class for a DIV differently for two elements? I want to have a DIV whose background color is light grey, but I want the background color for HRs to be black. I'd like to have one class for the DIV that can control both of these so I don't have to apply a separate class for each HR?

A: What you describe is not possible. However, you might be looking for this:
div hr {
  background-color: black;
}

div hr will match all hr which are descendants of div. This means you do not have to apply a class for each hr element, which is what you requested in the question.
For direct descendants only (children), use div > hr.

A: A class can't control both of them, but it's possible to not have to apply a separate class for each HR.


text:
Q: Multiplication of variables with a compass when a segment of length 1 is not given. "Suppose that length a and b are given. Construct sqrt(ab) (Not that a segment of length 1 is not given)." I know how to multiply ab together and then take the square root of ab if a length of segment 1 is given but not when it is not.

A: It seems you're familiar with constructing a length that is the product of two lengths, and with constructing a length that is the square root of another length. Those constructions are fine, but they need to refer to a given unit length to be meaningful.
The product of two lengths is more naturally represented as an area. ("Naturally" in the sense that it doesn't depend on a unit length being given. Also in that it's familiar to most people from their primary education.) Conversely, a square root is more naturally represented as obtaining a length from an area—specifically, the side length of a square with the given area.
So an alternative construction would be:

*

*Construct $ab$ as a rectangle.

*Square the rectangle.

*The side length of the square is $\sqrt{ab}$.

Here's a demonstration. The lengths $a$ and $b$ can be adjusted freely, although my construction seems to have relied on $a$ being shorter than $b$, so the square disappears if that stops being true!

A: Without a unit length, the square root of a length is undefined.[1] So let's throw our hands up in the air and say we might as well make up our own unit length. Then we can construct the lengths $\sqrt a$ and $\sqrt b$ according to this unit.
Now imagine that your teacher/professor has secretly kept the "real" unit length for this problem, and it isn't the same as ours. Theirs is 1; ours is $x$. When we show the professor the lengths we constructed, they say we "actually" constructed $\sqrt{xa}$ and $\sqrt{xb}$.[2]
But hang on… if we multiply our constructed lengths together to get (what we thought was) $\sqrt {ab}$ and show that to the professor, they'll measure it and say it's "really" $\sqrt{xa}\times\sqrt{xb}=x\sqrt{ab}$… right?
Nope! At this point we remember that, like the square root, multiplication of lengths isn't defined without a unit length either. If we multiply two lengths using unit $x$, and the professor looks at the answer using their "real" unit 1, they'd tell us our answer is too short by a factor of $x$.[3] (Or, well, too long if $x<1$.) So in this case, what we thought was going to look (to them) like $x\sqrt{ab}$ actually turns out to measure exactly $\sqrt{ab}$ using their "real" unit!
In short, the product $\sqrt{ab}$ comes out the same, no matter what arbitrary unit length we chose.
A visual demonstration.   Adjust lengths $a$, $b$, and the unit as you like. The product $ab$ and the square roots $\sqrt{a}$ and $\sqrt{b}$ vary depending on the unit, but $\sqrt{ab}$ doesn't.

[1] Consider: I have a 25 cm line, and using cm as my unit, I say its square root is 5 cm. But if you measure the same line to be 0.25 m, you'll say its square root is 0.5 m… ten times longer than the original line! (And let's not mention our American friend who insists the line is 10″…)
[2] If our unit lengths are in the ratio $1:x$, our square roots will be in the ratio $1:\sqrt x$.
[3] For example, I have my 2.5 cm line, and I multiply it by another line that's 1 cm long. Since my units are cm, I get 1 × 2.5 = 2.5 cm. But you, using mm as your unit this time, insist that it should be 10 × 25 = 250 mm (25 cm). Our units are in the ratio $10:1$, but our products are in the ratio $1:10$.

A: Note that the question does not ask you to construct a length $ab.$
It merely asks for $\sqrt{ab}.$
The expression $\sqrt{ab}$ is also known as the geometric mean of $a$ and $b.$
Usually when we say "mean" of two numbers we are talking about the arithmetic mean,
which is a number exactly halfway between the other two numbers in an arithmetic sequence: $m$ is the arithmetic mean of $a$ and $b$ if and only if there is an amount $d$ such that $m = a + d$ and $b = m + d$; that is,
$$ (a, m, b) = (a, a + d, a + 2d). $$
"Geometric mean of $a$ and $b$" is a bit different:
it describes a number that is halfway between $a$ and $b$ in a geometric sequence.
So $g$ is the geometric mean of $a$ and $b$ if and only if there is a ratio $r$ such that $g = ra$ and $b = rg$; that is,
$$ (a, g, b) = (a, ra, r^2 a). $$
Note that you don't need to have access to a unit length in order for the geometric mean of two lengths to have meaning, because the ratio of lengths of two segments is determined by those two segments alone, without reference to the length of a unit segment.
Now suppose you knew how to construct the geometric mean of $a$ and $b$
given segments of length $a$ and $b,$ without referring to any other previously given segment.
Then, given a unit length segment and a segment of length $b,$ you could use this exact same procedure to construct a segment of length $\sqrt b,$
because $\sqrt b$ is the geometric mean of $1$ and $b.$
This would work because $1, \sqrt b, b$ is a geometric sequence.
Now what you can think about is this: knowing a construction for the square root of a length, how does it work?
Does it, in fact, take whatever two input lengths you give it and find a length between the other two in geometric sequence,
so that if one of the lengths happens to be a unit length then the result will be the square root of the other length?
What if neither of the lengths you give to the construction is the unit length;
does it still construct a geometric sequence of lengths, and does it find the geometric mean of the two input lengths?


text:
Q: Should I use the unique_ptr as function return? In some usecases i want to use the unique_ptr as the function return, in order to transfer the ownership of function return to the function caller. Should i use unique_ptr as function return at all? If not, in which usecases should i use the unique_ptr as function return?
An example to explain my question detailedly:
unique_ptr<int> foo() {

  unique_ptr<int> rtn(0);

  *rtn = 10U;

  return std::move(rtn); // 1
  // return rtn; // 2
  // return rtn; // 3
}

void main() {
   unique_ptr<int> ptr = foo();// 1
   // unique_ptr<int> ptr = std::move(foo()); //2
   // unique_ptr<int> ptr = foo(); //3
}

In this example i just want to give the ownership of returned unique_ptr away from function foo() to caller. With the unique_ptr as function return, i want to tell the function caller, if you get the return value of this function, you must also take the responsibility to release it.
For this usecase should I use the unique_ptr at all? if yes, whcich variant from 1 to 3 should i use?
If not, in which usecase should I use the unique_ptr as function return?


text:
Q: Ansible - combining string with an existing variable to register into another variable I want to combine a fact set with set_facts with a string variable and register it as a new variable.
I think, we cannot register a new variable in an Ansible playbook. So can I use set_facts again to combine a previous set_fact with an existing variable?
I am not sure about the syntax here.
Here is an example:
- vars:
    list_1: usera,userb,userc

- set_fact:
    list_2: "userd,usere,userf"

Now I want to combine both of the string with comma in between and get a variable value like this:
final_list: usera,userb,userc,userd,usere,userf

A: set_fact:
  final_list: "{{ list_1 }},{{ list_2 }}"

or use the string concatenation operator
set_fact:
  final_list: "{{ list1 ~ ',' ~ list_2 }}"


text:
Q: Let A be a n x n matrix with n unique positive eigenvalues. Proof there exists a matrix B such dat $B^2 = A$ and that B is invertible. So I don't know how to proof that B exists but I managed to proof that B is invertible like this:
We know A is diagonalizable because A has n unique eigenvalues. This means det(A) must be a positve number. det(B^2) = det(A) so det(B)det(B) = det(A). Because det(A) is positive, det(B) is non-zero  and thus B is invertible.
Does this proof B exists? I think it doesn't but I have no other idea to proof a matrix exists.

A: No, your proof is not correct.
Hint: If you have a diagonal matrix
$$
A = \pmatrix{\lambda_1 \\ & \lambda_2 \\ & & \lambda_3}
$$
where $\lambda_1,\lambda_2,\lambda_3$ are positive, then show that there exists a diagonal matrix $B$ that satisfies $B^2 = A$.

Hint 2: Show that if $B = PDP^{-1}$ (where $D$ is diagonal), then $B^2 = PD^2P^{-1}$.


text:
Q: Decrease rate of the shadow
If a man of height $6ft$ moves with $5ft/sec$ velocity towards a lamp hanging at $15ft$ height, then at what rate his shadow will decrease?

My Work: Let the initial distance between the man and the lamp post be $x$ and the length of shadow be $y$.

Then, $\frac{x}{9} = \frac{y}{6} \implies y = \frac{2x}{3}$
Now how do I handle the $5ft/sec$ velocity and the decrease rate of the shadow?
I think the rest part is so easy. But I am missing somewhere.
Note: This is a problem from BdPhO 2016 but completely math related. So I posted it here.

A: Opps. I just found the answer.
In $1sec$ if he move $5ft$ then the length of shadow is
$y' = \frac{2(x-5)}{3} = \frac{2x-10}{3}$
So in one second    $$y'-y = \frac{2x}{3} - \frac{2x-10}{3} = \frac{10}{3}$$
So, the decrease rate of the shadow is $\frac{10}{3}ft/sec$.
Correct me if I am wrong.

A: Alternative approach: you already correctly showed that $y=2/3 \,x$. Now note that, assuming $x $ and $y $ expressed in feet, the time needed for the man to reach the base of the lamp is $x/5$ seconds. In the same time, the length of the shadow decreases from $y=2/3 \, x \, $ to $0$. So the decreasing rate is $$\frac {2/3 \, x}{x/5}=\frac {10}{3} \, \text { feet per second.} $$

A: Anatoly has given a simple solution,
but in case you are expected to use calculus, here's another simple solution.
Starting from $y = \dfrac23 x,\;\; \dfrac{dy}{dt} = \dfrac23 \dfrac{dx}{dt} = \dfrac 23\times -5 = -\dfrac{10}{3}$ ft/s,
the negative sign showing decreasing length of shadow.


text:
Q: PDE with non-constant boundary condition: why am I getting different results for the same problem in MATLAB vs. Mathematica? I am trying to solve the same PDE in Mathematica and MATLAB,  where  It has a Dirichlet boundary condition on the left, a section of non-constant Neumann boundary condition on the right and zero flux everywhere else. The non-constant boundary condition is defined by  where  was previously solved for and all other variables are constants. I have developed code for to solve this PDE in both Mathematica and MATLAB however, they do not produce the same results, and I do not know which code is incorrect.
Below is the full Mathematica code:
Needs["NDSolve`FEM`"]
e = 1.60217662*10^-19;
sige = 3.37*10^-4;
sigi = 18;
F = 96485;
n = -0.02;
c = 1;
pO2 = 1.52*10^-19;
Ie = -(2*F)*(c*pO2^n);
mu2 = -5.98*10^-19;
l = 10*10^-6;
y1 = 0.01;
y2 = 0.0025;
y3 = 0.0075;
meshRefine[vertices_, area_] := area > 10^-12;
mesh = ToElementMesh[
   DiscretizeRegion[ImplicitRegion[True, {{x, 0, l}, {y, 0, y1}}]],
   MeshRefinementFunction -> meshRefine];
bcmu = {DirichletCondition[mu[x, y] == 0, (x == 0 && 0 < y < y1)],
  DirichletCondition[
   mu[x, y] ==
    mu2, (x == l &&
     y2 < y < y3)]};
solmu = NDSolve[{Laplacian[mu[x, y], {x, y}] ==
    0 + NeumannValue[0,
      y == 0 ||
       y == y1 || (x == l && 0 <= y <= y2) || (x == l &&
         y3 <= y <= y1)], bcmu},
  mu, {x, y} \[Element] mesh];
bcphi = DirichletCondition[phi[x, y] == 0, (x == 0 && 0 < y < y1)];
A = (Ie - sigi/(4*e)*(D[mu[x, y] /. solmu, x] /. x -> l))/(-sigi);
solphi = NDSolve[{Laplacian[phi[x, y], {x, y}] ==
     0 + NeumannValue[0,
       y == 0 ||
        y == y1 || (x == l && 0 <= y <= y1) || (x == l &&
          y3 <= y <= y1)] +
      NeumannValue[-A[[1]], x == l && y2 < y < y3], bcphi},
   phi, {x, y} \[Element] mesh];
DensityPlot[phi[x, y] /. solphi, {x, 0, l}, {y, 0, y1},
 PlotLabel -> "Phi vs. x and y", PlotLegends -> Automatic]

The code produces this result for phi:
Mathematica result
And here is the MATLAB code:
% Define constants
e = 1.60217662*10^-19;
sige = 3.37*10^-4;
sigi = 18;
F = 96485;
n = -0.02;
c = 1;
pO2 = 1.52*10^-19;
Ie = -(2*F)*(c*pO2^n);
mu2 = -5.98*10^-19;
l = 10*10^-6;
y1 = 0.01;
y2 = 0.0025;
y3 = 0.0075;

% Rectangle is code 3, 4 sides, followed by x-coordinates and then y-coordinates
R1 = [3,4,0,l,l,0,0,0,y2,y2]';
R2 = [3,4,0,l,l,0,y2,y2,y3,y3]';
R3 = [3,4,0,l,l,0,y3,y3,y1,y1]';
geom = [R1,R2,R3];
% Names for the two geometric objects
ns = (char('R1','R2','R3'))';
% Set formula
sf = 'R1+R2+R3';
% Create geometry
g = decsg(geom,sf,ns);

% Create mu geometry model
mumodel = createpde;
geometryFromEdges(mumodel,g);

% Apply boundary conditions
applyBoundaryCondition(mumodel,'dirichlet','Edge',8,'u',0);
applyBoundaryCondition(mumodel,'dirichlet','Edge',9,'u',0);
applyBoundaryCondition(mumodel,'dirichlet','Edge',10,'u',0);
applyBoundaryCondition(mumodel,'dirichlet','Edge',6,'u',mu2);
applyBoundaryCondition(mumodel,'neumann','Edge',1,'g',0);
applyBoundaryCondition(mumodel,'neumann','Edge',3,'g',0);
applyBoundaryCondition(mumodel,'neumann','Edge',4,'g',0);
applyBoundaryCondition(mumodel,'neumann','Edge',2,'g',0);
applyBoundaryCondition(mumodel,'neumann','Edge',5,'g',0);
applyBoundaryCondition(mumodel,'neumann','Edge',7,'g',0);

% Solve PDE for mu
specifyCoefficients(mumodel,'m',0,'d',0,'c',1,'a',0,'f',0);
generateMesh(mumodel,'Hmax',l);
solmu = solvepde(mumodel);

% Create phi geometry model
phimodel = createpde;
geometryFromEdges(phimodel,g);

% Make sure initial condition is suitable
setInitialConditions(phimodel,0);
setInitialConditions(phimodel,-0.7,'Edge',6);

% Define nonconstant Neumann boundary condition
bcfun = @(location,state)(sigi/(4*e)*evaluateGradient(solmu,l,location.y)-Ie)/sigi;

% Apply boundary conditions
applyBoundaryCondition(phimodel,'dirichlet','Edge',8,'u',0);
applyBoundaryCondition(phimodel,'dirichlet','Edge',9,'u',0);
applyBoundaryCondition(phimodel,'dirichlet','Edge',10,'u',0);
applyBoundaryCondition(phimodel,'neumann','Edge',6,'g',bcfun);
applyBoundaryCondition(phimodel,'neumann','Edge',1,'g',0);
applyBoundaryCondition(phimodel,'neumann','Edge',3,'g',0);
applyBoundaryCondition(phimodel,'neumann','Edge',4,'g',0);
applyBoundaryCondition(phimodel,'neumann','Edge',2,'g',0);
applyBoundaryCondition(phimodel,'neumann','Edge',5,'g',0);
applyBoundaryCondition(phimodel,'neumann','Edge',7,'g',0);

% Solve PDE for phi and plot results
specifyCoefficients(phimodel,'m',0,'d',0,'c',1,'a',0,'f',0);
generateMesh(phimodel,'Hmax',l);
solphi = solvepde(phimodel);
phi = solphi.NodalSolution;
pdeplot(phimodel,'XYData',phi)
title('Phi vs. x and y')
xlabel('x-position')
ylabel('y-position')

The MATLAB code produces this as the results for phi:

Which code is correct? Where is the error?


text:
Q: Eclipse/IVY error indirectly referenced from required .class files I am periodically experiencing the "type [blah] cannot be resolved. It is indirectly referenced from required .class files" error, and reaching out for help.
I've searched this site and the web, and all of the many similar-sounding questions seem to be resolved by adding classes to the classpath.   But in this case, I'm pretty sure they already are on the classpath.
Here's the situation, pared down from an extremely large metaproject.  There are two eclipse projects ProjectOne and ProjectTwo.
Both projects are published by a build server to an Ivy repository, and ProjectTwo's ivy.xml refers to that version of ProjectOne.  However, I keep the ivy "resolve dependencies in workspace" preference turned on, so that I can work in both projects, and resolve to my modified classes instead of the published ones.
ProjectOne compiles in my workspace (as does ProjectTwo, except (occasionally) for the "indirectly referenced from required .class files" problem.
The structure looks basically like this:
// ProjectOne
   class Enum { **// I now suspect this name is the problem**
      public static class EnumObjectCache {
      }

// ProjectTwo
   class Bar { **// Occasionally gets error about Enum$EnumObjectcache being unresolvable**
   }

This is despite the facts that:

*

*This only affects Eclipse.  The real compiler handles this all with no problem

*ProjectTwo's ivy.xml file does contain a transitive dependency on ProjectOne.

*ProjectOne is present in the workspace, and successfully compiles.

*I always have "resolve dependencies in workspace" turned on.

*Regardless of how things are resolved, it should work class Enum (and EnumObjectCache) have been unchanged for more than a year.

*As an experiment, I've tried directly adding ProjectOne to ProjectTwo's classpath (by defining it as a required project).  No change.

*To make this more interesting, this problem doesn't happen all the time, and it only happens to a few classes in this very large codebase.  Oh, and when it does happen, it's always on Enum$EnumObjectCache.

*It doesn't happen to every one of the developers on the team at a time.

*The problem, when it happens, persists over multiple 'clean' and restarts of eclipse, and IVY re-resolves. (though I wasn't doing Ivy clean-all-caches).
10. I can "fix" the problem by introducing an otherwise unneccssary import of Enum from ProjectOne
Note: I had not previously tried cleaning the cache, as it's painfully slow to do (remote cache is transatlantic, and it's a very large project): 55 minutes to clean all caches and re-resolve, then another 20 or so to rebuild.
However, following a clean-all-cache, re-resolve, and rebuild, I still have the same problem.


text:
Q: SFSpeechRecognizer that recognizes few command words instead of a whole phrase? I have a SFSpeechRecognizer set up from Apple's sample app
https://developer.apple.com/library/content/samplecode/SpeakToMe/Introduction/Intro.html
I was wondering if it was possible to have the recognizer recognize individual words that are not connected to other previously recognized words.
For example, the recognizer right now would try to form a sentence when "Scroll" is uttered and then find the best transcription for the word that makes sense so when "Stop" is uttered, it would change it to something like "Down" which makes more sense in the context of the previous word.
But this is not what I want as I want my app to listen to individual words as commands that call functions while listening.
Is there any way to implement the framework in such a way that it will continuously listen for words and only capture individual words uttered?

A: Yes. You can scan the incoming words on partial results by setting recognitionRequest.shouldReportPartialResults = YES and then the results callback is called multiple times.
You can then process the results as you go, scanning for keyword / keyphrase before you get to the final result (ie ignore result.isFinal). When you find a keyword / keyphrase you are looking for, then just then cancel the recognition.
I have successfully implemented voice commands using this approach in Speaking Email as a modified Cordova plugin (source here).
Example:
- (void) recordAndRecognizeWithLang:(NSString *) lang
{
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:lang];
        self.sfSpeechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:locale];
        if (!self.sfSpeechRecognizer) {
                [self sendErrorWithMessage:@"The language is not supported" andCode:7];
        } else {

                // Cancel the previous task if it's running.
                if ( self.recognitionTask ) {
                        [self.recognitionTask cancel];
                        self.recognitionTask = nil;
                }

                [self initAudioSession];

                self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
                self.recognitionRequest.shouldReportPartialResults = [[self.command argumentAtIndex:1] boolValue];

                self.recognitionTask = [self.sfSpeechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult *result, NSError *error) {

                        if (error) {
                                NSLog(@"error");
                                [self stopAndRelease];
                                [self sendErrorWithMessage:error.localizedFailureReason andCode:error.code];
                        }

                        if (result) {
                                NSMutableArray * alternatives = [[NSMutableArray alloc] init];
                                int maxAlternatives = [[self.command argumentAtIndex:2] intValue];
                                for ( SFTranscription *transcription in result.transcriptions ) {
                                        if (alternatives.count < maxAlternatives) {
                                                float confMed = 0;
                                                for ( SFTranscriptionSegment *transcriptionSegment in transcription.segments ) {
                                                        NSLog(@"transcriptionSegment.confidence %f", transcriptionSegment.confidence);
                                                        confMed +=transcriptionSegment.confidence;
                                                }
                                                NSMutableDictionary * resultDict = [[NSMutableDictionary alloc]init];
                                                [resultDict setValue:transcription.formattedString forKey:@"transcript"];
                                                [resultDict setValue:[NSNumber numberWithBool:result.isFinal] forKey:@"final"];
                                                [resultDict setValue:[NSNumber numberWithFloat:confMed/transcription.segments.count]forKey:@"confidence"];
                                                [alternatives addObject:resultDict];
                                        }
                                }
                                [self sendResults:@[alternatives]];
                                if ( result.isFinal ) {
                                        [self stopAndRelease];
                                }
                        }
                }];

                AVAudioFormat *recordingFormat = [self.audioEngine.inputNode outputFormatForBus:0];

                [self.audioEngine.inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
                        [self.recognitionRequest appendAudioPCMBuffer:buffer];
                }],

                [self.audioEngine prepare];
                [self.audioEngine startAndReturnError:nil];
        }
}


text:
Q: Python function type hint with predefined type In Python, we can create aliases or custom types like following:
MyKindOfFunction = Callable[[int, int], int]  # alias
AlternativeType = NewType('AlternativeType', Callable[[int, int], int])  # new type

Consider the following function:
def myfunc(a: int, b: int) -> int:
    return a + b

Obviously, the signature matches the above definitions. Is there a more convenient way of notating this than annotating the parameters manually? I am unhappy with the way it is annotated for the following reasons:

*

*It does not check against AlternativeType, as AlternativeType is a subclass of Callable[[int, int], int].

*I am using many higher level functions, with equivalent signatures, but are logically of different types, and I would like to be able to differentiate between them.


text:
Q: different results compiling gcc and clang Can someone explain me, why compiling this piece of code have different behavior. For example gcc have infinite loop, but clang works as expected.
Yeap, I know that code more than ugly, it was wrote by me couple years ago, just wondering why switching machine have such impact on such an easy code, at least I didn't use stack, heap, pointers, nothing at all.
#include <stdio.h>
main()
{
    int a,b,state,nl,i,temp1,temp2;
    int words[10];
    nl = temp1 = 0;
    for( i = 0 ; i < 10 ; i++ )
        words[i] = 0;
    while((a = getchar()) != EOF)
    {
        nl++;
        if( a == ' ' || a == '\t' || a == '\n' )
        {
            words[nl-2]++;
            nl = 0;
        }
    }
    for(b=0; b < 10; b++)
        printf("%d",words[b]);
    printf("\n");
    for( b = 1 ; b <= 10 ; b++)
        printf("%d",b);
    printf("\n");
    for( b = 0 ; b <= 10 ; b++)
        if(words[b]>temp1)
            temp1=words[b];
    //printf("%d\n", temp1);
    for(; temp1 > 0 ; temp1--)
    {
        for(i= 0 ; i <= 10 ; ++i)
        {
            if(words[i]>0)
            {
                //  temp2 = i;
                //  for(; temp2 > 0; temp2--)
                //  printf(" ");
                printf("#");
                words[i]--;
            }
            else
                printf(" ");
        }
        printf("\n");
    }
}

A: At the very least:

*

*words[nl-2]++; could be called when nl == 1 which would cause undefined behavior.

*temp1=words[b]; can be called when b == 10 which is accessing an array out of bounds.

*if(words[b]>temp1) will be called when b == 10, which is accessing an array out of bounds.

*if(words[i]>0) will be called when i == 10, which is accessing an array out of bounds.

*words[i]--; could be called when i == 10, which is accessing an array out of bounds.

In general, different compilers will fall over differently when given undefined behavior.


text:
Q: Adding a global variable to a javascript function so that it can be used on another php page I have a script that contains the following code:
$(function(){
var e=$.cookie("list_grid");
if(e=="g"){
    $("#products").addClass("smallGrid");
    $("#smallGrid").addClass("disabled")
    }else if(e=="l"){
        $("#products").addClass("largeGrid");
        $("#products").removeClass("smallGrid");
        $("#largeGrid").addClass("disabled")
        }else{
            $("#products").addClass("listGrid");
            $("#products").removeClass("largeGrid");
            $("#products").removeClass("smallGrid");
            $("#list").addClass("disabled")}});
$(function(){
            $("#smallGrid").click(function(){
            $("#products").fadeOut(300,function(){
            $(this).removeClass("listGrid").fadeIn(300);
            $(this).addClass("smallGrid").fadeIn(300);
            $(this).removeClass("largeGrid").fadeIn(300);
            $.cookie("list_grid","g")});
            $(this).addClass("disabled");
            $("#list").removeClass("disabled");
            $("#largeGrid").removeClass("disabled");
            return false});

            $("#largeGrid").click(function(){
            $("#products").fadeOut(300,function(){
            $(this).addClass("largeGrid").fadeIn(300);
            $(this).removeClass("listGrid").fadeIn(300);
            $(this).removeClass("smallGrid").fadeIn(300);
            $.cookie("list_grid","l")});
            $(this).addClass("disabled");
            $("#smallGrid").removeClass("disabled");
            $("#list").removeClass("disabled");
            return false});

            $("#list").click(function(){
            $("#products").fadeOut(300,function(){
            $(this).addClass("listGrid").fadeIn(300);
            $(this).removeClass("smallGrid").fadeIn(300);
            $(this).removeClass("largeGrid").fadeIn(300);
            $.cookie("list_grid",null)});
            $(this).addClass("disabled");
            $("#smallGrid").removeClass("disabled");
            $("#largeGrid").removeClass("disabled");
            return false})
            })

I need to add a var that can be used in some php code on another page. The purpose of this var is to know what listing type was selected so that i can trigger a specific type of output depending on what format the user requests to see the data in.
I tried to change
$("#smallGrid").click(function(){

to include the var as such
$("#smallGrid").click(function(){
var listingStyle="small"

but when i echo the contents of $listingStyle in my php code it is empty.
The site can use global vars and they are set like
$GLOBALS['variable_name'] = 'this string';

but i don't seem to be able to get a javascript var into a php global var
If anyone has any suggestions it would be very much appreciated.

A:

but i don't seem to be able to get a javascript var into a php global var

That's correct, you can't do something in Javascript and have it somehow show up in PHP.  You can, however, use Javascript to set a GET variable in the URL which will then be populated into the $_GET array which you then use in PHP to store in the $_SESSION array so that it is then available to all other pages which can access the session.  You could also submit a POST so and used the $_POST array, but that's preferential or subject to the conditions of your site/program.

A: use session...
First include jquery-1.9.1.js and jquery.session.js
TO STORE:
        $(function() {
             $.session.set("myVar", "Hello World!");
        });

TO READ:
        $(function() {
            alert($.session.get("myVar"));
        });

use:
print_r($_SESSION); //to check what are the sessions created...

more reference here


text:
Q: node-opcua, nodejs, express: Add Variable nodes dynamically after run the OPCUAserver Reading the documentation and examples of the OPC-UA foundation, the variables nodes are always added before the statement to start run the server. Is it possible to add them after the server has been started? If I change the order of the statements that doesn't work.
Think with me the following situation: I need to do some HTTP requests as soon we start running the application/software (not the server) asynchronously. Then the server starts, after my HTTP request is done, I added variable nodes based on the information returned from the web.
The variables are added by file .json, "https" will send data by HTML form. My server will analyse and add them to the .json file. Then I need the server to add that.
OPCUA_SERVER.js
app.js
appconfig.json
for (let i = 0; i < appConfig2.SimulationData.length; i++)
{
    let nameDevice = appConfig2.SimulationData[i].deviceName;
    opcuaAddDevice(nameDevice, appConfig2.SimulationData[i], moduleData.uaNodeList, addressSpace, namespace);

}
// Start the server
try
{
    await (opcuaStartAsync(moduleData.serveropc));
}
catch (e)
{
    console.log("OPCUA Server start failed : " + e);
}

console.log("OPCUA Server started.");

//store some values from server and make the magic..
moduleData.connected = true;
let port = moduleData.serveropc.endpoints[0].port;
moduleData.endpointUrl = moduleData.serveropc.endpoints[0].endpointDescriptions()[0].endpointUrl;
console.log("OPCUA Server is now listening on port", port,"(press CTRL+C to stop Server).");
return moduleData;

});


text:
Q: All your choice of an employer depends on is whether I wonder whether this phrase below is grammatical?

All your choice of an employer depends on is whether

1) you possess necessary skills and expertise in the sphere of corporate finance.
2) you love what you do
3) you are ready for overtime work
4) bla-bla

A: It's grammatical (I think) but it's awkward.
It's awkward because of the words in between 'your choice' and 'depends on'. And because 'choice' is doing double duty: both 'your choice depends on' and 'your choice of an employer'.
I'd rephrase it as something like:

When you're choosing an employer, your choice should depend only on whether...
The only thing that counts when choosing an employer is...


text:
Q: Why the following does not work for autowired I have a class like
class A {
      @Autowired
      B b;
}

A a = new A()

I found b is not autowired
I already did <context:component-scan base-package="*">, anything else missing?

A: You have to get the bean from a bean factory, instead of creating an instance directly.
For example, here's how to do it with annotations. First, you need to add a bit more to your declaration of your class:
// Annotate to declare this as a bean, not just a POJO
@Component
class A {
    @Autowired
    B b;
}

Next, you do this once per application:
AnnotationConfigApplicationContext factory =
        new AnnotationConfigApplicationContext();
factory.register(A.class);
factory.register(B.class);
// Plus any other classes to register, or use scan(packages...) method
factory.refresh();

Finally, you can now get instances of the bean:
// Instead of: new A()
A a = factory.getBean(A.class);

A: Spring will only autowire the A object if Spring instantiates it as a bean.  if you instantiate your own, Spring knows nothing about it, so nothing gets autowired.