text:
Q: Implement sorting/filtering business logic into DDD aggregates I am fairly new to DDD and for me I search in practical terms to a good function for an aggregate. I have a long list of users (User) and a create an aggregate (UserAggregate) for that.
Now in my view I might display users based on different criteria. Let's assume here I don't sort the list in my database query, it is OK to have sorting in an aggregate? I cannot come up with another part of the application where I can do this properly, but I might misunderstand the function of an aggregate.
$users = new UserAggregate(array(
 $user1, $user2, $user3, $user4
));

foreach ($users->sortBySurname(), $user) {
 //
}

foreach ($users->sortByLastLoggedIn(), $user) {
 //
}

The same holds for filtering by the way. When I read about DDD aggregates, I immediately thought of the Doctrine\Common\Collections\Collection (link). That sort-of looks like an aggregate to me. So DDD experts, please enlighten me :-)
Update
The only way I was thinking btw was making aggregates rather immutual and have helpers to create new aggregates. But this seems not the way to go:
$aggregate = new UserAggregate(array($user1, $user2));
$helper    = new FilterSomething;
$aggregate = $helper->filter($aggregate);

The second aggregate is a new instance, so the helper looks like this:
class FilterSomething
{
  public function filter(Aggregate $aggregate)
  {
    $items = $aggregate->getItems();
    $items = $this->doFilter($items);

    return new Aggregate($items);
  }
}

A: A root aggregate is not a repository. A root aggregate represents a single user and all of it's domain specific information.
That sorting and filtering should be applied in a repository.


text:
Q: Using field in CASE without group by I have the following code and I am having trouble figuring out how to NOT include these into the group by. Some of the arguments are purely for the case and that is all. I can't include them in the group by. I cam't really group by anything else as I need to get the counts by TransactionTyp only but I keep getting this error: is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Maybe the use of CASE is the wrong way to go about this? But I need to replace some of the values based on other fields.
This is in MS SQL too.
SELECT  Count(*),
    CASE
        WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp
        WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected'
        WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected'
        WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate'
    END As TransactionTyp
FROM Table1 a
LEFT JOIN Table2 b
    ON a.ClaimNbr = b.ClaimDisputeNbr AND b.CreateDte = Convert(varchar,GetDate(), 101)
WHERE a.ClaimEntryDte = Convert(varchar,GetDate(),101)
AND a.ClaimTypCd  IN ('DEBS', 'DEBSI', 'DBCIN', 'DBCUS')
GROUP BY TransactionTyp

A: One problem might be that you can't refer to aliases in the group by clause.  Try to repeat the case definition in the group by:
GROUP BY
    CASE
        WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp
        WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected'
        WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected'
        WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate'
    END As TransactionTyp

Alternatively, use a subquery to define the alias:
select  TransactionTyp
,       count(*)
from    (
        SELECT  CASE
                WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp
                WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected'
                WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected'
                WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate'
                END As TransactionTyp
        FROM    Table1 a
        LEFT JOIN
                Table2 b
        ON      a.ClaimNbr = b.ClaimDisputeNbr
                AND b.CreateDte = Convert(varchar,GetDate(), 101)
        WHERE   a.ClaimEntryDte = Convert(varchar,GetDate(),101)
                AND a.ClaimTypCd  IN ('DEBS', 'DEBSI', 'DBCIN', 'DBCUS')
        )
GROUP BY
        TransactionTyp

