text:
Q: Is CROSSJOIN between a hierarchy and a dimension attribute possible? I am currently displaying the descendants of the agent branch hierarchy up to the agent name level using the MDX:
UNION (
{DESCENDANTS ([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Retail],5,SELF_AND_BEFORE) }
,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Digital],5, SELF_AND_BEFORE)}
,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Telesales],5, SELF_AND_BEFORE)}
,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Head Office],5, SELF_AND_BEFORE)}
)

However, I would like to display the AgentEmployeeNumber alongside the name of the agent. AgentEmployeeNumber is not part of the AgentBranch Hierarchy though and I can't seem to find a way of cross-joining the two together, is this possible at all? I have supplied a snip of the structure of the agent dimension below:

A: You can use a cross join (short form of that is *) for (I assume) the rows like this:
SELECT
    {} // add whatever you want, I assume you have measures here
    ON COLUMNS,
    UNION (
        {DESCENDANTS ([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Retail],5,SELF_AND_BEFORE) }
        ,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Digital],5, SELF_AND_BEFORE)}
        ,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Telesales],5, SELF_AND_BEFORE)}
        ,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Head Office],5, SELF_AND_BEFORE)}
    )
    *
    [Agent].[Agent Employee Number].[Agent Employee Number].Members
ON ROWS
FROM [Your Cube]

The downside is that for Agent Branch Hierarchy members not on single agent level, you will get many numbers. One way around this would be a calculated measure which you would put on the columns:
WITH MEMBER Measures.[Employee Number] AS
     IIf(
         (EXISTING [Agent].[Agent Employee Number].[Agent Employee Number].Members).Count = 1,
         (EXISTING [Agent].[Agent Employee Number].[Agent Employee Number].Members).Item(0).Item(0).Name,
         NULL
     )
SELECT
    Measures.[Employee Number] // add whatever you want, I assume you have measures here
    ON COLUMNS,
    UNION (
        {DESCENDANTS ([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Retail],5,SELF_AND_BEFORE) }
        ,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Digital],5, SELF_AND_BEFORE)}
        ,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Telesales],5, SELF_AND_BEFORE)}
        ,{DESCENDANTS([Agent].[Agent Branch Hierarchy].[Agent Business Division].&[Head Office],5, SELF_AND_BEFORE)}
    )
ON ROWS
FROM [Your Cube]

The member definition statesmore or less: "If the set of employee numbers for the current Agent Branch Hierarchy member has exactly one element, then take the first (and only) element's name as the measure value. Note that calculated measures can return strings, and need not necessarily be numeric.


text:
Q: Docker won't change VHD location So I am running on win10 with Hyper-V.
Docker is currently using a harddrive instance thats stored on my C drive (which is an ssd with very little space) I want it on my sshd which is my D drive.
The following is what I tried and has failed, because it looks like Docker just jumps back to its default every time.

*

*change is using the docker interface in the advance section (to a copy of the vhdx file in the d drive)

*changing it manually in the hyperv manager by having it migrate the harddrive to a new location

As well as other variations where I restart my computer after doing these.

A: Use docker > settings > advanced > change vhd location. Notice, you should select an empty directory instead of copy the VHD file by yourself.

A: *

*Stop  / Shutdown Docker

*Copy/Move the existing .vhdx from

C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx

to

D:\MobyLinuxVM.vhdx (your preferred ssd location)

*Edit the Docker settings.json file (%APPDATA%\Docker\settings.json) and configure

"MobyVhdPathOverride": "D:\MobyLinuxVM.vhdx"

*Now start the Docker again - the changes should be in place.

A: When I was having similar problems in that simply changing the Disk image location path would not stick upon a docker restart; this process worked for me:

*

*Create the destination folder, make sure its empty (so no copies of MobyLinuxVM.vhdx)

*In Docker>Reset>Restore to factory defaults... restore your docker to factory defaults

*In Docker>Settings>Shared Drives give the drive( in your case, D) shared access to docker. Hit apply.

*In Docker>Settings>Advanced browse under Disk image location to your destination folder. Hit Apply.
ref: https://github.com/docker/for-win/issues/2063

A: This is DockerDesktop verison 4.7.1.
Click on the docker icon on the taskbar and go to settings or right click the docker icon on the taskbar and select settings. The window below will popup.

Navigate to the Resources on the left pane and scroll down (if Disk Image Location is not in view). Click on Browse and select an empty folder of your choice. Click on Apply and Restart and Docker Desktop will move the .vhdx from C:\Users\Public\Documents\Hyper-V\Virtual hard disks to your select folder.
If Docker Desktop encounters an error, close Docker Desktop and navigate to C:\Users\<User>\AppData\Roaming\Docker\settings.json and edit the "dataFolder": "D:\\Hyper-V\\Virtual hard disks\\DockerDesktop", to your destination folder. Restart Docker Desktop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to have VirtualBox with XP - Accessing Ubuntu localhost? On my Ubuntu hosts file I have something like this:
127.0.0.1 something.dev

So when I type http://something.dev I got the desired result.
I wish to do the same, but by using the browser located on the virtualbox.
If I do: 10.0.2.2 I get my ubuntu localhost.
But I wish to access something.dev specifically.
How can we do such a thing ?

A: Add 10.0.2.2 something.dev to the hosts file of your host OS (WinXP)


text:
Q: How do I display a greyed out next_post_link when there is no next post Wordpress hides the next and previous post links if there are none, but for the sake of visual consistency I'd like to serve up a greyed out version of the link when there is no next or previous post.
I'm assuming a simple if else statement will do, but I don't really do PHP.  Any thoughts?

A: The short answer is that there's not really an easy way to do it.  There is a solution, but it's sort of ugly. (see waay below.)
A Longer Answer
I'm including this here in the hopes that it's helpful to someone.
Whenever you happen to be using a built in WordPress function, it's instructive to actually go look at what the function does.  This is especially true if you wish to modify the output.
So let's track down next_post_link.  Here's the source of that function from wp-includes/link-template.php.
<?php
/**
 * Display next post link that is adjacent to the current post.
 *
 * @since 1.5.0
 *
 * @param string $format Optional. Link anchor format.
 * @param string $link Optional. Link permalink format.
 * @param bool $in_same_cat Optional. Whether link should be in a same category.
 * @param array|string $excluded_categories Optional. Array or comma-separated list of excluded category IDs.
 */
function next_post_link($format='%link »', $link='%title', $in_same_cat = false, $excluded_categories = '') {
    adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false);
}

Not very exciting.  Just a wrapper around another function:
<?php
function adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true) {
    if ( $previous && is_attachment() )
        $post = & get_post($GLOBALS['post']->post_parent);
    else
        $post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);

    if ( !$post )
        return;

    $title = $post->post_title;

    if ( empty($post->post_title) )
        $title = $previous ? __('Previous Post') : __('Next Post');

    $title = apply_filters('the_title', $title, $post->ID);
    $date = mysql2date(get_option('date_format'), $post->post_date);
    $rel = $previous ? 'prev' : 'next';

    $string = '';
    $link = str_replace('%title', $title, $link);
    $link = str_replace('%date', $date, $link);
    $link = $string . $link . '';

    $format = str_replace('%link', $link, $format);

    $adjacent = $previous ? 'previous' : 'next';
    echo apply_filters( "{$adjacent}_post_link", $format, $link );
}

The trouble spot is here:
<?php
if ( $previous && is_attachment() )
    $post = & get_post($GLOBALS['post']->post_parent);
else
    $post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);

if ( !$post )
    return;

If there's not a next post (what get_adjacent_post does), the function just returns -- bypassing any filters we may want to hook into. Sucks.
A Hackish PHP Solution
Create a wrapper around next_post_link in your theme's functions.php file.  Accept all the same arguments as next_post_link.  The only difference is that you're going to start an output buffer before calling next_post_link.  Then flush the buffer into a variable -- if the variable is empty, replace it with your placeholder/disabled link.
<?php
function wpse53800_next_post_link($format='%link »', $link='%title', $in_same_cat=false, $exclude_cats='')
{
    // start the output buffer
    ob_start();

    // call next_post_link
    next_post_link($format, $link, $in_same_cat, $exclude_cats);

    // flush the output buffer into $rv
    $rv = ob_get_flush();

    // if there's nothing in the buffer, you can add it
    if(!$rv)
    {
        $rv = 'replace this with disabled link';
    }
    echo $rv;
}

An Equally Hackish JavaScript (jQuery) Solution
Somewhere in your theme's JS file(s), you can select the next post link container and add a placeholder if there isn't anything.
An example for TwentyEleven:


text:
Q: Get Method in Laravel's Route Class? I wanted to have a look at the defined methods of Route class in Laravel. The first method we commonly use is get. Route::get('/', function() {});
But I am unable to find the get method in documentation. Anyone can share the link for the same ?

A: The API of Laravel can be found on GitHub as well as via the 4.2 API browser.
The methods you are looking for are on Illuminate\Routing\Router.

A: You can read everything about routing in much detail from their source code.
Routing class path will be:
    X:\wamp\www\YOURLARAVELFOLDER\vendor\laravel\framework\src\Illuminate\Routing\Router.php
Plus, you can find some in the documentation also:
    http://laravel.com/docs/routing
The methods that you can use with Route is an array: array('GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');


text:
Q: JSON Serialization of a Django inherited model I have the following Django models
class ConfigurationItem(models.Model):

    path = models.CharField('Path', max_length=1024)
    name = models.CharField('Name', max_length=1024, blank=True)
    description = models.CharField('Description', max_length=1024, blank=True)
    active = models.BooleanField('Active', default=True)
    is_leaf = models.BooleanField('Is a Leaf item', default=True)

class Location(ConfigurationItem):

    address = models.CharField(max_length=1024, blank=True)
    phoneNumber = models.CharField(max_length=255, blank=True)
    url = models.URLField(blank=True)
    read_acl = models.ManyToManyField(Group, default=None)
    write_acl = models.ManyToManyField(Group, default=None)
    alert_group= models.EmailField(blank=True)

