text:
Q: resolve choice for Glue dataframe not working I have a Glue data frame with the following structure, due to some historical data we have differences in the structure.
When I try to change the structure the resolveChoice is not working.
|-- logs: array
|    |-- element: struct
|    |    |-- ...
|    |    |-- target: struct
|    |    |    |-- ...
|    |    |    |-- details: struct
|    |    |    |    |-- ...
|    |    |    |    |-- reviews: struct
|    |    |    |    |    |-- comment: string
|    |    |    |    |    |-- generalReason: choice
|    |    |    |    |    |    |-- array
|    |    |    |    |    |    |    |-- element: array
|    |    |    |    |    |    |    |    |-- element: choice
|    |    |    |    |    |    |    |    |    |-- int
|    |    |    |    |    |    |    |    |    |-- string
|    |    |    |    |    |    |-- string
|    |    |    |    |    |    |-- struct
|    |    |    |    |    |    |    |-- deleted: long
|    |    |    |    |    |    |    |-- brandId: string
|    |    |    |    |    |    |    |-- brand: string
|    |    |    |    |    |    |    |-- name_JP: string
|    |    |    |    |    |    |    |-- status: boolean
|    |    |    |    |    |    |    |-- modifiedDate: string
|    |    |    |    |    |    |    |-- name_EN: string
|    |    |    |    |    |    |    |-- id: string
|    |    |-- ...
|-- SK: string
|-- PK: string

The code I am running:
case_logs_temp = case_logs.resolveChoice(
    specs=[
        ("logs.target.details.reviews.generalReason", "project:struct")
        ],
    transformation_ctx="case_logs_resolveChoice",
)

# case_logs.printSchema()
case_logs_temp.printSchema()

The printschema looks exactly like the one above.
Any ideas how to resolve the issue?

A: The following code works:
    specs=[
        ("logs[].target.details.reviews.generalReason", "project:struct")
        ],
    transformation_ctx="case_logs_resolveChoice",
)

Thanks to issue In AWS Glue, how do I apply resolveChoice to a struct element within an array in a DynamicFrame?


text:
Q: Showing message from inner class of a managed bean I have used the solution described in this discussion to implement BackgroundJobManager as an inner class inside my JSF bean class. I have also created an ABCTask (also an inner class) as a thread that will run at the scheduled time for the BackgroundJobManager. I have a requirement to push a message onto the JSF page but doing so from the task class ABCTask results in an NPE. The same thing works for the outer bean so i'm convinced it's something to do with the context of this inner class and the bean. Would appreciate if anyone knows a solution for this.
My inner class code is as below :
 public class ABCTask implements Runnable {

    public ABCTask() {

    }

    @Override
    public void run() {
        setTimeoutOccuredFlag(true);

        try {
                if (getActiveControlledAgent().isEventLogRunning()) {
                    getActiveControlledAgent().setEventLogRunning(false);
                }
                printTimeoutMessage();
        logger_o.fine("Now leaving the ABCTask ...");
        } catch (Exception e) {
            logger_o.error("An error while idling "+e.getMessage());
        }
    }

}

The $printTimeoutMessage() is as follows :
void printTimeoutMessage() {
    FacesUtils.addErrorMessage(MESSAGES.getString("common.timeoutOccured"));
}

A: You're basically manually spawning a thread. The FacesContext is only available in the thread serving the HTTP request which matches the URL pattern of the FacesServlet, not in other threads. The FacesContext#getCurrentInstance() would return null in all other threads.
Think once again, how would you ever send a message to the HTTP response without that the client has sent a HTTP request? By default, you can't send anything to the client without that it has requested for it.
Look for poll/push techniques. This concrete problem is completely unrelated to the class hierarchy/scope. In the future, it'd be more helpful for you and us if you've identified what exactly is null. You seem to not have done that at all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Will a bash-script continue execution even if the go-routine it is defined within is killed? I am running a Go application which has multiple Go routines . In one of the go-routines we are executing a bash script using the os.exec command which on one particular condition will kill the main thread of the application using SIGKILL (kill -9) and respawn the application once more . My doubt is whether the bash script will resume its operations once the goroutine is killed or will it also be stopped.

A: A process has a Kill() method that needs to be invoked to stop the script. So by killing the parent process, you'll be leaking the child processes.


text:
Q: Cannot access any websites { other than google, yahoo, gmail, youtube and facebook (http type) } on macbook air A week ago I had installed avast antivirus plus avast vpn for about an hour. That exact moment I encountered this trouble for the first time.
Then I uninstalled avast by clicking on the uninstall avast icon.
The problem still persisted.
Then  I didnt switch on mac for a day.
When I did the problem was gone and mac was back to normal. And i started downloading el captain on appstore.
Then I switched it off and restarted after sometime. The problem returned and the downloading showed error.
Then again after 2 days I tried same technique and the internet was alrite. But after i switched it off and restarted the problem began again.
I am not able to view any websites other than the above mentioned ones. Nor am I able to download any apple apps or update them on appstore.
I have tried Pram, safe boot, Nvprm etc.....
(I can view websites in safe boot mode but not in normal mode)
Can anyone please explain to me .. how to solve this???

A: Assuming the actual issue lies in the fact that Avast has messed with some of your connectivity settings, I recommend re-installing the software, followed by performing another uninstallation.

(((Avast has some pretty good instructions letting us know that throwing it into the trash does not uninstall the software for Avast (I know your explanation mentioned you clicked on uninstall, but I'm just  covering basics here).)))

Avast Official Instructions:

*

*Click the Avast Menu bar icon  on the top-right of the screen and
select Open Avast to open the Avast user interface,

*...alternatively, open Finder, go to Applications, and double-click
the Avast icon.

*Then click Avast in the Menu bar on the top-left of the screen,
select Uninstall Avast,

*...and when asked to confirm the uninstallation, click Uninstall.

Source (has pictures to follow).


text:
Q: Angular 4 with nodejs and Mysql connectivity I am new in angular and node js. I want to know how angular connect with node js with mysql server. Which simple return query result. Can anyone help me.

A: Angular is a fronend framework and nodejs can be used to implement a backend for a system. And you can use mysql as your DBMS.
You have to implement your backend and frontend separately. From backend you are exposing endpoints, routes, apis to the external applications.
And you can access those apis,routes from angular using HttpClient module. You can make Http requests using that.
Hope this helps

A: You may need to use some libraries to make a connection between angular frontend and backend with MySQL database.
You will need the express.js to handle the backend for the data request. Because you use the MySQL database, the database language would be different from any others such as MongoDB. The express provided database integration for the different databases.
You also need a body-parser as a middleware to parse the request body. This is a very important part of your project. The req is very complicated and this middleware can help to get the information which you need.
 Here is a sample of how to use express connect mysql.
var express = require('express');
var query = require('./query')
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var app = express();
//Middleware for bodyparsing using both json and urlencoding
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});
//login
app.post('/login',(req,res)=>{
    var opts = req.body;
    query(" SELECT *FROM `v_users` WHERE userAcount = ?",opts.userName).then((result)=>{
        var response = result[0];
        if(opts.password !== response.u_password){
            return res.send({
                errorCode:'404',
                errorMsg:'password error'
            })
        }
        //loginToken
        var loginToken = response.userAcount + Math.random()*Math.pow(10,16)
        res.send({
            loginToken:loginToken
        })
    })
})
var server = app.listen(3000,()=>{
    console.log('success')
})

Here is the query method:
(function() {
    var mysql = require('mysql');
    // var session = require('cookie-session');
    var query = (sql,key) => {
        var connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'root123',
            database: 'm_users'
        });
        connection.connect()
        var promise = new Promise((resolve,reject)=>{
            connection.query(sql,[key], function(error, results, fields) {
                if(error){
                    reject(error)
                }else{
                    resolve(results);
                }
            });
            connection.end();
        });
        return promise;
    }
    module.exports = query;
})()


text: Q: socket.io creates empty localStorage I am using socket.io v2.0.1 on my nodeJS server and today I spotted some odd behavior. I saw it indicates on google chrome that i have 1 "cookie" and when I checked it was some empty localStorage instance. Removing the <script src="/socket.io/socket.io.js"></script> from my html page stops creating this instance. Is this normal behavior and how can I stop it? I am already using cookie:false option on my socket.io server


text:
Q: SelectList pulling info from ViewBag: not creating value="..." in generated html I'm trying to create a client-side validated dropdown list in an MVC4 application using the Razor view engine.
The code in the view to generate the dropdown list is as follows:
 @Html.DropDownList("Test", new SelectList(ViewBag.AvailableLoBsDescriptions, ViewBag.AvailableLoBsIds), "--none--")

Note that ViewBag.AvailableLoBsDescriptions is created in the controller using an IList while ViewBag.AvailableLoBsIds is also created in the controller using an IList.
What I expected to happen is have Razor generate a dropdown menu where Descriptions populates the inner html of each  while the Ids populates the value="...".  However, there is nothing generated for value at all, resulting in something like this:
<select id="Test" name="Test"><option value="">--none--</option>
<option>N/A</option>
<option>aaaa</option>
<option>bbbb</option>
<option>cccc</option>
<option>dddd</option>
<option>eeee</option>
<option>ffff</option>
</select>

Looking at the SelectList documentation, http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx, it seems to me that this should work.  Does anyone have an idea why the values are not being generated for anything other than the placeholder?
Thanks!

A: The constructor you are using looks like the following:
SelectList(IEnumerable, Object)

The second parameter here dictates the currently selected object from the collection in the first parameter. It does not dictate an object to use as a list of values.
What you should be doing is using SelectList(IEnumerable, String, String). This allows you to pass the name of a property (of each element of IEnumerable) to use for the description and one for the value. You can then produce something like this:
Controller:
// Create your IEnumerable
var LoBs = new List<LoB>();

// Assign some parameters to your objects
var exampleItem = new LoB();
exampleItem.Description = "Option text";
exampleItem.Value = "myValue";

// Populate your list and return your view.
LoBs.Add(exampleItem);
ViewBag.LoBs = LoBs;
return View();

View:
@Html.DropDownList("Test",
    new SelectList(ViewBag.LoBs, "Value", "Description"),
    "--none--")

Et voila...
<select id="Test" name="Test">
    <option value="">--none--</option>
    <option value="myValue">Option text</option>
</select>