A: Without adding create_on on group by how to get current Date result or current month result
select segment_name,
cast(SUM(case when t1.create_on=GETDATE()) then actual_total_sale    as currentDateData,
cast(SUM(case when MONTH(create_on) = MONTH(getDate()) then actual_total_sale    as currentMonthData,
 from
PR_DAILY_AOP_TARGET t1
where is_active=1 group by segment_name

A: The CASE must be in the Group BY Statement, not the ID.
Like this:
GROUP BY CASE
    WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp
    WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected'
    WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected'
    WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate'
END

A: When you get to specifying what to return from the query, the result has already been grouped, so anything that you want to return has to be specified in the group by.
The solution for this would be to make a subquery that calculates the values, then you can group the result from the subquery:
SELECT Count(*), TransactionTyp
FROM (
  SELECT
    CASE
        WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp
        WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected'
        WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected'
        WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate'
    END As TransactionTyp
  FROM Table1 a
  LEFT JOIN Table2 b
    ON a.ClaimNbr = b.ClaimDisputeNbr AND b.CreateDte = Convert(varchar,GetDate(), 101)
  WHERE a.ClaimEntryDte = Convert(varchar,GetDate(),101)
  AND a.ClaimTypCd  IN ('DEBS', 'DEBSI', 'DBCIN', 'DBCUS')
) as x
GROUP BY TransactionTyp

redpajama_set_name: RedPajamaStackExchange


text:
Q: Functional programming, Domain Driven Design, and Test/Behavior Driven Development I am posting because, first of all, I want to make sure my understanding on these 3 methodologies is correct. Secondly, I would like some clarification on how they could all fit in together. I see they are approaches used to tackle on different problems, and to me, it seems like they should all complement each other quite well because they address different levels of abstraction.
From what little exposure I've had to Functional Programming (Scala beginner), it seems to me like functional programming aims for idempotence and "real" functions are supposed to do one thing, and one thing only (no side effects).
Separation of concerns (having UI, application, domain, and infrastructure layers), along with having a ubiquitous language, and working closely with a domain expert on understanding the problem at hand before beginning implementation, is, from a high view, one of the biggest things DDD entails.
And then there's BDD, which seems to be an approach to TDD which takes some inspiration from certain aspects of DDD (especially the ubiquitous language and the importance understanding the domain has in design and implementation) in order to let tests drive development efforts.
Why do I say they complement each other? In a nutshell:

*

*TDD proponents say no design is necessary, just let the tests guide your code design. If you use BDD, though, you're making use of domain knowledge for your design, which relates to DDD. If you do some prior design work as in DDD, you're narrowing down your solution space from infinite to finite (and humanly approachable/understandable), which could help guide your tests and design

*Using BDD, your tests are supposed to test one thing only, and functional programming languages are great for this because functions are supposed to do one thing only, so this could help you design your functions and then have proof that they work because you've written a test for them.

*Because functions do one thing only, it should be helpful in enforcing a separation of concerns. So if you do DDD (higher level), a functional programming language should make it intuitive to implement the design (lower level) because of those features it enforces.

Am I completely wrong about any of these concepts, or am I making some sense?

A:

*

*TDD proponents say no design is necessary ...

No, TDD proponents say allowing for tests in your design can only improve your design.  They don't say you have an awesome design just because it's a testable design.
Let me explain it this way:
Testable == well designed? False
Testable -> well designed? False
Testable <- well designed? True

You have to DESIGN period.
Why? Because a good design is MORE than just testable.

*Using BDD, your tests are supposed to test one thing only ...

This is true of unit tests. BDD is about more than unit tests, and for that matter, so is TDD.

*Because functions do one thing only ...

f(g(x)) could be function h that does two things, an f thing and a g thing.  You're confusing returning one thing with doing one thing.
The single responsibility principle is where the idea of "one thing" comes from.  You can find it followed in functional and object oriented programming alike.  None of these make following this principle easy.  I can bloat functions as well as objects with needless crap that should be handled elsewhere if I'm not careful.
There is no crutch that will make this something you don't have to think about.  You have to remember it and follow it or you'll make a mess in any paradigm.

A: First, some clarifications, since you expressed interest in checking your understanding:
Functional Programming (FP)
Functional programming is a paradigm in which the primary unit of program composition is the function; contrast this with object oriented programming, a paradigm in which objects comprise the primary unit.
Side Effects and Purity (or Referential Transparency)
You mention idempotence and "reality", when I think you mean referential transparency and "purity". Idempotence means that applying a function twice (or thrice, or...) is no different than applying it once.
"Pure" functions are those without side effects, such as writing to disk or sending data over the wire. It is not necessary for them to do only "one thing". You can replace a pure function call with its value without changing the behaviour of the program at all:
> // pure function
undefined
> const f = x => x*2;
undefined
> const a = f(2);
undefined
> a
4
> console.log(f(2));
4
undefined
> console.log(a);
4
undefined
> // impure function
undefined
> function g(x) {
... console.log(x*2);
... return x*2;
... }
undefined
> const b = g(2);
4
undefined
> b
4
> console.log(g(2));
4
4
undefined
> console.log(b);
4
undefined
>

Notice how, after replacing g(2) with its value, 4, console.log(b) writes one less line. This makes it (under some definitions) an "impure" function. This has nothing to do with doing "one thing only"; const g = () => { console.log("Hello world!"); } only writes to console, and yet replacing g() with its value, undefined, would not produce the same program (there would be no console output).
This property of being able to replace a function call with its value, without changing the behaviour of the program as a whole, is called referential transparency. I use it as one definition of "purity". There are many others.
Not all functional programming languages necessarily enforce purity; one could argue that JavaScript (and especially ES6) is a functional language, and yet as we've seen it is possible to write impure functions very easily in the language.
Languages like Haskell and Elm, however, make certain classes of side-effects very explicit via their type systems (e.g. the IO monad in Haskell, and the Signal applicative in Elm). Executing code with side effects is only possible according to certain constraints, enforced by the typechecker.
Domain Driven Design (DDD)
Domain Driven Design is a means of thinking about, discussing, designing, and actually implementing software with a cross-functional team operating in a rich and complex problem domain (e.g. finance). It's comprised of modelling the problem conceptually and linguistically according to a Ubiquitous Language, which pervades all aspects of the software - user-facing language in the UI, conversations with designers, domain experts, class, file, and variable names in the code.
This conceptual model and the Ubiquitous Language used to describe and talk about it only apply within a Bounded Context, which you can think of as a namespace; a Ticket may refer to one thing in the context of Customer Support, and another thing entirely in the context of Cinema.
Separation of Concerns
On the level of the actual software implementation, DDD encourages us to model the problem domain, its structures, relationships, and constraints, as closely as possible within the code. This representation of the DDD conceptual model lives within the domain layer of code, which is exercised from the outside (via a GUI, a CLI, a webpage, etc.) via the application layer, which "plugs in" the domain into an environment where the operations of the domain are exposed. This layer encapsulates all technical details (broadly speaking) of the application; contrast this with the domain layer, which is exclusively concerned with the "business logic" of the problem domain. This is the separation of concerns you allude to, and while it is quite important, I would say that it is not the primary focus of DDD.
Relationships Between the Three
DDD and FP - Side Effects and Separation of Concerns
Domain Driven Design, extending beyond the mere software solution and its implementation, and into the minds of all people involved in the software's use - its end-users, maintainers, designers, and software developers - does not prescribe (to my knowledge) the use of any particular programming paradigm.
However, some functional programming languages are well suited for achieving the separation of concerns you describe; for instance, "business logic", operating on data types representing the Entities and/or Value Objects within a given domain, could be restricted to pure functions, or those without side effect. In order to actually execute this business logic, it could be plugged into, say, the IO monad from Haskell, where it would then be able to communicate over the network, or read and write files from disk. It would not be possible (in theory) to have technical concerns leak into the domain layer, since all application-level detail must take place in IO. This is possible because languages such as Haskell make side-effects explicit at the type level.
FP and BDD - "Doing Only One Thing", and Referential Transparency
If we proceed under the above definition, in which pure functions are those which can be replaced by their value without changing the way the  program runs (referential transparency), the principle of "doing only one thing" becomes irrelevant to the question of whether or not FP is well-suited to BDD. I think the two topics are somewhat distant.
DDD and BDD
They're pretty related. Cucumber is great.
Summary
Functional Programming and Domain-Driven Design are in some sense orthogonal to one another; DDD makes no hard prescriptions on what language or technology to use. However, the principle of separation of concerns, which DDD does employ in its separation of domain and application layers, can be easily achieved in some functional programming languages with explicit side-effects. Pure functions need not do only one thing; they only need by referentially transparent. FP's connection with BDD is tenuous; BDD's connection with DDD is quite close.
Hope that helped. Just sharing my own understanding, which of course is always in need of revision.


text:
Q: How do I release/delete a UIImageView class? I'm new to iPhone programming, so I might not even be using the correct methods... anyway, I'm trying to make a game, and when I want to create an enemy I make a new UIImageView, like this:
enemyBird *asdf = [[enemyBird alloc] initWithFrame:CGRectMake(30, -20, 45, 30)];
[self.view addSubview:asdf];

When enemyBird initializes, an NSTimer is made so the enemyBird can fly around and do its own thing. Now, I want to get rid of the bird after it leaves the screen, in this code here:
    if (self.center.y > 500)
    {   //[self dealloc];  //doesn't work
        //[self release];  //doesn't work
        //[self removeFromSuperview];   //this makes it disappear, but the NSTimer is still running
    }

But I don't know how to do that. Am I doing this properly? Or is there an entirely different way I should be doing this? Thanks in advance.

A: for game development better use cocos2d framework: It´s quite easy

A: You have to send removeFromSuperview to your image view, to put it out of the main view.
In the same time, you invalidate the timer, and you might be fine.
Also just after alloc/init the image view and add it to the main view, you should release it.

A: *

*As view retains all its subviews you can release your imageView right after you add it to controller's view:
enemyBird *asdf = [[enemyBird alloc] initWithFrame:CGRectMake(30, -20, 45, 30)];
[self.view addSubview:asdf];
[enemyBird release];

*In your timer handler when bird leaves the screen remove it from superview, set reference to nil (to make sure you won't access deallocated instance) and invalidate timer so it won't fire again:
if (self.center.y > 500)
{
    [enemyBird removeFromSuperview];
    enemyBird = nil;
    [timer invalidate];
}


text:
Q: Serial Port Read C# Console Hi to all i am new here and i have heard a lot about this website that it really helps you out. Hope you will be able to help me out!.
I have a very simple program which its only aim is to read from a serial port and prints it on the console window in C# for 2000 times.
I am just turning a variable resistor on a micro-controller that's all
Here below is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace Testing_serial_v3._0
{
    class Program
    {
        static void Main(string[] args)
        {

            string buff;

            SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
            port.Open();

            for (int i = 0; i < 2000; i++)
            {

                buff = port.ReadLine();
                Console.WriteLine(buff);
                //Console.ReadLine();
            }
        }
    }
}

But there is a funny thing happening in this code. When the console readline is commented as shown in the code above the value from the port changes as i turn the knob of the variable resistor. So this means it is working good.
On the other hand if i make the readline happen so that after each value i have to press a key the port reads the current value and even though i change the knob and press enter again the value will remain the first as if it is not resetting at all?
Do you have to include any other command lines so that the port will reset?
Hope you understand my problem and any other questions you need to know please don't hesitate i really need this problem fixed ASAP.
Many thanks and regards

A: The data coming through the port is a stream - when you read, you are gradually consuming the stream. You are not seeing "the most recent value", you are seeing "the next value in the stream". When you add the read-line, you add a delay which means there is a large backlog of data. It isn't that "it stayed the same"... Simply that you haven't read to the end (and the more recent values) yet.
In many cases, it would be preferable to deal with the network IO via an async callback so that reading values from the stream is not tied into delays like human data entry. That may involve some knowledge of threading, though.

A: You could also use a Task to read it in a separate thread and observe it there, kind of what @Marc Gravel mentions. You just have to wait until the task is finished or press enter to cancel it manually. Just another example of offloading the task to another thread.
Here's an example:
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ReadStreamAsyncTask
{
    internal class Program
    {
        private static CancellationToken _cancelTaskSignal;
        private static byte[] _serialPortBytes;
        private static MemoryStream _streamOfBytesFromPort;
        private static CancellationTokenSource _cancelTaskSignalSource;

        private static void Main()
        {
            _serialPortBytes = Encoding.ASCII.GetBytes("Mimic a bunch of bytes from the serial port");
            _streamOfBytesFromPort = new MemoryStream(_serialPortBytes);
            _streamOfBytesFromPort.Position = 0;

            _cancelTaskSignalSource = new CancellationTokenSource();
            _cancelTaskSignal = _cancelTaskSignalSource.Token; // Used to request cancel the task if needed.

            var readFromSerialPort = Task.Factory.StartNew(ReadStream, _cancelTaskSignal);
            readFromSerialPort.Wait(3000); // wait until task is complete(or errors) OR 3 seconds

            Console.WriteLine("Press enter to cancel the task");
            _cancelTaskSignalSource.Cancel();
            Console.ReadLine();
        }

        private static void ReadStream()
        {
            // start your loop here to read from the port and print to console

            Console.WriteLine("Port read task started");

            int bytesToReadCount = Buffer.ByteLength(_serialPortBytes);
            var localBuffer = new byte[bytesToReadCount];

            int bytesRead = 0;

            bool finishedReading = false;

            try
            {
                while (!finishedReading)
                {
                    _cancelTaskSignal.ThrowIfCancellationRequested();

                    bytesRead += _streamOfBytesFromPort.Read(localBuffer, 0, bytesToReadCount);

                    finishedReading = (bytesRead - bytesToReadCount == 0);
                }
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine("You cancelled the task");
            }

            Console.WriteLine(Encoding.ASCII.GetString(localBuffer));
            Console.WriteLine("Done reading stream");
        }
    }
}

A: You are sending thousands of data from micro-controller to the serial port (with delay of 1ms for ex.), which makes the buffer of the serial port filled with same values! If you read it one by one by pressing enter key, you are reading the first received ones...
I think if you want to read your data in computer by "Enter" key, you should send the date from micro-controller by a push button! It means you set the value by resistor, press the push button, the micro sends "One Byte" to the computer. You press the enter on the computer and let your computer read just "One Byte" from the serial port!
Also some modification to your code:
static void Main(string[] args)
{
    int buff;  // string to int

    SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    port.Open();

    for (int i = 0; i < 2000; i++)
    {
        Console.ReadLine();  // wait for the Enter key
        buff = port.ReadByte();  // read a byte
        Console.WriteLine(buff);
    }
}

I hope this will work for you! :)


text:
Q: Eclipse: comment entire code without it getting cut short by another comment Say I have the following code (in C++, but that's probably not important to the question):
int main() {
    ....random code....
    /*This is a comment*/
    ....random code....
    return 0;
}

In eclipse, when I want to comment out the entire code by putting /* and */ before and after the code, the comment is cut short by the */ at the end of the "This is a comment" on line 3, so the rest of the code is left uncommented.
/*    //<--overall comment starts here
int main() {
    ....random code....
    /*This is a comment*/    //<--overall comment ends here
    ....random code....
    return 0;
}
*/  //<--overall comment SHOULD end here

Anyone know a way of getting around this problem, or do I just have to deal with it or use // comments...?

A: There's no way of having nested comments in C++. One solution (especially if you don't want to change lots of /* */ to //) is to use the pre-processor, you can do something like
#ifdef SOME_RANDOM_SYMBOL

code that you want to comment here

#endif

Just make sure that SOME_RANDOM_SYMBOL is not somehow defined in your code.
As mentioned by @Caleb in the comment, you can also do
#if 0

code that you want to comment here

#endif

but using a symbol allows you to search for it.


text:
Q: Is there a tool that allows easy exporting of messages from a message queue (MSMQ)? I am currently working on batch processing application using MSMQ in C#.  In the application design, I have an error queue containing XML messages using the ActiveXFormatter.   I know that I can write an application to write these error messages to text files or database tables.
Are there other pre-built tools available allowing you to export messages to variety of formats  (i.e. text files, database tables, etc.)?  I am just looking for best practices.

A: Ok. I found the solution of writing code to be really easy.  Here's my reference solution.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;

namespace ExportMSMQMessagesToFiles
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnExportTextFiles_Click(object sender, EventArgs e)
        {
            //Setup MSMQ using path from user...
            MessageQueue q = new MessageQueue(txtMSMQ.Text);

            //Setup formatter... Whatever you want!?
            q.Formatter = new ActiveXMessageFormatter();

            // Loop over all messages and write them to a file... (in this case XML)
            MessageEnumerator msgEnum = q.GetMessageEnumerator2();
            int k = 0;
            while (msgEnum.MoveNext())
            {
                System.Messaging.Message msg = msgEnum.Current;
                string fileName = this.txtFileLocation.Text + "\\" + k + ".xml";
                System.IO.File.WriteAllText(fileName, msg.Body.ToString());
                k++;
            }

            MessageBox.Show("All done!");
        }
    }
}


text:
Q: Run sbt scoverage commande on Scala Play I have Play project, I am trying to publish the coverage result with scoverage plugin and sbt. Everything works locally but when I try to run the same commands with jenkins it shows following error.
My Jenkins Configuration for sbt is like this:

Also the configuration of build.sbt and plugins.sbt

A: Are you using the instructions from the github repo ?
sbt clean coverage test

and
sbt coverageReport

should do the work. It seems you are missing a camel case on coveragereport.
you can also have a look at the example they provide
also, is it an open source project we can have a look at? Or just paste the build.sbt and project/plugins.sbt files


text:
Q: How do I detect free fall event on Motorola MC3100 scanner? I've searched Google and come up with nothing.  There's tonnes of pages that tell me that the Motorola MC3100/MC3190 support free fall detection and event logging, but I can't find anything in the documentation or online to say how to achieve this by writing your own app and hooking into the event or if there's a log file somewhere on the device that already contains these free fall events.
How do I detect free fall event on Motorola MC3100 scanner?

A: This can only be a Motorola-specific solution. Windows CE doesn't have native free-fall function detection api.
Have you checked the Motorola 3100 Platform SDK? If it is not there, then you will probably need to contact Motorola technical support

A: The free fall event is handled by Motorola Interactive Sensor Technology (IST), the software for which comes pre-installed on hardware that supports it.
Unfortunately, the model we have is MC3190-SI4H04E0A – The digit before last determines if the device is capable of ITS or not.  I – means it's capable. 0 – means it's not capable.  So our device doesn't support IST.
If the device had this functionality, I would have seen an IST Settings control panel under "Start – Settings – Control Panel – IST Settings".


text:
Q: How to get PUT and DELETE parameters from HTTPRequest in SilverStripe? There are getVars(), postVars() and requestVars() methods in HTTPRequest.
They returns parameters from GET and POST requests.
But how can I get parameters from PUT and DELETE requests?
I know that there is a 'body' property somewhere in HTTPRequest. It contains PUT params in query string or something similar.
To use this property I need to parse 'body' field.
Is there a way to get these parameters with comfortable way, like for GET and POST?

A: You need to do it the old school way.
parse_str($request->getBody(), $params);
$foo = $params['Foo'];

Keep in mind the second parameter of parse_str is a reference, so no need to define that variable before invoking the function call.


text:
Q: VS 2010 web.config transformation displaying incorrectly in solution explorer The problem can be better explained with this image.

As you can see, the transformed files are displaying as part of web.config and also as individual files. But they are the same if I open them or delete them. If I delete and undo it using TFS, that restores as part of web.config. After another check-in that again it shows up as individual.
Any idea why this is happening?

A: I found a way to fix this by deleting them and then pressing right click to web.config -> Add Config Transform.


text:
Q: How to connect PHP GAE(Google App Engine) to Google Docs, Spreadsheets
*

*I have a PHP app deployed in GAE(Google App Engine)

*I need to connect to Google Docs, Google Spreadsheet URL below and do all editions/manage(edit a Doc, Edit a Sheet,...etc) as like I am able to do via GAS, just like we manage the CAL API.
https://developers.google.com/apps-script/reference/document/
https://developers.google.com/apps-script/reference/spreadsheet/

*What is the best approach for it? How to use those functions available in GAS via PHP GAE?
Plz someone help, a small tip would also help us.

A: In PHP, you can make an HTTP Request.  In Apps Script, you can create a Stand Alone Apps Script project, that detects either a GET or POST request, and runs code.  Then the code can do whatever you want it to do (E.g. write data to spreadsheet).  When the code is done, you can have it return something back to the PHP code that called it.
So, you can use an Apps Script project as an intermediary between your PHP and a Google spreadsheet.  This avoids needing to use the PHP API for Google Spreadsheets.  The Apps Script file is an intermediary between your PHP code and getting data written/read from your spreadsheet.  But an API is also an intermediary.  So, in that sense it's the same. If you already have Apps Script code that does what you want, you can trigger it to run with a doGet() or doPost() function.  And you can avoid learning the API.
For more information see the following post:
stackoverflow answer - Call a custom GAS function from external URL


text:
Q: How do I show an URL in input description of Jenkins pipeline During the pipeline execution, I need to ask user whether to proceed the stage with below shown input options which is working fine. However thinking of enhancing the input message by converting the description of the input message to a clickable URL instead of plain text which is happening now.
    environment {
        def delobjectsurl = "${env.BUILD_URL}/artifact/logs/stage2.log"
        def delconfirmation = input (id: 'delconfirmation', message: 'Proceed with mark as delete [YES/NO]?', parameters: [choice(choices: 'YES\nNO', description: "${delobjectsurl}", name: 'ONLINE_MARK_AS_DELETE')])
    }

I tried with below options but still showing the description as plain text.
Configure Global Security
Is it possible to achieve which I am trying to do? I am using Jenkins v2.107.1.


text:
Q: SerializationException: Invalid binary format when accessing a MarshalByRefObject I am trying to send constantly a jagged array of floats to a Unity app from another C# application.
I got a C# dll that uses a MarshalByRefObject and opens an Ipc channel for a simple test server app and a simple test client app. Both apps are able to share data successfully. Here is the code for the dll:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;

namespace U2SDLL
{
    /// <summary>
    /// shared object
    /// </summary>
    public class U2SSharedObject : MarshalByRefObject
    {
        public Int32 IntegerValue { get; set; }
        public Single[] DataArray { get; set; }

        /// <summary>
        /// iitialize array
        /// </summary>
        /// <param name="arraysize">Single array size</param>
        /// <returns>=true:succeeded =false:failed</returns>
        public Boolean Init(Int32 arraysize)
        {
            IntegerValue = 0;
            DataArray = new Single[arraysize];
            return true;
        }

        /// <summary>
        /// avoid disconnection
        /// </summary>
        public override object InitializeLifetimeService()
        {
            return null;
        }
    }

    /// <summary>
    /// server class
    /// </summary>
    public class U2SServer
    {
        public U2SSharedObject SharedObject { get; set; }

        /// <summary>
        /// constructor
        /// </summary>
        public U2SServer()
        {
            // Create server channel
            IpcServerChannel channel = new IpcServerChannel("ipcU2SDLL");

            // Registratio channel
            ChannelServices.RegisterChannel(channel, false);

            // Create object and sharing
            SharedObject = new U2SSharedObject();
            SharedObject.Init(10000);
            RemotingServices.Marshal(SharedObject, "ipcRemoteObject", typeof(U2SSharedObject));
        }

        /// <summary>
        /// get integer value
        /// </summary>
        public Int32 GetIntegerValue()
        {
            return SharedObject.IntegerValue;
        }

        /// <summary>
        /// set integer value
        /// </summary>
        public void SetIntegerValue(Int32 value)
        {
            SharedObject.IntegerValue = value;
        }

        /// <summary>
        /// get float value array
        /// </summary>
        public Single[] GetFloatArray()
        {
            return SharedObject.DataArray;
        }

        /// <summary>
        /// set float value array
        /// </summary>
        public void SetFloatArray(Single[] data)
        {
            //Create clone data
            SharedObject.DataArray = (Single[])data.Clone();
        }
    }

    /// <summary>
    /// client class
    /// </summary>
    public class U2SClient
    {
        public U2SSharedObject SharedObject { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        public U2SClient()
        {
            // Create client channel
            IpcClientChannel channel = new IpcClientChannel();

            // Registratio channel
            ChannelServices.RegisterChannel(channel, false);

            // Get remote object
            SharedObject = Activator.GetObject(typeof(U2SSharedObject), "ipc://ipcU2SDLL/ipcRemoteObject") as U2SSharedObject;
        }

        /// <summary>
        /// get integer value
        /// </summary>
        public Int32 GetIntegerValue()
        {
            return SharedObject.IntegerValue;
        }

        /// <summary>
        /// set integer value
        /// </summary>
        public void SetIntegerValue(Int32 value)
        {
            SharedObject.IntegerValue = value;
        }

        /// <summary>
        /// get float value array
        /// </summary>
        public Single[] GetFloatArray()
        {
            return SharedObject.DataArray;
        }

        /// <summary>
        /// set float value array
        /// </summary>
        public void SetFloatArray(Single[] data)
        {
            //Create clone data
            SharedObject.DataArray = (Single[])data.Clone();
        }

        public string TestDLL()
        {
            return "OK";
        }
    }
}

However, when trying to substitute the client app with a Unity app, I get an error whenever I try to access the SharedObject. This is what the Unity console says:
SerializationException: Invalid binary format
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadRefTypeObjectInstance (System.IO.BinaryReader reader, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:281)
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:179)
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadNextObject (BinaryElement element, System.IO.BinaryReader reader) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:130)
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectGraph (BinaryElement elem, System.IO.BinaryReader reader, Boolean readHeaders, System.Object& result, System.Runtime.Remoting.Messaging.Header[]& headers) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:104)
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize (System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:179)
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize (System.IO.Stream serializationStream) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:136)
System.Runtime.Remoting.Channels.Ipc.Win32.IpcTransport.Read (ITransportHeaders& headers, System.IO.Stream& responseStream)
System.Runtime.Remoting.Channels.Ipc.Win32.IpcClientChannelSink.ProcessMessage (IMessage msg, ITransportHeaders requestHeaders, System.IO.Stream requestStream, ITransportHeaders& responseHeaders, System.IO.Stream& responseStream)
System.Runtime.Remoting.Channels.BinaryClientFormatterSink.SyncProcessMessage (IMessage msg)