The full model file is here if it helps.
You can see that Company is a child class of ConfigurationItem.
I'm trying to use JSON serialization using either the django.core.serializers.serializer or the WadofStuff serializer.
Both serializers give me the same problem...
>>> from cmdb.models import *
>>> from django.core import serializers
>>> serializers.serialize('json', [ ConfigurationItem.objects.get(id=7)])
    '[{"pk": 7, "model": "cmdb.configurationitem", "fields": {"is_leaf": true,    "extension_attribute_10": "", "name": "", "date_modified": "2010-05-19 14:42:53", "extension_attribute_11": false, "extension_attribute_5": "", "extension_attribute_2": "", "extension_attribute_3": "", "extension_attribute_1": "", "extension_attribute_6": "", "extension_attribute_7": "", "extension_attribute_4": "", "date_created": "2010-05-19 14:42:53", "active": true, "path": "/Locations/London", "extension_attribute_8": "", "extension_attribute_9": "", "description": ""}}]'
>>> serializers.serialize('json', [ Location.objects.get(id=7)])
    '[{"pk": 7, "model": "cmdb.location", "fields": {"write_acl": [], "url": "", "phoneNumber": "", "address": "", "read_acl": [], "alert_group": ""}}]'
>>>

The problem is that serializing the Company model only gives me the fields directly associated with that model, not the fields from it's parent object.
Is there a way of altering this behaviour or should I be looking at building a dictionary of objects and using simplejson to format the output?
Thanks in advance
~sm

A: This is one of those times where the answer may come too late for the original poster, but might come in handy for the next Googler.
If you need significantly more advanced serialization, I can't help you, but if you only want graceful handling of multi-table inheritance, the place to look is in: django/core/serializers/base.py at the Serializer base class.
In the serialize method there is a line:

for field in concrete_model._meta.local_fields:

Monkeypatching or overriding that class & replacing that line with:

for field in concrete_model._meta.fields:

There are some caveats to be aware of however, see commit 12716794db in the Django Git repo & these two issues:
https://code.djangoproject.com/ticket/7350
https://code.djangoproject.com/ticket/7202
Long story short, you probably should be careful about doing this globally, though overriding that behavior may be fine depending on your goal.

A: You'll need a custom serializer to support inherited fields, as Django's serializer will only serialize local fields.
I ended up writing my own when dealing with this issue, feel free to copy it: https://github.com/zmathew/django-backbone/blob/master/backbone/serializers.py
https://github.com/zmathew/django-backbone/blob/351fc75797bc3c75d2aa5c582089eb39ebb6f19a/backbone/serializers.py
In order to use it on its own, you need to do:
serializer = AllFieldsSerializer()
serializer.serialize(queryset, fields=fields)
print serializer.getvalue()

A: Maybe it is very late, but I give my solution, in case it could be useful. I used an other Django library that do the trick:
from django.forms.models import model_to_dict

model_to_dict(Location.objects.get(id=7), fields = ['name', 'address', 'phoneNumber'])
model_to_dict(Location.objects.get(id=7))

You can specify or not fields list. I've tried with a model of mine, and it worked fine for me. The only difference is that in the output you will get only the filed value, not the model information.


text:
Q: SQL Server "Checking Database Table If there is a process going on the table" What I want to do is, inform the users about my program that "there is an update going on in database, so the results may not be correct." Thus I have to check if there is some process (like writing or deleting) on my table which my program uses.
Edit: The way that I update my table is I use MS Access, I copy from MS Excell about 10.000 rows and paste it to the database using MS Access. So when the copy paste is in progress, I want to be able see it from my web based program.
Thanks.

A: I'm not certain I understand what you are trying to achieve here.
SQL Server manages the integrity and consistency of your data for you, provided you are using a suitable Isolation Level.
So, if your count/reporting query attempts to access a record that is currently being updated, it will not be able to acquire a shared lock (on a record currently being updated) until after the update operation has completed, thereby ensuring only committed data is reported. The report is therefore correct as of the time it completes.
For further reading see: Transaction Isolation Levels

A: Update, re:

"Edit: The way that I update my table is I use MS Access, I copy from MS Excell about 10.000 rows and paste it to the database using MS Access. So when the copy paste is in progress, I want to be able see it from my web based program."

The principle is the same, at the start of your paste process, add a DB row, like in my first answer.  Or, you could set a global variable in your web application, something like updateInProgress = true.
But, how long does this copy take?   If it's less than about 5 minutes, then it's probably not worth doing anything else.
If you just want to let the user know that there is "fresh" data, you could query for recent datetimes.

What kind of update?   In the usual sense, SQL Server keeps the results accurate with default transaction locking.
Maybe you mean a long data-import job?  Or, Heaven forbid, some intensive, cursor-driven process?
Then you could do something like:

*

*Create a table in the database.  Call it, say LongJobLog.  It might have 3 columns: an ID, a start datetime, and an end datetime.

*At the beginning of each long job, add a new start time to this table, be sure to save the new ID to a variable.

*When the job ends, or errors out, update the ID's row with the endtime.

*Your application would query this table for recent rows (by the start time) that still had a null end time.   If such rows existed, then an "update" is in progress.

*You'll probably need a cron job to clear out entries where jobs crashed.
Alternatively, this start-stop information is probably available in the SQL logs.  It might take a bit of work to sort it out, though.

A: Make a shared counter somewhere (in the process, or if on a server, in a file or shared memory, etc.). Do your updates like this
increment the counter
query(UPDATE blablabla)
decrement the counter

Then you show the message if the counter is larger than 0.
(But is this what you really want? See comment)


text:
Q: How to Set Text Position in TextView with Compound Drawables? I have a textview.I have set setCompoundDrawablesWithIntrinsicBounds of textview.After that when I set text to the textfield the text shifted to right.How can I bring the text to the middle.Please help me.
Thanks for help in advance.
Drawable d =new BitmapDrawable(resizedbitmap);
description.setCompoundDrawablesWithIntrinsicBounds(d,null,null,null);
description.setText("hello");
description.setTypeface(Typeface.DEFAULT_BOLD);
description.setGravity(Gravity.CENTER);


text:
Q: 2 arguments in push_back I am trying to put 2 arguments inside a vector using push_back but its giving me an error since the function is allowed to take only one argument. How can I pass 2 arguments??
Vertex Class:
template <class VertexType, class EdgeType> class Vertex{
public:
std::vector<std::pair<int, EdgeType>> VertexList;
};

Outside Vertex Class inside Main():
project3::Vertex<string, string> v1("v1");
v1.VertexList.push_back(1,"e1");

Error is :
error C2661: 'std::vector<_Ty>::push_back' : no overloaded function takes 2 arguments
IntelliSense: too many arguments in function call

A: You need to do
v1.VertexList.push_back(std::pair<int, EdgeType>(1,"e1"));

A: Try push_back(make_pair(1, string("e1")));


text:
Q: Iterate an array multiple times depending on user input with new index added

import React, { useState } from 'react'
const data=["Red","Green","blue","orange","yellow"]

function App() {
  const [count, setCount] = useState(0)
  const [text, setText] = useState([])

  const handleSubmit = (e) => {
    e.preventDefault()
    let amount = parseInt(count)
    if (count <= 0) {
      amount = 1
    }
   //for now hardcoding to show only 5 item
    if (count > 5) {
      amount = 5
    }
    setText(data.slice(0, amount))
  }

  return (

Generate Fun Ipsum

      <form  onSubmit={handleSubmit}>
        paragraphs:
        <input
          type='number'
          name='amount'
          id='amount'
          value={count}
          onChange={(e) => setCount(e.target.value)}
        />
        <button  type='submit'>
          generate
        </button>
      </form>

        {text.map((item, index) => {
          return
{item}

        })}

  )
}

export default App

My query here is if user input value 8 then i should again reiterate the array and display 8 items
output should look like -
"Red","Green","blue","orange","yellow","Red","Green","blue"
if user inputs 10 then output should be:
"Red","Green","blue","orange","yellow","Red","Green","blue","orange","yellow"
if user inputs 12 then output should be:
"Red","Green","blue","orange","yellow","Red","Green","blue","orange","yellow","Red","Green"
I hope i am clear

A: You could combine simple for loop with modulo operator % to get the desired result

const data=["Red","Green","blue","orange","yellow"]
const { useState } = React

function App() {
  const [count, setCount] = useState(0)
  const [text, setText] = useState([])

  const handleSubmit = (e) => {
    e.preventDefault()
    let amount = parseInt(count)
    if (count <= 0) {
      amount = 1
    }

    const slice = []
    for (let i = 0; i < amount; i++) {
        slice.push(data[i % data.length])
    }

    setText(slice)
  }

  return (

Generate Fun Ipsum

      <form  onSubmit={handleSubmit}>
        paragraphs:
        <input
          type='number'
          name='amount'
          id='amount'
          value={count}
          onChange={(e) => setCount(e.target.value)}
        />
        <button  type='submit'>
          generate
        </button>
      </form>

        {text.map((item, index) => {
          return
{item}

        })}

  )
}

ReactDOM.render(<App />, document.querySelector("#app"))

A: You can try something like that:
setText(
    Array.from({length: amount}).map((_, i) => data[i % data.length])
)


text:
Q: Universal database GUI i need one GUI that will work on windows and i need to connect on several databases. Access, mySQL, MSSQL, Postgres, SQLite and maybe in future i will need connection to oracle.
It would be nice that tool can move database schemas from one db engine to others without lot user interference...
Can someone recomend me tool for this?
Thanks in advance

A: Try with navicat. It should do everithing you need...

A: Try on of these:

*

*SQL Workbench/j

*Aqua Data Studio
Both work on Windows, Linux and Mac.


text:
Q: Using an array in a MongoDB aggregation query with $or I'm trying to use an array in a MongoDB C# aggregation query with an $or statement. My code is as follows:
var groupsArray = new BsonArray
                          {new BsonDocument { { "role", 1 } },
                                new BsonDocument { { "role", 2 } },
                                new BsonDocument { { "role", 3 } }
                          };

      var bsonOr = new BsonDocument
                     {
                       {
                         "$or",
                         groupsArray
                       }
                     };

      var match = new BsonDocument { { "$match",
                                      new BsonDocument { { "$or", bsonOr } } } };

However, I'm getting the following exception:
MongoDB.Driver.MongoCommandException:
Command 'aggregate' failed: exception: bad query:
BadValue $or needs an array (response:
{ "errmsg" : "exception: bad query: BadValue $or needs an array",
"code" : 16810, "ok" : 0.0 }).

Is there a specific way to use an array in this query that I'm missing?

