text:
Q: why does dropbox keep syncing when nothing is changing? I've got a particularly large file (about 500MB) that frequently changes, one one of the machines that sync together isn't fast enough at times to keep up - it doesn't finish synching before another (small) change comes in, so it immediately starts resyncing.   So for the past several months I have turned off syncing on this machine.
This evening I decided to re-enable it, as I have reduced the frequency at which the file updates to twice per day. However, what I am seeing is, Dropbox still exhibits the behavior where it counts down the time until the sync is done (generally about 4 minutes), but then as soon as it reaches zero it does a bit of processing, and then indicates another sync is in progress.  No files are changing, so I am at a loss as to why it doesn't stop syncing.  None of the other machines that sync together have any activity.
Could Dropbox be trying to sync all the backup copies or something?  The disk usage in the cache directory doesn't exactly support this (cache usage seems to have dropped quite a bit since I began), but I don't know how else to explain why it keeps trying to resync a couple files.


text:
Q: SUM the data from the last update from a group So, we have a table where we store the predicted noise level for several rooms  on an hourly basis, along side the time when the prediction was made.
But this prediction can change several times a day and when this happen we add a new row to the table, to keep history, so we have something like this:
+----+----+-------+--------+------+-------+---------------------+
| room_id | reference_date | hour | noise |     update_time     |
+----+----+-------+--------+------+-------+---------------------+
|    1    |   2019-06-13   |   8  |    0  | 2019-06-13 07:15:23 |
|    1    |   2019-06-13   |   9  |    5  | 2019-06-13 07:15:23 |
|    2    |   2019-06-13   |   8  |    2  | 2019-06-13 07:15:23 |
|    1    |   2019-06-13   |   8  |    5  | 2019-06-13 08:15:23 |
|    1    |   2019-06-13   |   9  |    5  | 2019-06-13 08:15:23 |
+---------+--------+--------+-----+-------+---------------------+

Now we want to SUM the predicted noise level for the whole day, but using only the last update_time, else will have several entries for the same hour of the day, instead of only one.
I've tried several only examples but couldn't getting it working with a single query, we're using SQL Server 14.0.3030.27. I could do it in code, but I believe there is a better solution for that.
The query result should be something like this
+----+----+-------+--------+------+-------+----+
| room_id | reference_date | total_daily_noise |
+----+----+-------+--------+-------------------+
|    1    |   2019-06-13   |        10         |
+---------+--------+-------+-------------------+

Is it possible to do using a single query?
Thank you in advance for the help!

A: row_number() is one method to get the most recent prediction for each hour:
select room_id, reference_date, sum(noise) as noise
from (select t.*,
             row_number() over (partition by room_id, reference_date, hour order by update_time desc) as seqnum
      from t
     ) t
where seqnum = 1
group by room_id;

Another method uses a correlated subquery:
select room_id, reference_date, sum(noise) as noise
from t
where t.update_time = (select max(t2.update_time)
                       from t t2
                       where t2.room_id = t.room_id and
                             t2.reference_date = t.reference_date and
                             t2.hour = t.hour
                      )
group by room_id;

redpajama_set_name: RedPajamaStackExchange


text: Q: Can't switch my Bluetooth headset to A2DP by default Every time I try to connect my Bluetooth headset (SHB7150) the sound option is switched to HSP by default. If I try to change to A2DP, the sound config window switch and I cannot play any type of media in any type of program or browser. They too change to the first sound device of my laptop (internal speakers) every time I try to manually change to A2DP.


text:
Q: BorderLayout problems I have chartPanel (JFreeChart), buttonPanel and errorPanel.
    frame.add(chartPanel, BorderLayout.PAGE_START);
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    errorPanel = new JLabel("Error String");
    errorPanel.setHorizontalAlignment(JLabel.CENTER);
    frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
    frame.getContentPane().add(errorPanel, BorderLayout.SOUTH);

When I change height of application window, buttonPanel and errorPanel disappeared.
When I don't use JLabel:
    frame.add(chartPanel);
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);

it's okey in changing of height of application window. How to make it right and not have problems with window zoom?

A: When you add to the JFrame the default location is CENTER but since you add to the chart to the PAGE_START now its not scalable...
solution:
take it out and just say
frame.add(chartPanel);

and for the errorPanel and ButtonPanel
just make a new JPanel with BorderLayout and add it to the SOUTH of your Frame Layout.
Then inside that JPanel add your ButtonPanel and ErroPanel just like what you did in your Jframe..

A: Try this:
frame.addComponentListener(new ComponentListener(){

    public void componentResized(ComponentEvent e) {
        frame.pack();
    }

    public void componentMoved(ComponentEvent e) {}
    public void componentShown(ComponentEvent e) {}
    public void componentHidden(ComponentEvent e) {}
});


text:
Q: Mobile Backend or Frontend integration with GetStream From a Medium post in 2017, the recommendation from Stream is to use backend integration due to not placing the API secret into the frontend application. "our best practice is that your mobile application communicate with a fast backend API service hosted on your own systems, and that this backend application would communicate with Stream."
Now that stream supports user tokens, is doing backend integration still the recommended best practice for mobile applications?

A: Backend integration is not necessary for the entire application, but for some operations, such as generating user JSON web tokens, a back-end is necessary. This is because exposing the secret client side exposes your API credentials.


text:
Q: What did Darth Vader do for nineteen years? We see Anakin, who's just been rescued, in his brand new suit; almost all of Palpatine's (and his) enemies defeated, the universe at his feet and his imagination as the only limit.
Then, some nineteen years after, he's just the spooky guy with connections at high levels, but not enough so to prevent any stupid man from making fun of him and his "sad devotion to that ancient religion".
What did he do for all those years between the Revenge of the Sith and A New Hope?

A: He hunted Jedi for the Empire.  From Wookieepedia from the entry on the Great Jedi Purge:

In the nineteen years that followed Order 66, many Jedi fell to Vader, Inquisitors, Emperor's Hands, and even bounty hunters. By 1 BBY, so small a number of Jedi remained that the Emperor, considering the Jedi to be no longer a threat, put an end to the Purge.

A: First and foremost, Vader led the Great Jedi Purge, hunting down and killing all the Jedi who had survived Palpatine's coup:

A young Jedi named Darth Vader, who was a pupil of mine until he turned to evil, helped the Empire hunt down and destroy the Jedi Knights."
  ―Obi-Wan Kenobi in A New Hope

Apart from this, Vader became Palpatine's main enforcer, confronting anything (rebels, conspiracies, etc.) that threatened the Sith lord's power. This (and the Jedi purge) are described in great details in the "Extended Universe" of Star Wars novels. Vader also secretly trained an apprentice named Galen Marek - this is from The Force Unleashed video games.

Then, some nineteen years after, he's just the spooky guy with connections at high levels, but not enough so to prevent any stupid man to make fun of him and his "sad devotion to that ancient religion".

Vader was not a politician, and he didn't care much for amassing political power. An organization the size of the Galactic Empire cannot operate on the basis of direct personal threats. That kind of size requires a caste of politicians to effectively administer it. The Emperor needed these men; he couldn't allow Vader to kill them for petty insults.

A: Along with hunting down the Jedi, whom Palpatine convinced him in ROTS were a major threat to the Empire, Vader, in general, did the Emperor's dirty work--anything that was more effectively handled outside the political structure.
The raid on Leia's ship at the beginning of ANH is a perfect example.  As the first dialogue between Vader and Leia makes clear, Leia's high position in the Senate makes no difference to Vader; his orders to retrieve the stolen Death Star tapes come first.  He's not a politician but an enforcer.   Think of him as Heinrich Himmler to Palpatine's Hitler; much like Himmler commanded the SS and Gestapo, both of which operated outside any other authority with their own paramilitary structures, Vader commands a special subset of the Imperial military to do Palpatine's direct bidding.
Even if you don't take the Extended Universe novels as canon, it's easy to imagine that Palpatine would have had plenty of enemies in the Senate and elsewhere, and would have kept Vader busy helping to consolidate Imperial power in the time between the end of ROTS and the beginning of ANH.    (In TESB and ROTJ we see him in a more conventional military role, commanding the Imperial Navy, but that is after the Emperor has dissolved the Senate.)


text:
Q: Spellchecker in eclipse doesn't recognize certain strings Spellchecker in eclipse doesn't recognize certain strings like 'finalize', 'randomize' even though they are correct. Is there a setting which needs to be enabled so that these don't show up as issues in the Eclipse java file editor?

A: Add the strings to a user defined dictionary. Check out the General > Editors > Text Editors > Spelling page on the Preferences dialog (found under Window > Preferences).


text:
Q: How to test whether useState has been called or a button has been clicked? I've been trying to find a way to get 100% coverage on a simple tsx file and the only two lines that jest tells me need coverage are where I pass a callback that execute a setState from useState.
I've read that I shouldn't test hooks since user only cares about the UI. That's why my question goes as to how to get those two lines tested.
function App(): JSX.Element {
  const [step, setStep] = React.useState(0);
  return (

      <Grid className={style.header} centerAlign>
        <button
          id="home-button"
          className={style.headerHomeBtn}
          onClick={() => setStep(0)}
        >

        </button>

Financial Advisor

      </Grid>
      {step === 0 && <RiskSelector continue={() => setStep(1)} />}
      {step === 1 && <Portfolio />}

  );
}

Uncovered line #s: 18-24
Which are the onClick and continue props. And my test so far is:
describe('Dummy', () => {
  let wrapper: any;
  const setState = jest.fn();
  const useStateMock: any = (initState: any) => [initState, setState];

  beforeEach(() => {
    wrapper = shallow(<Dummy />);
  });
  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('Home button clicked', () => {
    it('calls setStep with 0', () => {
      jest.spyOn(React, 'useState').mockImplementation(useStateMock);
      console.log(wrapper.debug());
      wrapper.find('button').props().onClick();
      expect(setState).toHaveBeenCalled();
    });
  });
});

The console output just shows me that the button is there.
The test doesn't pass because setState was never called.

A: You should NOT mock React.useState() hook, and test the implementation details of the event handler. You should test the behavior of the component. The behavior is, for example, when the state changes, what happens to the view.
E.g.
App.tsx:
import { Grid } from './Grid';
import React from 'react';
import { RiskSelector } from './RiskSelector';
import { Portfolio } from './Portfolio';

const home = 'http://localhost:3000/home.png';

