text:
Q: actionscript 3.0 type coercion failed when dispatching error event I try to dispatch an error event in an AS3 application:
dispatchEvent( new ErrorEvent( ErrorEvent.ERROR, false, false, "my error message"));
but I get the following runtime error:
TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::ErrorEvent@2c04239 to com.adobe.protocols.dict.events.ErrorEvent.
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at my line of code..

these are my import statements at the top of the file:
import flash.display.MovieClip;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.security.IURIDereferencer;
import flash.security.ReferencesValidationSetting;
import flash.security.RevocationCheckSettings;
import flash.security.SignatureStatus;
import flash.security.XMLSignatureValidator;
import flash.utils.ByteArray;

import mx.utils.Base64Decoder;
import mx.utils.Base64Encoder;
import mx.utils.SHA256;

what's going on?
thanks

A: Sometimes that... happens. Between the IDE and Flash's ability to get confused, I'm surprised it doesn't happen more. I suspect the error is actually in your listener though.
Change your event handler to specify flash.events.ErrorEvent.
 function errorHandler( event:flash.events.ErrorEvent ):void

If that doesn't work, you can always either handle all Events or you can use the fully qualified name while constructing the ErrorEvent.


text:
Q: How to dynamically round off cell value for group of cell in excel 2016 I have excel template file which is  excel 2016 , I want from Column E23 to E100 if some one enter any value it round off till 3 digit . Example :- 12345.123456 should convert to 12345.123 .
Bu this should only effective to that cell where any value get change . In attached picture Column E is where I want round off . Any help will be greatly appreciated .

A: Try this:
To enter this event-triggered Macro, right click on the sheet tab.
Select "View Code" from the right-click drop-down menu.
Then paste the code below into the window that opens.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim C As Range

If Not Intersect(Target, Columns(5)) Is Nothing Then
    Application.EnableEvents = False
    For Each C In Intersect(Target, Columns(5))
        If IsNumeric(C.Value) And Len(C.Value) > 0 Then
            C.Value = Round(C.Value, 3)
        End If
    Next C
End If
Application.EnableEvents = True

End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sharing Webstorm Node.js Environment Variables I have a growing list of environment variables for my Node.js app in webstorm.  Is there a way to share this list so that any new developers we have to the project do not need to manually add them but can rather just import them?  As we add db connections or api keys that we don't want to be part of the codebase it would make things much easier to just be able to add those and then easily share the file with all of the team.

A: You can simply copy all env variables out of a shared text file and paste it into the env vars window via the Paste button


text:
Q: Windows XP network issue - Looking for wrong Workgroup Say my workgroup name is "MyGroup".  Every time I pull up Windows Explorer, go to My Network Places and then Computers Near Me, I keep getting a message that says, "MyGroup2 is not accessible..."  I then go to Control Panel and System, and it clearly says my workgroup is called "MyGroup".  So why on earth is it looking for MyGroup2, and how do I convince it that it should be looking for MyGroup??  I should note that when I installed Windows I did have it in the MyGroup2 workgroup, then discovered that it should have been called MyGroup.  However, after I changed it back I'd expect it to look for MyGroup but for some reason MyGroup2 is stuck in it's brain.
This is a new build, I recently reformatted the HD on this machine.  Also, it can connect to my wireless network and get online.  Also, the other computers on MyGroup can see the new computer, making matters even weirder...


text:
Q: Custom button in leftBarButtonItems to function as backBarButtonItem I am using leftBarButtonItems to group a negativeSeparator (to get rid of padding and align my custom button to the edge of the screen) and a custom UIBarButtonItem:
[navigationItem setLeftBarButtonItems:@[negativeSeperator, leftButton]];

How do I make my custom leftButton function as a backBarButtonItem? I understand that as soon as I use leftBarButtonItems, it hides/replaces the backBarButtonItem. So, how can I "transfer" the back button functionality to my custom button?

A: Set the action to the leftBarButton item you are placing on the navigationBar and add the below code in that action method
[self.navigationController popViewControllerAnimated:YES];


text:
Q: Why doesn't Mongo read the /usr/local/mongodb/mongod.conf file? In my /usr/local/mongodb/mongod.conf file, I have
# Store data alongside MongoDB instead of the default, /data/db/
dbpath = /usr/local/mongodb_data

# Only accept local connections
bind_ip = 127.0.0.1

But when I try to run Mongo (on my mac), I get an error:
Wed Sep 14 09:29:35 [initandlisten] exception in initAndListen std::exception: dbpath (/data/db/) does not exist, terminating

So apparently the conf file is not being read

A: You must specify if you want it to use another config; there isn't a default config file.
See Here:
File Based Configuration
To achieve what you want to do; you can either specify your config path or start your mongo server like:
mongod --dbpath /usr/local/mongodb_data

A: If you install MongoDB using brew, the LaunchAgent files that it generates for you will use a configuration file at /usr/local/etc/mongod.conf by default.
This behavior is defined in:
https://github.com/Homebrew/homebrew/blob/master/Library/Formula/mongodb.rb
Note that this "default" only applies when running MongoDB as a service via launchctl, not manually starting it by running mongodb.
As of 2015-03-09, the instructions given by Homebrew after installing MongoDB 3.0.0 are:
==> Caveats
To reload mongodb after an upgrade:
    launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
    mongod --config /usr/local/etc/mongod.conf

Note the explicit --config argument in the manual run command.

A: I wanted to just be able to type mongod and have it work decently.  This works, but with caveats:
% sudo mkdir /data
% sudo ln -s /usr/local/var/mongodb /data/db

Note that there are some useful configurations in homebrew's default /usr/local/etc/mongod.conf.  Here's the file for reference:
systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  bindIp: 127.0.0.1

So it'll log to the console, and connections won't be restricted to localhost.
Note: as in @ballPointPenguin's post, now that Homebrew has brew services, that is an excellent option.

A: As noted by @davidmc24, homebrew installation of mongo will use the configuration file by default when started with launchctl. Simply use:
brew services start mongodb

You can follow the logs at (default location):
tail -f /usr/local/var/log/mongodb/mongo.log


text:
Q: How to validate XHTML 1.1 in Java I'm trying to find a way to validate a XHTML 1.1 document. I have a method that validates XML against XSD and another against DTD.
The DTD one works with XHTML 1.0 Strict but runs forever with XHTML 1.1:
public static boolean validateAgainstDTD(String xhtml) {
        try {
                DocumentBuilderFactory factory = DocumentBuilderFactory
                                .newInstance();
                factory.setValidating(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                builder.setErrorHandler(new org.xml.sax.ErrorHandler() {
                        // Ignore the fatal errors
                        @Override
                        public void fatalError(SAXParseException exception)
                                        throws SAXException {
                        }

                        // Validation errors
                        @Override
                        public void error(SAXParseException e) throws SAXParseException {
                                System.out.println("Error at " + e.getLineNumber()
                                                + " line.");
                                System.out.println(e.getMessage());
                                System.exit(0);
                        }

                        // Show warnings
                        @Override
                        public void warning(SAXParseException err)
                                        throws SAXParseException {
                                System.out.println(err.getMessage());
                                System.exit(0);
                        }
                });
                Document xmlDocument = builder.parse(new ByteArrayInputStream(xhtml.getBytes()));
                DOMSource source = new DOMSource(xmlDocument);
                StreamResult result = new StreamResult(System.out);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
                                "xhtml11.dtd");
                transformer.transform(source, result);
                return true;
        } catch (Exception e) {
                System.out.println(e.getMessage());
                return false;
        }
}

and the other one always says that it is not valid even if I take the example from the W3C website:
try {
       // parse an XML document into a DOM tree
       DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
       Document document = parser.parse(new ByteArrayInputStream(str.getBytes()));

       // create a SchemaFactory capable of understanding WXS schemas
       SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

       // load a WXS schema, represented by a Schema instance: the XHTML 1.0 WXS schema
       Source schemaFile = new StreamSource("http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd");
       Schema schema = factory.newSchema(schemaFile);

       // create a Validator instance, which can be used to validate an instance document
       Validator validator = schema.newValidator();

       // validate the DOM tree
       validator.validate(new DOMSource(document));
  } catch (ParserConfigurationException e) {
       // parser configuration excepion
      System.out.println(e.getMessage());
  } catch (IOException e) {
       // io exception
      System.out.println(e.getMessage());
  } catch (SAXException e) {
       // instance document is invalid!
      System.out.println(e.getMessage());
  }

How do I validate XHTML 1.1 in Java?
I showed what I tried and nothing worked.
Does anyone see a mistake on my part, or have a solution?

A: Use the following process:

*

*Convert the DTD to an XML Serialization

*Convert the XML Serialization to XSD

*Retry with the local XSD

References

*

*NekoDTD: Converting DTD Grammars

*DTD Analyzer Wiki: Similar Tools

*DTD2Schema: A Conversion Tool from DTD to XML Schema


text:
Q: Sending message from background script to content script on startup I am currently trying to pass a message from the background script to a content script  on startup  (i.e. before the extension icon is clicked).
I have tried the following (inspired by https://stackoverflow.com/a/23895822/10500893 ), but it doesn't seem to be working.
background.js
function preloadPopupScript(){
    return new Promise(function(resolve, reject){
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.executeScript(tabs[0].id, {file: "popup.js"},
function(){
                if(chrome.runtime.lastError){
                    reject(Error("could not preload popup.js :("));
                }else{
                    resolve();
                }
            });
        });
    });
}

chrome.runtime.onStartup.addListener(function(){
    let preloadScript = preloadPopupScript();
    preloadScript.then(function(){

        let lastXHRresponse = chrome.storage.local.get("xhrResponse",
function(d){
            if(chrome.runtime.lastError){
                console.log("could not find past authentication data!");
                return;
            }

            // GETS TO HERE
            chrome.runtime.sendMessage({status: "hasPreviouslyLoggedIn"});
            checkAccessToken();
            chrome.runtime.sendMessage({status: "checkArtistReleases"});
        });
    });
});

popup.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    switch(request.status){

        // THE BELOW CASE DOES NOT SHOW ANY SIGNS OF GETTING TRIGGERED
        case "hasPreviouslyLoggedIn":
        case "successfulLogin":
            chrome.browserAction.setPopup({popup: "login_signedin.html"});
            window.location.href = "login_signedin.html";
            hasSignedIn = true;
            chrome.runtime.sendMessage({action: "canCreateAlarm"});
            break;
    }
});

Are there any issues with this code or did I mis-implement the suggested solution in https://stackoverflow.com/a/23895822/10500893?
Thanks much much much in advance!!!
(Also apologies in advance for noob styling issues, as I have just picked up JS >.<)