A: The or was being added twice. The code was changed to
var groupsArray = new BsonArray();

      foreach (var g in groups)
      {
        groupsArray.Add(new BsonDocument() { { "role", g.Id.ToString() } });
      }
      var bsonOr = new BsonDocument
                     {
                       {
                         "$or",
                         groupsArray
                       }
                     };

      var match = new BsonDocument { { "$match", bsonOr } };

And worked as I hoped.


text:
Q: JPanel's child components paint/layout problem I'm having a problem that when my frame is shown (after a login dialog) the buttons are not on correct position, then in some miliseconds they go to the right position (the center of the panel with border layout).
-- update
In my machine, this SSCCE shows the layout problem in 2 of 10 times I run it:
import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TEST {

    public static void main(String[] args) throws Exception {

    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {

        System.out.println("Debug test...");

        JPanel btnPnl = new JPanel();
        btnPnl.add(new JButton("TEST"));

        JFrame f = new JFrame("TEST");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(btnPnl);
        f.setPreferredSize(new Dimension(800, 600));
        f.pack();
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);
        f.setVisible(true);

        System.out.println("End debug test!");

        }
    });

    }

}

The button first appers in the up-left, and then it goes to the center. Is it a java bug?
--update
Looks like the SSCCE don't show the problem for everyone that is trying.
Maybe it's my computer performance problem. I still think Java Swing is creating new threads for make the layout behind the scenes. But I'm not sure.
--update
The problem only occur with the f.setExtendedState(JFrame.MAXIMIZED_BOTH);

A: Your problem intrigued me.  After some investigation I think I confirmed something that I recall about setting the window state (maximized, restored, etc) which is that setting the state is a request to the operating system and is left to the whim of the OS to process the request.  This means it is asynchronous, or at least done later, after you set it.  I confirmed using logging and adding resize listeners where you can see that the frame is resized after your block of code exits.  Because of this, the pack() will layout components to their preferred size.  So imagine the frame being sized to 800x600 and components positioned as such (button centered horizontally around 400).  Then later, the OS changes the size of the frame to full screen (e.g. 1024x768) - for a moment, you'll see the button still at 400.  Then the frame processes the new size and re-lays out components and centers the button at around 512.  So you'll see the flicker as it transitions during this process.  Perhaps a solution is to NOT pack() - it will remain at a size of zero and user will see minimum flicker.
Try this change first:
// pack()

If that looks good then you might have the next problem...if the user clicks the restore button, the whole frame shrinks into a black hole.  So try calling pack AFTER the frame has been predictably resized due to the maximize.  Something like this:
f.addComponentListener( new ComponentAdapter( ComponentEvent e ) {
  public void componentResized( Component) {
     if( f.getSize().getWidth() > 0 ) {
        e.getComponent().removeComponentListener( this );
        ((JFrame)e.getComponent()).pack();
     }
  }
}

So if the user later clicks restore button the frame will have a nicely packed size ready to go.
--Update
OK, one last attempt.  While I think my description of the problem has some truth, my solutions offered did nothing.  Here's one last attempt.  Remove pack() and setPreferredSize() and replace with setting the size to the screen size.  This seems to reduce the flicker greatly on my system.  This is because there should be no difference between the initial layout and the maximized layout done later.  You can see this if you switch between restore and maximized.  Although I still see a very slight flicker when switching the two, at least it seems to look better when first displayed.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TEST {

    public static void main(String[] args) throws Exception {

    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {

        System.out.println("Debug test...");

        JPanel btnPnl = new JPanel();
        btnPnl.add(new JButton("TEST"));

        JFrame f = new JFrame("TEST");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(btnPnl);
//        f.setPreferredSize(new Dimension(800, 600));
//        f.pack();
        f.setSize( Toolkit.getDefaultToolkit().getScreenSize() );
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);
        f.setVisible(true);

        System.out.println("End debug test!");

        }
    });

-Mike

A: I would guess that you need to call  pack() before making your frame visible.
If you are calling the above code not on the event thread then you have a race condition and all bets are off - you can only manipulate the GUI from the EDT (event dispatch thread).

EDIT: I tried your SSCCE on my system and it is not exhibiting the behavior you are seeing.  I tried it about 50 times, and also tried creating 10 windows by looping your code.  I am running 1.6.0_18 on Windows XP SP3.

A: Maybe you are missing a frameThatContainsCentralPanel.pack()?

A: Well, if it works with a SSCCE, then you've proven the problem isn't with the basic logic. There must be something different between the SSCCE and your real code. Since we don't have access to your real code you need to do the debugging yourself to see what the difference is.
However, in this case a better solution is to use a CardLayout, which is designed to let you swap panels easily. Read the Swing tutorial for a working example.
Or anther approach is to use a "login dialog". Once the login is successfull, you display your main frame with the panel for your application.

A: The "then in some milliseconds" part sounds to me like you need to call validate() on your frame.  Also, if you use f.pack(), your panel needs a preferred size, because pack() gives the parent's components their preferred sizes and resizes based on them.

A: If I copied your code, I had the same problem, but not so heavy.
I solved it by setting a preferred size for your frame before packing. So:
import java.awt.Dimension;

System.out.println("Debug test...");

JPanel btnPnl = new JPanel();
btnPnl.add(new JButton("TEST"));

JFrame f = new JFrame("TEST");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(btnPnl);
f.setPreferredSize(new Dimension(800, 600));
f.pack();
f.setVisible(true);
System.out.println("End debug test!");

I'm running on Linux.
It is indeed strange... I'm sure it is something about the size of all the containers in the swing tree.

A: I would expect the frame to be maximised both before it is shown, but after checking this I'm sure that on linux frame is maximised after it has been displayed.  You can make the frame size equal to a Screen size before calling setVisible, or you can make the components invisible until you know that the it's got preferred initial size. Here is modified sample which shows the elements after the frame has been activated (on linux activated event comes late enough to not show the "jumping button"):
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TEST {
public static void main(String[] args) throws Exception {

    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {

            final JPanel btnPnl = new JPanel();
            btnPnl.add(new JButton("TEST"));

            final JFrame f = new JFrame("TEST");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(btnPnl);
            // calculate preferred size for TEST frame
            // f.isDisplayable() will become true
            f.pack();

            // extended state, if can be applied, needs to be called after f.isDisplayable()
            WindowListener maxBoth = new WindowAdapter() {

                @Override
                public void windowOpened(WindowEvent e) {
                    f.setExtendedState(Frame.MAXIMIZED_BOTH);
                }
            };

            // after windows has been opened - maximize both
            f.addWindowListener(maxBoth);

            // initially hide the elements
            // after maximized state has been applied show them
            f.getContentPane().setVisible(false);
            f.addWindowListener(new WindowAdapter() {

                @Override
                public void windowActivated(WindowEvent e) {
                    f.getContentPane().setVisible(true);
                    // remove this listener
                    f.removeWindowStateListener(this);
                }
            });

            // set the frame visible
            f.setVisible(true);
        }
    });
}

}

A: Looks like a java bug. I've reported it (but for some reason it still not show on the bugs reports).


text:
Q: Is there a way to know which item has the focus in a WPF application? I there a way to know which item has the focus in and WPF application?
Is there a way to monitor all events and methods calls in wpf?

A: FocusManager.GetFocusedElement(this); // where this is Window1

Here's a full sample (when the app runs, focus a textbox and hit enter)
xaml:
<Window x:Class="StackOverflowTests.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" KeyDown="window1_KeyDown"
    Title="Window1" x:Name="window1" Height="300" Width="300">
    <StackPanel>
        <TextBox x:Name="textBox1" />
        <TextBox x:Name="textBox2" />
        <TextBox x:Name="textBox3" />
        <TextBox x:Name="textBox4" />
        <TextBox x:Name="textBox5" />
    </StackPanel>
</Window>

C#
using System.Windows;
using System.Windows.Input;

namespace StackOverflowTests
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void window1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if(e.Key == Key.Return)
                MessageBox.Show((FocusManager.GetFocusedElement(this) as FrameworkElement).Name);
        }
    }
}

A: ok on this page you'll find a solution but it's a bit nasty if you ask me:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a420dc50-b238-4d2e-9209-dfbd98c7a060
It uses the VisualTreeHelper to create a big list of all the controls out there and then asks them is they have the focus by lookin at the IsFocused property.
I would think that there is a better way to do it.
Perhaps do a search for Active control or Focussed control in combination with WPF.
EDIT:
This topic might be useful
How to programmatically navigate WPF UI element tab stops?


text:
Q: Apache Guacamole working fine over HTTP, but not over HTTPS I've recently installed Apache Guacamole on Ubuntu 20.04 LTS and use NGINX as the proxy server. Everything works fine with it over HTTP but when I use HTTPS, the application still loads, but then the connections are super slow (get stuck for some seconds). About configuration, I've exactly done what the official documentation says and all the services run on the same server.
EDIT: NGINX Configuration:
server {
    listen 80;
    server_name  guac.example.com;
    return 301 https://$host$request_uri;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

server {
    listen 443 ssl;
    server_name  guac.example.com;
    ssl_certificate /etc/ssl/certs/guacamole.crt;
    ssl_certificate_key /etc/ssl/private/guacamole.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5;
    location / {
        proxy_pass http://localhost:8080/guacamole/;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_cookie_path /guacamole/ /;
        access_log off;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

EDIT: As of the official documentation, the application uses WebSockets by default, but it will use HTTP requests if the WebSocket protocol is unavailable.
Any help is appreciated.


text:
Q: How to create an array based on two array I have an array of object, this array contains differents names.
[ "Foo", "Bar", "Test", "Other" ];

And another array of object
[ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ]

I need to create an array of them, the new array contains sub array with a size of 2, first index the name and second index the value.
The order of the array need to be the same of the first one (array of names).
Like
[ ["Foo", 120], ["Bar", 159], ["Test", undefined], ["Other", 1230] ]

So I try this code, but my output is not correct. The order of name is correct but the order of value is not.

var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];

var array = order.map(function(name, i) {
  return [name, (values[i] && values[i].value) ];
})

console.log(array)

A: You're nearly there - you just need to find the correct value:

var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];

var array = order.map(function(name, i) {
  return [name, values.some(e => e.name == name) ? values.find(e => e.name == name).value : undefined];
})

console.log(array)

ES5 syntax:

var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];

var array = order.map(function(name, i) {
  return [name, values.some(function(e) {
    return e.name == name;
  }) ? values.find(function(e) {
    return e.name == name;
  }).value : undefined];
});