NamedPipeException: The pipe is being closed.

System.Runtime.Remoting.Channels.Ipc.Win32.NamedPipeSocket.Send (System.Byte[] buffer, Int32 offset, Int32 count)
System.Runtime.Remoting.Channels.Ipc.Win32.NamedPipeStream.Write (System.Byte[] buffer, Int32 offset, Int32 count)
System.Runtime.Remoting.Channels.Ipc.Win32.IpcTransport.Write (ITransportHeaders header, System.IO.Stream requestStream)
System.Runtime.Remoting.Channels.Ipc.Win32.IpcClientChannelSink.ProcessMessage (IMessage msg, ITransportHeaders requestHeaders, System.IO.Stream requestStream, ITransportHeaders& responseHeaders, System.IO.Stream& responseStream)
System.Runtime.Remoting.Channels.BinaryClientFormatterSink.SyncProcessMessage (IMessage msg)

I get the "OK" string whenever I call the "TestDLL" function within the dll so I assume that the dll is correctly integrated as a plugin. I also tried building as x86 and x64 and downgrading the .net framework but the issue remains.
Could you please point me in the right direction to solve this issue? Or, if you know of a better way to send data from a non Unity App to a Unity App, please let me know!
Thank you!


text:
Q: Using Canvas and Drawimage in functions with video I am using the HTML5 canvas and DrawImage functions to display low rate video.  tnt gave excellent advice to get this project off the ground: Trying to use Canvas and DrawImage to display low-rate video at 90 degrees
While tnt's solution worked fine when the camera and angle are known at load time by using onload functions, I need to be able to turn the video off and on between several cameras  and change other parameters.  To handle that, a number of individual functions are needed, but I haven't been able to first do a setInterval on a camera and then pass the constantly changing image to DrawImage.  'cam_1.jpg' is the video in the example below.  The functions shown in body onload below will also have to be called by other routines during runtime.  Any advice will be appreciated.
var cam = null;
var c = null;
var ctx = null;
var ra = 0;