text:
Q: Read and Write on same Channel in Netty 4.1 Is there some issue with Netty handling read and write on the same Channel.
We have a message broker built in Netty 4.1. We performed two types of tests for load testing.
1) Client A sends a PUBLISH packet to the broker. The broker does some processing and sends the packet back to the same client via the same channel through which it came.
2) The second scenario is where Client A sends a PUBLISH packet to the broker via its Channel. The broker performs some processing and then sends the packet randomly to any one of the clients connected to the broker at that time (except for the current client ofcourse).
We found that in the first case, the read operation for Netty takes a lot of time whereas in the second case everything runs very smoothly and we get the desired theoretical latency.
So just wanted to confirm as to how Netty handles read and write on the same channel.

A: Read and write on the same channel is a very typical usage of Netty: for example, i think web server is almost doing the same thing. Web server/ proxy server in Netty's example codes could show how to do that and the performance should be ok.
I think the first step is to figure out where the "slow" is. If there is no slow in code, take a look at the tcp dump might help.


text:
Q: Elegant way to install Ansible task dependencies? I am using a 3rd party Ansible role that requires some python libraries to be present on the host running my playbook.
I expect Ansible Galaxy to actually install those dependencies for me, unfortunately, it's not the case since AG only install roles dependencies. So I have to manually take care of that.
I am looking for an automated approach, do you have any elegant way to do it?