console.log(array)

A: You could take a Map and get the items in the wanted order.

var names = [ "Foo", "Bar", "Test", "Other" ],
    objects = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }],
    map = new Map(objects.map(({ name, value }) => [name, value])),
    result = names.map(name => [name, map.get(name)])

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

A: Check out my solution. Hope this helps.

const a = [ "Foo", "Bar", "Test", "Other" ];
const b = [ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ];

const res = a.map((item) => [ item, (b.find(({ name }) => name === item) || {}).value ])

console.log(res)

A: You need to use entries in "order" to lookup "name" in values

var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];

var array = order.map(function(key, i) {
  let found = values.find(({name}) => name === key);
  return [key, found && found.value ];
})

console.log(array)

A: You could use map and take the Object.values of the found item, or a default one

const arr1 = [ "Foo", "Bar", "Test", "Other" ];

const arr2 = [ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ];

const res = arr1.map(e => Object.values(arr2.find(({name}) => name === e) || ({name: e, value: undefined})));
console.log(res);

A: var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var result = [];
orders.forEach((f) => {
let found = false;

values.forEach(s => {
    if (f === s.name) {
result.push([f, s.value]);
        found = true;
}
});
if (!found) {
    result.push([f, undefined]);
}
});


text:
Q: Display desired result by using Group by Mysql I have a mysql table with some repeated records, there was a column Error_code. In that if all data is correct then ok will be insert for all columns. If some data is wrong then Error will be insert for those wrong data records. If there is no Error, ok will be displayed in the related column.
But if Error is there then i want to display Error by using group by. How can I write query for that?
Sample table
voucherid ean error_code
123456    234 OK
123456    435 OK
123456    345 Ok

I am using below query by using group by
select voucherid, error_code
from voucher_info
group by voucher id

This query will return this data:
voucherid error_code
123456     ok

But if I have error code in the data the table will look like below
voucherid ean error_code
123456    234 OK
123456    435 Error
123456    345 Ok

Now I want to display error_code value as Error like below.
voucherid error_code
123456     Error

How to do that by using group by ? Any help would be greatly appreciated.

A: I am not sure if you have 2 tables or only one. If you have one table and
wants only to see if there a error you can do it like this:
SELECT
    vi.voucherid
    , GROUP_CONCAT(ean) eans
    , IF( COUNT(*) - SUM(IF(error_code = 'ERROR' OR @err = 'ERROR' , 0 , 1)) = 0 , 'OK', 'ERROR') error_code
FROM voucher_info vi
CROSS JOIN ( SELECT @err:='') AS initial
GROUP BY voucherid;

sample
mysql> select * from voucher_info;
+-----------+------+------------+
| voucherid | ean  | error_code |
+-----------+------+------------+
|    123456 | 234  | OK         |
|    123456 | 435  | OK         |
|    123456 | 345  | OK         |
|    123457 | 234  | OK         |
|    123457 | 435  | ERROR      |
|    123457 | 345  | OK         |
+-----------+------+------------+
6 rows in set (0,00 sec)

mysql> SELECT
    ->     vi.voucherid
    ->     , GROUP_CONCAT(ean) eans
    ->     , IF( COUNT(*) - SUM(IF(error_code = 'ERROR' OR @err = 'ERROR' , 0 , 1)) = 0 , 'OK', 'ERROR') error_code
    -> FROM voucher_info vi
    -> CROSS JOIN ( SELECT @err:='') AS initial
    -> GROUP BY voucherid;
+-----------+-------------+------------+
| voucherid | eans        | error_code |
+-----------+-------------+------------+
|    123456 | 234,435,345 | OK         |
|    123457 | 234,435,345 | ERROR      |
+-----------+-------------+------------+
2 rows in set (0,01 sec)

mysql>


text:
Q: TCP rsyslogd events showing up as 2000 character continuations I'm taking syslog events from a proprietary app.  This could be the app's fault or it could be rsyslogd.
Events are written like:
Aug 15 16:00:00 10.11.12.13 Event1 from this wonderful product using this odd
Aug 15 16:01:00 10.11.12.13 format. Event2 from this wonderful product using
Aug 15 16:02:00 10.11.12.13 this odd format. Event3 from this wonderful produ
Aug 15 16:03:00 10.11.12.13 ct using this odd format.

you get the picture.  Each record in syslog is ~2000 characters.
I'm not sure if this is an issue with the poorly defined nature of TCP syslog?
Does any expert on rsyslogd or syslog TCP have any advice as to where the problem might be?   Is it likely that there's something I can do on the rsyslogd side to fix this?  Or is this a normal mess for the state of TCP syslog?

A: rsyslogd is not configured to break lines like that. It's possible to use log format templates but I'm not sure they allow lines to be broken like that. This is most likely what the application is sending to rsyslogd.
You can try to capture the communication on port and check what is being sent (tcpdump -s 0 -A port 514).
Another test is to use logger to write a really long line. In my tests, rsyslogd wrote it as just a single line (no wrapping).


text:
Q: SQL Server Job runs successfully, but doesn't execute packages We have SQL Server 2012. We got .dtsx packages that run just fine. We run them manually and they execute properly, but when they are setup to be executed as SQL Server Job, the job executes successfully (no errors), but the SSIS packages are never executed. Nothing happens.
What would be the case? Permissions on packages are setup on FULL for SQLServerAgent user and same user is setup to be the owner of that job. Also that same user is setup to be DB admin on server.
Any clues how to resolve this?


text:
Q: How can I mark a message as read in MailKit I use MailKit to read some messages from a GMail Account. Works great, but when my application has read a message, I want to mark the message as read, and save that state to GMail. Is this possible with MailKit? I have not found anything about it yet.

A: The way to mark messages as read using the IMAP protocol is to set the \Seen flag on the message(s).
To do this using MailKit, you will first need to know either the index(es) or the UID(s) of the messages
that you would like to set the \Seen flag on. Once you have that information, you will want to call
one of the AddFlags() methods on the ImapFolder. For example:
folder.AddFlags (uids, MessageFlags.Seen, true);

To mark messages as unread, you would remove the \Seen flag, like so:
folder.RemoveFlags (uids, MessageFlags.Seen, true);