function init() {
cam = new Image;
c = document.getElementsByTagName('canvas')[0];
ctx = c.getContext('2d');
}
 function draw(cam) {
       ctx.save();
       ctx.clearRect( 0, 0, 240, 320 );
       ctx.translate( 240, 0);
       ctx.rotate(1.57);
       ctx.drawImage(cam, 0, 0 );
       ctx.restore();
       }

function inter() {
setInterval(function(){cam.src = 'cam_1.jpg?uniq='+Math.random();},500);
}

</script>

Thank you.

A: I suggest you use an object array; something like this:
var cams = []; // an array to hold you cams!

function addcam() {
  this.image = new Image;
  this.setting1 = 0;
  this.settingn = 0;
}

cams[1] = addcam();
cams[1].image.src = "cam1.jpg";
cams[1].setting1 = 2;

setInterval(function(){cam.src = '+cams[1].image.src+'?uniq='+Math.random();},500);

A: @tnt, Are you suggesting the following?  Thank you:
var cams = []; // an array to hold you cams!

function addcam() {
  this.image = new Image;
  this.setting1 = 0;
  this.settingn = 0;
}

function draw(camnum){
cams[1] = addcam();
cams[1].image.src = "cam_1.jpg";
cams[1].setting1 = 2;
cam = new Image;
c = document.getElementsByTagName('canvas')[0];
ctx = c.getContext('2d');
}

function inter() {
setInterval(function(){'cam.src = ' +cams[1].image.src+ '?uniq='+Math.random();},500);
}

function draw(cam) {
       ctx.save();
       ctx.clearRect( 0, 0, 240, 320 );
       ctx.translate( 240, 0);
       ctx.rotate( 1.57);
       ctx.drawImage(this, 0, 0 );
       ctx.restore();
}

</script>


text:
Q: Close dialog window on webpage I need to trigger some actions inside someone else's webpage. I have this code so far:
IHTMLElementCollection DeleteCollection =
    (IHTMLElementCollection)myDoc.getElementsByTagName("a");

foreach (HTMLAnchorElement buttonDelete in DeleteCollection){
    if (buttonDelete.title != null && buttonDelete.title.StartsWith("Delete")){
        buttonDelete.click();
            // problem goes here
        myDoc.activeElement.click();
        SendKeys.Send("{ENTER}");
    }
}

This dialog pops up:

I tried myDoc.activeElement.click(); and SendKeys.Send("{ENTER}"); but the dialog seems to be out of the page, so I don't know how to trigger the OK button. How can I close the window?

A: You cannot close a browser dialog programatically. What you can do is hijack browser popup behavior. This might work for you:
window.confirm=function(){ return true; };
window.alert=function(){ return true; };
window.prompt=function(){ return "textOfMyChoice"; };

Basically, insert this javascript before clicking your buttons. If you want to later restore the popup behavior store them in another global variable.

A: I suppose, any anchor tag in your example has a javascript native confirm dialog.
You don't close programmatically this dialog.
But you can change javascript for all anchor element and substitute confirm dialog with your custom jQuery dialog. this way allow you to have full control on this dialog: close, hide, set timeout etc etc.
Transform
...

to
...

So, user can continue with normal behavior, your script can take full control on all dialog element.


text:
Q: JMS. Не работает createDurableConsumer() Есть следующий код (для получателя сообщений):
ConnectionFactory factory = new ConnectionFactory();
    try (JMSContext context = factory.createContext("admin", "admin", JMSContext.AUTO_ACKNOWLEDGE))
    {
        factory.setProperty(ConnectionConfiguration.imqAddressList, "mq://127.0.0.1:7676,mq://127.0.0.1:7676");
        int id = new Random().nextInt();
        context.setClientID("" + id);
        Topic topic = context.createTopic("Topic");
        String selector= "name='value'";
        String dur_id = "DurableC" + id;
        JMSConsumer consumer = context.createDurableConsumer(topic,dur_id);
        while (true) {
            Message msg = consumer.receive();
            System.out.println(msg.getBody(String.class));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Есть следующий код для отправителя:
 ConnectionFactory factory = new ConnectionFactory();
    try (JMSContext context = factory.createContext("admin", "admin"))
    {
        factory.setProperty(ConnectionConfiguration.imqAddressList, "mq://127.0.0.1:7676,mq://127.0.0.1:7676");
        Topic topic = context.createTopic("Topic");
        TextMessage textMessage = context.createTextMessage("Message #" + msg);
        textMessage.setStringProperty("name", "value");
        context.createProducer().send(topic, textMessage);
        Thread.sleep(1000);
    }
    catch (Exception e)
    {
        System.out.println(e.getMessage());
    }

Проблема заключается в том, что если будет разрыв соединения, то никакие сообщения из Topic на консоль у меня не выводятся, хотя я создаю Durable Consumer. Объясните, что я делаю не так

A: В JavaDoc к методу createDurableConsumer пишется:

The JMS provider retains a record of this durable subscription and
  ensures that all messages from the topic's publishers are retained
  until they are delivered to, and acknowledged by, a consumer on this
  durable subscription or until they have expired.
A durable subscription will continue to accumulate messages until it
  is deleted using the unsubscribe method.

Т.е., под Durability подразумевается сохранение сообщений вне зависимости от того, подключен получатель к очереди или нет. Про восстановление разорванных соединений ничего не сказано.
Вы можете назначить слушателя ошибок:
context.setExceptionListener(new MyExceptionListener());

и реализовать в нём логику проверки наличия соединения и его восстановления в случае обрыва.


text:
Q: Trying to query multiple posts with WP_Query I have a custom field in my posts so the admin can enter a list of specific post ids they want included for the related content section in the sidebar. I am trying to insert the variable into my wp_query_object but it is only querying the first item.
When I echo the $related_vids variable it displays the ids I entered into the custom field: 45,14,10.
Any help with what I'm doing wrong would be awesome. I feel like I'm close but I've hit the wall.
<?php $related_vids = get_post_meta($post->ID, '_simple_fields_fieldGroupID_3_fieldID_2_numInSet_0', true);
$the_query = new WP_Query( array( 'post__in' => array( $related_vids ) ) );
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php endwhile; wp_reset_postdata(); ?>

A: The problem is that array( $related_vids ) actually creates an array that contains 1 element: ["45,14,10"] and not an array that contains 3 elements: [45, 14, 10]
What you need is explode( ', ', $related_vids )


text:
Q: send inputed value via javascript I found a nice tutorial about create search bar here: ...But I want to know how can I send inputed values to another page via get method?
for example if I typed 'google',It goes to http://example.com/google
I think JS can do it? can somebody guide me please

                <input type="text" id="s" name="s" value="Search Something...">

A:

Leads to nowhere as you now

That does


text:
Q: Store all received values in a different string with threads I got this code, and I'm trying to separate all the emails, passwords and the third line in a different string. Here is the code:
import random
from concurrent.futures import ThreadPoolExecutor

FILENAME = 'testing/pokens.txt'
NTHREADS = 5

def myfunc():
    with open(FILENAME) as infile:
        lines = infile.readlines()
        line = random.choice(lines).strip()
        tokens = line.split(':')
        return ' '.join(tokens)

def main():
    with ThreadPoolExecutor() as executor:
        futures = []
        printable = set()
        for _ in range(NTHREADS):
            future = executor.submit(myfunc)
            futures.append(future)
        for future in futures:
            printable.add(future.result())
        for p in printable:
            print(p)

if __name__ == '__main__':
    main()

So for example "p" prints out j3mxshasn12312zh@oncemail.co.kr 75d9d216fba123216-4e*%& third_line with removing duplicate line threads. I want all the emails, all the passwords and all the third lines stored in a different string (email1,email2,pass1,pass2,third_line1,third_line2, etc).
Pokens.txt file sample:
1thtx3213wqpzxn@oncemail.co.kr:2664a171322139489348:third_line
2bixr3123dxpdzz@oncemail.co.kr:b1*+b0ab9b(17213213^9$#@d1e:third_line
j3mxshasn12312zh@oncemail.co.kr:75d9d216fba123216-4e*%&:third_line


text:
Q: Updating plot using Select Widget issue I am currently trying to write a program that will switch between two sets of data when different options are chosen from the select widget. I am trying to make this program as autonomous as possible so in the future when people update the data they don't have to modify the code at all and the updates will happen automatically.
Currently, my issue is that when I select 'White' I want the plot to update but nothing is happening.
The two data sets are currently a dict of lists, one labeled 'White_dict' and the other labeled 'black_dict' solely to represent the color of the material for the data (I know its kinda ironic).
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource, Legend
from bokeh.models import Select
from bokeh.layouts import column
import pandas as pd
from plot_tools import add_hover
import itertools
from collections import defaultdict

bokeh_doc = curdoc()

material_types = pd.read_csv('data/material-information.csv')
df = pd.read_csv('data/Black_Materials_total_reflecatance.csv')
black_df = pd.read_csv('data/Black_Materials_total_reflecatance.csv')
white_df = pd.read_csv('data/SPIE18_white_all.csv')

names = []
w_names = []
black_dict = defaultdict(list)
white_dict = defaultdict(list)

for name, w_name in zip(df, white_df):
    names.append(name)
    w_names.append(w_name)

data = pd.read_csv('data/Black_Materials_total_reflecatance.csv', usecols = names)
w_data = pd.read_csv('data/SPIE18_white_all.csv', usecols = w_names)

for name, w_name in zip(names, w_names):
    for i in range(0, 2250):
        black_dict[name].append(data[name][i])
        white_dict[w_name].append(w_data[w_name][i])

mySource = ColumnDataSource(data = black_dict)

#create total reflectance figure
total_fig = figure(plot_width = 650, plot_height = 350,
           title = 'Total Reflectance',
           x_axis_label = 'Wavelength(nm)', y_axis_label = 'Total Reflectance',
           x_range = (250, 2500), y_range = (0,10),
           title_location = 'above', sizing_mode = "scale_both",
           toolbar_location = "below",
           tools = "box_zoom, pan, wheel_zoom, save")

select = Select(title="Material Type", options=['Black', 'White'])

def update_plot(attr, old, new):
    if new == 'White':
        mySource.data = white_dict
    else:
        mySource.data = black_dict

for name, color in zip(mySource.data, Turbo256):
    if name != 'nm':
        total_fig.line('nm', name, line_width = .7, source = mySource, color = color)

select.on_change('value', update_plot)

bokeh_doc.add_root(total_fig)
bokeh_doc.add_root(select)

I'm currently using bokeh serve bokehWork.py to launch the server. If anyone has any idea on what I should fix it would be much appreciated! Thanks!
EDIT:
Adding data for Black_materials_total_reflectance.csv
Black Reflectance Data sample
Adding data for White_all.csv
White Reflectance Data sample

A: There are two main issues with your code:

*

*You read the same files multiple times and you do a lot of work that Pandas and Bokeh can already do for you

*(the main one) You do not take into account the fact that different CSV files have different column names

Here's a fixed version. Notice also the usage of the palette. With just Turbo256 you were getting almost the same color for all lines.
import pandas as pd

from bokeh.models import ColumnDataSource, Select
from bokeh.palettes import turbo
from bokeh.plotting import figure, curdoc

black_ds = ColumnDataSource(pd.read_csv('/home/p-himik/Downloads/Black_material_data - Sheet1.csv').set_index('nm'))
white_ds = ColumnDataSource(pd.read_csv('/home/p-himik/Downloads/White Materials Sample - Sheet1.csv').set_index('nm'))

total_fig = figure(plot_width=650, plot_height=350,
                   title='Total Reflectance',
                   x_axis_label='Wavelength(nm)', y_axis_label='Total Reflectance',
                   title_location='above', sizing_mode="scale_both",
                   toolbar_location="below",
                   tools="box_zoom, pan, wheel_zoom, save")

total_fig.x_range.range_padding = 0
total_fig.x_range.only_visible = True
total_fig.y_range.only_visible = True

palette = turbo(len(black_ds.data) + len(white_ds.data))

def plot_lines(ds, color_offset, visible):
    renderers = []
    for name, color in zip(ds.data, palette[color_offset:]):
        if name != 'nm':
            r = total_fig.line('nm', name, line_width=.7, color=color,
                               source=ds, visible=visible)
            renderers.append(r)
    return renderers

black_renderers = plot_lines(black_ds, 0, True)
white_renderers = plot_lines(white_ds, len(black_ds.data), False)

select = Select(title="Material Type", options=['Black', 'White'], value='Black')

def update_plot(attr, old, new):
    wv = new == 'White'
    for r in white_renderers:
        r.visible = wv
    for r in black_renderers:
        r.visible = not wv

select.on_change('value', update_plot)

bokeh_doc = curdoc()
bokeh_doc.add_root(total_fig)
bokeh_doc.add_root(select)


text:
Q: ArrayList adding and removing Objects I'm working on an android application where I have to use custom listview with checkboxes. When user checks/unchecks, I need to add/remove objects in array list respectively.
here is my code:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
    selectedView=view;
    System.out.println("Position of list item:"+position);
    if(parent.getAdapter().equals(categoryAdapter))
    {
        System.out.println("First Adapter");
        fl=new FoodList();
        System.out.println("Tag:"+view.getTag());
        btOrder.setVisibility(View.GONE);
        addToOrder.setVisibility(View.VISIBLE);
        back.setVisibility(View.VISIBLE);
        buttonSeperator.setVisibility(View.VISIBLE);

        fl.bundleCategory=fc.list[position];
        fl.foodListService();
        checks=new SparseBooleanArray();
        quantity=new SparseArray<Integer>();

        orderList=new ArrayList<Order>();
        order=new Order();
        Order Null=null;
        for(int i=0;i<fl.foodList.size();i++)
        {
            checks.put(i, false);
            quantity.put(i, 0);
            order.setQuantity(0);
            order.setItem("");
            //orderList.add(i,Null);
            //orderList.add(i,order);
            orderList.add(order);
            System.out.println("Adding at pos:"+i+"Value:"+Null);
        }
        WaiterFoodAdapter foodAdapter=new WaiterFoodAdapter(this, R.layout.take_order_list, fl.foodList);
        categoryList.setAdapter(foodAdapter);
        categoryList.setOnItemClickListener(this);
        }
        else
        {
            System.out.println("Second Adapter:Id="+parent.getId());

            if(view != null)
            {
                final TextView tvItem=(TextView)selectedView.findViewById(R.id.foodName);
                final TextView tvQuantity=(TextView)selectedView.findViewById(R.id.quantity);

                selectedPosition=position;
                SelectFood = (CheckBox)view.findViewById(R.id.selectFood);

                if(SelectFood.isChecked())
                {
                    SelectFood.setChecked(false);
                    checks.put(selectedPosition, false);
                    quantity.put(selectedPosition,0);

                    //order.setQuantity(0);
                    //order.setItem("");
                    System.out.println("Removing at pos:"+selectedPosition+"Value:"+orderList.get(selectedPosition).getItem()+orderList.get(selectedPosition).getQuantity());
                    orderList.remove(orderList.get(selectedPosition));

                    tvQuantity.setText("0");
                    System.out.println("Position="+selectedPosition);
                }
                else
                {
                    SelectFood.setChecked(true);
                    checks.put(selectedPosition, true);
                    System.out.println("Position="+selectedPosition);

                    //orderList=new ArrayList<Order>();
                    final AlertDialog.Builder quantityAlert= new AlertDialog.Builder(TakeOrder.this);
                    quantityAlert.setTitle("Quantity");
                    quantityAlert.setMessage("Please enter quantity");

                    final EditText input = new EditText(TakeOrder.this);
                    input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    quantityAlert.setView(input);

                    quantityAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                            value = input.getText();

                            if(value.toString().equals(""))
                            {
                                SelectFood.setChecked(false);
                                Toast msg=Toast.makeText(TakeOrder.this, "Please provide quantity", Toast.LENGTH_SHORT);
                                msg.show();
                            }
                            else
                                if(value.toString().equals("0"))
                                {
                                    SelectFood.setChecked(false);
                                    Toast msg=Toast.makeText(TakeOrder.this, "Please enter valid quantity", Toast.LENGTH_SHORT);
                                    msg.show();
                                }
                                else
                                {
                                    tvQuantity.setText(value);
                                    quantity.put(selectedPosition, Integer.valueOf(value.toString()));
                                    order.setQuantity(Integer.valueOf(tvQuantity.getText().toString()));
                                    order.setItem(tvItem.getText().toString());
                                    orderList.add(selectedPosition, order);
                                    System.out.println("setting at pos:"+selectedPosition+"Value:"+orderList.get(selectedPosition).getItem()+orderList.get(selectedPosition).getQuantity());
                                }

                            //Log.v("Item:",orderList.get(selectedPosition).getItem());
                            //Log.v("Quantity:",String.valueOf(orderList.get(selectedPosition).getQuantity()));

                        }
                    });

                quantityAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
                {
                      public void onClick(DialogInterface dialog, int whichButton)
                      {
                          SelectFood.setChecked(false);
                      }
                    });

                quantityAlert.show();
            }
        }

    }

}