export function App(): JSX.Element {
  const [step, setStep] = React.useState(0);
  return (

      <Grid centerAlign>
        <button id="home-button" onClick={() => setStep(0)}>

        </button>

Financial Advisor

      </Grid>
      {step === 0 && <RiskSelector continue={() => setStep(1)} />}
      {step === 1 && <Portfolio />}

  );
}

Grid.tsx:
import React from 'react';

export function Grid({ children, centerAlign }) {
  return
{children}
;
}

Portfolio.tsx:
import React from 'react';
export function Portfolio() {
  return
Portfolio
;
}

RiskSelector.tsx:
import React from 'react';

export function RiskSelector({ continue: onContinue }) {
  return

;
}

App.test.tsx:
import React from 'react';
import { App } from './App';
import { shallow } from 'enzyme';
import { Portfolio } from './Portfolio';
import { RiskSelector } from './RiskSelector';

describe('67412919', () => {
  let wrapper: any;

  beforeEach(() => {
    wrapper = shallow(<App />);
  });
  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('Home button clicked', () => {
    it('calls setStep with 0', () => {
      wrapper.find('button').simulate('click');
      expect(wrapper.find(RiskSelector)).toHaveLength(1);
    });

    it('calls setStep with 1', () => {
      wrapper.find(RiskSelector).invoke('continue')();
      expect(wrapper.find(Portfolio)).toHaveLength(1);
      expect(wrapper.find(RiskSelector)).toHaveLength(0);
    });
  });
});

unit test result with 100% coverage for App.tsx file.
 PASS  examples/67412919/App.test.tsx (7.433 s)
  67412919
    Home button clicked
      ✓ calls setStep with 0 (24 ms)
      ✓ calls setStep with 1 (12 ms)

------------------|---------|----------|---------|---------|-------------------
File              | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files         |   84.21 |      100 |      50 |   84.21 |
 App.tsx          |     100 |      100 |     100 |     100 |
 Grid.tsx         |   66.67 |      100 |       0 |   66.67 | 4
 Portfolio.tsx    |   66.67 |      100 |       0 |   66.67 | 3
 RiskSelector.tsx |   66.67 |      100 |       0 |   66.67 | 4
------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        7.958 s, estimated 8 s

A: It's not that only the user only cares about UI, the tests for functional components also care solely about the UI :). In other words, test the changing rendered content, not the implementation of a function.
So, simulate that button click and test whether RiskSelector or Portfolio is rendered.


text:
Q: GWT CellTree with an optional pop-up menu triggered on click of a TreeNode I would like to craft a GWT CellTree with an optional pop-up menu triggered on click of a TreeNode.
So I've crafted a CustomTreeModel.  Here it is:
public class CustomTreeModel implements TreeViewModel {

/**
 * Save visited URL.  We'll use it later to determine if tree node needs to be opened.
 * We decode the query string in URL so that token has a chance of matching (e.g., convert %20 to space).
 */
private final String url = URL.decodeQueryString(Window.Location.getHref());

private final NavNode navNode;
private final TokenService<MainEventBus> tokenService;

/**
 * A selection model shared across all nodes in the tree.
 */
private final SingleSelectionModel<NavNode> selectionModel = new SingleSelectionModel<NavNode>();

public CustomTreeModel(NavNode navNode, TokenService tokenService) {
    this.navNode = navNode;
    this.tokenService = tokenService;
}

@Override
public <T> NodeInfo<?> getNodeInfo(T value) {
    DefaultNodeInfo<NavNode> result = null;
    if (value == null) {
        // LEVEL 0.
        // We passed null as the root value. Return the immediate descendants.
        result = new DefaultNodeInfo<NavNode>(getDataProvider(navNode), getCell(), selectionModel, null);

    } else if (value instanceof NavNode) {
        // all other levels
        // We pass a node, return its immediate descendants.

        // select node if URL contains params in node's target or one of node's option's target
        NavNode currNode = (NavNode) value;
        if (isSelected(currNode)) {
            selectionModel.setSelected(currNode, true);
        }
        if (currNode.hasOptions()) { // add pop-up menu to this node if it has options
            result = new DefaultNodeInfo<NavNode>(getDataProvider(currNode), getCell(), selectionModel, new NodeSelectionEventManager(currNode), null);
        } else {
            result = new DefaultNodeInfo<NavNode>(getDataProvider(currNode), getCell(), selectionModel, null);
        }
    }
    return result;
}

@Override
public boolean isLeaf(Object value) {
    boolean result = true;
    if (value == null) {
        if (navNode.hasChildren()) {
            result = false;
        }
    } else if (value instanceof NavNode) {
        NavNode currentNode = (NavNode) value;
        if (currentNode.hasChildren()) {
            result = false;
        }
    }
    return result;
}

// Create a data provider that contains the immediate descendants.
private ListDataProvider<NavNode> getDataProvider(NavNode node) {
    return new ListDataProvider<NavNode>(node.getChildren());
}

// Create a cell to display a descendant.
private Cell<NavNode> getCell() {
    Cell<NavNode> cell = new AbstractCell<NavNode>() {
        @Override
        public void render(Context context, NavNode value, SafeHtmlBuilder sb) {
            if (value != null) {
                sb.appendEscaped(value.getName());
            }
        }
    };
    return cell;
}

private boolean isSelected(NavNode node) {
    boolean selected = false;
    if (node != null) {
        if (url.contains(tokenService.getToken(node))) {
            selected = true;
        } else {
            for (NavOption option: node.getOptions()) {
                if (url.contains(tokenService.getToken(option))) {
                    selected = true;
                    break;
                }
            }
        }
    }
    return selected;
}

class NavNodeSelectionHandler implements SelectionChangeEvent.Handler {

    private final VerticalPanel optionsContainer;
    private final DecoratedPopupPanel optionsPopup;

    public NavNodeSelectionHandler() {
        optionsPopup = new DecoratedPopupPanel(true);
        optionsContainer = new VerticalPanel();
        optionsContainer.setWidth("125px");

        // TODO provide a debug id... this will most likely necessitate generation of a unique key
        optionsPopup.setWidget(optionsContainer);
    }

    @Override
    public void onSelectionChange(SelectionChangeEvent event) {
        NavNode node = selectionModel.getSelectedObject();
        for (NavOption option: node.getOptions()) {
            optionsContainer.add(new Hyperlink(option.getName(), tokenService.getToken(option)));
        }
        // Reposition the popup relative to node
        UIObject source = (UIObject) event.getSource();
        int left = source.getAbsoluteLeft() + 25;
        int top = source.getAbsoluteTop();
        optionsPopup.setPopupPosition(left, top);

        // Show the popup
        optionsPopup.show();
    }
}

class NodeSelectionEventManager implements CellPreviewEvent.Handler<NavNode> {

    private final VerticalPanel optionsContainer;
    private final DecoratedPopupPanel optionsPopup;

    public NodeSelectionEventManager(NavNode node) {
        optionsPopup = new DecoratedPopupPanel(true);
        optionsContainer = new VerticalPanel();
        optionsContainer.setWidth("125px");
        for (NavOption option: node.getOptions()) {
            optionsContainer.add(new Hyperlink(option.getName(), tokenService.getToken(option)));
        }
        // TODO provide a debug id... this will most likely necessitate generation of a unique key
        optionsPopup.setWidget(optionsContainer);
    }

    @Override
    public void onCellPreview(CellPreviewEvent<NavNode> event) {
        // Reposition the popup relative to node
        UIObject source = (UIObject) event.getDisplay();
        int left = source.getAbsoluteLeft() + 25;
        int top = source.getAbsoluteTop();
        optionsPopup.setPopupPosition(left, top);

        // Show the popup
        optionsPopup.show();

    }

}

}
I'm using a generic bean (NavNode) to help me determine when I have a leaf and when I have an option (NavOption) or options that contain a target used for Hyperlink construction.
I want, when I click on a node (TreeNode) in the CellTree, that a pop-up menu (DecoratedPopupPanel) appears, but only for those nodes that have options.
I have tried to employ either of the inner Handler implementations (on construction of a DefaultNodeInfo) to no success.  Hopefully from the above code sample you can see what I'm trying to do.
Here's a variant that adds a SelectionChangeEvent.Handler to SingleSelectionModel
if (currNode.hasOptions()) { // add pop-up menu to this node if it has options
            selectionModel.addSelectionChangeHandler(new NavNodeSelectionHandler());
            result = new DefaultNodeInfo<NavNode>(getDataProvider(currNode), getCell(), selectionModel, null);
        }

What's happening is that the attempt to cast the Event fails with a ClassCastException.
I want to get a handle on an UIObject so I can position the popup.  I think I need a handle on a TreeNode, but cannot see how to do it.
The CellTree, TreeViewModel, SelectionModel and friends are some of the most obtuse API I've come across.
Would really appreciate some help from a GWT expert!

A: A smart colleague of mine was able to sleuth a solution.
Here's what we wound up with:
public class CustomTreeModel implements TreeViewModel {

/**
 * Save visited URL.  We'll use it later to determine if tree node needs to be opened.
 * We decode the query string in URL so that token has a chance of matching (e.g., convert %20 to space).
 */
private final String url = URL.decodeQueryString(Window.Location.getHref());

private final NavNode navNode;
private final TokenService<MainEventBus> tokenService;

/**
 * A selection model shared across all nodes in the tree.
 */
private final SingleSelectionModel<NavNode> selectionModel = new SingleSelectionModel<NavNode>();

public CustomTreeModel(NavNode navNode, TokenService tokenService) {
    this.navNode = navNode;
    this.tokenService = tokenService;
}

@Override
public <T> NodeInfo<?> getNodeInfo(T value) {
    DefaultNodeInfo<NavNode> result = null;
    if (value == null) {
        // LEVEL 0.
        // We passed null as the root value. Return the immediate descendants.
        result = new DefaultNodeInfo<NavNode>(getDataProvider(navNode), getCell(), selectionModel, null);

    } else if (value instanceof NavNode) {
        // all other levels
        // We pass a node, return its immediate descendants.

        // select node if URL contains params in node's target or one of node's option's target
        NavNode currNode = (NavNode) value;
        if (isSelected(currNode)) {
            selectionModel.setSelected(currNode, true);
        }
        result = new DefaultNodeInfo<NavNode>(getDataProvider(currNode), getCell(), selectionModel, null);
    }
    return result;
}

@Override
public boolean isLeaf(Object value) {
    boolean result = true;
    if (value == null) {
        if (navNode.hasChildren()) {
            result = false;
        }
    } else if (value instanceof NavNode) {
        NavNode currentNode = (NavNode) value;
        if (currentNode.hasChildren()) {
            result = false;
        }
    }
    return result;
}

// Create a data provider that contains the immediate descendants.
private ListDataProvider<NavNode> getDataProvider(NavNode node) {
    return new ListDataProvider<NavNode>(NavNodeUtil.getHeadedChildren(node.getChildren(), 1));
}

// Create a cell to display a descendant.
private Cell<NavNode> getCell() {
    return new TreeCell();
}

private boolean isSelected(NavNode node) {
    boolean selected = false;
    if (node != null) {
        if (url.contains(tokenService.getToken(node))) {
            selected = true;
        } else {
            for (NavOption option: node.getOptions()) {
                if (url.contains(tokenService.getToken(option))) {
                    selected = true;
                    break;
                }
            }
        }
    }
    return selected;
}

class TreeCell extends AbstractCell<NavNode> {