text:
Q: Where will be store all my local database tables records into elasticsearch server after dumping?
At present I am using elasticsearch-1.0.0.Beta2 for quick search the
  records.But while dumping I have 20000 recods in user table. But in
  elasticsearch server(http://www.domain.com) I can see only fifty
  records.But all records are dumping(means when I using this
  http://www.domain.com/index/type/id
  (http://www.domain.com/salambc/Question/51f9ac9024c8ce5261f4ee55))  by this
  time I get every record data from elasticsearch server what ever I have in my
  local database. But It will show only 50 records in elasticsearch
  browser.

Can you please help me where is the remaianing records are store. Thanks in advance.


text:
Q: Unable to import Spring bean definition file using relative path I am new to Spring and inherited a Spring project that had all the XML configuration in ProjectName/WebContent/WEB-INF/applicationContext.xml.  I'm trying to break the configuration into different components so it is easier to substitute things like DataSources and Hibernate configuation when testing.
Here is my file structure:
ProjectName
  ->WebContent
      ->WEB-INF
          ->applicationContext.xml
          ->spring-datasource.xml
          ->spring-hibernate-properties.xml
          ->spring-persistence.xml
  ->test
      ->us.mn.k12... (Java pkgs with JUnit tests)
      ->spring-hsqldb-datasource.xml
      ->spring-test-bean-locations.xml
      ->spring-test-hibernate-properties.xml
  ->src
      ->us.mn.k12... (Java pkgs with production code)

In WEB-INF/applicationContext.xml, I import the following:
<import resource="spring-datasource.xml"/> <!-- Production datasource -->
<import resource="spring-hibernate-properties.xml"/> <!-- Production hibernate properties -->
<import resource="spring-persistence.xml"/> <!--  DAO's, hibernate .hbm.xml mapping files -->

The application works with the above configuration.
My JUnit tests run using DbUnit and an HSQLDB in-memory database.  So my JUnit test references spring-test-bean-locations.xml, which has the following:
<import resource="spring-hsqldb-datasource.xml"/> <!-- HSQLDB datasource for test -->
<import resource="../WebContent/WEB-INF/spring-persistence.xml"/>  <!--  Production DAO's, hibernate .hbm.xml mapping files -->
<import resource="spring-test-hibernate-properties.xml"/> <!-- Hibernate properties for test -->

In this way, I can specify test datasource and hibernate properties, but reuse the production mapping file for the DAO's, etc. However, I get an error running my JUnit test. Here is the relevant part of the exception:
Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [../WebContent/WEB-INF/spring-persistence.xml]
Offending resource: class path resource [spring-test-bean-locations.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [../WebContent/WEB-INF/spring-persistence.xml]; nested exception is java.io.FileNotFoundException: class path resource [../WebContent/WEB-INF/spring-persistence.xml] cannot be opened because it does not exist

Now if I move spring-persistence.xml into /test so that I don't have to use the relative path, and reference it with <import resource="spring-persistence.xml"/>, then the tests run fine. So I think the contents of my XML files are OK, but I'm not properly importing with a relative path.
Is there anything obvious I'm doing wrong with my import of the relative path? And maybe the bigger question is does this look like a reasonable strategy for breaking applicationContext.xml into components to make it easier for testing?
Thanks!

A: The problem is: anything inside WEB-INF is not available to the ClassLoader in a regular project setup (and spring uses the ClassLoader by default to access resources). There are some hacks to work around this (like referencing the contexts using the file: prefix), but those are mostly ugly.
A better practice I'd suggest is to move the context files out of WEB-INF and into a dedicated resource directory (src/main/resources if you have a maven setup). That way they will be available to both the webapp ClassLoader and local unit test ClassLoaders.
Read the resources chapter to further understand the mechanisms involved.

A: Use
 <import resource="file:**/WebContent/WEB-INF/spring-persistence.xml" />

It works in spring 3.2.1.RELEASE.  Old versions I am not sure.


text:
Q: How can I git push to a specific folder? I'm using Travis CI to build my Jekyll site and push to Github. A lot of documentation around is for keeping the Jekyll code in the master branch, and building the site and pushing _site to the gh-pages branch. I want to avoid doing that and use the username.github.io repo on Github.
This is currently my build script:
#!/bin/bash

# skip if build is triggered by pull request
if [ $TRAVIS_PULL_REQUEST == "true" ]; then
  echo "this is PR, exiting"
  exit 0
fi

# enable error reporting to the console
set -e

# cleanup "_site"
rm -rf _site
mkdir _site

# build with Jekyll into "_site"
bundle exec jekyll build

# push
cd _site
git config user.email "john.doe@gmail.com"
git config user.name "John Doe"
git add --all
git commit -a -m "Travis #$TRAVIS_BUILD_NUMBER"
git push origin master

Of course, git push origin master as of now replaces the entire branch itself with the generated site. How do I generate the site and keep it within _site?

A: I am assuming you are running this script inside some folder. lets call that my_project.
Inside my_folder, when you run this script, it creates a _site folder.
Next you are doing cd _site. Dont do this.
Instead, remain at my_project folder and do the git config steps and others at this level.
So this will push all the stuff inside this my_project folder and the site will be inside the _site folder.

A: TL,DR:
Change these lines:
git add --all
git commit -a -m "Travis #$TRAVIS_BUILD_NUMBER"
To:
git add ./ #I assume you've cd'd into the directory you want to commit.
git commit -m "Travis #$TRAVIS_BUILD_NUMBER"

Explanation:
This question smells like a problem that someone coming from svn would have.(Skip the next paragraph if you aren't coming from svn)
There is a big difference in the way svn and git handle commits.
When you use svn, the commit always works relative to the current directory. So, the line cd _site changes what is known as the present working directory to _site. And there on out, svn only is concerned about the current directory and its children.
On the other hand, git commands will climb the directory path till they reach the root. So, when you are in _site and give a command with a --allor -a it will commit all the changes in the whole branch.
So, you replace --all with ./ in the add command which is just linux shorthand for the present directory. And remove the -a in the commit command. So the "changes added" are only from the present directory ie _site. This stages the changes for commit. You remove the -a from the commit command so that it only commits the staged changes.
As an aside, git add --all followed by git commit -a is redundant. The -a in commit ignores what is added to the stage and just commits all changes.


text:
Q: Local Notification userinfo not getting in launch options I'm sending LocalNotification from my iOS app. All notifications are arriving successfully. I'm handling those notifications using notification userInfo which is receiving from didReceive response function and facing no issues when app is in either background or foreground state.
But when app is in terminated (close) state, as we know that will get that notification userInfo in launchoptions as launchOptions?[.remoteNotification] of didFinishLaunchingWithOptions function in AppDelegate. But here I'm not getting that userInfo in launchOptions.
Let me know, is there anything need to enable in project settings? Please help me.

A: Try UNUserNotificationCenterDelegate.
    extension AppDelegate: UNUserNotificationCenterDelegate {

        func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    willPresent notification: UNNotification,
                                    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            completionHandler([.alert, .badge, .sound])
        }

        func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    didReceive response: UNNotificationResponse,
                                    withCompletionHandler completionHandler: @escaping () -> Void) {
            completionHandler()
            //response.notification.request.content.userInfo
        }

    }

Also, in didFinishLaucnhingOptions
if let notificationData = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
        //notificationData
    }


text:
Q: How to send this post without the submit How to send this post without the submit?
I need that as I point to the this html page the form is posted without any button submission.
I am not so expert then please the example should be as simple as possible.
Many thanks for your help.
This is my Post base code:

Send sms text

<form method=POST action="http://111.111.111.111:1111/smssend.cgi">

 Destination number
<input type=text name=num value="+39111111111"

 Message text
 <textarea name=text value="My message"></textarea>

 Password
 <input type=text name=Pwd value="SMSxxx">

<input type=submit value=Send>
</form>

A: Try the following code:

Send sms text

<form id="myForm" method=POST action="http://111.111.111.111:1111/smssend.cgi">

            Destination number
            <input type=text name=num value="+39111111111">

            Message text
            <textarea name=text value="My message"></textarea>

            Password
            <input type=text name=Pwd value="SMSxxx">

    <input type=button value=Send onclick="send();">
</form>


text:
Q: How to switch split screen Emacs where one screen is the editor while the other is terminal emulator?  I have ssh'ed to a remote machine and started emacs. I opened one small python application, and then split the screen into two, and M-x terminal-emulator in the other. I would like to edit the script in one section, then press C-x o and run it on the other section. Unfortunately, I can't seem to C-x o away from the terminal emulator and it just ends up typing x o.
Is there a better quick way of doing what I'm trying to do? Or is there a keystroke that will let me switch back to the editor section?
Edit: I just tried doing 'M-x shell', instead of 'M-x term', and that allows me to use C-x o to switch.

A: While at the * terminal* window, C-^ o to switch to other window, and C-^ C-h for more help.

A: ALT-X other-window
C-TAB also works locally.  Will that translate over SSH?  If not, bind other-window to another key that will go over SSH.

A: I found this post and I customized the .emacs file accordingly.
http://nex-3.com/posts/45-efficient-window-switching-in-emacs


text:
Q: Intent recycling in MainActivty I am attempting to start an intent on my MainActivity class after receiving an entry from an EditText field.  I pass some data with extras.  In my MainActivity I check to see if there are any extras from an Intent.  If so I process the data in an asynchronous task.  The problem is that my MainActivity goes through the process twice of checking for the extras from an Intent and eventually the program bombs.  It is very confusing and I will show below how the program flows.  First below is the initiation of the intent in another activity below the MainActivity.
   thisLocation = (EditText) findViewById(R.id.restlocation);

        thisLocation.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)  ||
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    String location = thisLocation.getText().toString();
                    Log.d("Location in key listener", location);
                    try
                    {
                    List<Address> foundGeocode = null;

                    foundGeocode = new Geocoder(getApplicationContext()).getFromLocationName(location, 1);
                    double  newlat = foundGeocode.get(0).getLatitude(); //getting latitude
                    double  newlng = foundGeocode.get(0).getLongitude();//getting longitude
                    Log.d("Lat in key listener", String.valueOf(newlat));
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("lat", String.valueOf(lat));
                    intent.putExtra("lng", String.valueOf(lng));
                    startActivity(intent);

                    }

                    catch (IOException e) {
                        Log.e("Geocode", String.valueOf(e));
                    }

    return true;
    }
    return false;
   }
 });

I can tell from my logs that the processing goes through the above routine twice before going to the MainActivity.  After the first time through the listener, the logcat shows the tag 'MapActivity' and the Text of "onDestroy leaving light on for com.example.herbx.Restaurant" which is the above activity.  The next time through I enter my MainActivity which also goes through the below logic twice each time preceded by the following message on my logcat:  Tag = MapActivity  Text=Recycling map object.
Next below is the MainActivity processing of the extras from the Intent received from the above activity.
    protected void onCreate(Bubdke savedInstanceState) {
       ......  intialization code

        Bundle extras = getIntent().getExtras();
    if(extras != null)
    {

        lat = Float.parseFloat(extras.getString("lat"));
        lng = Float.parseFloat(extras.getString("lng"));
        Log.d("lat=", String.valueOf(lat));
        NewMap(lat, lng);  // This is an asynchronous task
    }
       }

Below is a dump of my logcat showing where I logged certain data.
    03-20 19:21:30.256: D/Location in key listener(4045): Peoria
    03-20 19:21:30.519: D/Lat in key listener(4045): 40.6936488
    03-20 19:21:30.616: D/MapActivity(4045): onDestroy leaving the lights on for com.example.herb4.Restaurant@40fc2f88
    03-20 19:21:30.736: D/Location in key listener(4045): Peoria
    03-20 19:21:30.986: D/Lat in key listener(4045): 40.6936488
    03-20 19:21:31.016: I/Choreographer(4045): Skipped 45 frames!  The application may be doing too much work on its main thread.
    03-20 19:21:31.168: W/MapActivity(4045): Recycling dispatcher android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher@40cf8f38
    03-20 19:21:31.207: V/MapActivity(4045): Recycling map object.
    03-20 19:21:31.426: D/lat=(4045): 40.9040412902832
    03-20 19:21:31.746: D/newmap addr=(4045): W 7th StMinonk, IL 61760
    03-20 19:21:31.896: W/MapActivity(4045): Recycling dispatcher android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher@40cf8f38
    03-20 19:21:31.948: V/MapActivity(4045): Recycling map object.
    03-20 19:21:32.166: D/lat=(4045): 40.9040412902832
    03-20 19:21:32.206: D/GetRestaurant lat=(4045): 40.9040412902832
    03-20 19:21:32.387: D/newmap addr=(4045): W 7th StMinonk, IL 61760
    03-20 19:21:32.446: I/Choreographer(4045): Skipped 69 frames!  The application may be doing too much work on its main thread.
    03-20 19:21:32.726: D/dalvikvm(4045): GREF has increased to 201
    03-20 19:21:32.956: D/InputEventConsistencyVerifier(4045): KeyEvent: ACTION_UP but key was not down.
    03-20 19:21:32.956: D/InputEventConsistencyVerifier(4045):   in android.view.ViewRootImpl@4109f880
    03-20 19:21:32.956: D/InputEventConsistencyVerifier(4045):   0: sent at 15675516000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_ENTER, scanCode=28, metaState=0, flags=0x8, repeatCount=0, eventTime=15675516, downTime=15675423, deviceId=0, source=0x101 }
    03-20 19:21:33.166: E/InputEventReceiver(4045): Exception dispatching input event.
    03-20 19:21:33.166: E/MessageQueue-JNI(4045): Exception in MessageQueue callback: handleReceiveCallback
    03-20 19:21:33.256: E/MessageQueue-JNI(4045): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
   03-20 19:21:33.256: E/MessageQueue-JNI(4045):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
   03-20 19:21:33.256: E/MessageQueue-JNI(4045):    at java.util.ArrayList.get(ArrayList.java:304)

So my question is why does the program go through the logic twice when I enter data in the first activity above?  It is very confusing and the net result I get a an erorr saying Exception in MessageQueue callbackL handleReceiveCallback and an IndexOutOfBoundsException.
If anyone needs more information on this confusing issue please let me know.
Below is the code in which it appears I get the nullexception but I get the first log of "GetRestaurant lat=" but I don't get the second log which is "GetRestaurant try".  I have no idea where a nullexception can occur between those 2 logs.  Also, I come into this routine from other sources and it works, just doesn't work in this context.
 List<String> result = new ArrayList<String>();