When user click addToOrder button it just search for checked checkboxes and gettin relevant textViews values of checked listItems..
public void addToOrder(View v)
{
    for(int i=0;i<fl.foodList.size();i++)
    {
        if(checks.get(i)==true)
            {
            System.out.println("Order is:"+orderList.get(i).getItem()+orderList.get(i).getQuantity());
            }
    }
}

this is my adapter which is just for custom view purpose
public class WaiterFoodAdapter extends ArrayAdapter<Food>
{
    Context context;
    TakeOrder holder;
    int layoutResourceId;
    List<Food> foodList;

    public WaiterFoodAdapter(Context context, int layoutResourceId,List<Food> foodList)
    {
        super(context, layoutResourceId, foodList);
        this.context=context;
        this.layoutResourceId=layoutResourceId;
        this.foodList=foodList;
    }

    @Override
    public View getView(int position,View convertView,ViewGroup parent)
    {
        View row=convertView;

        if(row==null)
        {
            LayoutInflater inflater=((Activity)context).getLayoutInflater();
            row=inflater.inflate(layoutResourceId, parent,false);
            holder=new TakeOrder();
            holder.foodIcon=(ImageView)row.findViewById(R.id.foodIcon);
            holder.tvFoodName=(TextView)row.findViewById(R.id.foodName);
            holder.cbSelectFood=(CheckBox)row.findViewById(R.id.selectFood);
            holder.cbSelectFood.setClickable(false);
            holder.tvFoodDescription=(TextView)row.findViewById(R.id.foodDescription);
            holder.tvFoodQuantity=(TextView)row.findViewById(R.id.foodQuantity);
            holder.tvQuantity=(TextView)row.findViewById(R.id.quantity);
            row.setTag(holder);

        }
        else
        {
            holder=(TakeOrder)row.getTag();
        }
        if(fl.bundleCategory.equals("Appetisers"))
        {
        holder.foodIcon.setImageResource(R.drawable.appetiser);
        }
        else
            if(fl.bundleCategory.equals("Main Courses"))
            {
                holder.foodIcon.setImageResource(R.drawable.main_course);
            }
            else
                if(fl.bundleCategory.equals("Sides"))
                {
                    holder.foodIcon.setImageResource(R.drawable.sides);
                }
                else
                    if(fl.bundleCategory.equals("Desserts"))
                    {
                        holder.foodIcon.setImageResource(R.drawable.desserts);
                    }
                    else
                        if(fl.bundleCategory.equals("Drinks"))
                        {
                            holder.foodIcon.setImageResource(R.drawable.drinks);
                        }
        holder.tvFoodName.setText(foodList.get(position).getMenuItem());
        holder.tvFoodDescription.setText(foodList.get(position).getDescription());
        holder.cbSelectFood.setChecked(checks.get(position));
        holder.tvQuantity.setText(String.valueOf(quantity.get(position)));
        return row;
    }

}