    public TreeCell() {
        super("click", "keydown");
    }

    @Override
    public void onBrowserEvent(Context context, Element parent, NavNode currNode,
            NativeEvent event, ValueUpdater<NavNode> valueUpdater) {
        // Check that the value is not null.
        if (currNode == null) {
            return;
        }

        if (currNode.hasOptions()) { // add pop-up menu to this node if it has options
            final DecoratedPopupPanel optionsPopup = new DecoratedPopupPanel(true);
            final VerticalPanel optionsContainer = new VerticalPanel();
            optionsContainer.setWidth("125px");
            for (NavOption option: currNode.getOptions()) {
                optionsContainer.add(new Hyperlink(option.getName(), tokenService.getToken(option)));
            }
            // TODO provide a debug id... this will most likely necessitate generation of a unique key
            optionsPopup.setWidget(optionsContainer);
            // Reposition the popup relative to node
            final int left = parent.getAbsoluteLeft() + 25;
            final int top = parent.getAbsoluteTop();

            optionsPopup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
                @Override
                public void setPosition(int offsetWidth, int offsetHeight) {
                    optionsPopup.setPopupPosition(left, top);
                }
            });
        }

        super.onBrowserEvent(context, parent, currNode, event, valueUpdater);
    }

    @Override
    public void render(Context context, NavNode value, SafeHtmlBuilder sb) {
        if (value != null) {
            sb.appendEscaped(value.getName());
        }
    }
}

}
Note the TreeCell overrides the onBrowserEvent. From here we can get a handle on the node and position the pop-up.  The pop-up is instantiated with a callback.  Weird!
NavNodeUtil does some magic where it counts the children and adds A,B,C...Z categorical headings for a node's children that exceed a certain threshold.


text:
Q: Uploading an audio recording to mysql and playing in website I have an upload phone app that uploads either images or audio recordings. The image can be uploaded to a mysql database and displayed no problem in a webpage, The problem i am having is playing the audio on the webpage, i have tested the webpage by playing mp3 files i have placed in the database myself though the webpage. When i upload an mp3 file from the phone or emulator nothing plays. The database is populated with a file size and on the webpage a media player does load, but nothing plays
Edit 1
Since writing this i have learnt that android records in .amr files and not .mp3 which i had been creating the file as. Since then i can play the file on my desktop using either quicktime or real player. When i attempt to play the file through a web browser i get a quicktime logo with a question mark in the middle. Below is my code for playing the file.
header('Content-type: audio/amr');

$query = mysql_query("SELECT * FROM media WHERE media_id= '$idd'");

$row = mysql_fetch_array($query);

echo $row['file'];

Embed code where 110 is $idd in the above
<object data="sound.php?id=110 width='391' height='298'"> <embed src='sound.php' width='391' height='298'></embed>'ERROR' </object>

Edit 2
If i put the same file directly on my server and NOT in the database this code downloads the file
<OBJECT classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' width="100" height="100"codebase='http://www.apple.com/qtactivex/qtplugin.cab'>
<param name='src' value="apr.amr">
<param name='autoplay' value="true">
<param name='controller' value="true">
<param name='loop' value="true">
<EMBED src="apr.amr" width="100" height="100" autoplay="true" controller="true" loop="true" pluginspage='http://www.apple.com/quicktime/download/'>
</EMBED>
</OBJECT>

Edit 3 upload code
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {

      $size = $_FILES['image']['size'];
      $type = $_FILES['image']['type'];

      // Temporary file name stored on the server
      $tmpName  = $_FILES['image']['tmp_name'];

      // Read the file
      $fp      = fopen($tmpName, 'r');
      $data = fread($fp, filesize($tmpName));
      fclose($fp);

      $data = addslashes($data);

      // Create the query and insert
      // into our database.
      $query = "INSERT INTO media";
      $query .= "(file, file_size, file_type) VALUES ('$data','$size','$type')";
      $results = mysql_query($query, $link);

      $mediaid = mysql_insert_id();

    $gender = $_POST['gender'];
    $cat_id = $_POST['cat'];
    $name = $_POST['name'];
    $lat = $_POST['lat'];
    $lon = $_POST['lon'];
    $user = $_POST['user'];

  $query="INSERT INTO instance (name, gender, cat_id, lon, lat, user_id) VALUES ('$name', '$gender', '$cat_id', '$lon', '$lat', '$user')";
  $result=mysql_query($query);

      $instanceid = mysql_insert_id();

      $query4 = "INSERT INTO media_link";
      $query4 .="(media_id, instance_id) Values ('$mediaid','$instanceid')";
      $results4 = mysql_query($query4, $link);

    }

// Close our MySQL Link
mysql_close($link);
?>

A: Yes.
// Get the file contents from the database...

// Assuming a DB wrapper here.
$results = $db->query('SELECT `file_contents` FROM `mp3s` WHERE `id` = :id', array(':id' => $_GET['id'])->execute();
$fileContents = $results[0]['file_contents'];

// Send appropriate headers for content type and force download
header('Content-Type: mpeg/audio');
header('Content-Disposition: attachment; filename="BullsOnPowerade.mp3"')
echo $fileContents;

A: So if you have an AMR file (I haven't tested this, so you'll have to try this out) you will need to extract the AMR audio and convert it to MP3. Unfortunately it appears to be rather rare in Java, but a (rather painful) Google search turned up this link: http://www.benmccann.com/blog/extracting-amr-audio-from-android-3gp-files/ which claims to demonstrate extracting the audio from a 3gpp video file, so they at least have an AMR parser. I would look at the underlying library they use, isobox4j (discussed at http://groups.google.com/group/android-developers/browse_thread/thread/245c9de4132c2ab0?fwc=1) and see if you can either:

*

*Extract the audio in the phone app, convert to mp3 and then upload the mp3 (probably the easiest option, frankly: keeps the server simple).

*Extract the audio on the server and convert to mp3 before streaming the mp3 to the web page (probably harder, frankly).

Good luck.
EDIT: or you could hope the client has an appropriate browser plugin: the broken quicktime mark indicates quicktime doesn't have a codec for it.
EDIT 2: You probably need to set a content-type for the plugin so it knows what to do. For AMR try adding
header("Content-type: audio/amr");

before the echo statement in your PHP and if that isn't enough add a mime type to your embed like this:
<object data="sound.php?id=110 width='391' height='298'"> <embed src='sound.php' type="audio/amr" width='391' height='298'></embed>'ERROR' </object>

See if that works.
EDIT: try this. Not sure if the $row['file'] is considered a string or an array, but the trim might do what you need.
<?php

header('Content-type: audio/amr');

$query = mysql_query("SELECT * FROM media WHERE media_id= '$idd'");

$row = mysql_fetch_array($query);

echo trim($row['file']);
exit;

A: If HTML5 is not an option, for inline playback, the best option supported out of the box by the majority of current browsers will be flash based. Flash still requires a plugin, but it's much more widely installed than Quicktime AFAIK.
The Google mp3 player that Tomasz suggested is a good choice. There are many more out there though. See for example http://www.webdesignbooth.com/10-easy-to-implement-flash-based-mp3-players-for-your-website/

A: This is a really really broad question, but here are some starter tips:

*

*Look at the apache httpcomponents project for a good HTTP library, including the ability to do multi-part MIME attachments and POST requests

*Take a look at the PHP docs for handling file uploads

*If you don't want your app to lock up during uploads, I would encourage you to look at the android AsyncTask pattern and supporting classes so that your UI thread does not block during the uploads

*There are any number of ways to play an audio file in a web page (Flash being the most prevalent probably)

A: Yes, the audio file is just a binary file and can be saved an a blob data field. Then recalled from a query. Then play it any way you want.You may be better off saving the audio file to local storage and keeping track of where you put it in the database.

A: You could use Flash on the web page. On 2.3 you could use the audio tag. See HTML5 <audio> tag on Android .

A: easiest method is to use nowadays is HTML5  tag..
html5 audio
<audio src="horse.ogg" controls="controls">
Your browser does not support the audio element.
</audio>
using google mp3 player - replace mp3_file_url with the actual url of the file... although im not sure if it runs .amr files
<embed type="application/x-shockwave-flash" flashvars="audioUrl=MP3_FILE_URL" src="http://www.google.com/reader/ui/3523697345-audio-player.swf" width="400" height="27" quality="best"></embed>
EDIT:
quicktime - change WIDTH and HEIGHT in both cases.. and choose false/true in the params you want
<OBJECT classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' width="_WIDTH_" height="_HEIGHT_"codebase='http://www.apple.com/qtactivex/qtplugin.cab'>
        <param name='src' value="apr.amr">
        <param name='autoplay' value="true/false">
        <param name='controller' value="true/false">
        <param name='loop' value="true/false">
        <EMBED src="apr.amr" width="_WIDTH_" height="_HEIGHT_" autoplay="true"
        controller="true" loop="true" pluginspage='http://www.apple.com/quicktime/download/'>
        </EMBED>
        </OBJECT>

A: If you want to embed a video on your webpage, you can read this support article on Apple's website and this is a list of tag attributes...
Hope this can help! :)


text:
Q: Javascript pseudo-enum with IDE completion Sometimes I need enum-like structures for fixed sets of string valus in Node.JS. Basically an object with keys for each enum value, and each value is a string equal to the key:
var State = {FOO: 'FOO', BAR: 'BAR', SOME_REALLY_LONG_NAME: 'SOME_REALLY_LONG_NAME'};