A: There is no elegant way of doing that (at least one that I'm aware of). Many Ansible modules require extra packages to be installed on the host that executes the task. It's common to hit those problems when first executing a play or task.
So I guess the most elegant way would be to create a pull request for the Galaxy role to add those dependencies to the play with an extra task.


text:
Q: (node:13040) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message case 'mute':
            if(!message.member.hasPermission('MUTE_MEMBERS', 'MANAGE_MESSAGES')) return message.channel.send(noperms);
            const reasonMute = args.slice(3).join(" ");
            const muteDuration = args[2];
            if(!args[1]) return message.channel.send('Nu ai specificat o persoana!');
            if(!muteDuration) return message.channel.send('Nu ai specificat durata sanctionarii!');
            if(!reasonMute) return message.channel.send('Nu ai specificat motivul sanctiunii!');
            var membermuted = message.guild.member(message.mentions.first() || message.guild.members.get(args[1]));
            guild.roles.create({data: {name: 'Muted', color: 'GRAY'}})
            let mutedRole = message.guild.roles.cache.find(mutedRole => mutedRlole.name === "Muted");
            const channels = message.guild.channels;
            channels.forEach(f => {f.overwritePermissions([{id: mutedRole.id,deny: ['SEND_MESSAGES', 'SPEAK'],},]);
            membermuted.roles.add(mutedRole.id);
            const muteembed555 = new Discord.MessageEmbed().setDescription(`output: discord.js mute var1 var2 var3`).setColor('RED');
            message.channel.send(muteembed555);
            setTimeout(function() {
                membermuted.roles.remove(mutedRole.id);
            }, ms(muteDuration));
        });
        break;

error: (node:13040) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message


text:
Q: How to use the Smith chart properly? In our electromagnetic waves class at our electrical engineering department, we came across the Smith chart, a valuable tool for designing transmission lines. This class covers the following topics: relation waves (inductive and capacitive coupling), transmission lines, impedance Transformation and Matching, electromagnetic waves in unbounded media, the study of shielding, waveguides with conductive walls, dielectric waveguides and electromagnetic radiation.
However, I always find it helpful to use formulas behind transmission lines to check whether my calculations are correct. Besides, in this example, it is clear why a Smith chart is being used. In this example is not much information given about the transmission line which results in some pesky calculations if one wanted to check it analytically. I was not able to find any errors in the analytic equations and thus, was not able to see if my Smith chart would give the correct answers since my end-equations don't give any answers that satisfy the problem.
The exercise given is (considering a lossless transmission line, so $\gamma$ of the transmission line only consists of a imaginary part $\beta$):

My calculations are to be found below:

Note that $Z_c$ is the characteristic impedance of the transmission line, $Z_R$ or $Z_L$ in figure the impedance of the ballast is, and $z$ the normalized impedance is. Actual impedances are expressed by a large Z, and normalized ones with a z.
This is the actual explanation of the Smith chart:

The Smith chart is used as follows:
We first traverse the circle in the anti-clockwise direction where $z = - j 2.5 $ and thus we get the point on the left of the given starting point. The VSWR and reflection coefficient could be easily derived from the radius of the impedance circle (see bottom Smith chart). The $V_{min}$ and $V_{max}$ points could be easily derived from the Smith chart. These are respectively the "shorted"- and "open-circuit"-points of the Smith chart.
If any parts of my question are not clear, feel free to address me on these parts. However, it is a bit busy with assignments at university and therefore I had not much time in putting this question together.


text:
Q: detect currently selected input field in javascript for bookmarklet I am trying to write a bookmarklet that fills the currently selected field in with a function of today's date.  How do I find the currently tabbed to or selected input field using javascript?

A: To get the active element you can use
var input = document.activeElement;

if (input.tagName == "INPUT" || input.tagName == "TEXTAREA")
{
    input.value = "today's date";
}

A: You can use
document.activeElement
To get the current active element.
Then you can use it to input the data, like so
if (document.activeElement.nodeName === 'INPUT') {
   document.activeElement.value = new Date().getTime();
}

But your better off adding a focus event to the element


text:
Q: Activating tool after cancel button is pressed in message box? I am building a plugin in QGis and I want to activate the plugin icon again when user clicks cancel button in the message box.
def run(self, checked):
    if checked == True:
        # icon is active
        # do something
    if checked == False:
        # icon is deactive
        reply = QtGui.QMessageBox.question(self.iface.mainWindow(), 'Continue?',
             'message', QtGui.QMessageBox.Yes, QtGui.QMessageBox.Cancel)
        if reply == QtGui.QMessageBox.Yes:
            # do something
        if reply == QtGui.QMessageBox.Cancel:
            # set the tool icon active again
            # do nothing

Maybe my solution is not the best one.

A: Perhaps use something like the following:
def run(self, checked):
    if checked:
        # icon is active
        print 'Do something'
    else:
        # icon is deactive
        reply = QtGui.QMessageBox.question(self.iface.mainWindow(), 'Continue?',
            'message', QtGui.QMessageBox.Yes, QtGui.QMessageBox.Cancel)
        if reply == QtGui.QMessageBox.Yes:
            # do something
            print 'Yes'
        else:
            # set the tool icon active again
            # do nothing
            self.your_icon.setChecked(True)


text:
Q: etoolbox error when using uni-wtal-ger style I get an error when I try to use the uni-wtal-ger citation style and since I am fairly new to Latex I am unable to make sense of it (at all).
My usepackage declaration for biblatex looks like this:
\usepackage[
citestyle=uni-wtal-ger,
bibstyle=authortitle,
sorting=nty,
backend=biber]{biblatex}

This works for all citation styles I tried, including uni-wtal-lin, but not for uni-wtal-ger, which throws the following error:
LaTeX Warning: Reference `edtranslog' on page 3 undefined on input line 60.

! Package etoolbox Error: Boolean '\ifbbx:annotation' undefined.

This seems similar to this problem but the proposed solution there is to use biber which I already do. Any help is much appreciated.
(Dist: Arch Linux with texlive-most, texlive-lang and texlive-bibtexextra)

A: uni-wtal-ger is depending on biblatex-dw. Like many other custom styles, the citation and bibliography styles included in those packages are mutually dependent. So mixing uni-wtal-ger or biblatex-dw with other styles will lead to errors.
The style does still work perfectly when using it completely as citestyle and bibstyle though.
So please try
\usepackage[
style=uni-wtal-ger,
backend=biber
]{biblatex}


text:
Q: Create EC2 instance with Boto3 I'm trying to create an instance using the following code.
import boto3
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2.create_instances(ImageId='ami-d0f506b0', MinCount=1, MaxCount=1)

I keep getting the following error;
An error occurred (InvalidAMIID.NotFound) when calling the RunInstances operation: The image id '[ami-d0f506b0]' does not exist

The AMI is the default Amazon Linux AMI 2016.03.1 (HVM), SSD Volume Type
I get the same error with my own AMI images and when I set the region name via ~/.aws/config
Any ideas why this is not working?

A: Your REGION does not match the image id.
You need to use image "ami-6e84fa0e"
us-west-1 --> US West (N. California) : use image ami-6e84fa0e
us-west-2 --> US West (Oregon): use image ami-d0f506b0


text:
Q: Kirchhoff's Law and Superposition Theorem For the given circuit I found the current and the voltage at R1, R2, R3, using the superposition theorem.
1.I replaced the VS2 with a short then calculated:
I1= 0.57mA, I2=0.33mA, I3=0.2mA, V1= 2.68V, V2=2.02V, V3=2.97V.
2. Then I replaced the VS1 with a short and then calculated:
I1=-0.99mA, I2=-0.58mA, I3=0.4mA, V1=3.19V, V2=6.7V, V3=3.2V
So, the total current and voltage  for each resistor is :
I1=0.26mA, I2=-0.65mA, I3=0.91mA
V1= 5.86V, V2=9.16V, V3=5.5V
I have to prove the Kirchhoff's voltage and current Law are valid in the circuit given.
Can someone help me with this?

A:
simulate this circuit – Schematic created using CircuitLab
First of all, mark all currents on all branches with their magnitude and direction as you calculated.
To verify Kirchoff's current law:

*

*For node E, consider currents entering and leaving the node - \$I_{R1}, I_{R2}, I_{R3} \$

*Similarly for node G, consider currents - \$I_{R3}, I_{DG}, I_{GB} \$

*Prove that the algebraic sum of currents leaving the node = algebraic sum of currents entering the node.

To verify Kirchoff's voltage law:

*

*Consider all 3 loops in the circuit - AEGB, ECDG, ACDB.

*Prove that the sum of all voltage drops and voltage sources = 0 in each loop.

A: I may have wrongly understood the question but... for Kirchhoff's Laws.
Assign nodes to the given circuit
Before you conduct KCL and KVL, assign nodes to the given circuit. This is necessary.
Apply Kirchhoff's Current Law
Utilize KCL at the middle node (bounded by the 10,000-ohm resistor and the ground). Let us label the node between the two X and Y where X is the top node and Y is the ground. Assign the directions of the current at your will but I will share mine at my own will.
As I have said, apply KCL at node X. By doing so, we have
$$i_1 = i_2 + i_3$$
where
\$i_1\$ is the current entering node X
\$i_2\$ and \$i_3\$ are the currents leaving the node X.
Apply Kirchhoff's Voltage Law
Assign loops to the given circuit. If there is an element that separates the given circuit into two planes, it will have two loops. The direction is assigned by free will.
Let 1 and 2 be the loops on the given circuit. We take the sign conventions into account both for sources and passive elements. A current passing from the negative polarity to the positive polarity of a voltage source is considered a voltage rise while a current that passes from the positive polarity to negative polarity is called voltage drop.
On a side note; I have defined both loops to be clockwise direction.
For passive elements, when the direction of the loop is the same as the direction of the current, the passive element takes a voltage drop and when the direction of the loop opposes the direction of the current, the passive element takes a voltage rise.
Let us formulate another set of equations.
At Loop 1:
$$ 5 - 4,700i_1 - 10,000i_2 = 0 $$
$$ 4,700i_1 + 10,000i_2 = 5$$
At Loop 2:
$$ -6,800i_3 - 10 + 10,000i_2 = 0$$
$$ 10,000i_2 - 6,800i_3 = 10$$
Solve the system of equations
Arrange the equations obtained from KCL and KVL respectively. Solve by any means.
Check whether the answers agree
You first did the Principle of Superposition. Double check if the answers are the same.

A: I have just come across this question and nearly 3 years late but wish to show the asked for equivalence.
Labelling the circuit using the [passive sign convention](Passive sign convention).

Applying Kirchhoff's voltage law for loop BACDB
$$-5 +xR_1+yR_2+10 =0$$
Now let the subscript for currents produced by the 5 volt supply be labelled 5 and those by the 10 volt supply be labelled 10.
$$-5 +(x_5+x_{10})R_1+(y_5+y_{10})R_2+10 =0$$
$$\left[-5+x_5R_1+y_5R_2 \right]+ \left[x_{10}R_1+y_{10}R_2 +10\right] = 0$$
Now note that the terms in the square brackets are those that you would have started with when solving the problem via superposition.


text:
Q: Do Homotopy Equivalent, Orientable n-Manifolds Have The Same Cohomology With Compact Support? Using Poincare duality, I believe that if $X$ and $Y$ are two orientable $n$-manifolds with $X\simeq Y$, then we should have $H^i_c(X)\cong H_{n-i}(X)\cong H_{n-i}(Y)\cong H^i_c(Y)$ for all $i$. However, in a comment to the question linked at the bottom, the user asserts that the torus with a point removed and a sphere with three points removed have different cohomology with finite support, despite having the same dimension and being homotopy equivalent.
Have I misunderstood the statement of Poincare Duality for compactly supported cohomology, and if so can someone explain how the commenter computed these groups for the sphere with three points removed and the torus with one point removed?
Torus minus a point homeomorphic to sphere with three points?

A: His calculation of the compactly supported cohomology of the sphere minus 3 points is incorrect, it's $H^1_c=\mathbb {Z}^2$ since it's compactification is the quotient of three points on a sphere. The way to answer the original question is to just see that the one point compactifications of the spaces are not homeomorphic (one is a manifold and one is not).
You are correct they should have the same compactly supported cohomology by Poincaré duality.


text:
Q: GXT-3 issue to load data for my Chart My problem is annoying. My server side is generating 12 random numbers (double here).
My Client side received the correct data but nothing is displayed in my Chart. That worked fine with hardcoded data in the store but not with a REST call.
The transfer between my server and my client is that :
[{"key":"key0","value":0.47222548599297787},{"key":"key1","value":0.6009173797369691},{"key":"key2","value":0.13880104282435624},{"key":"key3","value":0.01804674319345545},{"key":"key4","value":0.5547733564202956},{"key":"key5","value":0.8229999661308851},{"key":"key6","value":0.8959346004391032},{"key":"key7","value":0.6848052288628435},{"key":"key8","value":0.10222856671111813},{"key":"key9","value":0.6931371931409103},{"key":"key10","value":0.2994297934549003},{"key":"key11","value":0.47566752196381334}]

Here my simple class used for my test. I am a newbie with GXT 3
public void onModuleLoad() {

    final ListStore<JSOModel> store;
    final ContentPanel panel  = new FramedPanel();
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/ws/DocumentService/v1/test");
    builder.setHeader("Accept", "application/json");

    HttpProxy proxy = new HttpProxy(builder);

    final Loader<ListLoadConfig, ListLoadResult<JSOModel>> loader = new ListLoader<ListLoadConfig, ListLoadResult<JSOModel>>(proxy, new DataReader<ListLoadResult<JSOModel>, String>() {
        @Override
        public ListLoadResult<JSOModel> read(Object loadConfig, String data) {
            List<JSOModel> jsoModels = new ArrayList<JSOModel>();
            JsArray<JSOModel> jsoModelJsArray = JSOModel.arrayFromJson(data);
            if(jsoModelJsArray != null) {
                for(int i = 0; i < jsoModelJsArray.length(); i++) {
                    jsoModels.add(jsoModelJsArray.get(i));
                }
            }

            return new ListLoadResultBean<JSOModel>(jsoModels);
        }
    });

    store = new ListStore<JSOModel>(new ModelKeyProvider<JSOModel>() {
        @Override
        public String getKey(JSOModel item) {
            return item.get("key");
        }
    });

    loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, JSOModel, ListLoadResult<JSOModel>>(store) {
        @Override
        public void onLoad(LoadEvent<ListLoadConfig, ListLoadResult<JSOModel>> event) {
            ListLoadResult<JSOModel> loaded = event.getLoadResult();
            if(loaded.getData() == null) {
                store.replaceAll(new ArrayList<JSOModel>());
            } else {
                store.replaceAll(loaded.getData());
            }
        }
    });

    Chart<JSOModel> chart = new Chart<JSOModel>();
    chart.setStore(store);
    chart.setShadowChart(true);

    NumericAxis<JSOModel> axis = new NumericAxis<JSOModel>();
    axis.setPosition(Chart.Position.LEFT);
    axis.addField(new ValueProvider<JSOModel, Number>() {
        @Override
        public Number getValue(JSOModel JSOModel) {
            return JSOModel.getNumber("value");
        }

        @Override
        public void setValue(JSOModel JSOModel, Number number) {

        }

        @Override
        public String getPath() {
            return "key";
        }
    });
    axis.setTitleConfig(new TextSprite("Number of hits"));
    axis.setWidth(50);
    axis.setMinimum(0);
    axis.setMaximum(100);
    chart.addAxis(axis);

    PathSprite odd = new PathSprite();
    odd.setOpacity(1);
    odd.setFill(new Color("#dff"));
    odd.setStroke(new Color("#aaa"));
    odd.setStrokeWidth(0.5);
    axis.setGridOddConfig(odd);

    CategoryAxis<JSOModel, String> horizontalAxis = new CategoryAxis<JSOModel, String>();
    horizontalAxis.setPosition(Chart.Position.BOTTOM);
    horizontalAxis.setField(new ValueProvider<JSOModel, String>() {
        @Override
        public String getValue(JSOModel JSOModel) {
            return  JSOModel.get("key");
        }

        @Override
        public void setValue(JSOModel JSOModel, String s) {

        }

        @Override
        public String getPath() {
            return "key";
        }
    });
    horizontalAxis.setTitleConfig(new TextSprite("month of year"));
    chart.addAxis(horizontalAxis);

    LineSeries<JSOModel> column = new LineSeries<JSOModel>();
    column.setYAxisPosition(Chart.Position.LEFT);
    column.setStroke(new RGB(148,174,10));
    column.setHighlighting(true);
    chart.addSeries(column);

    axis.addField(column.getYField());
    chart.addSeries(column);

    chart.setHeight(100);
    chart.setWidth(100);

    Button b = new Button("ha");
    b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent clickEvent) {
            loader.load();
        }
    });

    RootPanel.get().add(b);

    panel.setCollapsible(true);
    panel.setHeadingText("Column Chart");
    panel.setPixelSize(620, 500);
    panel.setBodyBorder(true);

    VerticalLayoutContainer layout = new VerticalLayoutContainer();
    panel.add(layout);

    chart.setLayoutData(new VerticalLayoutContainer.VerticalLayoutData(1,1));
    layout.add(chart);

    chart.setBackground(new Color("#dff"));
    RootPanel.get().add(panel);

A: There are two ways to wire the chart into a store. One is to simply specify that the chart is using a store via setStore, as you have done:
    chart.setStore(store);

When you do this, you must also inform the chart when it must redraw everything - you must call:
    chart.redrawChart();

This call must be made shortly after the load is completed - consider doing it at the end of onLoad.
Why is this required? In some cases, developers want to make many changes to the store, one at a time, and if the chart automatically updated after each change, that would spawn many slow changes to the data model, and could end up looking strange. In a case like this, you would only call redrawChart() after all changes were complete.
There is another option however - instead of calling setStore, you can call bindStore, and ask the Chart to automatically update whenever any change occurs to the chart:
    chart.bindStore(store);

In your case, this is likely the correct answer.


text:
Q: Samba: Software caused connection abort I am trying to create samba file server (Ubuntu 14.04) on my local network,
I can connect to samba server from another Ubuntu 14.04 and enter the shared folder as a guest, but after creating a directory I'm getting following error:
Software caused connection abort

The point is that when I re-enter the shared folder I can see the created directory! So I have required write and read permissions,
I have tried different forms of configuration in smb.conf with no success,
even when I share a directory by right-clicking and selecting local network share from the context menu, I will face the same error!
Also when I do the same procedure using smbclient:
NT_STATUS_CONNECTION_DISCONNECTED making remote directory \test
smb: \> SMBecho failed (NT_STATUS_CONNECTION_DISCONNECTED). The connection is disconnected now

A: According to the Arch wiki this might be caused by deactivation of SMB1. SMB1 is deactivated by default since Samba 4.11 (at least on Arch). Adding the following to /etc/samba/smb.conf might solve to error:
[global]
client min protocol = CORE

A: In a security update (19 april 2016) a dependency has been forgotten. You have to update library libtalloc2 with
apt-get install libtalloc2

A: After two weeks, I finally solved it.
The problem is that the new version of samba has a mind-blowing bug,
so anyone who has a similar problem may want to use the following command to downgrade their samba:
sudo apt-get install samba=2:4.1.6+dfsg-1ubuntu2 samba-common=2:4.1.6+dfsg-1ubuntu2 \
  samba-libs=2:4.1.6+dfsg-1ubuntu2 samba-common-bin=2:4.1.6+dfsg-1ubuntu2  \
  samba-dsdb-modules=2:4.1.6+dfsg-1ubuntu2 python-samba=2:4.1.6+dfsg-1ubuntu2  \
  libldb1=1:1.1.16-1 python-ldb=1:1.1.16-1


text:
Q: How can I set the Secure flag on an ASP.NET Session Cookie? How can I set the Secure flag on an ASP.NET Session Cookie, so that it will only be transmitted over HTTPS and never over plain HTTP?

A: Building upon @Mark D's answer I would use web.config transforms to set all the various cookies to Secure. This includes setting anonymousIdentification cookieRequireSSL and  httpCookies requireSSL.
To that end you'd setup your web.Release.config as:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
    <httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    <anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
  </system.web>
</configuration>

If you're using Roles and Forms Authentication with the ASP.NET Membership Provider (I know, it's ancient) you'll also want to set the roleManager cookieRequireSSL and the forms requireSSL attributes as secure too. If so, your web.release.config might look like this (included above plus new tags for membership API):
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
    <httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    <anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
    <roleManager xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
    <authentication>
        <forms xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    </authentication>
  </system.web>
</configuration>

Background on web.config transforms here: http://go.microsoft.com/fwlink/?LinkId=125889
Obviously this goes beyond the original question of the OP but if you don't set them all to secure you can expect that a security scanning tool will notice and you'll see red flags appear on the report. Ask me how I know. :)

A: Things get messy quickly if you are talking about checked-in code in an enterprise environment.  We've found that the best approach is to have the web.Release.config contain the following:
<system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
  <authentication>
      <forms xdt:Transform="Replace" timeout="20" requireSSL="true" />
  </authentication>
</system.web>

That way, developers are not affected (running in Debug), and only servers that get Release builds are requiring cookies to be SSL.

A: In the <system.web> element, add the following element:
<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.
In that case, you need to add the requireSSL="true" attribute to the forms element as well.
So you will end up with:
<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.

A: There are two ways, one httpCookies element in web.config allows you to turn on requireSSL which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.
Edit for clarity:
Put this in <system.web>
<httpCookies requireSSL="true" />

A: secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.


text:
Q: headerTintColor ignored for back button in iOS15 (react-navigation v5) The value headerTintColor for the back button is being ignored in iOS 15 and instead uses the system standard blue color.  The Title and Header Right buttons still respect the value that I pass in.  I am using react-navigation v5 and I am trying to avoid upgrading to v6 right now, if I can avoid it. (And I don't know if this is happening in v6 or not?).  This occurs on both the device and the simulator.
iOS 15 (via Simulator):
screenshot from iOS 15 showing blue-colored back button
iOS <= 14 (via Simulator):
screenshot from iOS 13 showing white colored back button
 <Stack.Navigator
      initialRouteName="EventList"
      screenOptions={{gestureEnabled: true}}>
      <Stack.Screen
        name="EventListScreen"
        component={EventTabs}
        options={({navigation}) => ({
          title: parametersBand.APP_NAME,
          headerTintColor: colors.NAV_TEXT_COLOR,
          headerStyle: styles.navBar,
          headerTitleStyle: styles.navBarTextStyle,
          headerTitleAllowFontScaling: false,
          headerRight: () => (
            <HeaderRightContainer>
              <HeaderRightButton
                onPress={() =>
                  analytics()
                    .logEvent('extras')
                    .then(() => navigation.navigate('Extras'))
                }
                hitSlop={hitSlop}>
                <FontAwesome name="bars" style={styles.navBarButtonHamburger} />
              </HeaderRightButton>
            </HeaderRightContainer>
          ),
          headerBackAllowFontScaling: false,
          headerBackTitle: null,
          headerBackTitleVisible: false,
          backgroundColor: colors.PRIMARY,
          borderBottomWidth: 0,
        })}
      />
      <Stack.Screen
        name="EventDetailScreen"
        component={EventDetail}
        options={({route, navigation}) => ({
          title: route.params.event.title,
          headerTintColor: colors.NAV_TEXT_COLOR,
          headerStyle: styles.navBar,
          headerTitleStyle: styles.navBarTextStyle,
          headerTitleAllowFontScaling: false,
          headerRight: () => (
            <HeaderRightContainer>
              <HeaderRightButton
                onPress={() =>
                  analytics()
                    .logEvent('setlist', {
                      event: `${route.params.event.YYYYMMDD} ${route.params.event.altName}`,
                    })
                    .then(() =>
                      showBrowser(
                        navigation,
                        route.params.event.setlistURL,
                        parametersBand.SETLIST_TITLE,
                      ),
                    )
                }
                hitSlop={hitSlop}>
                <HeaderRightButtonText
                  style={styles.navBarButtonRight}
                  allowFontScaling={false}>
                  Setlist
                </HeaderRightButtonText>
              </HeaderRightButton>
            </HeaderRightContainer>
          ),
          headerBackAllowFontScaling: false,
          headerBackTitle: null,
          headerBackTitleVisible: false,
          backgroundColor: colors.PRIMARY,
          borderBottomWidth: 0,
        })}
      />
</Stack.Navigator>

Has anyone else encountered and fixed this yet?

A: I'm sure you fixed this by now but just in case anyone else runs into this, as I just did.
The tint color for the back button is handled by the theme so you can override theme.colors.primary to change the tint color for the button and title text.
<NavigationContainer theme={{
  ...DefaultTheme,
  colors: {
    ...DefaultTheme.colors,
    primary: 'custom color here'
  }}
>
  {...}
</NavigationContainer>


text:
Q: Query to select records belonging only to ID and SUB-ID I'm trying to construct a query to return only the records related to a given ID and SUB-ID. In case the condition is not met I would like to return the second possibility, i.e, the second combination ID, Sub-ID. Note: The data has thousands of IDs, but only 2 Sub-Ids per ID.
This is an example of input records:
    ID    |  Sub-id  | VALUE
  ------------------------------
     1    |     1    |  "T"
  ------------------------------
     1    |     1    |  "F"
  ------------------------------
     1    |     2    |  "Z"
  ------------------------------
     1    |     2    |  "G"

The desired output is:
    ID    |  Sub-id  | VALUE
  ------------------------------
     1    |     1    |  "T"
  ------------------------------
     1    |     1    |  "F"
  ------------------------------

If we only have records related to the second combination for a given ID, the output should be:
    ID    |  Sub-id  | VALUE
  ------------------------------
     1    |     2    |  "Z"
  ------------------------------
     1    |     2    |  "G"

I tried to get this via a CTE expression, but I was not successful. This approach led to returning only one record given my condition.
My try:
 WITH CTE (ID,SUB-ID,DuplicateCount,VALUE) AS (
    SELECT
        ID,
        Sub-id,
        ROW_NUMBER () OVER (PARTITION BY ID
        ORDER BY SUB-ID) as DUPLICATECOUNT,
        VALUE
    FROM TBL_SOURCE

What am I missing out?

A: If I follow you correctly, you want rank() rather than row_number():
select *
from (
    select t.*, rank() over(partition by id order by subid) rn
    from mytable t
) t
where rn = 1

rank() assigns the same number to records that have the same id and subid, as opposed to row_number(), which guarantees the uniqueness of the sequence.

A: If you want this for only a given id, you can use top with ties:
select top (1) with ties t.*
from t
where id = 1
order by subid;


text:
Q: How to pass Image and Some data as a parameter to web API Controller through Jquery Ajax I am trying to pass topicmedia and image file to web api post controller through jquery ajax. but not accomplish this task i am trying this from last 2 days. please any one tell this.
Ajax Code Here
Web API Controller Action Here i want to get data and image
$('#add').click(function () {
var topicmedia = {"topicid":"","createon":""};
            topicmedia.topicid = 1;
            topicmedia.createon = $('#txtCreateOn').val();
            var data = new FormData();
            var file = $("#img").get(0).files;
            data.append("file", file);
            debugger;
            $.ajax({
                url: 'http://localhost:4728/api/TopicMedias',
                method: 'POST',
                contentType: 'multipart/form-data',
               // processData: false,
                data: JSON.stringify(topicmedia, file),
                dataType: 'json',
                success: function () {
                    $('#successfullModel').modal('show');
                }
      });
  });

that is the code of web api where i want to get 2 parameters topicmedia which contain topicid and createon data and file parameter recive image
  public IHttpActionResult PostTopicMedia(TopicMedia topicMedia, HttpPostedFile files)
    {
        return null;
    }

}
After geting the image and data in web api action i want to save image in folder and other data and image path want to save in database table topicmedia which have datapath, topicid and createOn field.

A: public async Task<HttpResponseMessage> PostImage()
{
    Dictionary<string, object> dict = new Dictionary<string, object>();
    var httpRequest = HttpContext.Current.Request;
    foreach (string file in httpRequest.Files)
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
        var postedFile = httpRequest.Files[file];
        if (postedFile != null && postedFile.ContentLength > 0)
        {
            IList<string> AllowedFileExtensions = new List<string>{".jpg", ".png"};
            var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
            var extension = ext.ToLower();
            if (!AllowedFileExtensions.Contains(extension))
            {
                var message = string.Format("Please Upload image of type .jpg, .png.");
                dict.Add("error", message);
                return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
            }
            else
            {
                var filePath = HttpContext.Current.Server.MapPath("~/yourDirectory/" + postedFile.FileName + extension);
                postedFile.SaveAs(filePath);
            }
        }

        var successMsg = string.Format("Image Updated Successfully.");
        return Request.CreateErrorResponse(HttpStatusCode.Created, successMsg);
    }

    var res = string.Format("Please Upload a image.");
    dict.Add("error", res);
    return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}


text:
Q: Call webservice works from IE, not from Chrome or Firefox I have a webservice in the same domain of my site. I have an ajax call to consult that webservice and works fine from IE but from Chrome and Firefox, I cannot make it work.
My ajax call is:
       $.ajax({
        type: 'POST',
        async: false
        data: xml,
        url: url,
        dataType: "xml",
        success: function (data, textStatus, XmlHttpRequest) {
           //On sucess action
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
           //On error action
        },
        headers: {
            "Content-Type": "text/xml; charset=utf-8",
            "SOAPAction": soapAction,
            "Content-Length": xml.length + 1
        }
    });

But from chrome and firefox I receive:
 XMLHttpRequest cannot load https://mydomain:83/<webservice>/<webservice>.asmx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://mydomain' is therefore not allowed access. The response had HTTP status code 500.

I add to the webconfig:
   <system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="https://mydomain"/>
    <add name="Access-Control-Allow-Origin" value="http://mydomain"/>
    <add name="Access-Control-Allow-Credentials" value="true"/>
  </customHeaders>
</httpProtocol>

But no luck. Any idea what am I missing?

A: I gave up to soon. In my particular case, this do the trick for Chrome and Firefox
 <add name="Access-Control-Allow-Origin" value="https://mydomain" />
 <add name="Access-Control-Allow-Headers" value="Content-Type, SOAPAction" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />


text:
Q: Replace array inside object - Reducer I have an array of elements which was updated inside an action, now I want to update it in the store. Currently I have something like:
navigation
|_navigationItems:[{1:"foo"}, {2:"bar"}, {3:"foobar"}]

The thing is I was doing the following:
case types.UPDATE_NAVIGATION:
  return Object.assign({}, state, {
    navigationItems: action.payload.items,
  });

where items is: [{1:"zoo"}, {2:"foobar"}]
but store was not updated succesfully.
Did I miss something?

A: React docs suggest on using the spread operator syntax over Object.assign
Use:
case types.UPDATE_NAVIGATION:
     return {
         ...state, navigationItems: action.payload.items
     }


text:
Q: ElasticSearch won't search specific field I have a problem searching a specific field inside my index.
little background:
On my project we need to search inside a terminology Server like FHIR but then our own.
So we have an object that contains a Code (123564/A), multiple translations as term/display (urine problem) and mapping to other codes that are equal to that code but in a different system (ICD-10, SNOMED-CT, ICPC-2,..) example what has been indexed:
{
"Code": "10008220/A1",
"EffectiveTime": "0001-01-01T00:00:00Z",
"Active": true,
"System": "ibui",
"Purpose": "",
"Descriptions": [
    {
        "DescriptionId": "2464cf5c-d4fc-4a61-b6bc-746d003cb4ef",
        "Code": "10008220/A1",
        "System": "ibui",
        "Term": "gebroken arm",
        "LanguageId": "3d50c237-0add-43e7-92a2-5edf1ac7c6ee",
        "FSN": false,
        "Preferred": true,
        "EffectiveTime": "0001-01-01T00:00:00Z",
        "Active": true,
        "SendVersion": "2021-12-07T17:01:53.786755Z",
        "Purpose": ""
    },
    {
        "DescriptionId": "95501583-9f24-4964-bbc9-1a6e95eba30f",
        "Code": "10008220/A1",
        "System": "ibui",
        "Term": "fracture du bras",
        "LanguageId": "1238dde0-08df-4ae0-8676-59919f66737e",
        "FSN": false,
        "Preferred": true,
        "EffectiveTime": "0001-01-01T00:00:00Z",
        "Active": true,
        "SendVersion": "2021-12-07T17:01:53.786755Z",
        "Purpose": ""
    }
],
"Mappings": [
    {
        "MappingId": "",
        "FromSys": "ibui",
        "From": "10008220/A1",
        "ToSys": "icd-10",
        "To": "T10",
        "EffectiveTime": "0001-01-01T00:00:00Z",
        "Active": true
    },
    {
        "MappingId": "",
        "FromSys": "ibui",
        "From": "10008220/A1",
        "ToSys": "icpc-2",
        "To": "L76",
        "EffectiveTime": "0001-01-01T00:00:00Z",
        "Active": true
    }
],
"SendVersion": "2021-12-07T17:01:53.786755Z"

}
The problem:
We can search on 2 different fields : Code & Term. and when searching we keep in mind that we have some filters for a specific language code (Dutch,..) or A system like ICD-10 or ICPC-2,..
I have a query that is working and returns the above object when searching in 1 field (Descriptions.Term) that is the following:
working query
 {
  "query": {
    "bool": {
      "must": {
        "nested": {
          "inner_hits": {
            "highlight": {
              "fields": {
                "*": {}
              }
            }
          },
          "path": "Descriptions",
          "query": {
            "bool": {
              "should": [
                {
                  "multi_match": {
                    "fields": [
                      "Descriptions.Term",
                      "Descriptions.Term._2gram",
                      "Descriptions.Term._3gram"
                    ],
                    "query": "gebroken*~ n",
                    "type": "bool_prefix"
                  }
                }
              ],
              "filter": [
                {
                            "bool": {
                                "should": [
                                    {
                            "term": {
                                    "Descriptions.System": "ibui"
                                    }
                            },{
                            "term": {
                                    "Descriptions.System": "icd-10"
                                    }
                            },{
                            "term": {
                                    "Descriptions.System": "icpc-2"
                                    }
                            }
                                ],
                                "minimum_should_match": "1"
                                }
                            },

                {
                            "term": {
                                    "Descriptions.Active": "true"
                                    }
                            },
                {
                  "term": {
                    "Descriptions.LanguageId": "3d50c237-0add-43e7-92a2-5edf1ac7c6ee"
                  }
                }
              ]
            }
          }
        }
      }

    }
  }
}

But when we somethings need to search in multiple fields.
When adding the Descriptions.Code field to the fields map the query is not working and I can't figure out why. I have it decleared inside my mapping so it should be searchable?
I'm searching for the Code of the object above in both fields (Descriptions.Term & Descriptions.Code) but it doesn't returns the hit.
not working query
    {
  "query": {
    "bool": {
      "must": {
        "nested": {
          "inner_hits": {
            "highlight": {
              "fields": {
                "*": {}
              }
            }
          },
          "path": "Descriptions",
          "query": {
            "bool": {
              "should": [
                {
                  "multi_match": {
                    "fields": [
                      "Descriptions.Term",
                      "Descriptions.Term._2gram",
                      "Descriptions.Term._3gram",
                      "Descriptions.Code"
                    ],
                    "query": "10008220*~ n",
                    "type": "bool_prefix"
                  }
                }
              ],
              "filter": [
                {
                            "bool": {
                                "should": [
                                    {
                            "term": {
                                    "Descriptions.System": "ibui"
                                    }
                            },{
                            "term": {
                                    "Descriptions.System": "icd-10"
                                    }
                            },{
                            "term": {
                                    "Descriptions.System": "icpc-2"
                                    }
                            }
                                ],
                                "minimum_should_match": "1"
                                }
                            },

                {
                            "term": {
                                    "Descriptions.Active": "true"
                                    }
                            },
                {
                  "term": {
                    "Descriptions.LanguageId": "3d50c237-0add-43e7-92a2-5edf1ac7c6ee"
                  }
                }
              ]
            }
          }
        }
      }

    }
  }
}

mapping:
    {
    "settings": {
        "number_of_shards": 1,
        "analysis": {
            "analyzer": {
                "autocomplete": {
                    "tokenizer": "custom_tokenizer"
                }
            },
            "tokenizer": {
                "custom_tokenizer": {
                    "type": "ngram",
                    "min_gram": 2,
                    "max_gram": 6,
                    "token_chars": [
                        "letter",
                        "digit",
                        "symbol",
                        "punctuation"
                    ]
                }
            }
        },
        "max_ngram_diff" : "5"
    },
  "mappings": {
    "properties": {
      "Descriptions": {
        "type": "nested",
        "properties": {
          "Term": {
            "type": "search_as_you_type",
            "analyzer": "autocomplete"
          },
          "Code": {
            "type": "keyword",
            "index": true
          },
          "System": {
            "type": "keyword",
            "index": true
          },
          "LanguageId": {
            "type": "keyword",
            "index": true
          },
          "Purpose": {
            "type": "keyword",
            "index": true
          },
          "Active": {
            "type": "keyword",
            "index": true
          }
        }
      },
      "Mappings": {
        "properties": {
          "To": {
            "type": "keyword",
            "index": true
          },
          "ToSys": {
            "type": "keyword",
            "index": true
          }
        }
      }
    }
  }
}

Thank you for helping me out!


text:
Q: Implementing let! ... and! ... in a custom Computation Expression I want to add support to my Computation Expression builder for this construct:
let f =
  foo {
    let! x =
      foo {
        return 1
      }
    and! y =
      foo {
        return 2
      }

    return x + y
  }

The compiler says I must implement either Bind2 or MergeSource. However, I cannot find them in the docs.
What signatures should these have? Can you give a simple example?

A: Here's a simple builder that works with your example:
type Foo<'t> = MkFoo of 't

type FooBuilder() =
    member _.Bind(MkFoo x, f) = f x
    member _.Return(x) = MkFoo x
    member _.MergeSources(MkFoo x, MkFoo y) = MkFoo (x, y)

let foo = FooBuilder()

let f =
    foo {
        let! x = foo { return 1 }
        and! y = foo { return 2 }
        return x + y
    }
printfn "%A" f   // output: MkFoo 3

The purpose of MergeSources is to create a tuple of results that will be automatically de-tupled by the compiler. You might also find this example and this SO question useful.


text:
Q: Fill null values with next incrementing number | PySpark | Python I am having below dataframe with values. I want to add next concecative id in the column id which must be unique as well incrementing in nature.
+----------------+----+--------------------+
|local_student_id|  id|        last_updated|
+----------------+----+--------------------+
|          610931|null|                null|
|          599768|   3|2020-02-26 15:47:...|
|          633719|null|                null|
|          612949|   2|2020-02-26 15:47:...|
|          591819|   1|2020-02-26 15:47:...|
|          595539|   4|2020-02-26 15:47:...|
|          423287|null|                null|
|          641322|   5|2020-02-26 15:47:...|
+----------------+----+--------------------+

I want below expected output. can anybody hemp me? I am new to Pyspark. and also want to add current timestamp in last_updated column.
+----------------+----+--------------------+
|local_student_id|  id|        last_updated|
+----------------+----+--------------------+
|          610931|   6|2020-02-26 16:00:...|
|          599768|   3|2020-02-26 15:47:...|
|          633719|   7|2020-02-26 16:00:...|
|          612949|   2|2020-02-26 15:47:...|
|          591819|   1|2020-02-26 15:47:...|
|          595539|   4|2020-02-26 15:47:...|
|          423287|   8|2020-02-26 16:00:...|
|          641322|   5|2020-02-26 15:47:...|
+----------------+----+--------------------+

actually i tried
final_data = final_data.withColumn(
        'id', when(col('id').isNull(), row_number() + max(col('id'))).otherwise(col('id')))

but it gives the below Error:-
: org.apache.spark.sql.AnalysisException: grouping expressions sequence is empty, and '`local_student_id`' is not an aggregate function. Wrap '(CASE WHEN (`id` IS NULL) THEN (CAST(row_number() AS BIGINT) + max(`id`)) ELSE `id` END AS `id`)' in windowing function(s) or wrap '`local_student_id`' in first() (or first_value) if you don't care which value you get.;;

A: here is the code you need :
from pyspark.sql import functions as F, Window

max_id = final_data.groupBy().max("id").collect()[0][0]

final_data.withColumn(
    "id",
    F.coalesce(
        F.col("id"),
        F.row_number().over(Window.orderBy("id")) + F.lit(max_id)
    )
).withColumn(
    "last_updated",
    F.coalesce(
        F.col("last_updated"),
        F.current_timestamp()
    )
)


text:
Q: String.ValueOf() to replace NULL with string null when calling a method I'm trying to use String.valueOf() to replace the null when i'm calling some method.But it still shows nullpointerexception. This may be simple but i'm missing something.
I have statement like this
myvar = this.kind.name().toLowerCase()

It is throwing java.lang.NullPointerException. Im trying to keep string "NULL" whenever i get NPE. so i tried this
myvar = String.valueOf(this.kind.name().toLowerCase()) -- not working

I have found from other posts that it may not work as we have overloaded method String.valueOf(char[]) and String.valueOf(object) and suggested to use below. But still it s not working. How do i assign string null in this case?
myvar = String.valueOf((this.kind.name().toLowerCase()) null))

A: If this.kind is null, you should be able to determine that from the stacktrace.
You can handle the situation by adding an if-condition or code like
String.valueOf(this.kind == null ? null : this.kind.name()).toLowercase()

A: You should be using
myvar = String.valueOf(this.kind.name()).toLowerCase();

not
myvar = String.valueOf(this.kind.name().toLowerCase());

As documentation of valueOf() describes

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned

So,String.valueOf(this.kind.name()) would return "null"


text:
Q: How to add existing named_scope to anonymous scope? I have a model:
class Shirt < ActiveRecord::Base
  named_scope :red, :conditions => { :color => 'red' }
  named_scope :blue, :conditions => { :color => 'blue' }
  named_scope :xl,  :conditions => { :size  => 'xl'  }
end

I forgot, how to easy add named scope to existing anonymous scope:
scope = Shirt.scoped({})
#and how to add ie. :red to scope?

A: Shirt.scoped({}).red ?

A: This can be achieved with the following code:
named_scope :colour, lambda { |colour_id| {:conditions => ["colour_id = ?", colour_id])}}

You can chain named scopes:
Shirt.red.xl


text:
Q: Create dictionary where values are keys transformed to strings G is a graph object and sorted(G) returns a list of nodes:
[0,1,2...1860]

I need to rename those nodes mapping from a dictionary, like so:
mapping = {0: "0_cereb", 1: "1_cereb", 2: "2_cereb",..., 1860: "1860_cereb"}

And then I can apply dict to a method that relabels my graph:
import networkx as nx
Gnew = nx.relabel_nodes(G, mapping)

and sorted(Gnew)returns:
[0_cereb, 2_cereb, ..., 1860_cereb]

How do I create this mapping dict?

A: Use a dictionary comprehension to create the dictionary, and use string formatting to convert the numbers to the corresponding strings.
mapping = {x: f'{x}_cereb' for x in G}

A: The answer would be dict comprehension
mapping = {k: f"{k}_cereb" for k in sorted(G)}

will run through list and create key value pairs


text:
Q: Oracle database returns faulty rows from stored procedure using devart in C# I have an oracle database with a stored procedure:
PROCEDURE "CalculateChats"
  (
    "In_Conf" IN NUMBER,
    "In_From" IN TIMESTAMP,
    "In_To" IN TIMESTAMP,
    "Out_Cursor" OUT "Cursor"
  ) AS
  BEGIN
  OPEN "Out_Cursor" FOR
  SELECT
  TO_TIMESTAMP(SUBSTR("Started", 0, 13), 'yyyy-mm-dd hh24:MI' ) as "From",
  CAST(TO_TIMESTAMP(SUBSTR("Started", 0, 13), 'yyyy-mm-dd hh24:MI') + 1/24 AS TIMESTAMP) as "To",
  COUNT(*) as "Chats"
  FROM "SomeTableContainingChats"
  WHERE "Conf" = "In_Conf"
  AND "Started" >= "In_From"
  AND "Started" <= "In_To"
  GROUP BY SUBSTR("Started", 0, 13)
  ORDER BY SUBSTR("Started", 0, 13) ASC;
  END "CalulateChats";

When run, the stored procedure gives me a table [ From | To | NrOfOfferedChats ]
The dates are correct compared to the values.
(Example)
[ From                         | To                            | Chats ]
2014-09-15 08:00:00,000000000   2014-09-15 09:00:00,000000000   61
2014-09-15 09:00:00,000000000   2014-09-15 10:00:00,000000000   96
2014-09-15 10:00:00,000000000   2014-09-15 11:00:00,000000000   113
2014-09-15 11:00:00,000000000   2014-09-15 12:00:00,000000000   80

Now i pick it up from the C# code:
 using (var oraclePackage = new OraclePackage())
        {
            oraclePackage.Connection = DbConnection;
            oraclePackage.PackageName = @"CHAOS.""HiddenPackageName""";

            oraclePackage.Parameters.AddWithValue("In_Conf", conf);
            oraclePackage.Parameters.AddWithValue("In_From", from);
            oraclePackage.Parameters.AddWithValue("In_To", to);
            oraclePackage.Parameters.AddWithValue("Out_Cursor", null).Direction = ParameterDirection.Output;
            oraclePackage.Parameters["Out_Cursor"].OracleDbType = OracleDbType.Cursor;

            oraclePackage.ExecuteProcedure(@"""CalculateChats""", oraclePackage.Parameters, true);

            using (OracleDataReader oracleReader = ((OracleCursor)oraclePackage.Parameters["Out_Cursor"].Value).GetDataReader())
            {
                if (oracleReader.HasRows)
                {
                    while (oracleReader.Read())
                    {
                       oracleReader;
                    }
                }
            }
        }

And the data from the oracle is oracleReader = From: 0015-09-14 01:00:00,000000000, To: 0015-09-14 02:00:00,000000000, Chats: 80
Now for the question: What could be a possible cause for the alteration from the database to the C# code, and any suggestion on how to solve it would be apreciated.

A: After throwing this arround for 2 days i found out
CAST(TO_TIMESTAMP(SUBSTR("Started", 0, 13), 'yyyy-mm-dd hh24:MI') + 1/24 AS TIMESTAMP)

Was converting the timestamp from 2014-09-16 08:00:00 to 16-SEP-14 02:00:00 i'm still not aware why it was converted that way but:
CAST(TO_CHAR("Started", 'YYYY-MM-dd HH24') || ':00:00' AS TIMESTAMP)

Seemed to solve the problem.


text:
Q: How to authenticate in Remedy using Java I need to authenticate myself in Remedy. I'm following the documentation, but I still getting some errors.
https://communities.bmc.com/docs/DOC-17514
This is my code:
import com.bmc.arsys.api.ARException;
import com.bmc.arsys.api.ARServerUser;

public class Tutorial {
    public static void main(String[] args) {
        ARServerUser ctx = new ARServerUser();
        ctx.setServer("127.0.0.1");
        ctx.setUser("myusername");
        ctx.setPassword("mypassword");
        ctx.setPort(8080);

        try {
            ctx.verifyUser();
        } catch (ARException e) {
            System.out.println(e.getMessage());
        }
    }
}

I'm receiving this error:
ERROR (91): RPC call failed; 127.0.0.1:8080 can not receive ONC/RPC data
How can I fix that? I need to set the instance, like 127.0.0.1/arsys. My Remedy instance is arsys.
I can authenticate using the browser: http://127.0.0.1:8080/arsys
Thanks in advance.

A: is your midtier on the same server as your AR server?
if not, then You need to set the IP of your AR server instead.

A: Since you have mentioned that you are able to authenticate using http://127.0.0.1:8080/arsys via browser, it means that 8080 is being used by web server and AR Server can't use the same. Please provide your port number(where your AR Server is listening) in setPort(). Also try to make sure that your hostname/ip address is reachable from the machine where you are executing your program.

A: The setServer parameter expects the name of the ARS server, not the IP address. Here is the matching constructor signature:
ARServerUser(java.lang.String user, java.lang.String password, java.lang.String locale, java.lang.String serverName, int serverPort)

References

*

*com.remedy.arsys.api.ARServerUser

*How to authenticate in Remedy using Java


text:
Q: Spectrogram for image classification I am currently trying to replecate the paper: https://www.frontiersin.org/articles/10.3389/fneur.2019.00806/full
They achieve above 90% acc
Database: https://physionet.org/content/chbmit/1.0.0/
However this seems more challenging than i thought. The data i'm using consists of EEG with a sampling rate of 256 hz.
I've read that with epilepsy and EEG the most appearent difference between seizure and no-seizure is to be found at the lower frequencies therefore i have implemented a low pass filter using scipy:

My windows consists of 4 seconds of data = 4*256 = samples. Below i have the raw data and when filter is applied:

I have tried many different configurations to create my spectrograms for the cnn (this is the latest):
Fs = 256
interval = 128   # ... the interval size,
overlap = interval * 0.95  # ... and the overlap intervals

import matplotlib.colors as colors
from scipy.stats import lognorm
#plt.ylim(0, 10)
f, t, Sxx = signal.spectrogram(
    np.array(filtered),                # Provide the signal,
    fs=Fs,                # ... the sampling frequency,
    nperseg=interval,
    noverlap=overlap, mode='psd')

#Sxx = 10 * np.log10(Sxx)
normalize_color= colors.LogNorm(vmin=np.amin(Sxx), vmax=np.amax(Sxx))
                          # ... the number of samples to overlap,
plt.pcolormesh(t, f, Sxx, norm=normalize_color,
            cmap='jet')# Plot the result

which outputs the following (something weird going on at the highest freqs):

My problem is that when i use these different spectrograms as input i cannot achieve a validation acc above 50-60%. I've tried increasingly using dropout, data augmentation, reducing learning rate and different networks (resnet, inception, vgg16, effiecency net + my own shallow model)
During training i undersample my data so i have an equal amount of seizure non seizure data. I have been implementing an overlaping window function to generate more seizure data. I have around 2000 images of each class.
Here's my custom cnn:
model = Sequential()

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',
                        input_shape=(299,299,3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dropout(0.2))
model.add(layers.Dense(3, activation='softmax'))

It seems like something is wrong with my input. Is 1028 samples in a window not enough for FFT Spectrograms?

A: Comments contains the answer. he Fs, interval and overlap_interval are very important, they affect you signal a lot . The same with your low pass filter. I dont think there is anything wrong with the code here. You just need to play around with the parameters. I dont even think that the problem is with the CNN. You need to prepare the data carefully. What is the correct data prepossessing, I cant tell you you have to play with the data and find it. It seems that you are heavily manipulating your data, so be careful that you are not chopping or distorting information from the original signal. The code is fine.


text:
Q: Can I add script to SignUP & SignIn combined? I tried add custom fields into SUSI via Javascript, but won't work...  If I remove AllowExecution tag on SUSI XML it works...
Error raised on chrome dev tools:
Access to XMLHttpRequest at 'https://ctpocb2cgol.blob.core.windows.net/CTB2CPOCGOL.onmicrosoft.com/B2C_1A_Social_SUSI/client/perftrace?tx=StateProperties=eyJUSUQiOiJmMjQzMmJiNi0zODlhLTQ1NzMtODhhZC05NDhhYTk5YjI1YmYifQ&p=B2C_1A_Social_SUSI' from origin 'https://ctb2cpocgol.b2clogin.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
unified?local=signup&csrf_token=Wmo4aEx6OVpMNFJ4TTlhZjdJKzd3RVRpUjViOEZ3ZDEzdzZaN2VjYTNyRm1RVXh5N3ArZHkvNkJubFVaM2Jod2N5U3BzOEQyYys5TEpYazA5Um5PSGc9PTsyMDIwLTA5LTEwVDEyOjUxOjU4LjQyNzA2OTZaO2d1azJoUlVJRm9qMTV1bEhaUzQ0NHc9PTt7Ik9yY2hlc3RyYXRpb25TdGVwIjoxfQ==&tx=StateProperties=eyJUSUQiOiJmMjQzMmJiNi0zODlhLTQ1NzMtODhhZC05NDhhYTk5YjI1YmYifQ&p=B2C_1A_Social_SUSI:202

POST https://ctpocb2cgol.blob.core.windows.net/CTB2CPOCGOL.onmicrosoft.com/B2C_1A_Social_SUSI/client/perftrace?tx=StateProperties=eyJUSUQiOiJmMjQzMmJiNi0zODlhLTQ1NzMtODhhZC05NDhhYTk5YjI1YmYifQ&p=B2C_1A_Social_SUSI net::ERR_FAILED

SignIn screen


text:
Q: Trying to update Android SDK In trying to update my SDK to the latest, some things installed, but others* didn't.
*SDK Platform Android 4.0, API14, revision 3
Google APIs by Google Inc., Android API15 revision 1
Google APIs by Google Inc., Android API14 revision 2
Sources for Android SDK, API14, revision 1

I got this err msg:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-= Warning ! =-
A folder failed to be moved. On Windows this typically means that a program is uing that folder (for example Windows Explorer or your anti-virus software.)
Please momentarily deactivate your anti-virus software or close any running programs that may be accessing the directory 'C:\Program Files (x86)\Android\android-sdk\platforms\android-14'.
When ready, press YES to try again.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Even after manually stopping a McAfee service and MS Malware service (MS Security Essentials) via
Task Manager, I still got this err msg.
The error highlighted (in brick red) in the Android SDK Manager Log is:
Failed to rename C:\Program Files (x86)\Android\android-sdk\platforms\android-14 to C:\Program Files (x86)\Android\android-sdk\temp\PlatformPackage.old01.

*

*Is this something I should do manually - would that allow the update to take place?

A: If you started the update from eclipse, it might help to exit eclipse, and go to your sdk/utils directory and start de SDKmanager from there. This worked for me after I got the same message today.

A: I don't  know if this will help but generally a few things might cause problems like:
Having a device connected or the emulator running.
Forgetting to run the Android SDK tool as Administrator.
Some errors can occur with the windows "program files (x86)" path. I tend to just move the Android folder to the root C path so the SDK would be at C:\Android
If you've covered all that then I'm not sure. It should usually just work without you having to do anything else.

A: That is the answer. C:\Program Files is protected against user modification.
Unfortunately, the SDK Manager does not escalate it's privileges. That would be a nice addition to the Windows version.


text:
Q: Error opening 2 excel files using Aspose.Cells on Mono I'm writing a small program using Mono and Aspose.Cells. I stack with the problem, that Aspose.Cell don't open 2 excel files in one project. Here is my code:
    protected string GetCellValue(string excelFileName, int row, int cell)
    {
        string cellValue = null;
        Workbook wb = new Workbook (excelFileName);
        Worksheet sheet = wb.Worksheets[0];
        if (sheet.Cells [row, cell].Value != null) {
            cellValue = sheet.Cells [row, cell].Value.ToString ();
        }
        sheet = null;
        wb.Dispose ();
        GC.Collect ();
        return cellValue;
    }

    protected static int GetRowCount(string anotherExcelFileName)
    {
        int count = 0;
        Workbook wb = new Workbook (anotherExcelFileName);
        Worksheet sheet = wb.Worksheets[0];
        count = sheet.Cells.Rows.Count;
        return count;
    }


text:
Q: Are there plans for a scope for Personal Information Management? For Ubuntu touch/phone there are a number of core apps for different purposes like calendar, contacts, notes, etc. Unfortunately there's no scope to combine these seperate apps into a single "Personal Information Management"-Environment like for example Thunderbird, MS Outlook or Open-Xchange.
Are there plans to get there someday?

A: Today scope is mean to be "personal information manager". You can select  (in options)  displaying upcoming events (calendar), favorite contacts, upcoming tasks (notes) recent msg, calls and many more (etc).  It would not be fair to compare this to Thunderbird or Outlook yet, but it's so far ubuntu's best way of managing daily personal information.


text:
Q: Missing "six" module for astropy after using cx_freeze/py2exe I was trying to convert program written in python 3 to .exe using cx_freeze and py2exe. But after converting and running program i get the following error:
Traceback (most recent call last):
  File "astroConverter.py", line 8, in <module>
  File "C:\Users\Konrad\PycharmProjects\astroConverter\mainwindow.py", line 2, in <module>
    from widgets.widgets import MainMenu, Toolbar, TextField
  File "C:\Users\Konrad\PycharmProjects\astroConverter\widgets\widgets.py", line 1, in <module>
    from widgets.menus import FileMenu, EditMenu, HelpMenu
  File "C:\Users\Konrad\PycharmProjects\astroConverter\widgets\menus.py", line 2, in <module>
    from common import Info
  File "C:\Users\Konrad\PycharmProjects\astroConverter\common.py", line 2, in <module>
    from astropy.io import fits
  File "C:\Python34\lib\site-packages\astropy\__init__.py", line 73, in <module>
    _check_numpy()
  File "C:\Python34\lib\site-packages\astropy\__init__.py", line 61, in _check_numpy
    from .utils import minversion
  File "C:\Python34\lib\site-packages\astropy\utils\__init__.py", line 15, in <module>
    from .codegen import *
  File "C:\Python34\lib\site-packages\astropy\utils\codegen.py", line 15, in <module>
    from .introspection import find_current_module
  File "C:\Python34\lib\site-packages\astropy\utils\introspection.py", line 14, in <module>
    from ..extern import six
  File "C:\Python34\lib\site-packages\astropy\extern\six.py", line 60, in <module>
    _import_six()
  File "C:\Python34\lib\site-packages\astropy\extern\six.py", line 57, in _import_six
    "distribution.".format(_SIX_MIN_VERSION))
ImportError: Astropy requires the 'six' module of minimum version 1.7.3; normally this is bundled wi
th the astropy package so if you get this warning consult the packager of your Astropy distribution.
This is my cx_freeze setup.py script:
import sys
from cx_Freeze import setup, Executable

buildExeOptions = {"packages": ["astropy", "numpy", "matplotlib"],
                   "includes": ["six"],
                   "silent": ["-s"]}

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'
setup(name='astroConverter',
      version="0.4",
      description="Format converter used in astronomy",
      options={"build_exe": buildExeOptions},
      executables=[Executable("astroConverter.py", base=base)]
      )

and py2exe script:
from distutils.core import setup
import py2exe
setup(console=['astroConverter.py'])

Here is output for pip freeze:
C:\WINDOWS\system32>pip freeze
astropy==1.0.1
cx-Freeze==4.3.4
matplotlib==1.4.3
numpy==1.9.2
py2exe==0.9.2.2
pyparsing==2.0.3
python-dateutil==2.4.1
pytz==2015.2
six==1.9.0
UNKNOWN==0.0.0
virtualenv==13.1.0

As you can see, my six module is in newer version than required by astropy.
Strange thing is, i have all packages properly installed, and while running python astroConverter.py everything works fine. This is GUI application (it's using tkinter). Does anyone know how can i force cx_freeze or py2exe to properly include "six" module?


text:
Q: Backbone on Rails how to add a model to a collection from different views? I'm developing a Rails app using Rails 3, and the backbone-on-rails gem.
I have a backbone route which shows ProductTypes. It has a backbone view for the list, and a view for the form, so the usar can add new ProductTypes.
Everything works ok, but when I try to add the created model from the form view to the collection on the list view. I don't know how to connect both views.
Here's my route:
class Newgvbtool.Routers.ProductTypes extends Backbone.Router
  routes:
    'companies/:company_id/product_types': 'index'

  initialize: ->
    @container = $('#product-types-view')
    @company_id = @container.data 'company_id'
    @collection = new Newgvbtool.Collections.ProductTypes([],{ company_id: @company_id })
    @collection.fetch()

  index: (company_id) ->
    view = new Newgvbtool.Views.ProductTypesIndex(collection: @collection)
    @container.append view.render().el

    newModel = new Newgvbtool.Models.ProductType({ company_id: @company_id })
    editView = new  Newgvbtool.Views.ProductTypeEdit model: newModel
    @container.append editView.render().el

Her's my model:
class Newgvbtool.Models.ProductType extends Backbone.Model
  initialize: (model)->
    @company_id = model.company_id
    @id = model.id
  url: ()->
    "/api/companies/#{@company_id}/product_types/" + (@id || '')

Here are my views:
# Collection view
class Newgvbtool.Views.ProductTypesIndex extends Backbone.View

  template: JST['product_types/index']

  events: ->

  initialize: ->
    @collection.on 'reset', @render
    @collection.on 'add', @appendItem
    @collection.on 'remove', @removeItem

  render: =>
    $(@el).html @template()
    @collection.each @appendItem
    @

  appendItem: (model)=>
    view = new Newgvbtool.Views.ProductType model: model
    $('#product-types tbody').append(view.render().el)

  removeItem: (model)=>
    $('#product-types tbody').find("tr[data-id=#{model.get('id')}]").remove()

 #Item view
 class Newgvbtool.Views.ProductType extends Backbone.View

  template: JST['product_types/product_type']
  tagName: 'tr'

  events:
    'click .delete-item': 'deleteItem'

  initialize: ->
    @model.on 'highlight', @highlight
    @model.on 'change', @render

  render: =>
    $(@el).attr('data-id', @model.get('id')).html @template( model: @model)
    @

  highlight: =>
    @$('td').effect 'highlight', 1000

  deleteItem: ->
    @model.destroy(
      wait: true
    ) if confirm "Are you sure?"

#Form view
class Newgvbtool.Views.ProductTypeEdit extends Backbone.View

  template: JST['product_types/edit']

  render: =>
    $(@el).html @template( model: @model )
    @

  events: ->
    'submit #product-type-form': 'createProductType'

  createProductType: (e) ->
    e.preventDefault()

    attributes = $(e.currentTarget).serializeForm()['product_type']

    @model.save attributes,
      wait: true
      success: (model)->
        $('#product-type-form')[0].reset()
        model.trigger('highlight')

Is there a way so when a new model is saved in the form view I can actually add that model to the main collection so the add event is triggered and this new model appears in the collection's view?
And in the case of updating items, can I do the reverse operation, setting the model selected in the list into the form so it can be updated and those changes reflected into the collection's view?
Thank you very much in advance!

A: I would suggest that you create an event aggregator on your application so you can easily trigger a custom event on a view and a have a listener on another one reacting to it.
Here is a link to Derick Bailey post where he explains how this works and gives a couple of ideas of how to implement them.
If you are using a main object to instantiate your application you could do something like this:
window.App =
 Models: {}
 Collections: {}
 Views: {}
 Routers: {}

 initialize: ->
  @vent = _.extend({}, Backbone.Events)
  # More code here

$(document).ready ->
  App.initialize()

Then, App.vent would be your event aggregator, and you can trigger events like this:
App.vent.trigger "model:add:success", @model

Here you trigger the "model:add:success" passing the model "@model". Then you can catch it somewhere else with:
initialize: ->
  App.vent.on "model:add:success", @appendModel, this


text:
Q: how to add key of object in array? Guys.
I have array like this
array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]

And I want to edit this array to
array = [ "A":{name:"A",data:"..."},"B":{name:"B",data:"..."},"C":{name:"C",data:"..."}

How could I set object key from its own value?

A: Try this:
console.log(array.map(el => ({[el.name]: el})));

A: For getting an object, you could take Object.fromEntries with the mapped key/value pairs

var array = [{ name: "A", data: "..." }, { name: "B", data: "..." }, { name: "C", data: "..." }],
    result = Object.fromEntries(array.map(o => [o.name, o ]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: JavaScript array doesn't work that way. An array's index value can only have an increasing numeric indexes([0, 1, ..., n]). If you wan't to create such list you can create the object instead of an array.

const array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}];
const newList = {};

array.forEach(obj => {
    newList[obj.name] = obj;
});

console.log({ newList });

In this way you can create the object out of array. You can then loop the object's keys like in arrray using:
Object.keys(newList).forEach((key) => {
  console.log(newList[key]);
})

. Hope it helps.

A: Just do this.

var arr = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]

var output = arr.map(elem => ({[elem.name]: elem}))

console.log(output)


text:
Q: iOS app closes immediately after launch when accessing code from the Binding Library I am facing a strange issue. I have converted the Native framework (Serialio RFID reader) into Binding Library and using it in one of my samples. This sample has only one ViewController. Problem is, app launches in Simulator but it closes immediately in the real iPad device, based on if I write the following line or not.
public partial class SViewController : UIViewController
{
    public SViewController (IntPtr handle) : base (handle)
    {
    }

    //If I comment following one line, it launches in the iPad too.
    //If uncomment, app closes immediately after launch.
    //In Simulator this has no issue. It launches.
    SerialioDeviceManager sdm = SerialioDeviceManager.DefaultManager;

    public override void ViewDidAppear(bool animated)
    {
        base.ViewDidAppear(animated);

        //Even if I comment out above Initialization and write that line here, it doesn't allow app to launch in iPad.
        SerialioDeviceManager sdm = SerialioDeviceManager.DefaultManager;
    }
}

iPad Device Log:

Few More Details:

*

*App is closed even before this ViewController is called/initialized.

*This happens in DEBUG as well as RELEASE mode.

*Supported architecture is ARMv7 + ARM64

*Linker Behaviour : Link Framework SDKs Only

*Native SDK sample runs perfectly.

*This Framework required iPhoneos10.3 SDK while conversion.

EDIT:
Just to update, I am using the following file in the Binding Library.

Am I correct?
I appreciate your help. Thanks.


text:
Q: How to upload multiple images with php and sql I can upload one image at a time with my code, however it I have added multiple="multiple" and it lets me highlight more than one image to upload but only one image gets uploaded to the sql database.
Here is my form below -
<form action="upload_image.php" method="post" enctype="multipart/form-data">

Select files:
<input type="file" name="image[]" multiple="multiple"/>

    Choose an album

    <select name="album_id">
        <?php
        foreach ($albums as $album) {
                echo '<option value="', $album['id'], '">', $album['name'], '</option>';

        }
        ?>

    </select>

<input type="submit" value="Upload" />

</form>

and my PHP side looks like this -
<?php
if (isset($_FILES['image'], $_POST['album_id'])) {
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$image_dimension = $_FILES['image']['dimension'];

$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$image_ext = strtolower(end(explode('.', $image_name)));
$album_id = $_POST['album_id'];

$errors = array();

    if (empty($image_name) || empty($album_id)) {
        $errors[] = 'Something is missing';
    } else {

        if (in_array($image_ext, $allowed_ext) === false) {
            $errors[] = 'File type not allowed';
        }

        if($image_size > 10485760){
            $errors[] = 'Maximum file size is 10MB';
        }

        if (album_check($album_id) === false) {
            $errors[] = 'Couldn\'t upload to that album';

        }
    }

if (!empty($errors)) {
    foreach ($errors as $error) {
        echo $error, '
';
    }

} else {
    upload_image($image_temp, $image_ext, $album_id);
    header('Location: view_album.php?album_id='.$album_id);
    exit();
    }

}
Any help on this would be amazing!
Regards
Aaron


text:
Q: Duplicate environment variable in zsh I have two PATHS declared in zsh. How does this happen / or how can I reproduce it?
~ ❯ env | grep -i path
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/usr/texbin
PATH=/usr/bin:/bin:/usr/sbin:/sbin

A: There are lots ways of reproducing this output.
Cosmetically with line feeds:
% export foo=$'1\nfoo=2'
% env | grep foo
foo=1
foo=2

Cosmetically with carriage returns:
export foo=1
export bar=$'2\rfoo'

Cosmetically with non-printable characters:
env foo=1 $'foo\x01=2' zsh

But the most fun and interesting way is to actually set multiple variables by the same name.
People often don't realize that the environment doesn't consist of variables at all. It's just a list of arbitrary strings that is conventionally but not necessarily interpretted as key=value pairs.
We can simply add two strings foo=1 and foo=2, and it's up to the program to figure out how to interpret that. One way of doing this is a small C program:
int main() {
  char *argv[] = { "zsh", 0 };
  char *envp[] = { "foo=1", "foo=2", 0 };
  execvpe("zsh", argv, envp);
}

When executed, we're put into a shell with both values set:
% env | grep foo
foo=1
foo=2

You can inspect the output of env -0 | od -c to see which of the above you're currently experiencing.

As a bonus, let's ask zsh and bash what they think the value of $foo is when it's found twice:
% echo $foo
1
% bash -c 'echo $foo'
2

They each pick a different string from the environment.
Imagine if security depended on a zsh wrapper filtering environment variables for a bash script!
This is one of the many, many reasons why one should never try to reinvent sudo.


text:
Q: How to convert a string (representing key-value pairs) to Map How can I convert a String into a Map:
Map m = convert("A=4 H=X PO=87"); // What's convert?
System.err.println(m.getClass().getSimpleName()+m);
Expected output
HashMap{A=4, H=X, PO=87}

A: There is no need to reinvent the wheel. The Google Guava library provides the Splitter class.
Here's how you can use it along with some test code:
package com.sandbox;
import com.google.common.base.Splitter;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
@Test
public void testQuestionInput() {
    Map<String, String> map = splitToMap("A=4 H=X PO=87");
    assertEquals("4", map.get("A"));
    assertEquals("X", map.get("H"));
    assertEquals("87", map.get("PO"));
}

private Map<String, String> splitToMap(String in) {
    return Splitter.on(" ").withKeyValueSeparator("=").split(in);
}

}

A: package com.sandbox;

import com.google.common.base.Splitter;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

public class SandboxTest {

    @Test
    public void testQuestionInput() {
        Map<String, String> map = splitToMap("A=4 H=X PO=87");
        assertEquals("4", map.get("A"));
        assertEquals("X", map.get("H"));
        assertEquals("87", map.get("PO"));
    }

    private Map<String, String> splitToMap(String in) {
        return Splitter.on(" ").withKeyValueSeparator("=").split(in);
    }

}


text:
Q: How to add image to SVG with Bobril I am trying to add image to SVG with Bobril, but this code doesn't work:
{
    tag: 'svg',
    children: {
        tag: 'image',
        attrs: {
            'xlink:href': 'https://raw.githubusercontent.com/Bobris/Bobril/master/logo.png',
            x: 0,
            y: 0,
            width: 200,
            height: 200
        }
    }
}

Image tag is added to the page, but no image is shown. When I copy the element in Chrome's DevTools and paste it once again, the image is shown. What am I doing wrong?

A: Instead of 'xlink:href' use just href.
xlink:href is deprecated since SVG 2


text:
Q: Adding multiple rows and saving them using ListView and SimpleAdapter For this part, I am trying to create a button that will save data that has been entered into an EditText and a Spinner. For now this process does add a single row but everytime i click the button, it will just delete the first row and replace the data. Is there a way I can save multiple rows onto the ListView? I am unsure if I have to create multiple arrays for this or if it can be done in an easier way, please let me know. Below is the code I have for the button.
//listadapt
        ListAdapt = new SimpleAdapter(this, mylist, R.layout.row, new String[] {"columnone", "columntwo", "columnthree"}, new int[] {R.id.columnone, R.id.columntwo, R.id.columnthree});
//onclick todobutton
        SaveTodo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                map.put("columnone", Add_Item.this.TaskNameET.getText().toString());
                map.put("columntwo", Add_Item.this.SpinType.getSelectedItem().toString());
                map.put("columnthree", Add_Item.this.DateTimeET.getText().toString());
                mylist.add(map);
               MainActivity.getMainList().setAdapter(ListAdapt);
            }
        });


text:
Q: What's the difference between a Continuation (as in Smalltalk) and an interrupt (as in an Assembler)? I'm struggling to understand the concept of Continuations (as used in Seaside with Smalltalk).  A snippet from Wikipedia says:

"... refer to first-class continuations, which are constructs that give a programming language the ability to save the execution state at any point and return to that point at a later point in the program..."

Isn't this simply another way of expressing what an assembler programmer would do when programming an interrupt?  Or have I completely missed the point!

A: Continuations are roughly equivalent to setjump/longjump in C. You can expect your context be intact when you call the continuation (stack, flags, registers, instruction pointer and so on) after leaving it. So it is similar to a software interrupt call except you don't have to return (or more accurately, call the continuation) after the handler finishes and the continuation is not implicit.

A: A continuation can be seen as a snapshot copy of the running process. Capturing a continuation means that the current process is copied and put aside. After that, code continues to execute normally. Evaluating a continuation means that the current process is terminated and the copied one is resumed in exactly the state it was captured. Continuations can typically be resumed multiple times.
An interrupt is more like a coroutine, where there are two different execution threads (application code, interrupt handler) that interleave each other.

A: In some ways they are similar. However, continuations are called by the program itself, and interrupts are usually generated by the CPU or devices on the computer. Also, an interrupt is more like a C signal, it is just called and then control returns to the program. The interrupt is responsible for saving state and restoring it afterwards.
Also, it should be noted that you can implement continuations quite easily in assembler.