Suppose i select(check) two list items and then press addToOrder button it just prints the last seleccted item twice. I dont know why its just overridding a first object in my List
I think my logic is correct, but dont know why its not working??
Can any one please help

A: You should make a method in your adapter which lets your update the current arraylist or add/remove the item you pass. But I can't see how you implemented your adapter which probably is the most important code...
You need something like this, inside your adapter (this is to update a full list):
public void updateListArray(ArrayList<Item> list) {
    this.clear();
    for(Item item : list) {
        this.add(item);
    }
    notifyDataSetChanged();
}


text:
Q: Defining date attributes in openldap There doesn't appear to be a standard date syntax.  How do people handle entering dates into ldap so that they are comparable and invalid data can't be entered?  I'm hoping to enforce a fairly standard format such as YYYY-mm-dd.  Other people have to have done this before but I can't seem to find anything.  Anyone have suggestions or links?

A:
There doesn't appear to be a standard date syntax.

The standard representation of time/date information uses the "generalized time" syntax, defined in RFC 4517.  This is used by OpenLDAP, Active Directory, other directory servers, and elsewhere.


text:
Q: Tensorflow 2 batch norm no gradient issue for batch_step, batch in enumerate(self.batch_iterator_train):
    with tf.GradientTape() as tape:
         logits, _ = self.model(batch['images'], is_training=True)
         loss_value = self.loss_fn(labels=batch['labels'], logits=logits)
    grads = tape.gradient(loss_value, self.model.trainable_variables) # use gradient to automatically retrieve gradients of var. wrt loss
    self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables)) # apply one step of gradient descent

I'm using the code above to train my model in Tensorflow 2.1.0, but I'm getting the following error:
WARNING:tensorflow:Gradients do not exist for variables ['net/block/batch_norm_relu_1/batch_normalization_1/beta:0', .....]

Is there an issue with TF 2.10 with batch norm, especifically with the beta parameter? As far as I understand, the beta parameter is used for shifting the batch norm values - so it should be trainable.
UPDATE:
Upon closer inspection, I noticed that about half of my batch norm layers have weights of all 0s.
self.model.trainable_variables[17]
Out[63]:
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
      dtype=float32)>

I'm really not sure why though.


text:
Q: How to have remote standby PostgreSQL server in different location (AWS)? We have a primary PostgreSQL 9.4 server running multiple instances in our DC. It is using Continuous Archiving via WAL-E out to AWS S3. I would like to have a hot/warm standby server in our VPC within AWS EC2 that would be ready to take over should we need to DR. I can recover the server via WAL-E but can't seem to get it to work in hot_standby mode. What could I be missing? Docs I read seem to suggest that the standby needs to talk to the primary? Is this so? Is this required when log-shipping via WAL-E?

A: There are two ways to run a replica. You can use either, or both together:

*

*Streaming replication, where the replica makes a PostgreSQL protocol connection to the standby as configured with primary_conninfo in recovery.conf; or