This enables me to type State.S and the IDE will suggest State.SOME_REALLY_LONG_NAME, and typos are practically eliminated. I can do if (x === State.FOO) etc.
The above syntax is however obviously not ideal due to the duplication of each literal during creation of the set of values. So I can do for example:
var State = _.indexBy(['FOO', 'BAR', 'SOME_REALLY_LONG_NAME'];

However, as soon as the object is created indirectly, the IDE (WebStorm in my case) will be unable to suggest/auto-complete the values. Sure, with JavaScript we're not very spoiled with working auto-complete anyway, but in my case it bugs me because the whole purpose of my "enum" is to simplify usage of a fixed set of strings.
There are also several enum utilities to create more proper enums, but they will suffer from the same thing. Also, if what I need is basically a fixed set of strings, more proper enums would force me into writing State.FOO.key to get the string value.
Is there a clever way to accomplish these really simple {key: 'key'} mappings without having to type each key twice during creation, but while still maintaining the IDE's understanding of which properties exist in the object? I'm guessing WebStorm only performs a static code analysis which goes out the window as soon as a function is called? Or is there some clever trick?

A: It's been a while that i used Webstorm, and it's macro-utilities, but maybe u can write a simple macro that expands your String-Array into the desired Structure.
Otherwise, you could try the Typescript-plugin. First of All: every valid JS should be valid TS (don't know exactly about ES7, and if some of the ES6 may bug the plugin).
But TS has a Enum-implementation and webstorm should therefore give you autocompletition and type-safety


text:
Q: How to design a data model which is having a date range? In my Spring application I need to design a data model which is having date range. Is there any data type which can be used?
Currently I did something like this.
@Entity
@Table(name = "scheduled_period")
public class ScheduledPeriod {

    private Date oneDay;

    private Date fromDate;

    private Date toDate;
}

I want to put fromDate and toDate together in to something like dateRange

A: Best solution is yours, by using LocalDate.
By using two LocalDate to Start Date and End Date.
and working with them, see:
HQL / JPA find available items between date range

some DBMS's like PostgreSQL has datatype named: daterange
for example:
CREATE TABLE reservation (room int, during daterange);
INSERT INTO reservation VALUES
    (1108, '[2010-01-01 14:30, 2010-01-01 15:30)');

but Java (JPA) does not support datarange data type.
If you generate that table into Entity, it generated to Object.
private Object during;

public Object getDuring() {
    return this.during;
}
public void setDuring(Object during) {
    this.during = during;
}

finally, if you persist to use rangedate, you can define a new class (Entity) named RangeDate with two LocalDates or use array of LocalDate (if your DMBS support it).


text:
Q: 1 parameter, 2 given in ... after migrating from localhost I've moved my website live and I'm getting error.
1 parameter, 2 given in ... on line 57
The line is exactly:
file_put_contents( $files['owg'], json_encode( $data, true ) );
The whole thing is:
if( isset( $_POST['submit'] ) ) {
 if ( !empty( $_POST['owg'] ) ) {
    $data['owg'] = nl2br( trim( $_POST['owg'] ) );
    file_put_contents( $files['owg'], json_encode( $data, true ) );
    unset( $data );
  }
}

Chmods are 777 on files and folders. Why is this error not appearing at localhost?


text:
Q: React app fails compile when using image url in CSS I am trying to add a background image to a control in a ReactJS project, using css and it's url functionality.
.jumbotron {
    background-image: url(../images/image.jpeg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100% auto;
    color: 6b6b6b;
}

However, a loader is breaking, as it's trying to parse the binary file. An unexpected char. Removing the background line, and all works.
I am using webpack, and my modules are loaded like this:
module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            },
            {
                rules: [
                  {
                    test: /\.css$/,
                    use: [ 'style-loader', 'css-loader' ]
                  }
                ]
              }
        ]
    }

How can I get my react app to work with this css image as a background url? Creating the project with create-react-app - it works, but I can't see how it's handling the images.
I have a repo:
https://github.com/CraigInBrisbane/ReactLearning
Any assistance would be great.

A: When you use css-loader, webpack removes all your background-image: url(../images/image.jpeg); and inserts require(../images/image.jpeg). There is two way to solve this problem:
1) add file-loader/url-loader for these types of files
2) use absolute path instead of relative ( background-image: url(/images/image.jpeg); ) and css-loader will skip this image


text:
Q: How to differentiate the square root of the function inside another square root of the function? If a function is defined as sum of radicals in another radicals. Then how to differentiate this function
$$\sqrt{\cos x+\sqrt{\cos x+\sqrt{\cos x+\dots}}}\quad?$$