URL url;
Log.d("GetRestaurant lat=", thislat);  // this gets logged
try {
 Log.d("GetRestaurant try", "");   //  this doesn't get logged
String query = "?lat=" + thislat + "&lng=" + thislng + "&uid=&vegkey=1";
url = new URL("http://10.0.2.2:8000/herbivorenew/webservice/frontpage1.php" + query);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
    InputStream in = httpConnection.getInputStream();
    BufferedReader br = new BufferedReader(
        new InputStreamReader(in));
String line;

int x=0;
while ((line = br.readLine()) != null) {
    result = new ArrayList<String>(Arrays.asList(line.split("&")));
     Log.d("GetRestaurant result=", String.valueOf(result.get(0)));
    x++;
}

A: onKey() is called twice, once when the key is pressed and once when the key is released. What you need to do is something like this:
public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER ||
            keyCode == KeyEvent.KEYCODE_ENTER) {
            if (event.getAction()!=KeyEvent.ACTION_DOWN) {
                return true;
            }

            // here goes your code

            return true;
        }

        return false;
    }


text:
Q: Create multiple consumers for same topic in kafka I am newbie and can see one example with one consumer in below github repository, but any ideas how to create multiple consumers for same topic in go lang?
https://github.com/confluentinc/confluent-kafka-go/tree/master/examples
Any consumer factory (to generate N consumers) available in confluent-kafka to read same topic (with partitions)?

A: There is an example in the Confluent github repo :
https://github.com/confluentinc/confluent-kafka-go/blob/master/examples/consumer_example/consumer_example.go
If you want to create multiple consumers for the same topic, there are two scenarios :
1.Create each consumer with different group id.
c1, err := kafka.NewConsumer(&kafka.ConfigMap{
        "bootstrap.servers":    broker,
        "group.id":             group1,
        "session.timeout.ms":   6000,
        "default.topic.config": kafka.ConfigMap{"auto.offset.reset": "earliest"}})

c2, err := kafka.NewConsumer(&kafka.ConfigMap{
        "bootstrap.servers":    broker,
        "group.id":             group2,
        "session.timeout.ms":   6000,
        "default.topic.config": kafka.ConfigMap{"auto.offset.reset": "earliest"}})

*If you want multiple consumers for the same topic but with the same group id, it will start consuming from single partition. i.e. A topic contains 3 partitions and you create 3 consumers with same group id, each consumer will consume from one partition


text:
Q: How to align two diagrams on the same line I would like to know how can I put two diagrams on the same like rather than one of the top and one at the bottom. which consumed too much space on the paper. Here are the codes for the figure which I used.
  \begin{figure}[!htb]\centering
     \frame{\includegraphics[width=10cm]{Data1}}
     \caption{Interpolation for Data 1}
  \label{Fig:Data1}
  \end{figure}

  \begin{figure}[!htb]\centering
     \frame{\includegraphics[width=10cm]{Data2}}
     \caption{Interpolation for Data 2}
  \label{Fig:Data2}
  \end{figure}

A: \documentclass{article}
\usepackage[demo]{graphicx}% delete [demo] later
\begin{document}

\begin{figure}[!htb]\centering
   \begin{minipage}{0.49\textwidth}
     \frame{\includegraphics[width=\linewidth]{Data1}}
     \caption{Interpolation for Data 1}\label{Fig:Data1}
   \end{minipage}
   \begin {minipage}{0.49\textwidth}
     \frame{\includegraphics[width=\linewidth]{Data2}}
     \caption{Interpolation for Data 2}\label{Fig:Data2}
   \end{minipage}
\end{figure}

\end{document}

put them in one figure environment without an empty line between. The % is important here.

A: I changed the width to fit it on a page, the total width you can use is dependend on the documentclass.
I would use subfigures as follows (for the image I used the tex.sx logo):
Code
\documentclass{article}
\usepackage{graphicx}
\usepackage{subcaption}

\begin{document}
\begin{figure}
\centering
\begin{subfigure}[b]{5cm}
\frame{\includegraphics[width=5cm]{Data1}}
\caption{Interpolation for Data 1}
\label{Fig:Data1}
\end{subfigure}
%
\hspace{1cm}
%
\begin{subfigure}[b]{5cm}
\centering
\frame{\includegraphics[width=5cm]{Data2}}
\caption{Interpolation for Data 2}
\label{Fig:Data2}
\end{subfigure}
\caption{Interpolation}\label{fig:TOF}
\end{figure}
\end{document}

Output


text:
Q: How to Find Solution from Within a Github Issue? On Github issues pages, how do you know which post contains the solution to the issue?
Take this page, for example.
The issue is closed, so we are to presume the problem is solved... yet this discussion thread (and many are much longer) seems to be mostly people talking back and forth in circles and it's very confusing to try to determine which post is intended or generally accepted to be the solution.
I was thinking it would be nice if the repo owner/representative could designate a post as what they determine to be the solution... with some kind of graphic... but I don't see that.

A: Ideally, if a pull request fixes an issue they would be linked by referencing the issue from the PR. For example, if a PR closes issue #123 the PR description would say closes #123 or fixes #123. You can also link them manually.
The PR would appear in the issue's "Linked Pull Requests" sidebar, and vice-versa.
For example, we can see that this PR is linked to this issue.

And from the issue we can see the linked PR.

In the issue, we can see activity on the linked PR as well as anything which mentioned it. A mention is a commit log or comment or issue or PR with something like #43878.

If the issue is closed for some other reason, ideally the person closing mentions why in a comment.
If people keep coming back to the issue and are confused, that may indicate the issue is not closed, or perhaps there is a related documentation issue.

In your example, we can see where the issue was mentioned in other issues.

And, sure enough, its referenced in issue #63056 and in PR #9 https://github.com/aws-amplify/amplify-flutter/pull/9#issuecomment-670038832. That information might help.
And we can see why the issue was closed, the change was intentional.

Unfortunately, the reason and resolution is buried in a comment. Improving the documentation may have been a better choice. That would have been done in a linked PR.

I was thinking it would be nice if the repo owner/representative could designate a post as what they determine to be the solution... with some kind of graphic... but I don't see that.

That would be nice. I don't believe Github has that feature. Posting it here is unlikely to reach Github. You could suggest it in Github Community or ask Support.
As a work around, one can make their final comment and then lock the issue so no further comments can be made. This would avoid burying the resolution. Then people would have to open a new issue if they really want to comment.
Or, one can edit the description of the issue to include a prominent reference to the resolution.

See also

*

*Autolinked references and URLs

*Linking a pull request to an issue


text:
Q: HTML JS скачет страница при нажатии Сайт
При клике на элемент сердечко или звезда выкидывает наверх страницы, как можно решить эту проблему.Ссылку на сайт прикладываю.

A: При нажатии на ссылку нужно отменить ее событие.
$("a").click(function(e){
  e.preventDefault();
})


text:
Q: How to define this partial-order? One element x in a partial-order amount is maximal if it dosen't exists $x \neq y$  with $x \le y$ and we have something that is called minimal if there doesn't exist  $ y \neq x$ with $y \le x$.
And we have $ S = \mathbb{N} $ that we let to be the Natural Numbers.
And i wonder how i can define a Partial-order on $\vec{S} \times \vec{S}$
there it exists a unique maximal element but no minimal element.
And to draw the Hassel-Diagram that contains all $(a,b)$ with   $a+b\le 4.$
I know that a Partial-Order should be Reflexive and Symmetric and Transistive but this is very abstract to think in natural numbers i think i must be very general to test this?
I am stuck?


text:
Q: How to move a domain from Godaddy to AWS Route 53 Since Godaddy went down for some hours my client and I are very upset and want to change everything to AWS.
Everything is done so far, only the domains (blablabla.com) are missing, I'm having a hard time trying to migrate from godaddy to Route 53, Do I have to remove from one and create from scratch from AWS?
Does anyone have any experience on how to do this?

A: Here are the steps to migrate your internet domain name to AWS route 53 (DNS Manager).
** Be careful where your mail server is hosted, either in the Godaddy mail service, Gmail (gsuite) or in your Cpanel server (VPS/Server).
 ** To empower your Domain DNS capabilities, you need to transfer the name servers, DNS records and domain name to AWS route53, thats why it's recommended to move to AWS Route 53. You can keep Godaddy to be owner of your yourdomain.com and manage your DNS by Route 53
STEPS:

*

*Go to Godaddy DNS records and understand each of them and note them (Take a screenshot)

*Go to AWS route 53, Crete a Public hosted Zone (Create your domain on AWS route 53).  Here is a good tutorial about it:
https://www.clickittech.com/aws/migrate-godaddy-to-aws-route53/

*Copy your Godaddy DNs records into your Public hosted zone previously created. Remember, each record needs to exist in the new aws zone.

*Change your Name Servers to AWS Route 53. What does it means? In order to allow AWS route 53 to manage your domain, DNs records, etc. you need to change your actual Godadaddy Name server (NS) Records to AWS Records.

*

*Go to Godaddy admin Panel and Login

*Go to DNS Management

*Under Name Servers Click on Change - > Custom - > Change Name Servers

You need to change from NSx.domaincontrol.com to the AWS Name servers.
More info: https://www.clickittech.com/aws/migrate-godaddy-to-aws-route53/
After 4-8 hours your Name Servers will be reflected and propagated around your country, world and networks.
Practically you are done with this.
Additionally, if you need to migrate your website or web app to AWS go to this tutorial, great explanation, see below:
https://www.clickittech.com/aws-migration/transfer-domain-aws-migrate-move-website-aws/

A: You can transfer the domain registration to AWS Route 53.
You have to "unlock" the account.
Log On to Go Daddy.
Go to Domain Details Then Settings:

*

*Lock: Set to Off

*Authorization Code: Email My Code

Route 53 will need the authorization code to complete the transfer request.

A: The answer from The Poet above is good for moving everything, but it will also kill your email service with GoDaddy. If you want to keep the email servers running at GoDaddy, you will also need to get your MX email servers and their priority numbers. Mine looked like this...
0 smtp.secureserver.net
10 mailstore1.secureserver.net