*WAL shipping, where the replica runs a restore_command (set in recovery.conf that fetches WAL archives to replay.
See recovery.conf.
Both require that standby_mode be set in recovery.conf.
WAL-E is designed to be used as an archive_command on the master, to store WAL into S3, then as a recovery_command on the replica to fetch WAL. There is no need for a streaming replication connection. You can add one anyway, and it will be used where available, and the system will fall back to WAL archive recovery if it can't connect over streaming replication. Or you can just use WAL-based archiving.
The main advantage of using streaming replication as well is that it's more timely; you don't have to wait until an entire WAL archive is filled and shipped before the replica sees the changes.
For more information see the manual.


text:
Q: jquery ajax multiple dynamic forms processing I'm doing a simple PHP quiz app which uses jquery, the rules are:

*

*each quiz has many questions (max 100), user clicks to add more questions, which generates a new form, appended at the end of the list

*many answers for each question (max 5), user clicks to add more answers for a question, appended at the end of the answer list of that question

*questions are sorted/weighted by submit sequence, ajax post in this case

*answers are named "answer[]"

*The quiz loaded from db, user can remove, edit or add new questions/answers within above limits

I've decided to organized each question a form with "class='postable'". My script for quiz updating looks like this
$("#update-change").click(function(e){
    e.preventDefault();
    showupdate('Updating..');

       $('form.postable').each(function(){
           $.ajax({
                 type: "POST",
                 url: 'update_ask.php',

                 data: $(this).serialize()
            }).done(function( msg ) {
                feedbackMessage(msg);
            });
       });
});

So, each time "#update-change" hit, there are n ajax posted to 'update_ask.php' to save quiz contents.
The problem is the questions won't be sorted as seeing, it could be 'update_ask.php' fail to process ajax request in sequence due to lagging.
Do you have any idea/solution for this case? Please advise. Thanks.
HTML for one question sets looks like this:
<form action="update_ask.html" method="post" accept-charset="utf-8" name="aj_edit_ask2430" id="editaskform2430" class="postable">
    <input type="hidden" name="idask" value="2430" />
    <input type="hidden" name="idquiz" value="240" />

        <textarea name="ask" class="ask"  tabindex="24300" placeholder="Question">cau 5</textarea>

            <input type="hidden" name="askimg" id="saskimg2430" value="" />

            <textarea name="answer[]" class="answer" tabindex="24301" placeholder="Answer or Solution">answer 51</textarea>

            <input type="hidden" name="images[]" id="simg30684" value="" />

            <input type="radio" name="iscorrect" value="1" checked='checked'  />
            Correct Delete

            <textarea name="answer[]" class="answer" tabindex="24302" placeholder="Answer or Solution">answer 52</textarea>

                <input type="hidden" name="images[]" id="simg30685" value="" />

            <input type="radio" name="iscorrect" value="2"   />
            Correct Delete

            <textarea name="answer[]" class="answer" tabindex="24303" placeholder="Answer or Solution">answer 53</textarea>

                <input type="hidden" name="images[]" id="simg30686" value="" />

            <input type="radio" name="iscorrect" value="3"   />
            Correct Delete

    Add Delete this question
</form>

A: Putting each question in its own form and making an AJAX request for each question on the page seems like a bad idea. That would be a ton of overhead, making up to 100 server requests every time the user hits a button. You should put all the questions on one form.
As for the extra complications that make you think one form is necessary for each question, I'm betting that it can still be done with one form for all questions...but you'll have to post a code sample that shows that complication before I can help there.

UPDATE:
Having the extra stuff associated with each question doesn't mean that you need to use one form for every question. It just means that you need to revise your naming convention for your elements. Based on the HTML you provided, you could change it to something more like this (notice the changes in the names of the form elements):
<form action="update_ask.html" method="post" accept-charset="utf-8">
    <input type="hidden" name="questions[0][idquiz]" value="240" />

        <input type="hidden" name="questions[0][idask]" value="2430" />

            <textarea name="questions[0][ask]" class="ask"  tabindex="24300" placeholder="Question">cau 5</textarea>

                <input type="hidden" name="questions[0][askimg]" id="saskimg2430" value="" />

                <textarea name="questions[0][answers][]" class="answer" tabindex="24301" placeholder="Answer or Solution">answer 51</textarea>

                    <input type="hidden" name="questions[0][images][]" id="simg30684" value="" />

                    <input type="radio" name="questions[0][iscorrect]" value="1" checked='checked'  /> Correct
                    Delete

                <textarea name="questions[0][answers][]" class="answer" tabindex="24302" placeholder="Answer or Solution">answer 52</textarea>

                    <input type="hidden" name="questions[0][images][]" id="simg30685" value="" />

                    <input type="radio" name="questions[0][iscorrect]" value="2"   /> Correct
                    Delete

                <textarea name="questions[0][answers][]" class="answer" tabindex="24303" placeholder="Answer or Solution">answer 53</textarea>

                    <input type="hidden" name="questions[0][images][]" id="simg30686" value="" />

                    <input type="radio" name="questions[0][iscorrect]" value="3"   /> Correct
                    Delete

        Add
        Delete this question

        <input type="hidden" name="questions[1][idask]" value="2431" />

            <textarea name="questions[1][ask]" class="ask"  tabindex="24310" placeholder="Question">cau 5</textarea>

                <input type="hidden" name="questions[1][askimg]" id="saskimg2431" value="" />

                <textarea name="questions[1][answers][]" class="answer" tabindex="24311" placeholder="Answer or Solution">answer 51</textarea>

                    <input type="hidden" name="questions[1][images][]" id="simg30684" value="" />

                    <input type="radio" name="questions[1][iscorrect]" value="1" checked='checked'  /> Correct
                    Delete

                <textarea name="questions[1][answers][]" class="answer" tabindex="24312" placeholder="Answer or Solution">answer 52</textarea>

                    <input type="hidden" name="questions[1][images][]" id="simg30685" value="" />

                    <input type="radio" name="questions[1][iscorrect]" value="2"   /> Correct
                    Delete

                <textarea name="questions[1][answers][]" class="answer" tabindex="24313" placeholder="Answer or Solution">answer 53</textarea>

                    <input type="hidden" name="questions[1][images][]" id="simg30686" value="" />

                    <input type="radio" name="questions[1][iscorrect]" value="3"   /> Correct
                    Delete

        Add
        Delete this question

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

And now your PHP might look something like this:
$quizID = $_POST['idquiz'];

$questions = $_POST['questions'];
var_dump($questions);

/*
This will look something like:
array(
    [0] => array(
        'answers' => array('answer 51', 'answer 52', 'answer 53'),
        'ask' => 'cau 5',
        'askimg' => '',
        'idask' => '2430',
        'images' => array('', '', ''),
        'iscorrect' => '1'
    ),
    [1] => array(
        'answers' => array('answer 51', 'answer 52', 'answer 53'),
        'ask' => 'cau 5',
        'askimg' => '',
        'idask' => '2431',
        'images' => array('', '', ''),
        'iscorrect' => '1'
    )
)
*/

A: Per request, this example uses jQuery Deferred to process all the forms, rework that last function to your needs/how to react to failures of posts.  Note no ajaxStop needed as the events are managed by the deferreds.
$('#update-change').on('click', function (event) {
    var forms = $('form.postable');
    event.preventDefault();
    var quizIndex = 0;
    var countOfForms = forms.length;
    for (quizIndex = 0; quizIndex < countOfForms; quizIndex++) {
        saveQuiz(forms, quizIndex);
    }
});

function quizPost(quiz, dfd) {
    $.ajax({
        type: "POST",
        url: 'update_ask.php',
        dataType: "json",
        data: quiz.serialize(),
        success: dfd.resolve,
        error: dfd.reject
    }).done(function (msg) {
        feedbackMessage(msg);
    });
}

function saveQuiz(forms, quizIndex) {
    var form = forms.eq(quizIndex);
    formValid = true,
    messages = [],
    dfd = $.Deferred();
    showupdate('Updating...form ' + quizIndex);
    /*
    do a lot of client-side validation on the form here setting "valid"
   */
    if (!formValid) {
        dfd.resolve({
            success: false,
            errors: messages
        });
    } else {
        quizPost(form, dfd);
    }
    return dfd.promise();
}

saveQuiz(quizIndex).done(function (response) {
    if (response.success) {
        // saving worked; rejoice
    } else {
        // client-side validation failed
        // output the contents of response.errors
    }
}).fail(function (err) {
    // AJAX request failed
});


text:
Q: Every time I type elif in code it shows error when I start program Every time I type elif in code it shows error when I start program
# This is game creating practice
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')

# Ask the player to guess 6 times
for guessesTaken in range(1, 7):
    print('Take a guess.')
    guess = int(input())

    if guess < secretNumber:
        print('Your guess is too low.')
        elif guess > secretNumber:
            print('Your guess is to high.')
        else:
            break  # This condition is the correct guess!

if guess == secretNumber:
    print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!)
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))

A: In Python, whitespace is important.
Your elif should be on the same column as your if.


text:
Q: Calculating boundaries for a multiple integral from inequalities I was trying to solve for the region enclosed by y=Sqrt[x], z=1+x+y, y=0, and x=1, to evaluate a triple integral of 6xy.
So far I have tried to this code to only an error.
Integrate[(6*x*y)Boole[z=1+x+y && y==Sqrt[x] &&y==0 && x==1], {x, -∞, ∞}, {y, -∞, ∞}, {z, -∞, ∞}]

Could someone please help me understand how to calculate a region in Mathematica?

A: It is right?
reg = ImplicitRegion[ y <=  Sqrt[x] && z == 1 + x + y &&  y >= 0 && x <= 1, {x, y, z}]
% // Region
Integrate[6*x*y, {x, y, z} ∈ reg]

Sqrt[3]

Another way
According to the definition of the integral along a surface.
The normal of the surface z-(1+x+y)==0 is Grad[z - (1 + x + y), {x, y, z}
Integrate[
 6 x*y*Norm[Grad[z - (1 + x + y), {x, y, z}]], {x, y} ∈
  ImplicitRegion[y <= Sqrt[x] && y >= 0 && x <= 1, {x, y}]]

Sqrt[3]


text:
Q: Is it possible to adjust the heights of each individual item of a row in grid? I am trying to make a gallery that is uneven and staggered by using images and colored divs that are not the same size. I have the columns set to a min of 352px and to auto-fit the screen. So the container with grid looks something like this:
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(352px, 1fr));
    grid-gap: 20px;

The issue I am having is the tallest picture sets the height of the row and the divs that have the smaller images follow the same height. Is there a way to tell the items in the row to not all be the same size? Or rather just target certain items in each row and tell them to be a specific height?

.grey {
    background: #D9D9D9;
  }

.tan {
    background: #DCCEC8;
}

.light-brown {
    background: #DC997D;
}

.brown {
    background: #814A3D;
}

.black {
    background: #000;
}

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(352px, 1fr));
    grid-gap: 20px;
}

.grid > div {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
}

img {
  max-width: 350px;
  width: 350px;
}

.overlay {
    position: absolute;
    width: 350px;
    height: 100%;
    background: rgba(0, 0, 0, 0.05);
}

h4 {
  text-transform: uppercase;
  font-size: 26px;
  color: #fff;
  position: absolute;
  z-index: 9;
            }

h4:nth-child(2) {
  bottom: 35px;
}

h4:nth-child(3) {
  font-size: 18px;
  margin: 5px 0;
  bottom: 5px;
}