A: Putting all convergence problems aside, let:
$$f(x)=\sqrt{\cos(x)+\sqrt{\cos(x)+\sqrt{\cos(x)\cdots}}}$$
so that
$$f(x)=\sqrt{\cos(x)+f(x)}$$
By the chain rule
$$f'(x)=\dfrac{f'(x)-\sin(x)}{2\sqrt{\cos(x)+f(x)}}=\dfrac{f'(x)-\sin(x)}{2f(x)}$$
so that
$$f'(x)\big(2f(x)-1\big)=-\sin(x)$$
that is
$$f'(x)=\dfrac{\sin(x)}{1-2f(x)}$$
provided $f(x)\not=\dfrac{1}{2}$. We also see that
$$f(x)=\dfrac{1}{2}\Rightarrow\dfrac{1}{2}=\sqrt{\cos(x)+1/2}\Rightarrow\cos(x)=-\dfrac{1}{4}$$
but $f(x)$ is not defined for such $x$.

A: So $f^2(x) - \cos(x) = f(x)$.  Differentiating, $2 f(x) f'(x) + \sin(x) = f'(x)$ and then $f'(x) = \frac{\sin(x)}{1 - 2 f(x)}$.  Which suggests the requirement that "$f(x) \neq 1/2$".
You can solve the original quadratic for $f$ if you want to remove the $f$ from the right-hand side of the derivative.
I make no claim that this $f$ or its derivative exists.


text:
Q: Magento - Displaying custom attribute in accounts area (front-end) I have used this module creator to get an custom attribute (which takes the type 'file').
http://www.silksoftware.com/magento-module-creator/
This works and can be seen in the admin area. I also have other custom attributes for customers which I have used this tutorial to create:
http://www.fontis.com.au/blog/magento/know-more-about-your-customers-adding-custom-signup-attributes
This also works. The reason I used the module creator was because I was unsure of how to make the input type as 'file'.
The attributes created through the fontis tutorial can be displayed as needed on the front end (which was only needed in the registration form).
The problem I'm having is in the custom area in the logged in accounts area on the front end. What I need is to retrieve the value of the 'file' attributes which was created in the module creator. Could anyone point me in the right direction of how to display these please? I have tried getAttributeName but this is not working.
Thank you.

A: If you post the code from your custom module we could help you more.
Meanwhile, here is some info that could help you:

*

*Whenever you store something in the DB using a module, there is a Model class (that allows you to access the necessary data)

*You can find the class name by looking in your modules etc/config.xml file

*In the file look for section named <models>

*The sub nodes of <models> is the name of the namespace (see below)

*The sub node of your 'namespace' called <class> contains the rest of the info you will need

*Next you need to call the Model with Mage::getModel('namespace/class_name')->load($id); to get a collection of all the custom attribute records that are in the system

To break this down in to manageable pieces:
Let's assume this is what your config.xml contains:
<models>
    <customattribute> // this is your namespace
         <class>Mycompany_Customattribute_Model</class> //this tells you wher to find your model files
          <resourceModel>customattribute_resource</resourceModel>
    </customattribute>

...
</models>

This means that your 'namespace' is 'customattribute'.
Next you need to find the file that contains your Model.
In this case we look at the <class> node to give us the file location (in this case app/code/local/Mycompany/Customattrbute/Model), now we need to go there and see the file that is there (let's say it's called 'File.php')
To get all the data we call the follwoing function:
Mage::getModel('customattribute/file')->load();

This will give us all the data.
If we want to narrow it down we can use the following function:
Mage::getResourceModel('customattribute/file')->addFieldToFilter('name_of_filed_in_db', 'value_we_want');


text:
Q: Field seems not to be changed, Master-Detail relationships I am working on a trigger that compares two fields across a junction object. The field is not being updated as I would expect and I suspect it has to do with the relationship.
 for(Client_Financial_Account_Relationship__c rel :relatedClients) {
        // if the clients last OPA date is earlier than his enrollment date update accordingly
        if(rel.Financial_Account__r.Offer_Enrollment_Date__c < rel.Customer__r.OPA_Completion_Date__c) {

            if(rel.Customer__r.OPA_Temp_Dt__c != NULL){

                rel.Customer__r.OPA_Temp_Dt__c = NULL;
                rel.Customer__r.OPA_Completion_Date__c = rel.Financial_Account__r.Offer_Enrollment_Date__c;
                clientsToUpdate.add(rel.Customer__r.Id);
                System.debug('Financial Account trigger: end of second if: opa completion data: '+rel.Customer__r.OPA_Completion_Date__c+' fa Offer enrollment date: '+rel.Financial_Account__r.Offer_Enrollment_Date__c+' name: '+rel.Customer__r.Name);
                System.debug('Customer to change: '+rel.Customer__c);
            }

        }
    }

... here when I try to print out the customer's name I get null. I add the rel.Customer__r.id to a list then query with that id to find the customer to update...
  List<Account> clientsWithNewOPADates = [Select Id,Name,OPA_Completion_Date__c,OPA_Temp_Dt__c from Account Where Id in :clientsToUpdate];
  System.debug('client gettting updated: '+clientsWithNewOPADates[0].Name+' opa completion date: '+clientsWithNewOPADates[0].OPA_Completion_Date__c+'opa temp date'+clientsWithNewOPADates[0].OPA_Temp_Dt__c);
  System.debug('FINANCIAL ACCOUNT TRIGGER -> size of clients to update: '+clientsWithNewOPADates.size());
  update clientsWithNewOPADates;

Strangely the right client name is printed out here. Is there anything apparently wrong with my method ?
astoundingly I added System.debug(rel.Customer__r.Id); to the inner 'if' and the same just after the query and the Id's match exactly. But if that's the case why does the field OPA_Temp_Dt__c not show null after the query ?

A: There may be more than one issue here (I am not sure I follow the issue with a Name field being null in one place but not another), but there's certainly a central issue right here:
List<Account> clientsWithNewOPADates = [<PERFORM SOQL>];
update clientsWithNewOPADates;

This is basically a no-op. When you query clientsWithNewOPADates based on the Set clientsToUpdate, you're no longer working with the sObject instances you already have, wherein you nulled out the field OPA_Temp_Dt__c and possible made other changes. Those in-memory instances just go away because you don't perform DML to persist them.
The new instances you query here, which do have the same Id values, represent a brand new copy sourced from the database, so when you call update on them, you just persist those same starting values back to Salesforce without any of your updates.
I don't see enough of your code here to make a more concrete recommendation, but I think one shift that may help you is to remember that the value of rel.Customer__r is an Account. You can do
List<Account> stuffToUpdate = new List<Account>();

// .... go through and made updates ...
stuffToUpdate.add(rel.Customer__r);

update stuffToUpdate;

Customer__c is an Id. Customer__r is an sObject. It's confusing.
One thing to note though, since you're dealing with a junction object, is that you may want to store your updates in a Map<Id, Account> instead of a List<Account>. You'd do myMap.put(rel.Customer__c, rel.Customer__r); and then update myMap.values();. This shields you from errors that arise from having more than one "copy" of the same object in your DML operation.


text:
Q: How to create HTML field with Bootstrap tooltip in the Vuejs/Nuxtjs? I am trying to create a simple field with a tooltip using the Bootstrap something like this:

But for some reason, I am unable to create within my Vuejs/Nuxtjs project. I was able to find the code example where they are using the jQuery but was unable to convert it to my Vuejs/Nuxtjs code.
Can someone please let me know how can I create something similar within my Vuejs/Nuxtjs?
Following is the code sample for jQuery: http://www.java2s.com/Tutorials/HTML_CSS/Bootstrap_Example/Tooltip/Add_tooltip_to_info_icon.htm
Following is the code I have in my Vuejs/Nuxtjs project:
<template>

         Permissions

</template>

I am currently using the Bootstrap Version ^4.6.1 and able to create all Bootstrap button and other things which seems to be working as required. But only this one is not working for me.


text:
Q: Haskell: How do I create a function that allows none, one or two Applicatives? Control.Applicative.optional allows to handle zero or one Applicatives.
many & some allow for 0 or more, or 1 or more, respectively.
I'd like to create a function that handles zero, one or two, specifically.
The signature could be as for many/some, that is
zeroOneOrTwo :: Alternative f => f a -> f [a]

I feel this should be pretty straightforward, but I've been playing around with it for a while and cannot make it work.  Any pointers would be greatly appreciated.

A: How about this one:
zeroOneOrTwo :: Alternative f => f a -> f [a]
zeroOneOrTwo a = go (2 :: Int)
  where
    go n
      | n > 0 = ((:) <$> a <*> go (n - 1)) <|> pure []
      | otherwise = pure []

A: If you're going to the trouble of restricting the result like that, you might as well make its type reflect that.
data ZOT a = Zero | One a | Two a a

form :: a -> Maybe a -> ZOT a
form a Nothing = One a
form a (Just b) = Two a b

zeroOneOrTwo :: Alternative f => f a -> f (ZOT a)
zeroOneOrTwo a = (form <$> a <*> optional a) <|> pure Zero

What if you want up to three? Or up to four? You can cover all such cases at once with a couple language extensions.
{-# LANGUAGE DataKinds, GADTs #-}

data Nat = Z | S Nat

data Natty n where
  Zy :: Natty 'Z
  Sy :: Natty n -> Natty ('S n)

data AtMost n a where
  Nil :: AtMost n a
  Cons :: a -> AtMost n a -> AtMost ('S n) a

atMost :: Alternative f => Natty n -> f a -> f (AtMost n a)
atMost Zy _ = pure Nil
atMost (Sy n) a = (Cons <$> a <*> atMost n a) <|> pure Nil

What if you don't want to use any fancy extensions? Well, it won't look quite so pretty, but you can still do it if you like, taking a page from Ralf Hinze's "Numerical Representations as Higher-Order Nested Datatypes".
data Z a = Z deriving (Show)
data S f a = Nil | Cons a (f a) deriving (Show)

class AtMost g where
  atMost :: Alternative f => f a -> f (g a)

instance AtMost Z where
  atMost _ = pure Z
instance AtMost g => (AtMost (S g)) where
  atMost m = (Cons <$> m <*> atMost m) <|> pure Nil

Note that there are now two different ways to construct an empty result, Z and Nil, with different types. Z is used when the result is as large as requested, while Nil is used when it comes up short.
*AtMost> atMost (Just 3) :: Maybe ((S (S (S Z))) Int)
Just (Cons 3 (Cons 3 (Cons 3 Z)))

*AtMost> atMost Nothing :: Maybe ((S (S (S Z))) Int)
Just Nil

*AtMost> atMost undefined :: Maybe (Z Int)
Just Z


text:
Q: Google maps Autocomplete api not same as specifications I'm teasing google places API and I run into strange behavior at Autocomplete that I don't understand.
This is how I'm using it:
const AUTOCOMPLETE_OPTIONS = {
 types: ['address'],
 componentRestrictions: {
    country: 'cz'
 }
};
this.inputPlaceElement = $('#search-around-input')
this.inputPlaceSearchBox = new google.maps.places.Autocomplete(this.inputPlaceElement[0], AUTOCOMPLETE_OPTIONS);
google.maps.event.addListener(this.inputPlaceSearchBox,'places_changed', () => {
  console.log('place change')
})

Autocomplete input is working as it should but place_changed is not triggered, I was trying some stuf with it, and the object that is returned  from constructor is weird.
When I call methods getBounds() or getPlace() there are undefined
This is the object: I'm not sure what is wrong

A: The event triggered when a Place is selected is 'place_changed', while your sample uses 'places_changed'
Try:
google.maps.event.addListener(this.inputPlaceSearchBox,'place_changed', function() {
  console.log('place change')
});


text:
Q: apache ignite transaction in thick client I have a code that use locking and it worked fine whn I used think client. After I switch the code to use thick client I get the following exception:

Apache.Ignite.Core.Common.IgniteException: Cannot start/stop cache within lock or transaction [cacheNames=SQL_MYAPP_MODELS_COUNTERS, operation=dynamicStartCache] ---> Apache.Ignite.Core.Common.JavaException: class org.apache.ignite.IgniteCheckedException: Cannot start/stop cache within lock or transaction [cacheNames=SQL_MYAPP_MODELS_COUNTERS, operation=dynamicStartCache]
at org.apache.ignite.internal.processors.platform.utils.PlatformUtils.unwrapQueryException(PlatformUtils.java:520)
at org.apache.ignite.internal.processors.platform.cache.PlatformCache.runFieldsQuery(PlatformCache.java:1409)
at org.apache.ignite.internal.processors.platform.cache.PlatformCache.processInStreamOutObject(PlatformCache.java:1000)
[... truncated...]

I am not sure what it means by "start/stop cache." The transaction block only contains logics to create the SqlFieldsQuery() then call cache.Query() (which is where the code breaks)
Why and how can I use transaction with thick client?

A: It turns out "start/stop" means the cache is first accessed or something. So I wrote a query outside my transaction using-block to access the cache and that seems to have solved it.


text:
Q: How to remove a whole project from SVN synchronization? I have a project i no longer want synchronised to SVN (as this is just a copy and i have another project synchronised)... How in the life do i remove it from SVN using Eclipse, or anything basically?
I can't see any .svn file in the directory folder.
Thanks,
Mike

A: Right click on your project folder, and select Team>Disconnect (this is for subversive, it should be the same with subclipse).

A: Export your project from SVN using:

svn export repo_url

then replace files under eclipse with exported ones.
See http://svnbook.red-bean.com/en/1.0/re10.html for details about export option
Update:
greg0ire's way seems to be much easier. Disconnect option is available under subclipse too.


text:
Q: Summing the contents of two collections.Counter() objects I am working with collections.Counter() counters.  I would like to combine two of them in a meaningful manner.
Suppose I have 2 counters, say,
Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})

and
Counter({'menu': 1, 'good': 1, 'bar': 3})

I am trying to end up with:
Counter({'menu': 21, 'good': 16, 'happy': 10,'bar': 8})

How can I do this?

A: All you need to do is add them:
>>> from collections import Counter
>>> a = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})
>>> b = Counter({'menu': 1, 'good': 1, 'bar': 3})
>>> a + b
Counter({'menu': 21, 'good': 16, 'happy': 10, 'bar': 8})

From the docs:

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements.

Note that if you want to save memory by modifying the Counter in-place rather than creating a new one, you can do a.update(b) or b.update(a).