Take these over to your Route53 settings, click Create Record Set, choose a type of MX Mail Exchange, and paste these values in (with the number in the front as shown above). Save the record set.
Also PJT was correct; all domain info in Route53 ends with an extra period for some reason specific to AWS, but don't worry about it--it doesn't affect production behavior. When you copy your four from Route53 to paste in GoDaddy's Name Servers, you will need to do them one at a time and trim off the extra period at the end.

A: the solution:
Login on your aws console;
Click on Route 53;
Create Hosted Zone;
Select your new created host title and click "Go to Record Sets", take note of the nameservers;
Login on your Godaddy account;
Select your domain;
Go to Nameservers and click SetNameservers;
paste all the four you took from "Go to Record Sets" Route 53;
and that's it..., you don't have to rely on this horrible service Godaddy provides anymore

A: If you want to migrate your DNS records to Route 53, you'll need to export them from GoDaddy and recreate them manually in Route 53.
To do this in one automated step, consider a DNS migration tool such as DNSTools.ninja, as outlined here: https://dnstools.ninja/migrate-bind-aws-route53-safely-3-commands/

A: Be careful with google mx records if you have them.
Why switch to route 53?

*

*AWS Route 53 doesn't limit you to 64 subdomain.

*AWS allows you to host buckets with route 53

It all comes at a 50 cent/month.
AWS Nameservers
Now to answer your question, you need move the name servers to route 53. That means in godaddy name server section should be filled with aws name servers.
See the steps here.
https://metamug.com/article/dns-migrate-godaddy-to-route-53.php

A: The detailed steps to transfer the domain registrar from GoDaddy to Route 53 is given at https://cloudopian.com/blog/how-to-transfer-domain-registrar-from-godaddy-to-amazon-route-53/
Remember, you first need to transfer your name servers by creating a hosted zone in Route 53 and pointing your godaddy hosted domain to use Route 53's name servers instead of it's own name servers.


text:
Q: JSOUP website scraping How can this link be scraped: https://www.higheredjobs.com/details.cfm?JobCode=176261274&Title=Student%20Services%20Advisor?
It seems that site has a strong protection.
I tried smth like that:
Document doc = Jsoup.connect("https://www.higheredjobs.com/details.cfm?JobCode=176261274")
                .timeout(0) // Relax the server by according it infinite time...
                .maxBodySize(0)
                .header("Accept-Encoding", "gzip")
                .userAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36")
                .referrer("https://www.higheredjobs.com/details.cfm?JobCode=176261274")
                .cookie("D_HID","/iHO5bR2qxwBL4Zf0KOB6W28KoU9Q4K9/Ou8c5S+V3o")
                .cookie("D_UID","E0FB6547-868C-38AC-BAF2-A752089887E0")
                .cookie("D_IID","915B5DF8-71F1-3991-82F0-ED68EBA81949")
///all other cookies
                .get();

but response is:
<!DOCTYPE html>
<html>
 <head>
  <meta name="ROBOTS" content="NOINDEX, NOFOLLOW" />
  <meta http-equiv="cache-control" content="max-age=0" />
  <meta http-equiv="cache-control" content="no-cache" />
  <meta http-equiv="expires" content="0" />
  <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
  <meta http-equiv="pragma" content="no-cache" />
  <meta http-equiv="refresh" content="10; url=/distil_r_blocked.html?Ref=/details.cfm?JobCode=176261274&distil_RID=90819EF6-155B-11E6-97F5-80CDFCB63E7D&distil_TID=20160508202929" />
  <script type="text/javascript">
    (function(window){
        try {
            if (typeof sessionStorage !== 'undefined'){
                sessionStorage.setItem('distil_referrer', document.referrer);
            }
        } catch (e){}
    })(window);
</script>
  <script type="text/javascript" src="/ga100524.js" defer=""></script>
  <style type="text/css">#d__fFH{position:absolute;top:-5000px;left:-5000px}#d__fF{font-family:serif;font-size:200px;visibility:hidden}#qczbxvczrsvrrb{display:none!important}</style>
 </head>
 <body>
  <div id="distil_ident_block">

  </div>
 </body>
</html>


text:
Q: list of current logged users on a given sp web application
Possible Duplicate:
how to check how many users are currently logged in sharepoint foundation 2010

Is there a way to know who all are logged into the portal.abcd.com site? Is there a powershell or web analytic or Central admin process I can run to who all the logged into the portal site? or any SP site under sp web application.


text:
Q: Exposing osgi service as JAX-RS using apache cxf Can somebody provide me a simple example to expose a Restful service using apache cxf in an osgi bundle deployed on apache felix. We do not have the option to use Apache Karaf or any other application server.
Also , we plan to use iPojo for dependency injection.

A: Unfortunately installing CXF in plain apache felix is not very easy. Your best bet is to install on apache karaf first and get the list of required bundles from there.
You can find an example for cxf and rest with Apache Karaf here.
As you migrate you might need to tune the system package exports of felix to exclude the packages CXF wants to install as bundles.
I found something that may further help you. Type these commands in karaf 3.0.3:
feature:repo-add cxf 3.0.4
kar:create cxf-3.0.4 cxf-jaxrs

This will create a kar file in data/kar that contains the cxf feature file as well as all the jars (from the cxf feature). It allows you to specify which cxf features you need and quickly gather the required bundles. It will still be some work to make it work in felix but at least it helps a bit on the way.


text:
Q: No duplicates after insertion I'm (was) trying to make a LinkedList that removes duplicates during the insertion. This is my code:
LinkedList<WordInDocument> list = new LinkedList<WordInDocument>();
/**
 * Insert a word.
 *
 * @param insertWord The word that'll be inserted for, the word and it's Part Of Speech.
 * If you print "insertWord.word" you'll get the String of the word.
 */
public void insert (Word insertWord) {
    ListIterator<WordInDocument> listIt = list.listIterator();
    WordInDocument entry = new WordInDocument(insertWord);
    if (list.isEmpty()) {
        listIt.add(entry);
    }
    else {
        while (listIt.hasNext()) {
            //the iterator iterate with this if-statment,
            //if the iterator finds a equal word, then break
            if (listIt.next().wordInEntry.word.equalsIgnoreCase(insertWord.word)) {
                break;
            }
        }
        //only true if an equal word wasn't found, then ad the word at the end
        if (!listIt.hasNext()) {
            listIt.add (entry);
        }
    }
}

But if it's alot of inputs then it takes a long time to execute this (around 1 minute). Is their any better way of removing duplicate values during insertion?
EDIT:
Thanks for the help. I solved it by using "binary insertion" as I call it. That way it also is sorted after every insertion wich I inteded to do after the last insertion. Here is my code:
WordInDocument[] list = new WordInDocument[MAX_INDEX];
int currentMaxIndex = 0;
/**
 * Insert a word, it uses binary search to find where to put it, if the
 * current word dosn't exists, then insert it, this can bee called "Binary insert".
 * If the current word already exists, then ignore.
 *
 * @param insertword The word that'll be inserted for, the word and it's Part Of Speech.
 * If you print "insertWord.word" you'll get the String of the word.
 */
public void insert(Word insertword) { // put element into array
    WordInDocument entry = new WordInDocument(insertword);
    //First element
    if (list[0] == null) {
        list[0] = entry;
        currentMaxIndex++;
        return;
    }
    int inputIndex = binaryInsert(insertword);
    //It's at the end
    if (list[inputIndex] == null) {
        list[inputIndex] = entry;
        currentMaxIndex++;
        return;
    }
    //It's equal to another word
    if (list[inputIndex].wordInEntry.word.equalsIgnoreCase(word.word)) {
        return;
    }
    //It's between two entries
    for (int i = currentMaxIndex; i > inputIndex; i--) { // move bigger ones one up.
        list[i] = list[i - 1];
    }
    list[inputIndex] = entry;
    currentMaxIndex++;
}

 private int binaryInsert(Word word) {
    int lowerBound = 0;
    int upperBound = currentMaxIndex - 1;
    int compareStrings = list[mid].wordInEntry.word.compareToIgnoreCase(word.word);
    while (true) {
        int mid = (upperBound + lowerBound) / 2;
        if (lowerBound == mid) {
            if (compareStrings > 0) {
                return mid;
            }
        }
        if (compareStrings < 0) {
            lowerBound = mid + 1; // its in the upper
            if (lowerBound > upperBound) {
                return mid += 1;
            }
        } else if (lowerBound > upperBound) {
            return mid;
        } else {
            upperBound = mid - 1; // its in the lower
        }
    }
 }

Now it takes 2 seconds instead of 45 seconds.

A: If you would still like to use a LinkedList data structure (not a Set) and do this with Java8, here it is an easy and faster solution:
LinkedList<WordInDocument> list = new LinkedList<>();

public void insert (WordInDocument insertWord) {
    // try to find any matching element
    Optional<WordInDocument> optionalExistingWord =
        list
        .stream()
        .parallel()
        .filter(element -> element.word.equalsIgnoreCase(insertWord.word))
        .findAny();
    // if none is found, add the new element to the list
    if(!optionalExistingWord.isPresent()) {
        list.add(insertWord);
    }
}

A: You can remove duplicates via TreeSet:
    LinkedList<WordInDocument> list = new LinkedList<>();
    TreeSet<WordInDocument> set = new TreeSet<>(
            new Comparator<WordInDocument>() {
                @Override
                public int compare(WordInDocument d1, WordInDocument d2) {
                    return d1.word.compareToIgnoreCase(d2.word);
                }
            });
    set.addAll(list);
    list = new LinkedList<WordInDocument>(set);

this should be faster


text:
Q: How to process shortcodes with post_id outside `The Loop` I'm reading emails using postie.
I'm using the following filter to process keywords inside the email and convert them into wp_postmeta items.
My postie_post_before filter.
//look for ':keyword attribute:' tags and convert them to '[keyword attribute]'
function filter_content($post) {
    $content = $post['post_content'];
    $length = strlen($content);
    $pos = array(
        'name' => strpos($content, ':name '),
        'cost' => strpos($content, ':cost '),
        'price' => strpos($content, ':price ')
    );
    foreach ($pos as $key => $value) {
        if (false !== $value) {
            $content[$value] = '[';
            $value = strpos($content, ':', $value+1);
            if ( (false !== $value) && (ctype_alnum($content[$value-1])) ) {$content[$value] = ']'; }
        }
    }
    //if there is no name attribute then steal it from the subject line.
    if (strpos($content, '[name ') === false) {
        $content = ' [name ' . $post['post_name'] . '] ' . $content;
    }

    $post['post_content'] = $content;
    return $post;
}