text:
Q: Concentration of sums of random vectors under moment conditions on the marginals Let $X_1,\dots,X_n\in {\bf R}^d$ be $d$-dimensional iid zero mean random vectors with covariance matrix $\Sigma$. I am interested in tail bounds for the Euclidean norm
$$N_n\equiv \frac{1}{\sqrt{n}}\|X_1 + X_2 + \dots X_n\|.$$
The main assumption should be that the one-dimensional marginals of $X_1$ have finite $L^p$ norm for some $p>4$, ie that there exists $c>0$ such that:
$${\bf (A)}_p:\forall v\in {\bf R}^d, {\bf Ex}\langle X_1,v\rangle^p\leq c \langle v,\Sigma v\rangle^{p/2}$$
where $\langle,\rangle$ is the usual inner product (edit: fixed typo in above display). More specifically, I am interested in Central-Limit-Theorem like bounds of the form:
$$(\star)\Pr(N_n>\sqrt{a_1 tr(\Sigma) + a_2 \|\Sigma\|_{{\rm op}}t})\leq e^{-t} + C n^{-\beta}$$
where $a_1,a_2$ are universal and $\beta,C$ depend only on $c$ and $p$ (and not on the dimension $d$); $tr(\Sigma)$ is the trace; and $\|\Sigma\|_{{\rm op}}$ is the operator norm.
If the $X_i$ are Gaussian, this result follows from an explicit calculation without the $n^{-\beta}$ term. A similar result holds if the $X_i$ are subgaussian [1].
Much less seems to be known for more general distributions. All results I found (see eg. [2]) assume less about the $X_i$'s but also give poorer bounds with respect to dependence on d. On the other hand, these results also go for an actual CLT whereas I just want the looser inequality $(\star)$.
Is there a (perhaps obvious) obstruction to this? Do you know any references that prove/disprove $(\star)$ or something close?
[1] A tail inequality for quadratic forms of subgaussian random vectors.
Daniel Hsu, Sham M. Kakade, and Tong Zhang.
Electronic Communications in Probability, 17(52):1-6, 2012.
[2] On the rate of convergence of the multivariate CLT.
F. Götze
Annals of Probability, 19 (2): 724-739, 1991.


text:
Q: How to select value from TcxDBLookupComboBox component? I am using Delphi 10.3 Rio and DevExpress 18.1.6 library.
Inside my project I have TcxDBLookupComboBox component.
I populate that combo box as you can see here

But when I select one of values and click on it, nothing happens.
I check properties of that component, but I can't find anything that could help me.
Any idea on how can I achieve that?

A: If you are getting that behaviour, you form isn't configured correctly.
Below is an extract from a sample project which is "self contained" in that
it creates its data annd look-up data in code in the Form's FormCreate event.
It works completely correctly - when I click in the DBLookUpcombo list
the value from the selected list entry immediately appears in the Value
field of ClientDataSet1
  procedure TForm1.FormCreate(Sender: TObject);
  var
    AField : TField;
  begin
    //  First create some dataset fields
    AField := TIntegerField.Create(Self);
    AField.FieldName := 'ID';
    AField.FieldKind := fkData;
    AField.DataSet := ClientDataSet1;

    AField := TStringField.Create(Self);
    AField.FieldName := 'Value';
    AField.FieldKind := fkData;
    AField.Size := 40;
    AField.DataSet := ClientDataSet1;

    ClientDataSet1.CreateDataSet;
    ClientDataSet1.InsertRecord([1, 'SomeValue']);

    AField := TStringField.Create(Self);
    AField.FieldName := 'luValue';
    AField.FieldKind := fkData;
    AField.Size := 40;
    AField.DataSet := cdsLU;

    cdsLU.CreateDataSet;
    cdsLU.InsertRecord(['One']);
    cdsLU.InsertRecord(['Two']);
    cdsLU.InsertRecord(['Three']);

    DBLookupComboBox1.DataSource := DataSource1;
    DBLookupComboBox1.DataField := 'Value';

    DBLookupComboBox1.KeyField := 'luValue';
    DBLookupComboBox1.ListField := 'luValue';
    DBLookupComboBox1.ListSource := DataSource2;

  end;

Remainder of TForm1:
  type
    TForm1 = class(TForm)
      DataSource1: TDataSource;
      DBGrid1: TDBGrid;
      DBNavigator1: TDBNavigator;
      ClientDataSet1: TClientDataSet;
      DBLookupComboBox1: TDBLookupComboBox;  // or TcxDBLookupComboBox
      cdsLU: TClientDataSet;
      DataSource2: TDataSource;
      procedure FormCreate(Sender: TObject);
    public
    end;


text:
Q: Sencha touch scroll is not working I have a main.js
**Ext.define('EDevlet.view.Main', {
viewport: {
    autoMaximize: true
},
extend: 'Ext.Container',
xtype: 'mainview',
defaultColumnCount: 2,
config: {
    scrollable:"vertical",
    cls: "page-content-style page-with-main-buttons",
    fullscreen: true,
    title: i18n["edevlet_title"],
    flex:1,
    height:800,
    layout: {
        type: 'vbox',
        align: 'stretch'

    },
    defaults: {
        flex:1
    },
    items: [{
        xtype: "panel",
       id: "greeting-message",
        cls: "greeting",
        docked: "top"
    }
    ]
},**

loadMenu: function () {
    Logger.log("@Main::loadMenu");
    this.removeAll(true, false);
    var services = SegmentUtil.getServiceContent(), // boş olma ihtimali yok, BE den gelmez ise yereldeki DEFAULT segment içeriğini kullanıyor
        maxServiceSize = SegmentUtil.getHomePageMaxServiceSize(),
        columnCount = this.defaultColumnCount,
        rowCount = Math.ceil((maxServiceSize + 1) / columnCount), // +1 diğer servisler düğmesi için !
        index,
        service,
        title,
        itemId,
        button,
        menuRow,
        rowIndex,
        isLeftSide,
        verticalPosition = -1;

    Logger.log('services: ' + services);
    Logger.log('rowCount: ' + rowCount + ', columnCount: ' + columnCount + ', maxServiceSize: ' + maxServiceSize);

    // satırları oluştur
    var newCount=rowCount+1;
    for (index = 0; index < newCount; index++) {
        if(index==0){

               **this.add({
                   id: 'mainRow-' + index,
                   xtype: 'carousel',   flex:3,
                   layout: 'hbox',
                  defaults: {
                       flex:1
                   },       items: [
                                    {    id: 'Image1',
                                         html: ''
                                    },
                                    {  id: 'Image2',

                                        html: ''
                                    },
                                    {    id: 'Image3',
                                        html: ''

                                   },
                                    {   id: 'Image4',
                                       html: ''
                                    }
                                ]
        });
                this.requestBackEndForNewsUrl();
        }
        else{

        this.add({
            id: 'mainMenuRow-' + index,
            xtype: 'container',
            flex:2,
          layout: 'hbox',
            defaults: {
                flex:1
            }
        });
        }**
    }

        }

    }

And I have a load function.Load function add items(this items is image).But my scrool seem but not working.I hold scroll but if a release scroll is going up.
I have a  vbox.After two hbox is added.But scroll is not working.

A: Try this. Write this override code in app.js file & then check.
// Fix for scroll
Ext.override(Ext.util.SizeMonitor, {
constructor: function (config) {
    var namespace = Ext.util.sizemonitor;
    return new namespace.Scroll(config);
}
});
Ext.override(Ext.util.PaintMonitor, {
constructor: function (config) {
    return new Ext.util.paintmonitor.CssAnimation(config);
}
});

A: Change your view's config to this:
scrollable: {
            direction: 'vertical',
            directionLock: true
},
flex:1,
height: '100%',

This will serve your purpose. Let me know if it helps or not.


text:
Q: 404 implementation in MVC Razor I am using ASP.NET MVC 4.5.1 razor C#
My Web.config is configured with one of the below tags.
<customErrors mode="On" defaultRedirect="Error">
  <error statusCode="404" redirect="/Error.htm"/>
</customErrors>

I have a class to catch all exceptions like below.
public class Error : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);
    }
}

My Base Controller is like below.
[Error]
public class BaseController : AsyncController
{

}

My Controller Action Method is like below
[HttpGet, Route("All-User"), LoginAuthentication, AdminAuthorization]
public async Task<ActionResult> AllUsers()
{
    var list = await _user.List();
    return View(list);
}

My Url is like below and works perfectly
localhost/All-User
When I execute below url, I get 404 but catch block of Error class is not being executed.
localhost/All-Userabc
Am I missing something ?
I also tried to Install-Package NotFoundMvc but this is not working and getting an exception "Invalid Operation Exception"

A: Your Error class won't be called for this url as it inherits HandleErrorAttribute which is called only when action method throws an exception. In your case no action method is executed as your URL does not match any route.
If you want your code to be executed for 404 errors try using default route example from this question - ASP.NET MVC - Catch All Route And Default Route


text:
Q: Change webview height based on html text using autolayot in ios swift created a webview which loads html text.
var html_string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."

self.webView.loadHTMLString(html_string, baseURL: nil)

i want set webview height to its content.without scrolling in the webView

A: Mind that the component is WKWebView, Webview is a thing of the past.
Try this function:
func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.frame.size.height = 1
    webView.frame.size = webView.sizeThatFits(.zero)
    webView.scrollView.isScrollEnabled=false;
    myWebViewHeightConstraint.constant = webView.scrollView.contentSize.height
    webView.scalesPageToFit = true
}

Remember to create an outlet for myWebViewHeightConstraint and updateConstrain as well.
You have a nice day!

A: Use following code for this, I hope this helps you.
Note:- 'UIWebView' was deprecated in iOS 12.0: No longer supported, So please use WKWebView instead of UIWebView
For UIWebView
func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.frame.size.height = 1
    webView.frame.size = webView.sizeThatFits(.zero)
    webView.scrollView.isScrollEnabled=false;
    myWebViewHeightConstraint.constant = webView.scrollView.contentSize.height
    webView.scalesPageToFit = true
}

For WKWebView
If you want to use WKWebView then you need to do the following things.
1) import WebKit
2) make your ViewController inherit from WKNavigationDelegate
3) hook up the WKWebView's delegate: webView.navigationDelegate = self
4) implement the following protocol function:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.frame.size.height = 1
    webView.frame.size = webView.scrollView.contentSize
}


text:
Q: Code Signing Certificate - Creating a PFX from a godaddy SPC & Key File Problem:
I generated a CRT using openssl; first I made a Key file; then Used the key file to generate a CRT.
I put the CRT text into the godaddy window; when they issued the code signing cert, they issued a SPC.
My Key and CRT are both TEXT, so I cannot import them through windows and standard utilities were unrecognized.
How do I create a PFX out of this? I cannot use internet explorer and windows sdks arent installing tools i need properly?