text:
Q: What does this function do in the Chrome extension? I am looking at how a Google extension (SAML Chrome Panel) is constructed. The source code for this extension is here on GitHub.
My question is about a function in the panel.js script, located here.
The panel.js script has the code shown below on lines 33-37. The function in question is the anonymous one that takes the parameters function(i,s,o,g,r,a,m).
SAMLChrome.controller('PanelController', function PanelController($scope, $http, toolbar) {
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://ssl.google-analytics.com/analytics.js','ga');

I can gather that the anonymous function loads the analytics.js file from a Google server. But besides that, does it embed an event listener into the elements that it finds using getElementsByTagName(), or what does it do?

A: It is the analytics.js library of Google Analytics. It is a JavaScript library for measuring users interaction.
In the panel.js file, below the code you entered there is the part  that send info to Google Analytics:
ga('create', 'UA-67121118-1', 'auto');
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. @see: http://stackoverflow.com/a/22152353/1958200
ga('require', 'displayfeatures');
ga('send', 'pageview', '/panel.html');

You can find more info about this code here:
https://developers.google.com/analytics/devguides/collection/analyticsjs/


text:
Q: What did I do wrong with my html/css website?
I am busy making a website and have trouble with a vertical navigation menu. My first approach was to try to delete some lines of code to see if something blocks what I want it to do but I just cant seem to find it.
The second thing I tried to do was search for a vertical navigation menu similiar to mine but I couldnt find one exactly similiar.
So my question is how can I fix this?
This is how it is acting now: Image now.
This is how I want it to act: How I want it.
My code is here:

body{
 background-color:purple;
 height:100%;
}
.list{
 list-style-type: none;
 background-color:black;
 origin: top left;
 margin:8px 0 -50px -40px;
 width:210px;
 height:100%;

}
.button{
 background:grey;
 margin: 0px 0px 0px 20px;
 padding:20px 25px 16px 25px;
 width:100px;
 border-radius:0 0 0 0;

 display:block;
 text-align:center;
 font-size:17px;
 font-weight:bold;
 font-family:Baskerville;
 color:black;
 text-decoration:none;
 transition-duration:0.4s;
}
.buttonA{
 background:#675bcc;
 margin: 0px 0px 0px 20px;
 padding:20px 25px 16px 25px;
 width:100px;
 border-radius:10px 10px 0 0;

 display:block;
 text-align:center;
 font-size:17px;
 font-weight:bold;
 font-family:Baskerville;
 color:white;
 text-decoration:none;
 transition-duration:0.4s;
}
.buttonB{
 background:grey;
 margin: 0px 0px 0px 20px;
 padding:20px 25px 16px 25px;
 width:100px;
 border-radius:0 0 10px 10px;

 display:block;
 text-align:center;
 font-size:17px;
 font-weight:bold;
 font-family:Baskerville;
 color:black;
 text-decoration:none;
 transition-duration:0.4s;
}
.button:hover, .buttonB:hover{
 background-color:purple;
 color:white;
 opacity:0.8;
}
.active-has-sub{

}
.has-sub{
 list-style-type: none;
 float:left;
 z-index:1;
 display:inline;
 position:relative;
 top: -35px;
 left:140px;
}
.has-sub> a{
 text-decoration:none;
 text-align:left;

 background:grey;
 padding:20px 25px 16px 25px;
 font-size:15px;
}

.nav{
 background-color:black;
 origin: top left;
 margin:-8px 0 -50px -8px;
 width:210px;
 height:100%;
 z-index:1;
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="stylesheet.css">

Home

Herplaatsen

Ik wil herplaatsen

Sub Product

Rescue's

Wil

Handig

Vakantie

Opendag

Doneren

Sponser

Contact

Vakantieadres

If someone could tell me what I did wrong and how I can fix this.
That would be extremely helpfull and great :)

A: The
 HTML tag just creates an unordered list, which would just create a plain vertical list, and by looking at the examples you have shared, it looks like a horizontal list is what you want. One way you could do this is by using the <form> HTML tag, which creates a form with all of the contents on the same line.
Here is an example of this:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="stylesheet.css">

    <form>
        <a href="<link1>">Menu option 1
        <a href="<link2>">Menu option 2
    </form>

This does something like this:
Click here for image.
This is not the best way of doing it, but it is one of the easiest.
Best of luck!


text:
Q: Transaction two methods with Spring JPA repository @Transactional(readOnly=false)
    public Do12 saveReport(Do12 report) {
        try {
// This is where I get a do12 record.
            Do12 findReportByDate = do12Repository.findByDate(report
                    .getBeginPeriod());
            if (findReportByDate != null) {
// This is where I delete the do12 record.
                if (deleteReport(findReportByDate) != 0)
                    throw new Exception("Не удалось удалить запись о ДО12");
            }
            if (report.getCancelByService() != null)
                for (CancelByService cancelByService : report
                        .getCancelByService())
                    cancelByService.setReport(report);
            if (report.getLateByService() != null)
                for (LateByService lateByService : report.getLateByService())
                    lateByService.setReport(report);
// Here I save the new one and get an Exception.
            return do12Repository.save(report);
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

    public int deleteReport(Do12 report) {
        try {
            do12Repository.delete(report);
            return 0;
        } catch (Exception e) {
            logger.error("", e);
            return -1;
        }
}

This is my output. It says that I try to save a do12 with same beginPeriod in database, but it is an unique constraint on it.
Apparently, that first hibernate message says that he get do12 record whereas the second one shows that he try to save the new report.
But where is the delete query?

Hibernate: select ... from reports.do12 do12x0_ where
  do12x0_.beginPeriod=?
Hibernate: insert into reports.do12
  (beginPeriod, countAreaCancelTrain, countCancelTrain,
  countFullCancelTrain, countTrainFollow, countTrainLate,
  countTrainOnGraph, countTrainOnSchedule, percentExecGraph,
  percentExecWithoutOtherCause, timeLate, typeOfReportPeriod) values (?,
  ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
11:50:49,546  WARN
  http-bio-8080-exec-26 SqlExceptionHelper:logExceptions:144 - SQL
  Error: 0, SQLState: 23505
11:50:49,547 ERROR http-bio-8080-exec-26
  SqlExceptionHelper:logExceptions:146 - ОШИБКА: повторяющееся значение
  ключа нарушает ограничение уникальности "do12_beginperiod_key"
  Подробности: Ключ "(beginperiod)=(2014-09-01)" уже существует.


text:
Q: this.state.account and this.state.followers are not updated onMouseOver? When Bootstrap table rows are hovered the twitter_account in Twitter state is updated.But when passed as props for TwitterChart class It is not updated.
const twitterData = [
  {
    account: "marwilliamson",
    followers: 2610335,
  },
  {
    account: "BernieSanders",
    followers: 9254423,
  },
  {
    account: "Hickenlooper",
    followers: 144816,
  }
]
export {twitterData};

/////////

import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import {twitterData} from './twitter_data'

export const Twitter = () => {
  const data = useMemo(() => twitterData, [])
  const [twitter_account,settwitter_account] = useState('');
  const [twitter_followers,settwitter_followers] = useState(0);
   function onRowMouseOver(row){
    settwitter_account(row.account);
    settwitter_followers(row.followers);
    }
  const options = {
    onRowMouseOver: onRowMouseOver,
  };
  return (

        <BootstrapTable data={ data } options={options}>
            <TableHeaderColumn dataField='account' dataFormat={CellFormatter} isKey={true} dataSort={ true } dataAlign='left' width='120' headerAlign='left' className="header">ACCOUNT</TableHeaderColumn>
            <TableHeaderColumn dataField='followers' dataSort={ true } width='120' dataAlign='center'  headerAlign='left' className="header">FOLLOWERS</TableHeaderColumn>

        </BootstrapTable>

    <TwitterBarChart account={twitter_account} followers={twitter_followers}/>

  )
}

/////////

class TwitterBarChart extends React.Component {

    constructor(props){
        super(props);
        this.state = {
            data : twitterData,
            account:props.account,
            followers:props.followers,
        }
    }
   render() {

      console.log(this.state.account);
      return(

{this.state.account} has {this.state.followers} followers on Twitter

     )

}

twitter_account , twitter_followers are not getting updated on props.

console.log(this.state.account) //account value is not updating onMouseOver.

A: Finally after many references I got the answer.
should use componentWillRecieveProps(newprops){}
Thanks for contributing


text:
Q: JUnit test in Spring - overriding and ignoring beans from application other configuration classes We have large application written in Spring 3. I need to write JUnit test checking behavior of some service. It is not a unit but part of a system. There are some services and repositories working together insite it -> lot of injected beans inside. The app also uses aspects.
My question is. How to manage config and beans in this case of tests? I need to use beans defined in app configes and in tests only redefine beans using persistence to work with a embedded db. So I need to use beans from src as they are defined and override only some causing troubles (persistance beans, beans using webservices,...)
In test package I made Config class definying beans for persistance, using datasource for hsql. But I don`t know what next. I tried to annotate Test config class with:
@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)
@ComponentScan(basePackages = "com.example.our.app")
public class MyTestConfig implements TransactionManagementConfigurer {

to scan whole application and use configuration of beans from src folder. But this also takes configs from other tests causing problems. Is this whole good strategy or not? What now - use excludeFilters to remove other test configs? Or is this strategy whole bad?
thanks

A: You can selectively overwrite beans with the context merging functionality supplied by the @ContextHierarchy annotation.
In order to get this working for your use case you will have to create a base context that scans your app for Spring beans:
@Configuration
@ComponentScan({"com.example.our.app"})
public class MyTestConfig implements TransactionManagementConfigurer {

Then create a base class that utilizes this context and names it - this won't work with named contexts!:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy( {
    @ContextConfiguration(name="testContext", classes = MyTestConfig.class),
})
public class BaseTest {

And finally write a unit test that extends the base class and defines a new context under the same name to overwrite individual beans with a test specific configuration:
    @ContextHierarchy(@ContextConfiguration(name="testContext", classes = OneUnitTest.Config.class))
    public class OneUnitTest extends AggroBaseTest {
      @Configuration
      static class Config {
            ..
      }

A: I think best way here to use is Spring profiles.
Check here now to use H2 for tests with profiles.

A: You can also override with another import
<beans>
    <import resource="classpath*:applocationContext.xml" />
    <bean id="dataSourceFactory" class=com.demo.MyNewClass/>
</beans>

And in you class if you
this.applicationContext.getBean("dataSourceFactory");

retrieve the class, you would see the instance of new class
Further
<bean id="dataSourceFactory" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

So there are different ways you can override the default behaviour


text:
Q: ConTeXt: strange issue with typescript I am trying to use some fonts installed on my computer with typescript as explained in this post in order to create some fancy titles but I have a strange issue with \setuphead.
Here is an example with \switchtobodyfont in \setuphead's style:
\starttypescriptcollection [fira]
  \starttypescript [sans] [fira]
    \setups[font:fallback:sans]
    \definefontsynonym [Sans]           [file:FiraSans-Regular.otf]       [features=default]
    \definefontsynonym [SansItalic]     [file:FiraSans-RegularItalic.otf] [features=default]
    \definefontsynonym [SansBold]       [file:FiraSans-Bold.otf]          [features=default]
    \definefontsynonym [SansBoldItalic] [file:FiraSans-BoldItalic.otf]    [features=default]
    \definefontsynonym [SansCaps]       [file:FiraSans-Regular.otf]       [features={default,smallcaps}]
  \stoptypescript

  \starttypescript [mono] [fira]
    \setups[font:fallback:mono]
    \definefontsynonym [Mono]     [file:FiraMono-Medium.otf] [features=default]
    \definefontsynonym [MonoBold] [file:FiraMono-Bold.otf]   [features=default]
  \stoptypescript

  \starttypescript [math] [fira]
    \definefontsynonym [MathRoman] [file:Fira-Math.otf] [features=mathextra]
  \stoptypescript

  \starttypescript [fira]
    \definetypeface [\typescriptone] [rm] [serif] [modern] [default]
    \definetypeface [\typescriptone] [ss] [sans]  [fira]   [default]
    \definetypeface [\typescriptone] [tt] [mono]  [fira]   [default]
    \definetypeface [\typescriptone] [mm] [math]  [fira]   [default]
    \quittypescriptscanning
  \stoptypescript
\stoptypescriptcollection

\setuphead[section][style={\switchtobodyfont[fira,sans]}]

\starttext
  \section{section 1}
  \section{section 2}
  \section{section 3}
\stoptext

What do happens here?

A: When you write typescripts for a new font ConTeXt stores these settings but no fonts are loaded at this point, this allows complicated typescript defintions where the upright, italic. etc styles can be changed when the fonts are loaded which is usefull for large font families.
Once you create a typeface with the \definetypeface commands ConTeXt loads all the necessary typescripts which can be a problem when you do this within regular text, because many line ends in typescripts blocks produce extra spaces with appear now in the output.
In the example below I create a simple typescript for the TeX Gyre Pagella font. The problem is that I load the font in a \hbox which flushes all spaces from my typescripts in horizontal mode.
\starttypescript [serif] [tex-gyre-pagella]
    \definefontsynonym [Serif]           [file:texgyrepagellaregular]    [features=default]
    \definefontsynonym [SerifItalic]     [file:texgyrepagellaitalic]     [features=default]
    \definefontsynonym [SerifBold]       [file:texgyrepagellabold]       [features=default]
    \definefontsynonym [SerifBoldItalic] [file:texgyrepagellabolditalic] [features=default]
\stoptypescript

\starttypescript [tgy]
    \definetypeface [tgy] [rm] [serif] [tex-gyre-pagella]
\stoptypescript

\starttext

\ruledhbox{\strut\space}

\ruledhbox{\strut\space\switchtobodyfont[tgy]}

\ruledhbox{\strut\space\ntimes{\kern\spaceamount}{5}}

\stoptext

Each linebreak in my typescript at the end of the \definefontsynonym settings creates a visible space and a additional space is created from the \definetypeface setting.

To avoid this problem you can drop the typescript environment for the \definetypeface commands which loads all necessary typescript before you load the fonts, e.g.
\definetypeface [tgy] [rm] [serif] [tex-gyre-pagella]

or you preload the typescript you want to use before you load it in your document, e.g.
\usetypescript[tgy]


text:
Q: List based on variable from two tables My program is a task program of sorts. What I'd like to do is construct a UI for a user/employee to see tasks they have to do on the given day the log in.
I have two tables, PostOne and PostEig, in a 1-M.

*

*PostOne is the master table that contains the information about a single task.

*PostEig is a table of users that are assigned to a task in Post One.

The models [simplified]
public class PostOne
{
    public string One { get; set; }
    [Key]
    public string Two { get; set; }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime ThrD { get; set; }
}

public class PostEig
{
    public string EigOne { get; set; }
    public string EigTwo { get; set; } //foreign key
    [Key]
    public string EigID { get; set; }
    [Required]
    public string EigA { get; set; }  //user login
}

I'm having trouble with the controller. I'm not even sure how to start on the code necessary to achieve my goal, so I'm going to try to write it out:

*

*call a list of PostEigs Where EigA == User.Identity.Name

*and from this list.. call a list of PostOnes Where Two == EigTwo

*and from this list.. call a list of PostOnes Where ThrD == DateTime.UtcNow.Date

I did try something like this:
public ActionResult SkedList()
{
    return View(db.PostEigs.Where(m =>
            m.EigA == User.Identity.Name ||
            m.EigTwo == db.PostOnes.Where(o => o.ThrD == DateTime.UtcNow.Date)
            ).ToList());
}

If this is unclear, please let me know. I appreciate any advice or solutions, even if in a different direction.

A: Sounds like this is a candidate for an Inner Join. I find it's much easier to think in terms of SQL then transform it into LINQ.
SQL Query:
SELECT
    po.*
FROM
    PostOnes po
INNER JOIN
    PostEig pe
ON
    pe.EigTwo = po.Two
WHERE
    pe.EigA = AUTH_NAME AND po.ThrD = TODAY()

C# LINQ Query:
var DB_PostEig = new List<PostEig>()
{
    new PostEig(){EigTwo = "Foo1", EigA =  "Foo"},
    new PostEig(){EigTwo = "Foo2", EigA =  "Foo"},
    new PostEig(){EigTwo = "Bar1", EigA =  "Bar"},
    new PostEig(){EigTwo = "Bar2", EigA =  "Bar"}
};

var DB_PostOnes = new List<PostOne>()
{
    new PostOne(){Two = "Foo1", ThrD = new DateTime(1900,1,1)},
    new PostOne(){Two = "Foo2", ThrD = new DateTime(2000,1,1)},
    new PostOne(){Two = "Foo3", ThrD = new DateTime(1900,1,1)},
    new PostOne(){Two = "Bar1", ThrD = new DateTime(1900,1,1)},
    new PostOne(){Two = "Bar2", ThrD = new DateTime(1900,1,1)}
};

var authName = "Foo";
var currentDate = new DateTime(1900,1,1);

//Not sure if this is the most optimal LINQ Query, but it seems to work.
var queryReturn = DB_PostOnes.Join(DB_PostEig.Where(x => x.EigA == authName), x => x.Two, y => y.EigTwo, (x, y) => x)
    .Where(z => z.ThrD == currentDate)
    .ToList();

queryReturn.ForEach(x => Console.WriteLine(x.Two + " - " + x.ThrD)); //Foo1 - 1/1/1900

Edit:
LINQ Query without a join
var queryTwo = DB_PostOnes
    .Where(x => DB_PostEig.Any(y => y.EigTwo == x.Two && y.EigA == authName) && x.ThrD == currentDate)
    .ToList();


text:
Q: How do I open WPS files in Word Starter 2010? Ok, this is driving me crazy. My parents have 100s of old WPS documents from an ancient version of MS Works, and they just bought a new computer with MS Word 2010 Starter on it. I ap trying to set it up so that the default program to open the WPS files is MS Word, but there is no EXE anywhere in program files or programfilesx86. I opened up process explorer and tried to figure out where the executable for Word is, and it turns out it is on the Q drive... the same Q drive that seems to be inaccessible no matter what I try. I tried adding the exact address of Word, but if I try and set that on anything, it says that it cannot find the file. This is driving me insane, is there any way to make it real easy to open these WPS files in Word?!?

A: oh my, the q drive? App-V! Seems like this gives a wee background on your setup.
Basically, this program isn't "installed" on their computer, rather, it is running in a virtual sandboxed environment from the Q drive making it a real rascal with file association.
Since I don't have the same set up as you, I can't try any of the below out, so, no promises:
Try the instructions found here, seems it'll fix your dilemma. Instead of locating excel.exe though, you should look for winword.exe inside the office14 folder.
After doing a bit of a search, I also found this thread on Microsoft Answers where a recent post by Angloblaxon gives a registry-based solution. You need to save the following to a text file with .reg extension, double-click it and say "yes" to importing into the registry:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.wps]
@="Word.Document.8"
"Content Type"="application/msword"
"SoftGridSource"="{90140011-0066-0409-0000-0000000FF1CE}"

A: Just as Jonas put in the thread above my solution seems to work. i also found another link if this one is giving you trouble
http://answers.microsoft.com/en-us/office/forum/office_2010se-word/how-do-i-associate-my-old-wps-documents-with/315f674e-a749-e011-8dfc-68b599b31bf5
This one seems to have built off of my original idea (allowing spreadsheets to work) and may prove to be better. I have not tried this one so please use at your own risk :)
http://mypersonalnerd.blogspot.com/2012/02/how-to-open-microsoft-works-xlr-wps.html

A: I opened Microsoft starter, after I put in my usb with wps files.  then I opened a blank page in Microsoft word starter and opened a file from my usb in the library and put it in word 6 - 9 (*.wps).  It cautions it may change the file.  Then I saved my wps in word 6.

A: Other possibilities are to use some open-source tools to convert the files into something more palatable to current editors.  You might try this link for some hints on getting into WPS files.


text:
Q: Reading from API And compare Date to display something So, the this is about consuming an API that has a date/time property. The content should change every 3 hours by comparing current user Date/time with that of the API and also assigning past and upcoming hours in a separate an arrays to be displayed in other section of the page. I managed to assign past and upcoming dates to their respective arrays. I need to compare the date and to assign "current data" if the user Date/Time is equal to or within 3 hours in a property to display it for the whole duration of three hours.
this.dataService.getData().subscribe((data:any[])=>{
const now = new Date('2021-02-14 09:00:00');

 for (const item of data) {
   const apiDate = new Date(item.dateTime);

    if(now.getTime() > apiDate.getTime()){
     this.future.push('future dates')
   } else if(now.getTime() < apiDate.getTime()){
     this.past.push('past dates')
   }else if(now.getTime() == apiDate.getTime()){
    //in real time, they'll only be equal for one second
    this.current = 'Show NOW'
   }
 }

This is the structure of API/Json Data retuned
[ {  "number": 10,   "dateTime": "2021-02-14 00:00:00" }, {  "number": 20,   "dateTime": "2021-02-14 03:00:00" }, {  "number": 30,   "dateTime": "2021-02-14 06:00:00" }, {  "number": 40,   "dateTime": "2021-02-14 09:00:00" }, {  "number": 50,   "dateTime": "2021-02-14 12:00:00" }]

a better approach to this would even be better.
Thanks

A: If your want to show time within range, then you can create an object with your time boundaries:
getTimeInterval = () => {
    const from = new Date();
    const to = new Date(from);
    to.setHours(to.getHours() + 3)
    return { from, to };
}

and then just check both boundaries of date from and to:
this.dataService.getData().subscribe((data:any[])=>{

    const dateRange = this.getTimeInterval();

    for (const item of data) {
       const apiDate = new Date(item.dateTime);

        if (dateRange.from.getTime() > apiDate.getTime()
           && dateRange.to.getTime() > apiDate.getTime())
        {
            this.future.push('future dates');
        }
        else if(dateRange.from.getTime() < apiDate.getTime())
        {
            this.past.push('past dates')
        }
        else if (dateRange.from.getTime() >= apiDate.getTime()
            && dateRange.to.getTime() <= apiDate.getTime())
        {
            this.current = 'Show NOW'
        }
 }


text:
Q: Creating a censor program - infile to outfile I am working on creating a censor program that takes a txt file and replaces all 4 letter words with **** and then the new text with the censored words is saved to the outfile. With this I am printing the infile with the censored words but it is not saving to the outfile. I am new to this and am having trouble figuring out what I'm missing to get it to print to the outfile. Any help is appreciated, thank you!
def censor():

    infile = open("word.list.txt", "r")
    outfile = open("new.word.list1", "w")

    for line in infile:
        words = line.split()
        for word in words:
            if len(word) == 4:
                print ("****")
            else:
                print (word)
                print(line.rstrip(), file=outfile)

    infile.close()
    outfile.close()

censor()

A: you need an empty array that will store the new line each line, then edit them the way you want. Then after that you just push the new line to the outfile
def censor():

    infile = open("word.list.txt", "r")
    outfile = open("new.word.list1", "w")

    for line in infile:
        words = line.split()
        newline=[]
        for word in words:
            if len(word) == 4:
                newline.append("****")
            else:
                newline.append(word.rstrip())

        print(" ".join(newline), file=outfile)

    infile.close()
    outfile.close()

censor()


text:
Q: Using Pivot for Age Ranges Issue I am using a pivot to group age ranges from an age column and all of the columns are not being filled as they should. I am taking the sum of LOS (length of stay) and the age range totals should equal the TotalLOS, but currently it is not. Please help!!
This is the T-SQL query:
SELECT *
FROM
(
SELECT [Hosp Name],
    Cnty,
    Max([Hosp County]) as [FirstOfHosp_County],
    Max(Hosp) as UID,
    LOS,
    Age,
    Sum(LOS) as TotalLOS,
    CASE
        WHEN Age <=17 THEN '0-17'
        WHEN Age Between 18 and 64 THEN '18-64'
        WHEN Age >=65 THEN '65 Up'
        ELSE NULL
    END AS AGERANGE
FROM [S1:  Basic Source Query]
GROUP BY [Hosp Name], Cnty, Age, [Hosp County], Hosp, LOS
) AS S

PIVOT
(
    Sum(S.LOS)
    for S.AGERANGE
    in ([0-17], [18-64],[65 Up])
) as pvt

I'm converting this query from Access.  This is the Access query:
TRANSFORM Sum([S1:  Basic Source Query].LOS) AS Days
SELECT [S1:  Basic Source Query].[Hosp Name],
[S1:  Basic Source Query].Cnty,
FirstOfHosp County:  First([S1:  Basic Source Query].[Hosp County])
UID:  First([S1:  Basic Source Query].Hosp)
Total:  Sum([S1:  Basic Source Query].LOS)
FROM [S1:  Basic Source Query]
GROUP BY [S1:  Basic Source Query].[Hosp Name],
[S1:  Basic Source Query].Cnty
PIVOT Switch([Age] Between 0 And 17,"0-17",[Age] Between 18 And 64,"18-64",[Age]>=65,"65 Up");

This is a sample of the Access data before the pivot. It doesn't have all the columns.
Hosp      Hosp Name             LOS     Age
HOSP301   Apple Hospital        16      92
HOSP301   Apple Hospital        5       34
HOSP301   Apple Hospital        14      85
HOSP301   Apple Hospital        7       21
HOSP301   Apple Hospital        4       79
HOSP301   Apple Hospital        2       26
HOSP301   Apple Hospital        2       19

And once the Access query runs, it turns it into this:
UID       Hosp Name             TotalLOS    0-17    18-64     65 Up
HOSP301   Apple Hospital        130                  117      13
HOSP301   Apple Hospital        5                    5
HOSP301   Apple Hospital        722         60       455      207
HOSP301   Apple Hospital        23          17                6
HOSP301   Apple Hospital        15                            15
HOSP301   Apple Hospital        6                    6
HOSP301   Apple Hospital        3           3
HOSP301   Apple Hospital        32          1        31

This is the incorrect SQL results I am getting. The numbers under the Age Ranges should match the TotalLOS column:
UID     Hosp Name       Cnty    FirstOfHosp_County    Age   TotalLOS    0-17    18-64   65 Up
HOSP301 Apple Hospital  Apple   Apple                 57    24                  4
HOSP301 Apple Hospital  Apple   Apple                 68    13                          13
HOSP301 Apple Hospital  Apple   Apple                 69    12                  4
HOSP301 Apple Hospital  Apple   Apple                 71    10                  10
HOSP301 Apple Hospital  Apple   Apple                 73    8                   2
HOSP301 Apple Hospital  Apple   Apple                 74    7                   7
HOSP301 Apple Hospital  Apple   Apple                 75    6                   6
HOSP301 Apple Hospital  Apple   Apple                 79    34                  17
HOSP301 Apple Hospital  Bacon   Apple                 63    2            2
HOSP301 Apple Hospital  Bagwin  Apple                 68    16                  16

So as you see the numbers in the ranges don't always match what's in the TotalLOS column. I believe I didn't convert it correctly from Access to T-SQL.

A: Not sure what your actual problem is, but if you change the SQL to something like this it might work better:
SELECT [Hosp Name],
    Cnty,
    Max([Hosp County]) as [FirstOfHosp_County],
    Max(Hosp) as UID,
    LOS,
    Sum(LOS) as TotalLOS,
    Sum(CASE WHEN Age <=17 THEN LOS else 0 end) as [0-17],
    Sum(CASE WHEN Age Between 18 and 64 THEN LOS else 0 end) as [18-64],
    Sum(CASE WHEN Age >=65 THEN LOS else 0 end) as [65 Up]
FROM [S1:  Basic Source Query]
GROUP BY [Hosp Name], Cnty, [Hosp County], Hosp, LOS

Edit: Removed Age, it makes no sense as a column.


text:
Q: Loop through Json, search for same key endings, delete key ending and put it in new objects I got a json from my database. I want two create a new object from this json. I want find all keys with the same ending and put it to a new object. The key endings can be different and morein other jsons from my database. I want also to delete this ending. Please see my example
This is my json:
   {
          "QMSI1_EndingTwo": "Anaesthetist",
          "QMSI2_EndingTwo": "1899-12-30  15:36:57",
          "QMSI3_EndingTwo": "1899-12-30 17:32:00",
          "QMSI4_EndingTwo": "note1",
          "QMSI5_EndingTwo": "ivf",
          "QMSI1_EndingOne": "Small culture bowl",
          "QMSI5_EndingOne": "lucas"
       }

i want this result:
 [{
    "QMSI1": "Anaesthetist",
    "QMSI2": "1899-12-30  15:36:57",
    "QMSI3": "1899-12-30 17:32:00",
    "QMSI4": "note1",
    "QMSI5": "ivf"
  },
  {
    "QMSI1": "Small culture bowl",
    "QMSI5": "lucas"
  }]

A: use .reduce to group the values in an object having keys as the "beginnings" that you get from splitting the key, then extract the Object.values :

const data = {
  QMSI1_EndingTwo: "Anaesthetist",
  QMSI2_EndingTwo: "1899-12-30  15:36:57",
  QMSI3_EndingTwo: "1899-12-30 17:32:00",
  QMSI4_EndingTwo: "note1",
  QMSI5_EndingTwo: "ivf",
  QMSI1_EndingOne: "Small culture bowl",
  QMSI5_EndingOne: "lucas"
};

const resultObj = Object.entries(data).reduce((acc, [key, value]) => {
  const [k, ending] = key.split("_");

  acc[ending] = acc[ending] || {};

  acc[ending][k] = value;

  return acc;
}, {});

const result = Object.values(resultObj).flat();

console.log(result);


text:
Q: Is union all going to work on this? I have two tables, income and expenditure, tried using union all, but the problem is the expense column is getting displayed in income and therefore affecting the balance. Any idea on where I am going wrong?
<?php
include "connection.php" ;

$result = mysql_query("select date, particulars, trntype, subincome, income, remarks,1 AS dummy from income UNION ALL select date, particulars, trntype, subexpense, expense,remarks, 2 AS dummy from expenditure ORDER BY `date` ASC, dummy ASC");
echo "

Date
Particulars
Transaction Type
Sub Expense
Expense
Sub Income
Income
Cash In Hand
Remarks

";

while($row = mysql_fetch_array($result))
  {
   echo "
";
  echo "" . $row['date'] . "	";
  echo "" . $row['particulars'] . "	";
  echo "" . $row['trntype'] . "	";
  echo "" . $row['subexpense'] . "	";
  echo "" . $row['expense'] . "	";
  echo "" . $row['subincome'] . "	";
  echo "" . $row['income'] . "	";
  $cashinhand = $cashinhand + $row['income'] + $row['income'] - $row['subexpense'] - $row['expense'] ;
    echo "" . $cashinhand . "	";
      echo "" . $row['remarks'] . "	";
  echo "
";
  }
  echo "
";

?>

Here, instead of displaying the subexpense and expense, in Sub Expense and Expense column, they are printed into Sub Income and Income column. Naturally, the Balance is getting added instead of reduced.

A: What happens in your query is that you mix expense and income in the same columns (cols 3 and 4).
Try adding null on columns you don't need for each query :
SELECT date,
       particulars,
       trntype,
       NULL as subexpense,
       NULL as expense,
       subincome,
       income,
       remarks,
       1 AS dummy
FROM   income
UNION ALL
SELECT date,
       particulars,
       trntype,
       subexpense,
       expense,
       NULL as subincome,
       NULL as income,
       remarks,
       2 AS dummy
FROM   expenditure
ORDER  BY `date` ASC,
          dummy ASC

This way, each subquery is formatted the same way as the expected HTML output, with a different column for each value type.

A: You have to add a pseudo column in each query to keep the separated for the union.
select date, particulars, trntype, subincome, income,
  null as expence, remarks,1 AS dummy
from income
UNION ALL
select date, particulars, trntype, subexpense, null as income,
    expense, remarks, 2 AS dummy from expenditure ORDER BY `date` ASC, dummy ASC


text:
Q: Inverse Function of sum of exponential function What is the inverse function for
$$y=a^x+b^x+...+z^x$$
where $a, b, .. , z$ are positive constant and $x>0$
Thanks in advance!

A: I doubt you can come up with a closed form for such an inverse, when an inverse exists.
This can be written as a generalized polynomial: $$y=u^{\alpha_0} + u^{\alpha_1}+\dots$$ where $u=e^{x}$ and $\alpha_0=\log a, \alpha_1=\log b,...$. The case $\alpha_i = i$ for $i=0,\dots,n-1$ then would give you an inverse to the function:
$$ y = 1+ u+u^2+\cdots+u^{n-1}= \frac{u^n-1}{u-1}$$
There is not even a known closed form for the inverse function for this polynomial, as far as I know, for $n>4$. It has an inverse, because it is increasing when $u>0$ (which is true when $u=e^{x}$.)
Inverses are hard.