.fill {
    max-width: 350px;
    height: 100%;
    width: 100%;
}

Person One

@person1

Person TWO

@person2

Person 3

@person3

Person four

@person4

Person Five

@pesron5

Person Six

@person6

Person Seven

@person7

Person Eight

@person8

Person Nine

@Person9

Person Ten

@person10

A: Use height on the grid items. Moreover, the headings should be wrapped in a container and their default margins should be overwritten so that headings fit in container with image's height < 150px.

.grey {
  background: #d9d9d9;
}

.tan {
  background: #dccec8;
}

.light-brown {
  background: #dc997d;
}

.brown {
  background: #814a3d;
}

.black {
  background: #000;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(352px, 1fr));
  grid-gap: 20px;
}

.grid>div {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

img {
  max-width: 350px;
  width: 350px;
}

.overlay {
  position: absolute;
  width: 350px;
  height: fit-content;
  background: rgba(0, 0, 0, 0.05);
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
}

h4 {
  text-transform: uppercase;
  font-size: 26px;
  color: #fff;
  z-index: 9;
  text-align: center;
  margin: 0;
  margin-bottom: 10px;
}

.fill {
  max-width: 350px;
  height: 100%;
  width: 100%;
}

.grid-item {
  height: fit-content;
  height: -moz-fit-content;
}

Person One

@person1

Person TWO

@person2

Person 3

@person3

Person four

@person4

Person Five

@pesron5

Person Six

@person6

Person Seven

@person7

Person Eight

@person8

Person Nine

@Person9

Person Ten

@person10


text:
Q: Keytool error: java.lang.Exception: Failed to parse input This question may be duplicate, but i am not able to get the solution,
I tried to create SSL certificate with following commands,
C:\Program Files\Java\jdk1.6.0_05\bin>keytool -genkey -alias tomcat -keyalg RSA
-keystore E:\key
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  Raghu
What is the name of your organizational unit?
  [Unknown]:  BFS
What is the name of your organization?
  [Unknown]:  iGate
What is the name of your City or Locality?
  [Unknown]:  Bang
What is the name of your State or Province?
  [Unknown]:  KA
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=Raghu, OU=BFS, O=iGate, L=Bang, ST=KA, C=IN correct?
  [no]:  y

Enter key password for <tomcat>
        (RETURN if same as keystore password):
Re-enter new password:

I have tried get certificate request using following command
C:\Program Files\Java\jdk1.6.0_05\bin>keytool -certreq -v -alias tomcat -keyalg
RSA -keystore E:\key
Enter keystore password:

And got following response in the command prompt
**-----BEGIN NEW CERTIFICATE REQUEST----- MIIBlzCCAQACAQAwVzELMAkGA1UEBhMCSU4xCzAJBgNVBAgTAktBMQ0wCwYDVQQHEwRCYW5nMQ4w
DAYDVQQKEwVpR2F0ZTEMMAoGA1UECxMDQkZTMQ4wDAYDVQQDEwVSYWdodTCBnzANBgkqhkiG9w0B
AQEFAAOBjQAwgYkCgYEA0Aoxz2V/Cqs00d7d4iVysIcfMxXDA4ydD5+AY2Q2hPqIOAbfrz0HiSjZ
JwKV0/g7P/oWPU9fCFYnLXAynusbaAtw5xIolMNqj9gtxmD1BzrwxcVIX3oWY0LzO768TMY3Szjp
tS64z5q1KSTYqeZww0f11N2JssjtMch8gw50FIcCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBAK1v
sE0BNxGrGKNBXhYuSdgwF14ZnELtjWBzDJDzbzgJbK6RJlOEstKxdStR2fq7iv0ow+Df7TnVWidm
+0PRLuhtr3DMZVX2acNQY4c4ynKWgLyBV2lAXbYfgZdzQr3ClY+40lkbmHQaMxZcxz2q7u8Np6sH
n0iytY6U0CqJpRcB
----END NEW CERTIFICATE REQUEST-----**

And I am saved in cert.txt file and to Verify the Certificate Reply
 C:\Program Files\Java\jdk1.6.0_05\bin>keytool -printcert -file E:\cert.txt

**keytool error: java.lang.Exception: Failed to parse input**

I got the above error. please suggest for the same.

A: You're confusing certificate and certificate request.
When you use -certreq, you're producing a certificate request (CSR), which you should send to your CA, which will send you a certificate in return. You'll then be able to import that certificate into your keystore, against the private key it already holds (and that was generated with -genkey.
-printcert is for printing certificates, not certificate requests (BEGIN NEW CERTIFICATE REQUEST).

A: I think you missed one step which is causing the issue.
keytool -exportcert -rfc -keystore D:\key -file D:\cert.crt

Please check this link.


text:
Q: Integrate SFDC with our personal websites We do not have SFDC Devs in our environment; we will be utilizing our webmaster for this integration execution. I hope to guide him from an administrator perspective, but I have little knowledge of integrations and plenty admin skills.
Could you please guide me with some information I should present in our initial meeting of expectations and how to's and requirements in order to integrate our SFDC to sync from our private website that data is entered to sync once submitted. (Ideally would like information to sync both ways)

A: Salesforce provides REST API which can be used to integrate Salesforce with any external system. It all depends what is your existing language. Salesforce also provides SDK for different languages such as PHP, JAVA, .NET
You can check Example section of REST API to understand how easy it is to create, update, delete records in Salesforce using REST API.
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_sobject_create.htm
If you want to send data out of Salesforce you can also do httprequest callout which can post data to your external webservice once any record created/update inside Salesforce.
You can also use external ID concept of Salesforce which can work as primary key between your external system and Salesforce.
Using the Lightning connector you can show external system data on real time basis inside Salesforce.
You can also use Streaming API for your requirement.
Salesforce work in multitenant architecture it has some limit so you should opt your option wisely.
here are the resource for API limits
https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/limits.htm
https://help.salesforce.com/HTViewHelpDoc?id=integrate_api_rate_limiting.htm


text:
Q: Managing SQL Server Connections What is the the best practice for SQL connections?
Currently I am using the following:
using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING))
{
    sqlConn.Open();
    // DB CODE GOES HERE
}

I have read that this is a very effective way of doing SQL connections. By default the SQL pooling is active, so how I understand it is that when the using code ends the SqlConnection object is closed and disposed but the actual connection to the DB is put in the SQL connection pool.  Am i wrong about this?

A: Microsoft's Patterns and Practices libraries are an excellent approach to handling database connectivity. The libraries encapsulate most of the mechanisms involved with opening a connection, which in turn will make your life easier.

A: That's most of it. Some additional points to consider:

*

*Where do you get your connection string?  You don't want that hard-coded all over the place and you may need to secure it.

*You often have other objects to create as well before your really use the connection (SqlCommand, SqlParameter, DataSet, SqlDataAdapter), and you want to wait as long as possible to open the connection.  The full pattern needs to account for that.

*You want to make sure your database access is forced into it's own data layer class or assembly.  So a common thing to do is express this as a private function call:

.
private static string connectionString = "load from encrypted config file";
private SqlConnection getConnection()
{
    return new SqlConnection(connectionString);
}

And then write your sample like this:
using (SqlConnection sqlConn = getConnection())
{
    // create command and add parameters

    // open the connection
    sqlConn.Open();

   // run the command
}

That sample can only exist in your data access class.  An alternative is to mark it internal and spread the data layer over an entire assembly.  The main thing is that a clean separation of your database code is strictly enforced.
A real implementation might look like this:
public IEnumerable<IDataRecord> GetSomeData(string filter)
{
    string sql = "SELECT * FROM [SomeTable] WHERE [SomeColumn] LIKE @Filter + '%'";

    using (SqlConnection cn = getConnection())
    using (SqlCommand cmd = new SqlCommand(sql, cn))
    {
        cmd.Parameters.Add("@Filter", SqlDbType.NVarChar, 255).Value = filter;
        cn.Open();

        using (IDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                yield return (IDataRecord)rdr;
            }
        }
    }
}

Notice that I was also able to "stack" the creation of the cn and cmd objects, and thus reduce nesting and only create one scope block.
Finally, a word of caution about using the yield return code in this specific sample.  If you call the method and don't complete your DataBinding or other use right away it could hold the connection open for a long time.  An example of this is using it to set a data source in the Load event of an ASP.NET page.  Since the actual data binding event won't occur until later you could hold the connection open much longer than needed.

A: Your understanding of using is correct, and that method of usage is the recommended way of doing so.  You can also call close in your code as well.

A: Also : Open late, close early.
Don't open the connection until there are no more steps left before calling the database. And close the connection as soon as you're done.


text:
Q: What is the difference between "might be" and "must be"? (C ) 7 —You look worried. What's wrong?
—I can't find my wallet anywhere. It________lost.
A. must be
B. might be
Question:
Which one is right? A or B?

A: Might be implies that there is a possibility it is lost. Must be lost states there is no other possibility.

A: If you can't find your wallet anywhere, it is lost:

lost adjective 1.1 Unable to be found. Source: Lexico

But if you must use a modal auxiliary verb, you'll have to choose A. must be; it's the modal we use  for certainty—for deductions and conclusions:

I can't find my wallet anywhere. It must be lost.

That means that since you are unable to find your wallet, you have concluded that it is lost.
Or, as we say around here . . . No shit, Sherlock.

A: It's definitely b), because "might be" implies that you are not sure if it's stolen, while "must be" means you are 100% sure that it's stolen, which you are not.