A: While many had success using visual studio toolkits, IE, etc, - all errored out for me. The best way to do this was to use the OPENSSL functions used to create the key & crt
1) Convert my KEY file (text) into a PVK file (binary)
openssl rsa -in EXAMPLE.key -outform PVK -pvk-strong -out EXAMPLE.pvk

2) Download PVK Import utility from microsoft (avoids Visual Studio packs, etc)
Download Microsofts PVK Import Util Here
3) Convert using the newly made PVK file (above) and the GoDaddy issued SPC
pvkimprt -PFX EXAMPLE.spc EXAMPLE.pvk

Source: PvkImport Instructions Walkthrough
Note, you will need to use the proper directories. In this example, I put the EXE in the same folder as my CRT, KEY, PVK, SPC files.


text:
Q: parsing a sentence - match inflections and skip punctuation I'm trying to parse sentences in python- for any sentence I get I should take only the words that appear after the words 'say' or 'ask' (if the words doesn't appear, I should take to whole sentence)
I simply did it with regular expressions:
sen = re.search('(?s)(?<=say|Say).*$', current_game_row["sentence"], re.M | re.I)

(this is only for 'say', but adding 'ask' is not a problem...)
The problem is that if I get a sentence with punctuations like comma, colon (,:)  after the word 'say' it takes it too.
Someone suggested me to use nltk tokenization in order to define it, but I'm new in python and don't understand how to use it. I see that nltk has the function RegexpParser but I'm not sure how to use it.
Please help me :-)
**
I forgot to mention that- I want to recognize 'said'/ asked etc. too and don't want to catch word that include the word 'say' or 'ask' (I'm not sure there are such words...).
In addition, if where are multiply 'say' or 'ask' , I only want to catch the first token in in the sentence.
**

A: Everything after a Keyword
We can deal with the unwanted punctuation by using \w to eat up all non-unicode.
sentence = "Hearsay? With masked flasks I said: abracadabra"

keys = '|'.join(['ask', 'asks', 'asked', 'say', 'says', 'said'])
result = re.search(rf'\b({keys})\b\W+(.*)', sentence, re.S | re.I)

if result == None:
    print(sentence)
else:
    print(result.group(2))

Output:
abracadabra

case-sensitive: You have case-insensitive flag re.I, so we can remove Say permutation.
multi-line: You have re.M option which directs ^ to not only match at the start of your string, but also right after every \n within that string.  We can drop this since we do not need to use ^.
dot-matches-all: You have (?s) which directs . to match everything including \n.  This is the same as applying re.S flag.
I'm not sure what the net effect of having both re.M and re.S is.  I think your sentence might be a text blob with newlines inside, so I removed re.M and kept (?s) as re.S


text:
Q: Is it possible to give a default to an output port, to allow sizing in the event the port is not required? Lets say I have an entity that looks like this:
constant NULL_PORT  : std_logic_vector(1 to 0);

entity some_verification_ip is
port (
  write_port : in  std_logic_vector  := NULL_PORT;
  read_port  : out std_logic_vector        -- Sized on connection
);

In one test, a user's DUT only does reads, and so only connects the read port, and the write port gets sized from the default assignment to the NULL_PORT constant.
In another test, a user's DUT only does writes, and only connects the write port, but you get an elaboration error because the read_port is not sized. So the user then needs a dummy_signal in the testbench (that isnt used) just to avoid this error.
You cannot do a := assignment to the output, as this is an initial value, and you get an elaboration error when the port is connected as the NULL_PORT width missmatches the user's port connection.
Is the dummy signal in the testbench the only way to get a size? Is this changing in VHDL 2018?
NOTE: In reality, my Verification IP is an AXI4 memory model, and in the design different parts handle reads and writes, so the various channels are not needed for all tests, but are needed for larger scale tests that cover reads and writes.

A: As @paebbles writes in the comments you can do such a thing when you add one or two generics to the module.
entity some_verification_ip is
generic (
    in_width  : positive; -- could use a := <default width>
    out_width : positive -- could use a := <default width>
);
port (
    write_port : in  std_logic_vector(in_width-1 downto 0);
    read_port  : out std_logic_vector(out_width-1 downto 0)
);