My postie_post_after filter.
function resolve_shorttags($post) {
    $content = $post['post_content'];
    $content = do_shortcode($content);
    $post['post_content'] = $content;
    wp_update_post($post);
    storeDefaults($post['ID']);
    return $post;
}

Because I'm running do_shortcode outside of The Loop. get_the_ID() does not work. However I need the post_id in order for the processing to work correctly.
How do I pass the post_id of the posts I process in resolve_shorttags() to the shorttag hooks?
Remarks
I know this will get resolved if I leave the shorttags in and wait for display time and The loop to process the shorttags, but I want to process this data beforehand.
If there is a way to only process specific shortcodes or get the shortcode keys and attributes I'd be happy also. I can just call the handlers manually. What I don't want to do is write my own shortcode parser.


text:
Q: how to extract Elements in NSMutable Dictionary Array my server sends me an response in hierarchy way i do no how to grab the  value from that

here my sample response :

  {
    id = "-1";
    result =         (
                    {
            keyname = "Warranty Expiry Date";
            value = "06-14-2017";
        }
    );
},
    {
    id = "-1";
    result =         (
                    {
            keyname = Owner;
            value = "";
        }
    );
},
    {
    id = "-1";
    result =         (
                    {
            keyname = Model;
            value = "";
        }
    );
},
    {
    id = "-1";
    result =         (
                    {
            keyname = "Price $";
            value = 1000;
        }
    );
},
    {
    id = "-1";
    result =         (
                    {
            keyname = Vendor;
            value = "";
        }
    );
},
    {
    id = "-1";
    result =         (
                    {
            keyname = "Purchase Date";
            value = "";
        }
    );
}
)

here is sample Java code how they extracted the values

   Hashtable htAttrs = (Hashtable) editedAttrHash.get(assItmId);
        if (htAttrs != null) {
            Set<String> keys = htAttrs.keySet();
            for (String deAttr : keys) {
                xmlSerializer.startTag("", "attribute");
                xmlSerializer.attribute("", "keyname", deAttr);
                xmlSerializer.attribute("", "value",
      htAttrs.get(deAttr).toString());
                xmlSerializer.endTag("", "attribute");
            }
        }

i need to do no how to from this structure past one day i am blocked here anyone can fix my problem

A: How to extract values from nsmutablearray?If it is really nsmutablearray object, then extract the values is simple.
For example, to get id of first element:
NSString firstId = response[0][@"id"]

But it seems, like for now, it is just a json object. So, you should serialize it to nsarray object first.


text:
Q: SDL: Window freezes I wanted to start working on SDL. I got a sample code to see if it worked fine. When compiling I get no errors, but when I run it the window shows up but the program freezes until the delay time is over.
I'm new to this so I would really appreciate some help.
int main(int argc, char* argv[]) {

SDL_Init(SDL_INIT_EVERYTHING);

SDL_Window *window = 0;

window = SDL_CreateWindow("Hello World!",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        640, 480,
        SDL_WINDOW_SHOWN);

SDL_Delay(10000);

SDL_DestroyWindow(window);
SDL_Quit();

return 0;

}

A: As mentioned by @HolyBlackCat, you need an event loop :
https://wiki.libsdl.org/SDL_PollEvent
It should look something like this :
while (true) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        /* handle your event here */
    }
    /* do some other stuff here -- draw your app, etc. */
}

Edit
You will need to replace your delay with the event loop.
Instead, you can close the application on an event. The least you can/should do, is handle the SDL_QUIT event, which is sent when the user try to close the window:
while (!quit) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        /* handle your event here */

       //User requests quit
        if( event.type == SDL_QUIT )
            quit = true;
    }
    /* do some other stuff here -- draw your app, etc. */
}


text:
Q: FFMPEG Decoding - Memory Leak Developing an application for a test, I encountered an error. Meanwhile the packets were proccessed, I got a very horrible problem, a memory leak.
The av_free_packet is applied correctly, I think (See the code). When I run the app, the memory grows up to 500MB meanwhile it's playing the audio file, that's not normal. VLC or WMplayer (Windows Media Player) just wastes 30/20mb reading that file.
Here is the code:
static AVPacket pkt;
static uint8_t *audio_pkt_data = NULL;
static int audio_pkt_size = 0;
static AVFrame frame;
static bool first_time = true;

if(first_time){
    first_time=false;
}

int len1, data_size = 0;

for(;;){
    bool do_rt = false;

    while(audio_pkt_size > 0){
        int obt_frame = 0;

        len1 = avcodec_decode_audio4(_audio_ccontext,&frame,&obt_frame,&pkt);
        if(len1 < 0){
            audio_pkt_size = 0;
            break;
        }
        audio_pkt_data+=len1;
        audio_pkt_size-=len1;
        if(obt_frame){
            data_size = av_samples_get_buffer_size(NULL,channel_count,sample_fr,_audio_ccontext->sample_fmt,1);
            memcpy((int16_t*)audio_buf,frame.data[0],data_size);

        }
        if(data_size <= 0){
            continue;
        }
        do_rt = true;
    }

    if(pkt.data){
        //MessageBox(0,"hi","Hi",MB_OK); // This is only for test if the app si reaching this av_free_packet
        av_free_packet(&pkt);
    }

    if(do_rt){
        return data_size;
    }

    // Try to get a new packet
    if(!audio_packets.empty()){
        WaitForSingleObject(Queue_Audio_Mutex,INFINITE);
            pkt = *audio_packets.front();
            audio_packets.pop();
        ReleaseMutex(Queue_Audio_Mutex);

        audio_pkt_size = pkt.size;
        audio_pkt_data = pkt.data;
    }else{
        return -1;
    }
}
return 0;
}

I would appreciate your help. Thank you very much.

A: I think you would need to free frame too. As per ffmpeg reference
avcodec_decode_audio4()
The decoder will allocate a buffer for the decoded frame by calling the AVCodecContext.get_buffer2() callback. When AVCodecContext.refcounted_frames is set to 1, the frame is reference counted and the returned reference belongs to the caller. The caller must release the frame using av_frame_unref() when the frame is no longer needed. Please follow the link.
You can try adding
av_frame_unref(&frame)


text:
Q: jsp <% %> tags is displaying in browser and html tags is working fine when I am running the web application in server <% response.sendRedirect("sitesList.action"); %>

When I am running the application in server then jsp tags are displaying in browser. Please suggest what is the correct way.

A: 1.use<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=utf-8"%> in the file of first line.
2.check the file name is ".jsp"
try it.

A: have you used < and > for scriptlet tag?
if yes then please remove that and use<% %> scriptlet tag.


text:
Q: Sum over bilinear form in finite-field vector space Let $A$ be a linear map over the finite-field vector space $(F_2)^n$, i.e., an $F_2$-valued  $n\times n$ matrix, not necessarily symmetric. I'm interested in the sum
$$\sum_{X\in F_2^n} X^T A X\;.$$
Is there a way to efficiently compute this sum? Can one say anything interesting about when this sum is going to be $0$?

A: In interesting cases ($n\geq 3$) this is always $0$. Observe that
\begin{align*}
\sum_{x\in F_2^n} x^T A x &= \sum_{x\in F_2^n}\mathrm{Tr}( x^T A x)\\
&= \sum_{x\in F_2^n}\mathrm{Tr}( A x x^T)\\
&= \mathrm{Tr}( A \sum_{x\in F_2^n} x x^T)
\end{align*}
Let $B\triangleq\sum_{x\in F_2^n} x x^T$, then $B_{ii}=\sum_{x\in F_2^n} e_i^T x x^T e_i = 2^{n-1} \sum_{a\in F_2} aa=2^{n-1}$ which is $0$ as $n\geq 2$ and $1$ for $n=1$. Now if you take a non diagonal element $B_{ij}=\sum_{x\in F_2^n} e_i^Tx x e_j^T=2^{n-2}\sum_{a\in F_2} a\sum_{b\in F_2} b=2^{n-2}$, this is $1$ for $n=2$ and $0$ for $n\geq 3$ (the case $n=1$ does exist because there would not be diagonal elements).
In conclusion, if $n\geq 3$, $B=0$ and so $\sum_{x\in F_2^n} x^T A x =0$. If $n= 2$, then you get $\sum_{x\in F_2^n} x^T A x = A_{12}+A_{21}$ and for $n=1$ you get $\sum_{x\in F_2^n} x^T A x = A_{11}$.


text:
Q: Can I transfer iTunes credit between accounts? How would I go about transferring iTunes credit between accounts?
The question pretty well speaks for itself. I have two accounts, one for my iPod, one for my iPhone, I have passwords to both accounts, I can handle talking to Apple Support if that's what needs be, but I was curious if I can transfer the funds without going through customer service. Should I just "gift" myself purchases?

A: This totally will not work. iTunes explicitly says gift certificate balances can not be used to purchase other gift certificates. I will call apple tomorrow to find another work around.

A: You can not transfer allowance you have already redeemed onto a separate account - I am having just this problem at the moment and I am seriously pissed off with the difficulty and the lack of help ITunes give

A: Gifting content from one account to the other would be the simplest way to accomplish what you are looking for (albeit, this means you have to do the gifting from the device with the funds).

A: IIRC, you can use your account balance to send another user a (virtual) gift card.

A: Have you tried making an allowance to the desired account? That works between $10 and $50 so you should be able to drain any amount more than $10 this way over time by making sure the last month balance is at least $10. It doesn't involve purchasing a new gift card which is explicitly not allowed and may just work.
You can gift apps for the last $10 if the balance is initially less than $10 or the math doesn't work out nicely.
You might want to remove your credit card temporarily from the sending account in case it charges the allowance instead of spending down a store credit.

A: By the way, it's totally possible to call and get a credit issued as a check, if the balance was put there by a credit card or the like. This was how I ended up with such a balance, and I did not know you could do this. :D

A: In lieu of transferring an iTunes balance to another account, I have used dollars on my iPad to Purchase an app on my grandson's iPod, by using my iPad apple ID on his iPod.  The problem with that is that to update the app, he has to have your iPad apple ID.  Another way is to purchase apps on the iPad, back up to my PC, then connect his iPod to my PC and Install the app on the iPod.  You still have the same problem if he wants to update the app on his iPod, he has to have my iPad apple ID and password.