And when i stantiating you can use
.
.
generic map(
  in_witdth => inputsignal'length,
  out_width => outputsignal'length
)
port map (
.
.

If the in- and output widths are the same one generic can be used.
Initialising can then be done in a function.
I think this should work, but maybe i forgot something. The example should be enough to get yoh started though.
function null_port(width : positive) return std_logic_vector is
    ret : std_logic_vector(width-1 downto 0);
begin
    ret := (others => '0'); --use loops or other more elaborate stuff to construct the value you need
    return ret;
end function


text:
Q: SUMIFS not working in table (is working outside of table format) We have the below formula inside column D of our table
=SUMIFS(Table1[@[10/10/2022]:[30/11/2026]],Table1[[#Headers],[10/10/2022]:[30/11/2026]],">="&TODAY())
Using SUMIFS as we may add other parameters in the future.
Basically we are trying to sum entire rows but only from today in to the future. Historical data entered in these rows would not form the sum total as this would be catered for in the Actual column.
When we built this in a non table format it worked completely fine but now it is not working.
Fore reference, some of the date columns will be filled with numbers to sum and others not. Basically it's hour allocations dependant on the tasks being performed.

I'm hoping there is something simple we are missing to get this to work but haven't been able to find anything online.
Can someone please point us in the right direction?
Thanks very much

A: The dates in the headers will be interpreted as text unless coerced otherwise, so try:
=SUMPRODUCT(Table1[@[10/10/2022]:[30/11/2026]],N(0+(Table1[[#Headers],[10/10/2022]:[30/11/2026]])>=TODAY()))

A: =SUM((Table1[@[10/10/2022]:[30/11/2026]])*((Table1[[#Headers], [10/10/2022]:[30/11/2026]]+0)>=TODAY()))

The dates in the header are interpreted as text in the Excel formulas. They should be interpreted as date numbers to compare by summing number 0.
But in the SUMIFS() function, sum_range and criteria_range can't be edited.
So you can do a sum using the SUM() function simply. Also, "Multiply by TRUE and FALSE" is used for other parameters in the future.


text:
Q: Where can i find the C++ stl map implementation in C? Where can i find the C++ STL map implementation in C?Is Red Black Tree code which is used in c++ STL available in C language?

A: The code used to implement STL containers differs by compiler, but for all compilers, it's heavily dependent on C++ features (in particular, templates and classes with complex inheritance for implementation hiding, etc.). It's usually completely unreadable; trying to use it as a base for C code is only going to end in tears.
If you want red black tree code, might I suggest looking for implementations already written in C, e.g. this MIT alum's code.


text:
Q: Unable to login to MySQL with new user I currently have a MySQL database which I have added a new user (abbvs) to identified by a password.
The users I have:
mysql> select user,host from mysql.user;
+-------+-----------+
| user  | host      |
+-------+-----------+
| abbvs | %         |
| stnd  | %         |
| stnd  | 127.0.0.1 |
| root  | 127.0.0.1 |
| root  | ::1       |
|       | ATTD      |
| root  | ATTD      |
|       | localhost |
| stnd  | localhost |
| root  | localhost |
+-------+-----------+
10 rows in set (0.00 sec)

I have added SELECT for all databases, and ALL PRIVILEGES to another followed by flush_privileges;
SHOW GRANTS gives me the following:
mysql> show grants for 'abbvs'@'%';
+-------------------------------------------------------------------------------------------------------+
| Grants for abbvs@%                                                                                |
+-------------------------------------------------------------------------------------------------------+
| GRANT SELECT ON *.* TO 'abbvs'@'%' IDENTIFIED BY PASSWORD '####' |
| GRANT ALL PRIVILEGES ON `vardb`.* TO 'abbvs'@'%'                                                         |
+-------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

However, when I attempt to login via the CLI with the new user I get the following:
[root@ATTD ~]# mysql -u abbvs -p vardb
Enter password:
ERROR 1045 (28000): Access denied for user 'abbvs'@'localhost' (using password: YES)

Is there anything that could be causing this? All other logins work as expected.

A: This turned out to be the system lacking a localhost user as well as a remote (any host) user.
Once the additional user had been added for localhost everything worked as expected.


text:
Q: $(\partial_{tt}+\partial_t-\nabla^2)f(r,t)=0$ Hi I am trying to find the kernel of the linear differential operator $D$
$$
D\equiv\partial_{tt}+b\partial_t-a\nabla^2,\quad a,b>0.
$$
We have
$$
\nabla^2\equiv \frac{1}{r}\partial_r(r\partial_r)-\frac{1}{r^2}=\partial_{rr}+\frac{1}{r} \partial_r -\frac{1}{r^2}.
$$
So I am trying to solve
$$
Df(r,t)=\left(\partial_{tt}+b\partial_t-a\nabla^2\right)f(r,t)=0
$$
$$
\partial_t f(0,t)=0, \quad \partial_t(R,t)=v_0\cos \omega t
$$
What is the general way to do this for this linear PDE?  Thanks.
I assume we can just solve the pde by an ansatz for $f(r,t)$, however I am unsure of what to use.  Since this problem is in cylindrical geometry (hence the Laplacian like operator), maybe there will be Bessel functions as the Kernel?  I am not sure but trying to prove something.  Thanks!

A: Solutions can be found, thanks to the separation of variables. Not really a smart method, but effective anyways.

In addition, the boundary condition $\left(\frac{\partial(f(r,t)}{\partial t} \right)_{r=R}=v_0 \cos(\omega t)$ leads to look for a solution made with real sinusoidal functions of $\omega t$ . This implies a particular form of the exponential terms :


text:
Q: Client/Server TLS Authentication in Go What's the easiest way to get TCP Client/Server authentication via TLS/Certs/Keys in Go?
That is, I have a TCP server, and when a new client tries to connect to it, it should receive a certificate/key from the Server to allow it to connect again in the future without re-authenticating (or at least until the certificate expires). Both the client and the server should authenticate the other. OpenSSL isn't an option to create keys as the clients will be cross platform (Windows/macOS/Linux). Essentially, the server should only accept connections from known clients, and authorize new clients as needed (the clients can have some sort of known secret when installed).
Here's what I think the general flow is (correct me if I'm wrong)
Server: Get Cert/Key pair --> if they don't exist, create them --> listen on port --> receive connection --> verify Certificate is valid --> if not, reject --> if it is, continue to do what the server is supposed to do
Client: Get cert/key pair --> if they don't exist (i.e just installed), request from the server (Signed by the server) --> continue to connect as normal
This is still in the planning phase and open to all suggestions!
Thanks!


text:
Q: Add Swipe Event to my WP jQuery // Slide Show? I'm wondering how I can add the jQuery / Mobile Swipe event to my Wordpress Slide Show:
I'd like to be able to 'Swipe' through my slides with this using at Mobile.
Slide Show Code // Mark-Up with WP's PHP:

<?php $slide_id=1; ?>
<?php
 $featuredPosts = new WP_Query();
 $featuredPosts->query("showposts=3");
 while ($featuredPosts->have_posts()) : $featuredPosts->the_post();
 ?>

    <div id="slide-<?php echo $slide_id; $slide_id++;?>">
     <a href="<?php the_permalink() ?>" class="post-image">
         <?php the_post_thumbnail( 'rotator-post-image' ); ?>
         <?php the_title(); ?>

    <?php endwhile; ?>

        <?php $nav_id=1; ?>
        <?php while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>

                <a href="#slide-<?php echo $nav_id; ?>">

<? the_title(); $nav_id++;?>

                    <?php if($text= get_post_meta($post->ID, "slidetext", true)) { ?>

<?php echo $text; ?>

                        <?php } //else { print"
"; } ?>

        <?php endwhile; ?>

Script allowing the Slide Show:

Update: I've just tried:

With no such luck ~
ANY SUGGESTIONS - ?

A: To expand on my comment, here is how to programatically change a tab with jQuery UI's tab widget:
//cache all the tabs (I called them slides...)
//get the number of tabs
var $slides    = $('div[id^="slide"]')
    slideCount = $slides.length;

//bind the event handlers necessary
$slides.bind('swipeleft', function () {
    //this is to go to the next index

    //get current slide index and figure out the next one
    var currentIndex = $(this).index();
    if ((currentIndex + 1) < slideCount) {
        currentIndex++;
    } else {
        //the end was reached, so go back to the first tab
        currentIndex = 0;
    }

    //now select the new tab
    $("#photo-rotator").tabs( "select" , currentIndex);
}).bind('swiperight', function () {
    //this is to go to the previous index

    //get current slide index and figure out the previous one
    var currentIndex = $(this).index();
    if ((currentIndex - 1) >= 0) {
        currentIndex--;
    } else {
        //the beginning was reached, so go to the last tab
        currentIndex = slideCount;
    }

    //now select the new tab
    $("#photo-rotator").tabs( "select" , currentIndex);
});


text:
Q: Weird IE7 div resize float bug? Form buttons remain fixed! I have a form:
<form>

 form content (fields, etc)

      submit button
      cancel button

</form>

When I display error messages, the content div gets a bit bigger in height to fit in the error messages.
The weird thing is, in IE7 ONLY, the buttons div gets pushed down as it should, but the buttons remain fixed, thus the top content div is overlapping the buttons by a bit!! HOWEVER, if I move my mouse over the buttons (I assume it's triggering a hover?), they move themselves down.
wtf?

A: You could try using this to see if a forced redraw will correct things.


text:
Q: Simple Encryption Algorithm I'm working on an elevator project just for fun, it's actually hardware.  But I think this is more of a software question.  I don't need to have this feature, in fact it is completely redundant, but I was curious so I'm adding it anyway so I can learn :P
I have an 8 bit address, 8 bit data bus, and an 8 bit encryption code.
I have a master and many slave devices.
The master knows the address of the slaves and knows the encryption code.
The slaves know their address and the encryption code as well.
I want a really simple algorithm such that:
The master sends "y" where, y = function(data,encryption code)
The slave receives "y" and can extract data by data = function2(y,encryption code)
I tried playing around with AND, XOR, OR, etc... and combinations of them, but couldn't figure it out.
Again I'm looking for simple algorithms.  If you don't mind you could do me a bigger favour and explain some theory on how I can come to such a solution/functions.
Thanks so much!

A: You can use XOR cipher it's very simple:
E(x,key)=> y= x XOR key
D(y,key)=> x= y XOR key

very simple!
You can upgrade the encryption  and to make it to cipher-block chaining that means  for example you have a data D you need to divide it to blocks, let say block of size B. for the first block you do:
E(b0,key)=> y0= b0 XOR key

the result its going to be the key for the next block encryption:
E(b1,y0)=> y1= b0 XOR y0 .... E(bn,yn-1)=> yn= bn XOR yn-1

The original data was D={b0,b1.....bn} and the encrypted data its now E={y0,y1....yn}
to decrypt the encrypted data you need to do the opposite way! that's all!


text:
Q: When to use an EC2 server? This question is a little more general than the title implies. I haven't been exposed to almost any server related code, so I hope you can be gentle with your replies.
What I want to know, really, is what kind of server I want, or need for a particular task. Here is the hypothetical task: I have an iPhone app, everybody on the app participates in a bunch of "text message" like conversations. So I can look at all the different conversations going on, and add my comments to any conversation. The conversations will also be broken down by category.
What is the appropriate way to both store, and retrieve this information (and update, etc)? Will I need an EC2 server in conjunction with S3 storage? Should I even bother with the cloud? Essentially, how would I access this information?
Sorry for such basic questions, I am learning as I go here. Any point in the right direction, even if it's not an answer, would be greatly appreciated.

A: Generally you would want to decide how you are hosting your server side code. Changes are you would want to write a rails application as a back end.
You don't really need to worry about EC2 or S3. You probably want something a little higher up. Check out www.heroku.com for a great way to host ruby on rails applications. Rails makes it relatively easy to write server applications and Heroku will set you up with a database, web server, etc.
If you just want a way to store data in the cloud you could take a look at something like MongoHQ which is a cloud database. You could interface directly via the iPhone but generally this is a bad idea.


text:
Q: non-linear ODE method? I have the following system which I am trying to solve.
$$
(1) \qquad x' = ax(1-x) + b (1-x)^2
$$
The solution is:
$$
x(t) = \frac{e^{at}-1}{e^{at}-1 +(a/b)}
$$
My method is to first multiply out the brackets in (1) to obtain:
$$
x' = ax -ax^2 + b + 2bx + bx^2
$$
This is not separable so can't be directly integrated. I then collect like powers.
$$
x ' = (b-2a) x^2 + (a+2b)x + b
$$
I was trying to get it into a Bernoulli form apart from the $b$ term on the end! I do not know where to proceed from here.

A: Let $x=y+\lambda$ then with substitution in
$$x ' = (b-2a) x^2 + (a+2b)x + b$$
we have
\begin{align}
y '
&= (b-2a) (y-\lambda)^2 + (a+2b)(y-\lambda) + b\\
&= (b-2a) y^2 + y(2\lambda(b-2a)+(a+2b))+((b-2a)\lambda^2+(a+2b)\lambda + b)
\end{align}
determine $\lambda$ such that $(b-2a)\lambda^2+(a+2b)\lambda + b=0$, then you have the Bernoulli equation
$$y'-sy=(b-2a)y^2$$
where $s=\pm\sqrt{a^2+12ab}$.


text:
Q: Scanner returning an error for no reason? I'm trying to do this line of code. I want it to take a String, if it is 1,2,3,4,5,6,7,8,9 or 10 to parse it into a int and then check if it is between 0 and 9 (after a -1). The issue is right after the scanner happens I get an error no matter what I do...
public void guessEnter() {
    Scanner scan = new Scanner(System.in);

    String guessXS;
    String guessYS;
    boolean pass1;
    boolean pass2;

    do{
        do{
            System.out.println("Enter a value for the column!");
            guessXS = scan.nextLine();
            switch(guessXS){
                case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9":case "10":
                    System.out.println("TRUE");
                    pass1 = true;
                    break;
                default:
                    System.out.println("FALSE");
                    pass1 = false;
                    break;
            }
        }while(pass1 == false);
        do{
            System.out.println("Enter a value for the row!");
            guessYS = scan.nextLine();
            switch(guessYS){
                case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10":
                    pass2 = true;
                    System.out.println("TRUE");
                    break;
                default:
                    pass2 = false;
                    System.out.println("FALSE");
                    break;
            }
        }while(pass2 == false);
        guessX = Integer.parseInt(guessXS) - 1;
        guessY = Integer.parseInt(guessYS) - 1;
    }while(guessX >= 0 && guessX <= 9 && guessY >= 0 && guessY <= 9);
}

Why this is happening is beyond me. I am fairly new to java and need this error sorted out.
The error is...
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)

at java.util.Scanner.next(Scanner.java:1485)

at java.util.Scanner.nextInt(Scanner.java:2117)

at java.util.Scanner.nextInt(Scanner.java:2076)

at shipLocation.xyInput(shipLocation.java:11)

at battleShipMain.main(battleShipMain.java:53)

Thanks for the help.

A: Even if the question has already been answered (the error was in a different class) and the provided code caused no error you maybe want to improve your code a bit. To make it easier to read and understand in case you have to change it later.
You could for example wrap the input and validation part in a method:
private int readIntBetweenMinAndMax(String msg, int min, int max) {
    Scanner scanner = new Scanner(System.in);
    System.out.println(msg);
    int userInput;
    do {
        try {
            userInput = Integer.parseInt(scanner.nextLine());
        } catch (NumberFormatException e) {
            System.err.println("Please enter a valid integer");
            continue;
        }
        if (userInput > max || userInput < min) {
            System.err.println("Please enter a integer between " + min + " and " + max);
            continue;
        }
        return userInput;
    } while (true);
}

The method above prints a provided string msg and then reads in an integer. It checks if the user input is an integer and if it's greater or equals than min and less or equals than max. In case one of the three conditions fails the method will print an error message and prompt the user for a new input until its correct.
Note: You could of course also include the "TRUE" and "FALSE" outputs if you want
So you would only have to call the method two times in your guessEnter method:
public void guessEnter() {
    guessX = readIntBetweenMinAndMax("Enter a value for the column!", 1, 10) - 1;
    guessY = readIntBetweenMinAndMax("Enter a value for the row!", 1, 10) - 1;
}

This would accept one, ten and any number between the them. And subtract one as you did in your code.
As a said, it's just a suggestion and I'm not sure if a got everything form your code right but I hope it helps (:


text:
Q: How to make AJAX request in CodeIgniter with csrf protection? I'm trying to make an AJAX request with csrf protection ON. This is my code:
View:
var csrfName    = "<?php echo $this->security->get_csrf_token_name(); ?>";
var csrfHash    = "<?php echo $this->security->get_csrf_hash(); ?>";
$.ajax({
        url         : url,
        type        : 'POST',
        dataType    : 'json',
        data        : {[csrfName]: csrfHash, param_val : combo_val, param_src : combo_function}
    })
    .done(function(data){
        alert(JSON.stringify(data));
    })
    .fail(function(jqXHR, textStatus, errorThrown, data){

        alert(JSON.stringify(jqXHR));
        alert(JSON.stringify(textStatus));
        alert(JSON.stringify(errorThrown));
        alert(JSON.stringify(data));

    });

Controller:
public function get_addr_by_par(){
    $param_val  = $this->input->post('param_val');
    $param_src  = $this->input->post('param_src');

    if($param_src == "get_city_by_province_id"){
        $data_domisili  = $this->MAuth->get_city_by_par($param_val,$param_src);
    }
    else{
        $data_domisili  = NULL;
    }

    $data       = array ('data_domisili'    => $data_domisili,
                         'csrfName'         => $this->security->get_csrf_token_name(),
                         'csrfHash'         => $this->security->get_csrf_hash()
                        );

    echo json_encode($data);
}

Model:
function get_city_by_par($param_val,$param_src){
    $this->db->select(" addr_city.PROVINCE_ID AS 'source_id',
                        addr_city.CITY_ID AS 'val_id',
                        addr_city.CITY_NAME AS 'val_nama'
                      ");

    $this->db->from("addr_city");

    return $this->db->get()->result_array();
}

Basically, I following this accepted answer, but I got this response from AJAX Fail :
    {
  "readyState": 4,
  "responseText": "<!DOCTYPE html>\r\n\r\n\r\n\r\n\r\n<meta charset=\"utf-8\">\r\n<title>BIGI Logistic</title>\r\n\r\n<link href=\"http://localhost:80/bigilogistic/media/themes/cargo/asset//css/bootstrap.css\" rel=\"stylesheet\">\r\n<link href=\"http://localhost:80/bigilogistic/media/themes/cargo/asset//css/style.css\" rel=\"stylesheet\">\r\n<link href=\"http://localhost:80/bigilogistic/media/themes/cargo/asset//css/responsive.css\" rel=\"stylesheet\">   \r\n\r\n<link href=\"http://localhost:80/bigilogistic/media/themes/cargo/asset//css/color-switcher-design.css\" rel=\"stylesheet\">\r\n\r\n<link id=\"theme-color-file\" href=\"http://localhost:80/bigilogistic/media/themes/cargo/asset//css/color-themes/default-theme.css\" rel=\"stylesheet\">\r\n\r\n<link rel=\"shortcut icon\" href=\"http://localhost:80/bigilogistic/media/themes/cargo/asset//images/favicon.png\" type=\"image/x-icon\">\r\n<link rel=\"icon\" href=\"http://localhost:80/bigilogistic/media/themes/cargo/asset//images/favicon.png\" type=\"image/x-icon\">\r\n\r\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\r\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\">\r\n\r\n\r\n\r\n\r\n
\r\n    \r\n
\r\n
\r\n
404
\r\n
Page not found
\r\n
Please try one of the following pages:
\r\n            Home Page\r\n
\r\n
\r\n    \r\n\r\n\r\n    \r\n    \r\n\r\n        \r\n
\r\n
\r\n
\r\n
\r\n
\r\n

\r\n

\r\n

\r\n

\r\n

\r\n
\r\n
\r\n                    \r\n
\r\n                       Webdev\r\n
\r\n
\r\n
\r\n
\r\n    \r\n    \r\n\r\n
\r\n\r\n\r\n\r\n\r\n

\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
  "status": 200,
  "statusText": "OK"
}

Any suggestion to solve my issue? Disabling csrf protection is my last option which I don't want to do for obvious reasons.


text:
Q: Open CMD and it immediately crashes When I open cmd (through Ctrl+R or from system32 folder) in Windows 10, it seems to be running a code (mode 20,5) and after a while, it kills itself.
Same problem happens when I try to execute .bat file.
Anyone will know how to fix this problem?


text:
Q: What is a shortcut for hints in kdevelop? For example I have a function f:
int f(int a) {
  return a;
}

or something. Then whenever I call it, I want to see what arguments it takes, in Eclipse I can do ctrl + space, what about kdevelop?

A: This is from the Customizing code auto-completion web page:

On the other hand, Full completion will additionally show the type for
  each entry, and in the case of functions, also the arguments they
  take. Also, if you are currently filling in the arguments to a
  function, full completion will have an additional info-box above the
  cursor that will show you the current argument you are working on.

I think you need to switch to the Always full completion:

The editor's code completion can be customized via Settings →
  Configure Editor → Editing → Auto Completion.

Read more about customization in here.


text:
Q: How do I get form data? I'm writing a React app, and when trying to get the login form data to send to the backend, it is empty.
// Login component class
submitLoginForm = (event) => {
    event.preventDefault();
    const target = event.target;
    const data = new FormData(target);
    // data is empty, but I need it to contain the form data.
    // ...
}

render() {
    return (
        <div>
            <form onSubmit={this.submitLoginForm}>
                <input type="hidden" name="csrfmiddlewaretoken" value={Cookies.get("csrftoken")} />
                <label htmlFor="username">Username: </label>
                <input id="username" name="username" type="text" />

                <label htmlFor="password">Password: </label>
                <input id="password" name="password" type="password" />

                {this.state.errorText}
                <input type="submit" value="submit" />
            </form>
        </div>
    );
}

EDIT: While the FormData object does have form data, passing it to a fetch request fails to pass along any of the data and simply sends an empty JSON object instead.  The same result happens with JSON.stringify.  How do I get the data as a JSON object?

A: TBH I've not had much luck getting FormData to work well with react. You can access the form fields of the form's onSubmit event object.
// Login component class
submitLoginForm = (event) => {
  event.preventDefault();
  const target = event.target;
  const data = {
    username: target.username.value,
    password: target.password.value,
  };
  // JSON.stringify(data) in request body
}

A: Not sure this is the ideal way to do it, but you could build up a pojo from formData.entries() like this, and then do whatever you need to do from there.

const submitLoginForm = e => {
  e.preventDefault();
  const fd = new FormData(e.target);
  const formObj = [...fd.entries()].reduce((acc, [key, value]) => ({...acc, [key]: value}), {});
  console.log(formObj);
}
<form onsubmit="submitLoginForm(event)">
  <label htmlFor="username">Username: </label>
  <input id="username" name="username" type="text" />

  <label htmlFor="password">Password: </label>
  <input id="password" name="password" type="password" />
  <input type="submit" value="submit" />
</form>


text:
Q: LibGDX - Lwjgl canvas in JFrame not working cross-platform The problem: I have a GDX desktop application that I want to run inside a JFrame, so that I can spawn other JFrames parented to it, so that when I close the main game the other windows will close as well.
The attempted solution: I run the GDX app in the JFrame application, then get its canvas and add it to the content pane.
Previous code, which works just fine (cross-platform):
public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.width  = 800;  config.height = 600;
        new LwjglApplication(new GDXRoot(), config);
    }
}

New JFrame-based approach (so far, I have only gotten it to work on Windows 8. It doesn't work on OS X, Windows 7, or even Windows 10 technical preview):
public class EditModeLauncher extends JFrame {
    final LwjglCanvas canvas;
    LwjglApplicationConfiguration config;

    public EditModeLauncher() {
        config = new LwjglApplicationConfiguration();
        config.width  = 800;  config.height = 600;
        config.resizable = false;
        canvas = new LwjglCanvas(new GDXRoot(), config);
        canvas.getCanvas().setSize(800, 600);
        getContentPane().setPreferredSize(new Dimension(800,600));

        final JFrame test = new TestUI(this);
        test.setLocation(800,300);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                Runtime.getRuntime().halt(0); // because of deadlocks with shut down
            }
        });

        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                getContentPane().add(canvas.getCanvas());
                setVisible(true);
                canvas.getCanvas().requestFocus();
            }
        });
        test.setVisible(true);
    }

    private class TestUI extends JFrame {
        private TestUI(final EditModeLauncher parent) {
            // code omitted ...
        }
    }

    public static void main (String[] arg) {
        new EditModeLauncher();
    }
}

Any ideas what could be the issue?

A: I don't have windows, but this works for me on Linux Mint:
    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
    config.width = 800;
    config.height = 600;
    ApplicationListener appListener = new MyGdxGame();
    Canvas canvas = new Canvas();
    new LwjglApplication( appListener, config, canvas );

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.add( canvas );
    frame.setSize( config.width, config.height );
    frame.setLocationRelativeTo( null );
    frame.setVisible(true);


text:
Q: Stripe connect doesn't giver error but doesn't create accounts I am currently working on integrating stripe connect to my app but it isn't working. I don't get any errors when I run it and it asks me to create an account and redirects back to the website but when I check my stripe dashboard, it doesn't show any added accounts. Any help would be appreciated! I looked over their documentation and copied that but I got the same results.
Here is some of my code:
class StripeController < ApplicationController
   def connect
       response = HTTParty.post("https://connect.stripe.com/oauth/token",
       query: {
         client_secret: ENV["STRIPE_SECRET_KEY"],
         code: params[:code],
         grant_type: "authorization_code"
       }
     )

       if response.parsed_response.key?("error")
           redirect_to welcome_path,
           notice: response.parsed_response["error_description"]
       else
           stripe_user_id = response.stripe_user_id
           current_user.stripe_user_id = stripe_user_id
           redirect_to mypage_path,
           notice: 'User successfully connected with Stripe!'
       end
   end
end

module UsersHelper
    def stripe_button_link
        stripe_url = "https://connect.stripe.com/express/oauth/authorize"
        redirect_uri = stripe_connect_url
        client_id = ENV["STRIPE_CLIENT_ID"]

       "#{stripe_url}?response_type=code&redirect_uri=#{redirect_uri}&client_id=#{client_id}&scope=read_write"
      end
end

<% if current_user.stripe_user_id %>
<%= link_to "Go to Stripe Dashboard", stripe_dashboard_path(current_user.id) %>
<% else %>
    <%= link_to image_tag("ConnectwithStripe.png", width:"120px", height:"40px"), stripe_button_link %>
<% end %>

A: Before I dive in to your specific code and question I wanted to flag that using OAuth with Express accounts is no longer recommended by Stripe.  You should be creating Express accounts using the /v1/accounts API and using Account Links instead.
With that out of the way, I believe the main issue with your code is that you're using HTTParty.post instead of HTTParty.get.  When the user is redirected from the OAuth flow back to your website it will be a regular GET request, not a POST.
Once the user is redirected back to your site you need to use the authorization code in the URL to complete the connection process.  It's not clear if the code for this is missing or was omitted from your question, but you need to do something like this somewhere:
response = Stripe::OAuth.token({
  grant_type: 'authorization_code',
  code: 'AUTHORIZAION_CODE_FROM_URL_HERE',
})

# Store the response.stripe_user_id (the Stripe account ID) in your database for use in the Stripe-Account header when making Connect requests
stripe_account_id = response.stripe_user_id


text:
Q: Generic Identifier handling implementations Since my application has to work with a lot of identifiers, I thought about abstracting them using a Id<T> class. This class would work like a Guid, it has a CreateNew() method and so on, but would create a different Id depending on the type of T.
Examples:
var id = Id<Individual>.CreateNew(); // == "INDIVIDUAL-12345"
var id = Id<Organization>.CreateNew(); // == "ORGANIZATION-67890"
Now, Individual and Organization implement the interface IUser.
Now I would like my Id<> to handle different implementations, but this does not work.
i.e. consider the following class, using Ids:
class Transaction{
    private Id<IUser> _sender;
    private Id<IUser> _receiver;
    private Amount _amount;

    public Transaction(Id<IUser> sender, Id<IUser> receiver, Amount amount {...}
}

I would like to be able to call:
new Transaction(Id<Individual>.CreateNew(), Id<Organization>.CreateNew(), new Amount());

but this is not possible as the constructor requires the types to be Id<IUser>. Can you think about any workaround?

Update
Thanks for the answers until now.
Id<IUser> is just an example (and the content of IUser is not that important here), I'd like to support identifiers for many objects (10/15, more in the future?).
Id<T> uses a static class as helper, called TypesMatcher, whose job is to translate a type to a prefix (i.e. "Individual", "Organization", "Transaction"..).
Id<T>.CreateNew() looks more or less like this:
    [Pure]
    public static Id<T> CreateNew()
    {
        if (!TypesMatcher.IsSupported<T>()) throw new Exception($"Type {typeof(T)} is not supported.");

        string prefix = TypesMatcher.GetPrefixForType<T>();
        string body = Guid.NewGuid().ToString();

        return new Id<T>($"{prefix}-{body}");
    }

A: I'd start by looking into your desired syntax: Id<Individual>.CreateNew().
It means there should be an Id<T> class and have a static CreateNew method.
The static method cannot be overridable, so a good way to make it extensible, is injecting the behavior inside the method.
So for each entity type we can create a class like SomeEntityId deriving from Id<SomeEntity>. The class should contain the custom logic for generating the id. Then we can register them in a DI container. Then in the static CreateNew method, I'd get instance of the registered classes based on T from the container. This way you can inject the custom logic based on T.
I'll also change the Transaction class to rely on IId<IUser>, this way I can create a Variant Generic Interface like IId<T>.
Example
public interface IId<out T> where T : IUser
{
    string Value { get; }
}
public class Id<T> : IId<T> where T : IUser
{
    public string Value { get; protected set; }
    protected virtual Id<T> GenerateId() => new Id<T>() { Value = $"{Guid.NewGuid()}" };
    public static Id<T> CreateNew() => Container.GetInstance<Id<T>>().GenerateId();
}
public class IndividualId : Id<Individual>
{
    protected override Id<Individual> GenerateId()
    {
        var instance = new IndividualId();
        instance.Value = $"IndividualId-{Guid.NewGuid()}"; //Example of custom logic
        return instance;
    }
}
public class Transaction
{
    private IId<IUser> _sender;
    private IId<IUser> _receiver;
    public Transaction(IId<IUser> sender, IId<IUser> receiver) { }
}

For each type which you have custom logic, make sure you register the type instance for Id<yourtype>, for example register IndividualId for Id<Individual> in the container.
Then for usage, you can use this:
new Transaction(Id<Individual>.CreateNew(), Id<Organization>.CreateNew());

A: I am not sure I am getting your goal/the problem you are trying to solve here.
Generics are about allowing a person that is using your code to put in any class, without breaking compile time type checks. Prior to generics, we had to either make a special collection for every type or use Object as the type. One was a unsuiteable amount of work with tons of pitfalls. The other just broke type safety. It is just a mess we mostly prefer to stay burried in pre-generics history. Still I feel it is important to understand why Generics exist, what they are about solving and what they can not solve.
As you use a Interface function to access the values, they can only be resolved at runtime. While they might be a compile time constant in the class, there is no way for the compiler to ever be sure of it as they are handed out by a function at runtime. However it seems possible to add a sort-of-compile time Constant to Interfaces, with the Literal Keyword. But I am unsure if Implementers of that interface can add a tiffrent "typeID" value. I just read about this being a thing, while writing.
Personally that code you shared reminds me a lot of a variant of the Factory/not quite singleton pattern. A factory method where the same input (the same Collection, Type) will result in the same output. But I can not find a example right now.
With the shared code, the only thing I can see being made generic is the transaction Method:
public <senderType, ReceiverType> Transaction (senderType sender, ReceiverType receiver, Amount amount) { }

But again, I am unsure what you tried to do and particular the problem you tried to solve.

A: Generics cannot handle any idea of inheritance.
Covariance is only available on Interfaces.
If you have a covariant interface
  interface IID<out IUser>
  {
        IID<IUser> CreateNew();
  }

And you use this instead of ID<User>, and Individual and Organization implement IUser,
and ID<Invdidual> implements IID<Individual> and ID<Organization> implements IID<Organization>.
Then you can make this assigment:
  IID<IUser> id = = ID<Individual>.CreateNew();

or use it as a Parameter.
But on the other hand side, to use it in this way:
  IID<Individual> id =  (IID<Individual>)ID<Individual>.CreateNew();

you would need a cast.


text:
Q: What is the best manner to run many Scrapy with multiprocessing? currently I use Scrapy with multiprocessing. I made a POC, in order to run many spider.
My code look like that:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from multiprocessing import Lock, Process, Queue, current_process

def worker(work_queue, done_queue):
    try:
        for url in iter(work_queue.get, 'STOP'):
            status_code = run_spider(action)
    except Exception, e:
        done_queue.put("%s failed on %s with: %s" % (current_process().name, action, e.message))
    return True

def run_spider(action):
    os.system(action)

def main():
    sites = (
        scrapy crawl level1 -a url='https://www.example.com/test.html',
        scrapy crawl level1 -a url='https://www.example.com/test1.html',
        scrapy crawl level1 -a url='https://www.example.com/test2.html',
        scrapy crawl level1 -a url='https://www.example.com/test3.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test4.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test5.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test6.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test7.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test8.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test9.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test10.html',
        scrapy crawl level1 -a url='https://www.anotherexample.com/test11.html',
    )

    workers = 2
    work_queue = Queue()
    done_queue = Queue()
    processes = []

    for action in sites:
        work_queue.put(action)

    for w in xrange(workers):
        p = Process(target=worker, args=(work_queue, done_queue))
        p.start()
        processes.append(p)
        work_queue.put('STOP')

    for p in processes:
        p.join()

    done_queue.put('STOP')

    for status in iter(done_queue.get, 'STOP'):
        print status

if __name__ == '__main__':
    main()

According you, what is the best solution to run multiple instance of Scrapy  ?
It would be better to launch a Scrapy instance for each URL or launch a spider with x URL (ex: 1 spider with 100 links) ?

A:
It would be better to launch a Scrapy instance for each URL or launch a spider with x URL (ex: 1 spider with 100 links) ?

Launching an instance of Scrapy is definitely a bad choice, because for every URL you would be suffering from the overhead of Scrapy itself.
I think it would be best to distribute URLs evenly across spiders.


text:
Q: Websphere running on Java 1.7, applet does not load on JRE 1.6 but loads on 1.8 I have Websphere 8.5.5.6 running on JRE 1.7.1. I have a vendor supplied applet that works on all JREs that are 1.6+. All client machines are running JRE 1.6.0_35. Logging and Tracing are enabled and the console to show. IE 11/Edge is the client browsers.

*

*When I access the webpage, the applet fails to load. There is not even an error icon or anything, console does not open. When I go to "C:\Users...AppData..." and check for errors, there is an entry in the file when I access the webpage, however no error.

*Now, when I upgrade a client from JRE 1.6.0_35 to JRE 1.8 - the applet loads flawlessly.

*Please don't advise me on upgrading JRE, not in my hands and its an enterprise decision. The same applets are already working on an application deployed on IIS and is running in production successfully for the last 1 year on the same JRE client 1.6.0_35. When I access the application from a HTML page from local folder, it works with JRE 1.6.0_35. The applet vendor also confirmed the it does work on JRE 1.6.0_35.

*Is there any relation between the client JRE version and the JRE version running on the Server?
Summarizing, applet does not seem to work only when running from WAS running on Java/JRE 1.7. Any suggestions or help is appreciated.
Thank you

A: Are you in a corporate environment?
In this case it maybe necassary to add a permision rule for websphere's url into the ruleset.xml inside %windir%\Sun\Java\Deployment\DeploymentRuleSet.jar.
Particularly if the vendor supplied applet is signed with an certifiacte from a CA unknown by JRE 1.6
For further information see this link


text:
Q: Websocket Server as Service on Android Tablet I have the following scenario.
A Websocket server, that runs on an android tablet as a service in the background.
This Service also starts Websocket client, after the Server is started to handle in-app communication. I also have a java web-socket client in a seperate project to connect and communicate with the server.
This all works fine, as long as i don't try to implement the WebSocket Server as a service.
I can connect and send data like there's no tomorrow.
But as soon as i run the Websocket server as a service i cannot connect to it any longer. Neither with my "inAppClient" nor with my seperate java client.
I set the permissions for internet in the manifest and also tried different ports. I also do portforwarding using adb forward tcp:38301 tcp:38301
The error i get when i try to connect to the server with my in-app-client is the following:
E/WSCLient﹕ Error failed to connect to /127.0.0.1 (port 38301): connect failed: ECONNREFUSED (Connection refused)
I also tried to use localhost instead of 127.0.0.1.
This is the sourcecode for my server:
private class WSServer extends WebSocketServer{
        private static final String TAG = "WSServer";
//      private static final int TIMEOUT = 60;
        private int port = 38301;
        private int testLevel = Constants.BOUNCE_MESSAGES;

        public WSServer( InetSocketAddress address ) {
            super( address );
            Log.d(TAG, "creating instance of local WSServer");
            wsClient = new WSClient(port);
        }

        public WSServer(int port)
        {
            super( new InetSocketAddress( port ) );
            Log.d(TAG, "creating instance of local WSServer on port " + port);
            wsClient = new WSClient(port);
        }

        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            Log.d(TAG, "connection Details: " + conn.getLocalSocketAddress() + "; " + conn.getRemoteSocketAddress());
            Log.d(TAG, "Connection successfully opened on port: " + this.getPort());
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            Log.d(TAG, "Connection closed");
        }

        @Override
        public void onMessage(WebSocket conn, String message) {
            Log.d(TAG, "Received Message: " + message);
            if(testLevel == Constants.BOUNCE_MESSAGES)
            {
                conn.send(new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()) + ": " + message);
            }
        }

//      @Override
//      public void onFragment( WebSocket conn, Framedata fragment ) {
//          System.out.println( "received fragment: " + fragment );
//      }

        @Override
        public void onError(WebSocket conn, Exception ex) {
            Log.d(TAG, "onError()", ex);
        }
}

And this is the sourcecode of my Service:
public CommManager(){
        wsServer = new WSServer(port);
        Log.d(TAG, "Server Adress: " + wsServer.getAddress());
    }

    public CommManager(int port){
        this.port = port;
        Log.d(TAG, "CommManager is starting");
        wsServer = new WSServer(port);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle extras = intent.getExtras();
        if(extras == null) {
            Log.d(TAG, "Port wurde nicht gesetzt. Default Port " + port + " wird verwendet");
        }
        else {
            port = (Integer)extras.get("port");
        }

        return startMode;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "Binding Service to Activity");
        return commManagerBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return allowRebind;
    }

And last but not least my in-app-client:
private class WSClient {

        public String message;
        private static final String TAG = "WSCLient";

        private WebSocketClient mWebSocketClient;
        private int port = 38301;

        public WSClient(){
            connectWebSocket();
        }
        public WSClient(int port) {
            Log.d(TAG, "starting local WSClient");
            if(port != 0){
                this.port = port;
            }
            connectWebSocket();
        }

        private void connectWebSocket() {
            Log.d(TAG, "establishing Connection to local WSServer");
            URI uri;
            try {
                uri = new URI("ws://localhost:" + port);
            } catch (URISyntaxException e) {
                Log.e(TAG, "uri-error: " + "ws://localhost:" + port);
                e.printStackTrace();
                return;
            }

            mWebSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    Log.d(TAG, "Opened");
                    mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
                }

                @Override
                public void onMessage(String s) {
                    Log.d(TAG, "received Message: " + s);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    Log.d(TAG, "Closed " + s);
                }

                @Override
                public void onError(Exception e) {
                    Log.e(TAG, "Error " + e.getMessage());
                }
            };
            mWebSocketClient.connect();
        }

        public void sendMessage(String message) {

            if(mWebSocketClient != null) {
                mWebSocketClient.send(message);
            }
            else {
                Log.e(TAG, "No WebSocketClient available. Trying to reconnect and create new Client instance");
                connectWebSocket();
            }
        }

    }

I have no clue, why i cannot establish a connection with my server.
Hopefully you can help.

A: So i solved the problem by just changing the way of my implementation. I subclassed the Server and Client classes and then it worked. :)


text:
Q: rerun mocha using supervisor... on windows I am trying to rerun mocha tests using supervisor. I have tried:
supervisor node_modules\.bin\mocha

It goes into loop with error:
basedir=`dirname "$0"`

Suggestions?

A: I think all you want to do is mocha -w:
-w, --watch                     watch files for changes

It works nicely with the dot-matrix reporter (default) and -G to give you growl notifications when your tests fail.
Edit:
I've found the Windows-related issues you mention: "No such module" error when trying to get Mocha to watch my project
I can't help with that, either.
But back to the supervisor question: When I install mocha, the "bin" script is in node_modules/mocha/bin, and I can get tests to run repeatedly with the following
supervisor node_modules/mocha/bin/mocha

supervisor does print some annoying DEBUG lines between each test run, but those can be silenced with --quiet. Because mocha quits after each run, you have a busy loop of constant tests, though.


text:
Q: This "if else" statement don't work in my socket.io/Node.js environment So I am developing a simple game. The logic flow is when 2 players connect to the room, the game will initialize and emit a 3 seconds countdown event alongside with a button . if one player clicks the button, that player will emit an event making him/her the host of the game.
The button will appear for 3 seconds. If it disappear without being clicked, the server will randomly pick the host.
Whether or not the button is clicked,after 3 seconds all clients will emit a "ready" event.
Here is my code.
if the button is clicked, the "host" event will be emitted by the client,and my server side code is
client.on('host',function(){

   var player = room.getPlayer(client.id);
   player.isHost=true;

 });

Then here is the server side for the "ready" event.
 client.on("ready", function() {
  var player = room.getPlayer(client.id);
  var table = room.getTable(player.tableID);
   if (2>1) {
      for (var i = 0; i < table.players.length; i++) {

        if (table.players[i].isHost===true){

          console.log("you are the host")
        } else {
          console.log("we are going to randomly pick a host")
          }

       }
     }
 })

Now if no players click the button the terminal will show
we are going to randomly pick a host
we are going to randomly pick a host
we are going to randomly pick a host
we are going to randomly pick a host
Otherwise it will be like
we are going to randomly pick a host
you are the host
we are going to randomly pick a host
you are the host
At this stage only 2 clients are allow for the game so the players.length is 2.It seems like the if/else will be executed same time as the players.length?

A: I think the first thing to mention is that the if (2>1) { ... is completely unnecessary. The code will simply go through to the for loop as if it's not there.
Your code besides the if statement, is honestly ok. There's nothing that screams 'I cause more loops then necessary'. At this point I would suggest posting anything in the project related to:

*

*Multithreading

*Socket Handling / connecting the socket outside of this

I believe more information is due.

A: Thanks for the helps. Yes the for loop is not necessary and it is the cause of the problem. My solution is to detach it from the if-else statement.
for (var i = 0; i < table.players.length; i++) {
}
//test if Host exit in the table
 if (table.ifHost===true){

      console.log("you are the host")
    } else {
      var randomNumber = Math.floor(Math.random() * table.playerLimit);

       var Host=table.players[randomNumber]
      }

The interesting thing I found out about the socket io is when two sockets fire this event, if Host doesn't exit,the first one will execute the else(noHost) and then create a Host. The second socket will execute the if condition as the host was created by the previous socket....


text:
Q: Solving this simple(?) JSONPath I am new to this topic, but I hope you can help me. I can't figure out a correct JSON expression for solving my problem.
Given JSON structure (coming from zigbee2mqtt):
{
  "message" : "announce",
  "meta" : {
    "friendly_name" : "Lamp1"
  },
  "type" : "device_announced"
}

What I am trying:
if $.type == 'device_announced' then return the friendly_name
which in this case is

Lamp1

A: If I understand correctly, you are looking for an expression like this:
$[?(@.type=='device_announced')].meta.friendly_name

So, we are filtering the root collection on types equal to the search string, and then drill down to the friendly_name. You can test this online here.
Note: Some implementations require you to wrap your JSON in an array [ ] to allow this kind of filtering.


text:
Q: XML De-serialization giving null WCF Objects I am having an XML string like
<?xml version="1.0"?>
<FullServiceAddressCorrectionDelivery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <AuthenticationInfo xmlns="http://www.usps.com/postalone/services/UserAuthenticationSchema">
    <UserId xmlns="">FAPushService</UserId>
    <UserPassword xmlns="">Password4Now</UserPassword>
  </AuthenticationInfo>
</FullServiceAddressCorrectionDelivery>

In Order to map the nodes with Class, i am having the class structure in WCF like
[DataContract]
[Serializable]
public class FullServiceAddressCorrectionDelivery
{
    [XmlElement("AuthenticationInfo", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
    [DataMember]
    public AuthenticationInfo AuthenticationInfo { get; set; }
}

[DataContract]
[Serializable]
public class AuthenticationInfo
{
    [DataMember]
    [XmlElement("UserId", Namespace = "")]
    public string UserId { get; set; }

    [DataMember]
    [XmlElement("UserPassword", Namespace = "")]
    public string UserPassword { get; set; }
}

For De-serialization , i used xmlserializer to De-serialize the object
XmlSerializer xs = new XmlSerializer(typeof(FullServiceAddressCorrectionDelivery));
var result = (FullServiceAddressCorrectionDelivery)xs.Deserialize(stream);

this method returned me a Null FullServiceAddressCorrectionDelivery object..
but when i used DataContractSerializer .. like
DataContractSerializer xs = new DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery));
var result = (FullServiceAddressCorrectionDelivery)xs.ReadObject(stream);

then following exception came out..
Error in line 2 position 46. Expecting element 'FullServiceAddressCorrectionDelivery' from namespace 'http://schemas.datacontract.org/2004/07/WcfService1'.. Encountered 'Element'  with name 'FullServiceAddressCorrectionDelivery', namespace ''.
i am stuck with this...
i somehow with the help of RENE(StackOverFlow member) succeded to deserialize if the class was in same project .. but when i converted them to WCF Datacontracts.. i came across that issue ..... please guide me where i am doing wrong here...

A: Depending on how you want to use the data contract serializer (DCS) for that input, you may or may not be able to do that. The namespace of the data members in the DCS are defined by the namespace of the contract to which they belong, unless it's the root element (in which case the [DC] namespace also defines the namespace of the element).
Your root element, FullServiceAddressCorrectionDelivery, has one namespace in your sample XML (empty), and its member, AuthenticationInfo, has another (http://www.usps.com/postalone...). That means that unless you actually change how the serializer is created, you won't be able to use the DCS for this type.
The XmlSerializer (XS), however, should work just fine - members of the type can have different namespaces. As you can see in the code below, I can post the XML you provided verbatim to an operation which takes the FullServiceAddressCorrectionDelivery as an input, and the object is properly populated - you need to mark the operation (or the contract) with the [XmlSerializerFormat] attribute to get this behavior.
public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a
{
    const string XML = @"<?xml version=""1.0""?>
 <FullServiceAddressCorrectionDelivery xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
 xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
   <AuthenticationInfo xmlns=""http://www.usps.com/postalone/services/UserAuthenticationSchema"">
     <UserId xmlns="""">FAPushService</UserId>
     <UserPassword xmlns="""">Password4Now</UserPassword>
   </AuthenticationInfo>
 </FullServiceAddressCorrectionDelivery>";

    [XmlRoot(ElementName = "FullServiceAddressCorrectionDelivery", Namespace = "")]
    public class FullServiceAddressCorrectionDelivery
    {
        [XmlElement("AuthenticationInfo", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
        [DataMember]
        public AuthenticationInfo AuthenticationInfo { get; set; }
    }

    public class AuthenticationInfo
    {
        [XmlElement("UserId", Namespace = "")]
        public string UserId { get; set; }

        [XmlElement("UserPassword", Namespace = "")]
        public string UserPassword { get; set; }
    }

    [ServiceContract(Namespace = "")]
    public interface ITest
    {
        [XmlSerializerFormat]
        [OperationContract]
        FullServiceAddressCorrectionDelivery Echo(FullServiceAddressCorrectionDelivery input);
    }

    public class Service : ITest
    {
        public FullServiceAddressCorrectionDelivery Echo(FullServiceAddressCorrectionDelivery input)
        {
            return input;
        }
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        c.Headers[HttpRequestHeader.ContentType] = "text/xml";
        Console.WriteLine(c.UploadString(baseAddress + "/Echo", XML));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

For completeness sake, this is how you'd change the serializer creation (passing the root name and namespace) to be able to deserialize the XML you provided using the data contract serializer.
public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a_b
{
    const string XML = @"<?xml version=""1.0""?>
 <FullServiceAddressCorrectionDelivery xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
 xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
   <AuthenticationInfo xmlns=""http://www.usps.com/postalone/services/UserAuthenticationSchema"">
     <UserId xmlns="""">FAPushService</UserId>
     <UserPassword xmlns="""">Password4Now</UserPassword>
   </AuthenticationInfo>
 </FullServiceAddressCorrectionDelivery>";

    [DataContract(Name = "FullServiceAddressCorrectionDelivery", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
    public class FullServiceAddressCorrectionDelivery
    {
        [DataMember]
        public AuthenticationInfo AuthenticationInfo { get; set; }
    }

    [DataContract(Name = "AuthenticationInfo", Namespace = "")]
    public class AuthenticationInfo
    {
        [DataMember]
        public string UserId { get; set; }

        [DataMember]
        public string UserPassword { get; set; }
    }

    static string Serialize(object obj, bool useDataContractSerializer)
    {
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = false,
            Encoding = new UTF8Encoding(false)
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        if (useDataContractSerializer)
        {
            var dcs = new DataContractSerializer(obj.GetType(), "FullServiceAddressCorrectionDelivery", "");
            dcs.WriteObject(w, obj);
        }
        else
        {
            new XmlSerializer(obj.GetType()).Serialize(w, obj);
        }

        w.Flush();
        string result = Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine(result);

        w.Close();
        ms.Close();
        return result;
    }

    public static void Test()
    {
        Console.WriteLine("Serialization:");
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = false,
            Encoding = new UTF8Encoding(false)
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        var dcs = new DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery), "FullServiceAddressCorrectionDelivery", "");

        var obj = new FullServiceAddressCorrectionDelivery
        {
            AuthenticationInfo = new AuthenticationInfo
            {
                UserId = "FAPushService",
                UserPassword = "Password4Now"
            }
        };

        dcs.WriteObject(w, obj);

        w.Flush();
        string result = Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine(result);
        Console.WriteLine();

        Console.WriteLine("Deserialization:");
        ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));

        var obj2 = (FullServiceAddressCorrectionDelivery)dcs.ReadObject(ms);
        Console.WriteLine("{0} - {1}", obj2.AuthenticationInfo.UserId, obj2.AuthenticationInfo.UserPassword);
    }
}


text:
Q: my SiteMap don't work Correctly What is this error when I use SiteMapPath . when I click One link in my webSite , this error appeared in a page . of course when I upload my website,I See this error :
The page cannot be found The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.

A: Based on the error, it appears that the URLs in your SiteMap are not relative. For example, let's say you have a subdirectory called "Example" and a page called "test.aspx" located in that "Example" directory. This entry would produce a 404 error (page not found).
<siteMapNode url="Test.aspx" title="Test Page" />

This would be the correct siteMapNode entry:
<siteMapNode url="~/Example/Test.aspx" title="Test Page" />


text:
Q: Dynamically load ajax content on fancybox from MySQL database I have this code to display fancybox links. How it works now is:
I select 4 entries from MySQL database which are matching a category. And again for all categories on my page. I set a rel='x' for entries matching category 'x'.
Idea of what i want to do is 'go deeper into category'. It means when finish viewing 4 items from rel='x' group, select from mysql database nextcoming entry to display but not display at the page where these 4 links are. Entries are ordered by id DESC.
<a  class="various fancybox.ajax" data-fancybox-type="ajax" rel="group"
    href="view.php?&id=<?php echo $rw10['id']; ?>">

    $(document).ready(function() {
    $(".various").fancybox({
        maxWidth    : 800,
        maxHeight   : 800,
        fitToView   : false,
        width       : '70%',
        height      : '100%',
        autoSize    : false,
        closeClick  : false,
        openEffect  : 'none',
        closeEffect : 'none',
        'closeBtn' : false,
         openEffect  : 'none',
        closeEffect : 'none',
        nextEffect  : 'none',
        prevEffect  : 'none',
        preload: true,
        padding     : 10,
        margin      : [20, 60, 20, 60] // Increase left/right margin
    });

A: What you could do is to get the coming (related) items from your database and store them in a json variable like :
var databaseResponse = [{
    href: "path/image05.jpg", // 4 are visible on page so
    type: "image",
    title: "Image #5",
    isDom: false
}, {
    href: "path/image06.jpg",
    type: "image",
    title: "Image #6",
    isDom: false
}, {
    href: "path/image07.jpg",
    type: "image",
    title: "Image #7",
    isDom: false
}]; // etc

Then push the items from that variable into the gallery within the beforeLoad callback like :
var done = false; // initialize switch
jQuery(document).ready(function ($) {
    $(".fancybox").fancybox({
        // loop : false, // optional
        beforeLoad: function () {
            // here get next items from database
            // and store them in a json variable
            // e.g. "databaseResponse"
            if ((this.index == this.group.length - 1) && !done) {
                for (var i = 0; i < databaseResponse.length; i++) {
                    this.group.push(databaseResponse[i]);
                };
                done = true; // push items only once
            }
        },
        afterClose: function () {
            done = false; // reset switch
        }
    });
}); // ready

Notice that we are using a switch (the done variable) to push the items only once (we may need to reset the switch after closing fancybox though)
JSFIDDLE
NOTE : the items will be added (pushed) only after we are seeing the last item in the DOM (the 4th in your case) so if you start browsing the gallery backwards, you won't see the new items but until the second loop.
You may want to  set loop to false though


text:
Q: What does the asterisk in the netstat output mean? # netstat -at
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:30037         *:*                     LISTEN
tcp        0      0 localhost:ipp           *:*                     LISTEN
tcp        0      0 *:smtp                  *:*                     LISTEN
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN

What does the asterisk * in *:smtp mean ?
Why is there no IP address shown?

A: It is a wildcard meaning "any".
For example, in the third line:
tcp        0      0 *:smtp                  *:*                     LISTEN

The first *, in *:smtp, means the process is listening on all of the IP addresses the machine has.  The second *, in *:*, means connections can come from any IP address.  The third *, in *:*, means the connection can originate from any port on the remote machine.


text:
Q: invalidSearchFilter when searching my videos using YouTube api v3 I keep getting invalidSearchFilter error when using YouTube API v3. I have the following params:
part: snippet
q: testtag
forMine: true
type: video

I am using the API playground, and noticed that if I do an OAuth call, it will work, but with just the API key (Execute without OAuth), it fails. Same thing happens in my code. A basic list call works in both, so I am suspecting a bug in their API, or I'm missing something.
Can anyone else confirm this to see if I'm missing something?
It works if I leave off the forMine and type params, but then it searches globally, which is not what I want.
I have searched for this, and the only other references I've found have been related to not setting the type param, but I have it set.
I found this link which suggests a possible API bug: youtube v3 api error when searching with forMine set to false

A: The documentation is your friend Search: list

forMine   boolean This parameter can only be used in a properly
  authorized request. The forMine parameter restricts the search to only
  retrieve videos owned by the authenticated user. If you set this
  parameter to true, then the type parameter's value must also be set to
  video.

So yes you are missing something the part where you can only use forMime type parameter with authorized requests. Using an Api key is an unauthorized request you are accessing the public API.  How do you think it would be able to search videos that yours if you aren't authenticated? It doesn't know who you are.


text:
Q: How to stop loading multiple copies of jquery My wordpress header.php and function.php is given below.please help me to modify my php code to stop problems due to loading jquery multiple times. My plugins and themes are loading jquery multiple times.
My files
Header.php
Function.php

All experts are telling that i need to include enqueue script !!! I read different documents related to it.
I'm new to coding , i dont know where to add this enqueue script, what type of code I need to add?

A: You should remove these lines from your header.php
<script language="javascript" type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascripts/jquery.js"></script>
<script language="javascript" type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascripts/tabber.js"></script>
<script language="javascript" type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascripts/superfish.js"></script>

And instead add the following function in your functions php...
right at the top.
wp_enqueue_script
function sg_theme_js(){

    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'tabberjs', get_template_directory_uri().'/javascripts/tabber.js', array('jquery'), 1.0, true);
    wp_enqueue_script( 'superfishjs', get_template_directory_uri().'/javascripts/superfish.js', array('jquery'), 1.0, true);

}
add_action( 'wp_enqueue_scripts', 'sg_theme_js' );

Explenation:
Since many plugins use jQuery (and other js files) they need to know (and wordpress too) that you already loaded jQuery... but, they cannot check it after the page has loaded meaning by checking your header becouse that is too late!
That is why we should enqueue scripts and those allow plugins to depened on them.
Now... a small comment.
if you wish to manage your theme meaning deal with code you need to learn this stuff ;) - take a moment to read about wp_enqueue_script.
Here is additional information about: wp_enqueue_script

A: The simple answer is to never add script tags directly to template files. This is exactly why the WordPress script registration and enqueue system exists.