text:
Q: RestSharp - Authorization Header not coming across to WCF REST service I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
  System.Net.HttpRequestHeader.Authorization,
  "Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));

WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
    if (webStream != null)
    {
        using (StreamReader responseReader = new StreamReader(webStream))
        {
            string response = responseReader.ReadToEnd();
        }
    }
}

When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;

var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");

var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);

What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");

will come thru, only "Authorization" seems stripped out/missing.

A: You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);

A: instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");

A: I used milano's answer to get my REST service call to work (using GET)
    Dim client2 As RestClient = New RestClient("https://api.clever.com")

    Dim request2 As RestRequest = New RestRequest("me", Method.GET)

    request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)

    Dim response2 As IRestResponse = client2.Execute(request2)
    Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")

The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header

A: I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");

var request = new RestRequest("/antiforgerytokensso", Method.Get);

restClient.Authenticator = new JwtAuthenticator(accessToken);

var response = await restClient.ExecuteAsync(request);

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));


text:
Q: Connecting to ActiveMQ Artemis with QueueExplorer I have a new install of ActiveMQ Artemis on a local virtual machine using Ubuntu 18.04. I'm trying to connect to it with a JMS client called QueueExplorer.

Cannot read queues from machine 192.168.1.13/ (ActiveMQ).

StackTrace:  Cogin.ActiveMQ.AMQException: Could not connect to ActiveMQ: Unable to connect to the remote server
   at Cogin.ActiveMQ.Internal.JolokiaConnection.SendJsonRequest(String uriString, JToken requestJson)
   at Cogin.ActiveMQ.Internal.JolokiaConnection.RequestBrokerName()
   at Cogin.ActiveMQ.Internal.JolokiaRequest.GetMBeanObject(AMQMachineItem machine)
   at Cogin.ActiveMQ.Internal.JolokiaConnection.Execute(JolokiaRequest request)
   at Cogin.ActiveMQ.Internal.AMQBrokerProxy.GetBrokerInfo(IWorker worker)
   at Cogin.ActiveMQ.Services.AMQBrokerService.GetQueuesTree(IWorker worker, Boolean showNonWritableQueues)
   at a8.a.e(IWorker A_0)
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ab.a.e()

Version: QueueExplorer Standard 4.3.15.26129 .Net Framework Version: 4.8.0 OS: Windows 10

I can ping the system successfully. The firewall is not enabled, and I can reach the web console. I followed this guide for setting it up, but I think I'm missing something. QueueExplorer needs Jolokia and OpenWire. The web console uses Jolokia, but the error in QueueExplorer complains about it.
When connecting to ActiveMQ with QueueExplorer, I didn't need to make any configuration changes. Are there additional steps in Artemis to allow a client to connect?

A: It's impossible to say with 100% certainty what the problem is since QueueExplorer is closed source software as far as I can tell. However, I can say with certainty that ActiveMQ Artemis does support OpenWire and it ships with Jolokia to expose its management beans (i.e. MBeans) via HTTP.
I believe the issue is that QueueExplorer expects to find in ActiveMQ Artemis the same MBeans as ActiveMQ 5.x and that simply isn't the case. While ActiveMQ Artemis supports many of the same features and functionality as ActiveMQ 5.x it is a fundamentally different architecture under the covers which is designed to provide a much higher level of performance and a protocol/API agnostic addressing model.
I believe the only solution here would be for the author(s) of QueueExplorer to update it to work with the ActiveMQ Artemis MBeans.

redpajama_set_name: RedPajamaStackExchange


text:
Q: loading the source of a BitmapImage in WPF? In a silverlight app, I have a BitmapImage defined as System.Windows.Media.Imaging.BitmapImage and it as a method called "SetSource" where I can set the source like this:
BitmapImage bitmap = new BitmapImage();
System.IO.Stream stream = _scene.GetStream();
if (stream == null) return;
bitmap.SetSource(stream);

In a WPF application I have also have a
Bitmap image defined as System.Windows.Media.Imaging.BitmapImage but there is no SetSource method.  How do I set the source in a WPF app like I do in a Silverlight app?
Also, it is a stream, not a string.  It is not a URI.  so "UriSource" method does not work.  I tried this:
        System.IO.Stream stream = _scene.GetStream();
        if (stream == null) return;
        BitmapImage bitmap = new BitmapImage();

        bitmap.UriSource = new Uri(stream.ToString());

And at runtime, it threw an error tha URI cannot be determined.  Is the URI an identifier for the intranet?  Are you sure that this is not a silverlight thing?  I am doing a WPF application

A: You'll have to set the BitmapImage.StreamSource property:
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = _scene.GetStream();
bitmap.EndInit();

If you want to close the stream right after creating the bitmap, you would also have to set the BitmapCacheOption.OnLoad option:
using (Stream stream = _scene.GetStream())
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

A: You can use the constructor to specify the UriSource
BitmapImage bmp = new BitmapImage(uriSource: new Uri());

Or you can use BitmapImage.StreamSource property to set the StreamSource


text:
Q: C# winforms instantiating unknown (at design time) form at runtime (late binding?) I have a need to instantiate an instance of a dll containing a form at runtime. Currently I have a long switch statement with 75+ cases and growing rapidly. As this has all developed we have also developed a List that contains all the info to dynamically call the form.
Sample case now
...
case "state"
  State state = new State();
  state.Parent = this.Parent;
  state.ScreenNameLong = "State ";
  state.ScreenTitle = "St11 - State";
  state.SetupForm();
  this.OpenForm(state, state.ScreenTitle);
  break;
...

All info needed is now contained in a list element called menuItem which is already selected. It has form ("State"),  ScreenNameLong, ScreenTitle etc.. All forms to be called have Parent objects and SetupForm() methods.
All dll's are referenced in "using" statements and in project references.
It seems I should somehow be able to do something similar to this, once:
Form formToLaunch = (menuItem.form);
formToLaunch.Parent = this.Parent;
formToLaunch.ScreenNameLong = menuItem.descr;
formToLaunch.ScreenTitle = menuItem.scrNumber + " " + formToLaunch.ScreenNameLong;
formToLaunch.SetupForm();
this.OpenForm(formToLaunch, formToLaunch.ScreenNameLong );

I have beat my head against the wall and not found a good solution to this. I have researched using Reflection and Interfaces and they don't seem to fit the bill, or I am just not getting it...

A: All your forms will need to implement an interface defining the common members, for example:
interface IForm : IDisposable
{
    Form Parent { get; set; }
    string ScreenNameLong { get; set; }
    string ScreenTitle { get; set; }
    void SetupForm();
}

Here IForm inherits from IDisposable per dbc's comment below.
Get the Type from the typename (presumably in your menuItem.form).  You might need to play around with this:
var type = Type.GetType("form_namespace." + menuItem.form + ", form_assembly_name");

Instantiate the type, cast as your interface, and do whatever you want with it:
var formToLaunch = Activator.CreateInstance(type) as IForm;
if (formToLaunch != null)
{
    formToLaunch.Parent = this.Parent;
    formToLaunch.ScreenNameLong = menuItem.descr;
    formToLaunch.ScreenTitle = menuItem.scrNumber + " " + formToLaunch.ScreenNameLong;
    formToLaunch.SetupForm();
    this.OpenForm(formToLaunch, formToLaunch.ScreenNameLong);
}


text:
Q: My sql query to get product count for Attribute I need the mysql query for the following magento code. Need to get the count of products with the given brand option id.
count($this->productCollectionFactory->create()
                ->addAttributeToSelect('*')
                ->addFieldToFilter('status','1')
                ->addAttributeToFilter('brand','120')
                ->load()->getData());

A: Can use echo $collection->getSelect()
Example:
$collection = $this->productCollectionFactory->create()
                ->addAttributeToSelect('*')
                ->addFieldToFilter('status','1')
                ->addAttributeToFilter('brand','120')
                ->count();
echo $collection->getSelect();

A: $collection = $this->productCollectionFactory->create()
                ->addAttributeToSelect('*')
                ->addFieldToFilter('status','1')
                ->addAttributeToFilter('brand','120');
echo $collection->count();

A: This helped me to get the query string
  $collection = $this->productCollectionFactory->create()
                ->addAttributeToSelect('*')
                ->addFieldToFilter('status','1')
                ->addAttributeToFilter('brand','120');
            $collection->getSelect()->__toString();


text:
Q: Zip Archive Progress has Incompatible block pointer types assigned I'm merely trying to run an app in simulator to see if assets and changes to a .json file were implemented correctly, however, when I attempt to run the app it fails and returns:
Incompatible block pointer types assigning to 'ZipArchiveProgressUpdateBlock' (aka 'void (^)(int, int, unsigned long)') from 'void (^)(int, int, int)'
The whole block is below and the issue references the specific line:
zip.progressBlock = ^ (int percentage, int filesProcessed, int numFiles)
ZipArchive* zip = [[ZipArchive alloc] init];
[zip UnzipOpenFile:pathToZipFile];
zip.delegate = self;
zip.progressBlock = ^ (int percentage, int filesProcessed, int numFiles){
[self showProgress:PackageDownloadStateUnzipping progress:(float)percentage/100.0f];
};
BOOL success = [zip UnzipFileTo:unzippedDestination overWrite:YES];

if ( !success ){
    self.state = PackageDownloadStateUnzipError;
}else{
    self.state = PackageDownloadStateUnzipped;
}

A: Read the error. It tells you the problem. The block expects three parameters with type of int, int, and unsigned long. But your block has three int parameters.
Simply change the 3rd parameter's type from int to unsigned long.
zip.progressBlock = ^ (int percentage, int filesProcessed, unsigned long numFiles){
    [self showProgress:PackageDownloadStateUnzipping progress:(float)percentage/100.0f];
};

A: Well, the block you assign takes (int,int,int) but the ZipArchive expects you to pass one that takes (int,int,unsigned long) -- at least, that's what the error message says.
I'm surprised that its getting to running - are you sure it isn't failing at compile time?


text:
Q: Are there compelling reasons not to use Groovy? I'm developing a LoB application in Java after a long absence from the platform (having spent the last 8 years or so entrenched in Fortran, C, a smidgin of C++ and latterly .Net).
Java, the language, is not much changed from how I remember it. I like it's strengths and I can work around its weaknesses - the platform has grown and deciding upon the myriad of different frameworks which appear to do much the same thing as one another is a different story; but that can wait for another day - all-in-all I'm comfortable with Java. However, over the last couple of weeks I've become enamoured with Groovy, and purely from a selfish point of view: but not just because it makes development against the JVM a more succinct and entertaining (and, well, "groovy") proposition than Java (the language).
What strikes me most about Groovy is its inherent maintainability. We all (I hope!) strive to write well documented, easy to understand code. However, sometimes the languages we use themselves defeat us. An example: in 2001 I wrote a library in C to translate EDIFACT EDI messages into ANSI X12 messages. This is not a particularly complicated process, if slightly involved, and I thought at the time I had documented the code properly - and I probably had - but some six years later when I revisited the project (and after becoming acclimatised to C#) I found myself lost in so much C boilerplate (mallocs, pointers, etc. etc.) that it took three days of thoughtful analysis before I finally understood what I'd been doing six years previously.
This evening I've written about 2000 lines of Java (it is the day of rest, after all!). I've documented as best as I know how, but, but, of those 2000 lines of Java a significant proportion is Java boiler plate.
This is where I see Groovy and other dynamic languages winning through - maintainability and later comprehension. Groovy lets you concentrate on your intent without getting bogged down on the platform specific implementation; it's almost, but not quite, self documenting. I see this as being a huge boon to me when I revisit my current project (which I'll port to Groovy asap) in several years time and to my successors who will inherit it and carry on the good work.
So, are there any reasons not to use Groovy?

A: Two reasons why Scala might be a compelling alternative to Groovy:

*

*Performance on par with Java

*Static typing without clutter

A: One of the biggest things you lose when you use dynamic languages, especially in a large codebase is the ability to use an IDE to re-factor.  Languages that allow dynamically adding code to objects simply can't be parsed by today's IDEs to allow the kind of easy refactoring methods you can get from Eclipse, etc. for Java, C++, etc.
It's not really a case of "Dynamic languages are better than Static".  Use what's best for you.  The really cool thing about Groovy in particular is you can mix and match Java and Groovy in the same project, and it all runs on the VM.  Yes, Scala is another example.

A: There are two reasons I can think of not to use Groovy (or Jython, or JRuby):

*

*If you really, truly need performance

*If you will miss static type checking

Those are both big ifs. Performance is probably less of a factor in most apps than people think, and static type checking is a religious issue.  That said, one strength of all of these languages is their ability to mix and match with native Java code. Best of both worlds and all that.
Since I'm not responsible for your business, I say "Go for it".

A: I think the biggest issue is lack of IDE support compared to java, however the plugins for Eclipse and Netbeans are getting better all the time. Also, if I remember correctly Groovy does not support anonymous inner classes if you really need them for some reason. I would personally choose Groovy anytime though.

A: If you use Groovy, you're basically throwing away useful information about types. This leaves your code "groovy": nice and concise.
Bird b

becomes
def b

Plus you get to play with all the meta-class stuff and dynamic method calls which are a torture in Java.
However -- and yes I have tried IntelliJ, Netbeans and Eclipse extensively -- serious automatic refactoring is not possible in Groovy. It's not IntelliJ's fault: the type information just isn't there. Developers will say, "but if you have unit tests for every single code path (hmmmm), then you can refactor more easily." But don't believe the hype: adding more code (unit tests) will add to the safety of massive refactoring, but they don't make the work easier. Now you have to hand fix the original code and the unit tests.
So this means that you don't refactor as often in Groovy, especially when a project is mature. While your code will be concise and easy to read, it will not be as brilliant as code that has been automatically refactored daily, hourly and weekly.
When you realize that a concept represented by a class in Java is no longer necessary, you can just delete it. In Eclipse or Netbeans or whatever, your project hierarchy lights up like a Christmas tree, telling you exactly what you've screwed up with this change. def thing tells the compiler (and therefore your IDE) nothing about how a variable will be used, whether the method exists, etc. And IDEs can only do so much guessing.
In the end, Java code is filled with "boilerplate," but it's been kneaded into its final form after many refactorings. And to me, that's the only way to get high-quality, readable code for future programmers, including when those future programmers are you-in-the-future.


text:
Q: make a single figure composed of several plot I've to make a single figure composed of several plot but I can't do it.
Can anyone help me?
Thank you all

A: I would suggest two methods:
Show[{
  Plot[Cos[2 x], {x, 0, 4 \[Pi]}, PlotStyle -> Blue],
  Plot[Sin[x], {x, 0, 2 \[Pi]}, PlotStyle -> Red]
  }]

or even more simply
Plot[{Sin[x], Cos[x]}, {x, 0, 2 \[Pi]}]

Note that when you use Show, you simply put plots together. The axes are automatically defaulting to the parameters of the first graph you have added. Here I created a plot that has a smaller range than the other to demonstrate the effect. Had you reversed the order in the Show, then you'd crop the second function.
Putting all your functions under the same plot simplifies some of that and automatically colours them for you, but the evaluation parameters for x {x,min,max} is common for all of them.
I hope that helps!


text:
Q: address already in use error in java on udp server I have an application that does many things. I'd like to add a method that enables this application to behave like a udp server on a socket. In particular it listens on the localhost address on port 8888. I tried implementing this behaviour with the following code but i get an Address already in use error. Plus the whole application is stuck on this udp server method. I guess its probably due to the fact that its all running on one thread.
1) Can you please show me how to correct my method. In particular how to make this udp server listener start on a new thread.
2) This server will listen forever for pks from the client. Depending on wether the server receveid a specific packet or not it needs to do certain things. Is the logic correct: if the packetReceived is != null and the packet has not been processed then process it. repeat forever (as show in the code)?
public void startSocketListening(){
        byte[] receiveData = new byte[1024];
        DatagramPacket receivePacket;
        System.out.println("Waiting to receive...");
        while (true) {
            receivePacket = new DatagramPacket(receiveData, receiveData.length);
            try {
                DatagramSocket serverSocket = new DatagramSocket(8888);
                serverSocket.receive(receivePacket);
                //if i receive a packet and it doesn't already have a flow rule process it
                if ((receivePacket != null) && (newOFRuleAdded == false)){
                    this.rlocAddress = new String(receivePacket.getData());
                    System.out.println("RECEIVED: " + rlocAddress);
                    System.out.println("RLOC: " + rlocAddress);
                    //process the message
                    newOFRuleAdded = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

A: For 1.)
First move the socket creation (serverSocket = new DatagramSocket(8888);) out of the loop. That is where your bind failed errors come from.
Best put your whole startSocketListening() code in the run() method of a class extending Thread or implementing Runnable (see code below for threadexample)
For 2.) there might be a misunderstanding.
"serverSocket.receive(receivePacket);" will wait till a packet is received. So whatever comes later on is for the newly received packet that has never been processed.
The while loop just gets you back to waiting for a new packet.
Something like this might do. If you are unsure debug it step by step how it behaves when a packet is received.
public class UdpListener extends Thread
{
    public void run()
    {
        byte[] receiveData = new byte[1024];
        DatagramPacket receivePacket;
        System.out.println("Waiting to receive...");
        DatagramSocket serverSocket;
        try {
            serverSocket = new DatagramSocket(8888);
            while (true) {
                receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                //if i receive a packet and it doesn't already have a flow rule process it
                if ((receivePacket != null) ){
                    System.out.println("First byte of received package is: " + receivePacket.getData()[0]);
                }
            }
        } catch (SocketException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Called like this:
Thread t = new UdpListener();
t.start();


text:
Q: Java Runtime Environment 1.4.2 Installation I´ve got HP Proliant dl380 g3 and I can´t use few things from the "iLO(integrated lights-out)" because this tool needs the Java Runtime Environment 1.4.2 to run in my browser
HP does not support this Old server so I tried to install it by myself:
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase14-419411.html#j2sdk-1.4.2_30-sol-JPR
I downloaded the j2re-1_4_2_19-linux-i586.bin and executed it in the terminal and this is the result:
Do you agree to the above license terms? [yes or no]
yes
Unpacking...
Checksumming...
0
0
Extracting...
./j2re-1_4_2_19-linux-i586.bin: 383: ./j2re-1_4_2_19-linux-i586.bin: ./install.sfx.5638: not found
Done.

Any idea of what should I do?
Thanks for your Time!

A: If you need an elder version of Sun Java (bought by Oracle), you need to download it from http://www.oracle.com/technetwork/java/archive-139210.html, unpack it yourself, and update your $PATH to point to it.  Possibly also your $JAVA_HOME for some tooling.
The oficial Installation Notes for Linux

*

*Make sure that execute permissions are set Run this command:
chmod    +x j2re-1_4_2_-linux-i586.bin

*Run the self-extracting binary.
Execute the downloaded file, prepended by the path to it. For
example, if the file is in the current directory, prepend it with "
./" (necessary if " ." is not in the PATH environment variable):
./j2re-1_4_2_-linux-i586.bin

Note about System Preferences: By default, the installation script
  configures the system such that the backing store for system
  preferences is created inside the Java 2 Runtime Environment's
  installation directory. If the J2RE is installed on a network-mounted
  drive, it and the system preferences can be exported for sharing with
  Java runtime environments on other machines. As an alternative, root
  users can use the -localinstall option when running the installation
  script, as in this example:
j2re-1_4_2_-linux-i586.bin -localinstall This option causes
  the system preferences to be stored in the /etc directory from which
  they can be shared only by VMs running on the local machine. You must
  be root user for the -localinstall option to work.

A: lets try to install Full JDK(Java Development kit) JRE(Java Run-Time Environment) (included) to avoid problems.
type these in terminal if your system is Debian:
the first thing ,we need to add repository
sudo add-apt-repository ppa:webupd8team/java

do an update
sudo apt-get update

and finally installing jdk with jre
sudo apt-get install oracle-java8-installer

to verify that you installed java Successfully (optional)
 java -version

as shown there how to install Java in Linux Deb


text:
Q: How to interpret the "there is some non P" existential graph Here's the image:

I know its interpretation is "Some x is not P", but to me, it seems that the enclosure reads:
There is no x that is P, $\neg \exists x Px$
And then you add an extra line of identity that is defined as being the same as the one inside the enclosure:
There is a y so that there is no x so that x is y and y is P, $ \exists y \neg \exists x(=xy \space \text {&} \space Py)$
I know this reading is either wrong, or at least logically equivalent to $ \exists x \neg P x$, but I can't solve it either way.
Can you give me an explanation of the correct interpretation?

A: The interpretation of lines of identity going inside cuts is indeed not completely straightforward, but here is the correct way to think about this:
Whenever you have such a line, trace it to its most 'outside' context. This can be seen as the 'introduction' of that object: it is when the object's existence is being asserted. When the line goes inside some cut, then that is used to make reference to that object.
In this case, the most outside context is the very outside canvas; the Sheet of Assertion. So, the fact that there is a line a this level means that we immediately assert the existence of this object. However, the line then goes inside a cut amd is attached to a $P$. As such, we are denying that the object, whose existence was being asserted earlier, has property $P$.
In sum, there is an object, but that object does not have property $P$. In classicL notation: $\exists x \ \neg P(x)$
Another way of looking at this is as follows.... and I think this will be a little closer to what you were trying to do.  OK, so we have a cut with a line inside, and so we could read this as the negation of the existence of some object, i.e. as $\neg \exists y$
But wait!  There is more going on inside the cut: the line is attached to a $P$, and so what we have inside the cut is not just the existence of some object, but the existence of some object with property $P$, and it is all that that the cut is negating, i.e. we have $\neg \exists y \ P(y)$
This is an important point: a cut is the negation of whatever is represented inside the cut. So, a cut is not negating each of the invidual pieces that are inside the cut, but rather it is negating the whole of what os inside the cut.
Thus, for example, a cut with both a $P$ and a $Q$ inside is the negation of the juxtaposition, and thus conjunction, of $P$ and $Q$. That is, we have $\neg (P \land Q)$, rather than $\neg P \land \neg Q$
Likewise, the fact that we had more going on than just an object inside the cut (i.e. that we are negating something 'more' than just the existence of some object) does not mean that we are negating something in addition to the negation of some object, but rather that what is being negated is a claim that says something more than just the existence of some object.
As such, we thus have $\neg \exists y \ P(y)$, rather than something like $\neg \exists y \land \neg \exists z \ P(z)$
But wait!  It's not $\neg \exists y \ P(y)$ either, because there is still more going on: The inside line is attached to an outside line. Thus, we also have an identity statement as part of what is inside the cut: the $y$ is equal to some $x$ ... whose existence is asserted outside ... and this 'earlier' (or, if you want: the 'inside' object $y$ occurs within the 'scope' of the 'outside' object $x$. Thus, we have: $\exists x (\neg \exists y (P(y) \land y=x))$
And this is exactly what you got as well! Good job!
But this last statement, you'll find, is equivalent to just $\exists x \ \neg P(x)$
Why is it equivalent? Well, unfortunately the standard equivalence principles for first-order logic are not strong enough to show this equivalence. However, using some standard inference rules, it's not hard to show this equivalence with a formal derivation.


text:
Q: rails whenever delete records sql I tried to a records cleanup after certain period of time (6 month) using gem 'whenever'.
In my whenever scheduler :
every 1.month, at: '1am' do
  rake 'lib/tasks/cleanup_user.rake'
end

In the lib/tasks/cleanup_user.rake
@user = User.all.where(:created_at > 'Time.6.month.ago').delete

It seems about right. However, I got error 'uninitialized constant User'. I am relatively new in rails. Please assist me.
EDIT : I changed the game by run clean one line command :
set :output, "log/cron.log"
    every 1.minutes, :environment => :development do
      command 'User.where("confirmed = 0 AND created_at <= ?", 6.months.ago).delete'
    end

I set the specific environment,and run this in command :
whenever --set environment=development --update-crontab userscleaning

Checking at crontab, its there but still not work. Any thought?

A: Try adding the environment dependency to your task.
task :cleanup_users => :environment do
  User.where(:created_at > 'Time.6.month.ago').delete_all
end

If you want the callbacks to trigger, use destroy_all
task :cleanup_users => :environment do
  User.where(:created_at > 'Time.6.month.ago').destroy_all
end

Here is a relevant Railscasts.

A: According to the answers here:
# lib/tasks/delete_old_records.rake
namespace :delete do
  desc 'Delete records older than 6 months'
  task old_records: :environment do
    User.where('created_at > ?', 6.month.ago).destroy_all
  end
end

Run with:
RAILS_ENV=production rake delete:old_records

In whenever:
every 1.minutes do
  rake "delete:old_records"
end

Or in cron:
0 8 * * * /bin/bash -l -c 'cd /my/project/releases/current && RAILS_ENV=production rake delete:old_records 2>&1'


text:
Q: Get value of array in javascript I have this list of node :

10,  16 ,  21,  26,  fils_de_10,  fils_de_16,  fils_de_21 are on the same level and files_de_10 is supposed to be the child of 10 in term of the structure of my project.
I want to create a function checkChild(node,id) , so example when i call checkChild(_obj,10), It will return 15,14,13,11,12 that are the child and sub child of 10.
I have been trying to come up with a recursive function but it becomes messy.
It would be good if anyone already has some similar function.
Edited : This is the json data of the node :
var _str = '{"10":{"0":"0","1":"DISPONIBILITES","2":"t","style":"font-weight: bold;"},"16":{"0":"0","1":"TRESORERIE NETTE","2":"t","style":"font-weight: bold;"},"21":{"0":"0","1":"COMPTES","2":"t","style":"font-weight: bold;"},"26":{"0":"0","1":"LIGNE DE CREDIT BNP/HSBC","2":"f","style":"color:black;"},"fils_de_21":{"22":{"0":"21","1":"EXASOLAR SA","2":"f","style":"color:black;"},"23":{"0":"21","1":"EXASOLAR CORP","2":"f","style":"color:black;"},"24":{"0":"21","1":"EXASOLAR SARL","2":"f","style":"color:black;"},"25":{"0":"21","1":"EXASOLAR SL","2":"f","style":"color:black;"}},"fils_de_10":{"13":{"0":"10","1":"Disponibilits France","2":"t","style":"font-weight: bold;"},"14":{"0":"10","1":"Dispo exasolar SL","2":"f","style":"color:black;"},"15":{"0":"10","1":"Dispo exasolar corp","2":"f","style":"color:black;"},"fils_de_13":{"11":{"0":"13","1":"Dispo exasolar SA","2":"f","style":"color:black;"},"12":{"0":"13","1":"Dispo exasolar sarl","2":"f","style":"color:black;"}}},"fils_de_16":{"17":{"0":"16","1":"Trso nette exasolar SA","2":"f","style":"color:black;"},"18":{"0":"16","1":"Trso nette exasolar SL","2":"f","style":"color:black;"},"19":{"0":"16","1":"Trso nette exasolar corp.","2":"f","style":"color:black;"},"20":{"0":"16","1":"Trso nette exasolar sarl","2":"f","style":"color:black;"}}}';

A: Not sure if what you want is something like this.
What I've done is to check inside the function is the current item key is something starting with fils_de_, if it is, then we call the function recursively. If not, we simply add the value to our list array.
Take a look and let me know if that works for you.
Cheers!

var my_data = {
  10: {
    0: "0",
    1: "blabla",
    2: "t"
  },
  fils_de_10: {
    13: {
      0: "10",
      1: "blabla 10_13",
      2: "t"
    },
    14: {
      0: "10",
      1: "blabla 10_14",
      2: "t"
    },
    15: {
      0: "10",
      1: "blabla 10_15",
      2: "t"
    },
    fils_de_13: {
      11: {
        0: "10",
        1: "blabla 10_11",
        2: "t"
      },
      12: {
        0: "10",
        1: "blabla 10_12",
        2: "t"
      }
    }
  }
};

function checkChild(node,id) {
  var list = [];

  if(node['fils_de_'+id])
    for (var item in node['fils_de_'+id])
      if(item.match(/fils\_de\_(\d+)/))
        list.push(...checkChild(node['fils_de_'+id], item.split('_')[2]));
      else
        list.push(item);
  else
    for (var item in node)
     if(item.match(/fils\_de\_(\d+)/))
       list.push(...checkChild(node[item], id));

  return list;
}

console.log(checkChild(my_data, 10));
console.log(checkChild(my_data, 13));

A: If i get it right, what you need is a simple Breadth-first tree traversing. Check out the well known algorithm - it should work.
In steps you should:

*

*Build the name of the node you want to examine ("fils_de_10" in you example).

*Traverse the tree until you find this node.

*Traverse a subtree of this node and store all leaves as your result.

Hope it works.


text:
Q: Custom route in Zend Framework I'm working on a Zend Framework API and need to follow a particular format for URLs, so I was hoping for some help regarding how to configure the routing correctly.
http://example.com/module/controller/method/actionNameHere
The above URL would need to route to the function actionNameHereAction.
Any help is appreciated.

A: The beauty of routing is that it gives you the tools for hiding exactly those pieces of information you are putting into your URL.
Apart from that, as far as I know ZF routes by default so that your URL would end up in ...

*

*the action with name method of

*the controller with name controller of

*the module with name module

So either your example-URL is complicating things or you are almost there.
B/c actionNameHere would be a paramter you could handle in your action with name "methodAction".
But I think you want your URL to look like:
example.com/module/controller/actionNameHere

A: In order to produce the URLs needed, I ended up creating a custom Dispatcher, as it wasn't in the routing that URLs were being converted from actionNameHere to actionnamehereAction, but in the dispatcher. I extended the standard dispatcher and overrode this behaviour so that the action name in the URL remained case-sensitive.


text:
Q: MS Teams Localization for developer websiteUrl and privacyUrl I'm trying to find a way to localize developer privacyUrl and websiteUrl. Teams docs seems to not provide informations about that.
I'm using the following json for my localization file but Teams tell me that it is incorrect:
{
  "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.8/MicrosoftTeams.Localization.schema.json",
  "name.short": "My App Test",
  "developer.websiteUrl": "http://myapptest.com",
  "developer.privacyUrl": "http://myapptest.com",
}

A: Well that's because website/privacy URLs are not localizable as of now.

A: The schema doesn't support localized versions of these, but you can do whatever you want on those pages - they are just web pages. They could do locale detection and show localized content, just like any other webpage on the internet.


text:
Q: After upgrading to 17.10 it takes 1 minute to start sometimes more than 1 minute. 1-After upgrading the system totally became slow. It takes more time to load files even to open files it takes 10 to 20 seconds. How can I solve this issue?
2- When I start it shows your PC at risk.


text:
Q: Change bean property/value during runtime in spring I am using spring mvc+hibernate+two databases
So for example:
I create 2 sessionFactories. sessionFactory1 (using datasource1) and sessionFactory2 (using datasource2).
Would it be possible to change sessionFactory1 or sessionFactory2 to sessionFactory at runtime so that the dao/s references them. sessionFactory is already autowired to all dao/s.
I am searching for it right now I think @Configuration can help me but I am not sure.
I am trying AbstractRoutingDataSource but don't think it helps.

A: Usually Spring wires your beans on application startup, so "re-wiring" (replacing references to sessionFactory1 with references to sessionFactory2 on runtime) does not seem easy to implement.
Maybe you could implement a "proxy bean" that is wired to your DAO objects and change the "target SessionFactory" of your proxy bean.

A: AbstractRoutingDataSource will work for you.
First you'll need to create a class that will store the current DB in use:
public class MyContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public static void setDBContext(String dBContext) {
        contextHolder.set(dBContext);
    }

    public static String getDBContext() {
        return (String) contextHolder.get();
    }

    public static void clearDBContext() {
        contextHolder.remove();
    }

}

You'll need to create a class that extends this one and implements determineCurrentLookupKey(), and return the current db you have in your context holder:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class MyRoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return MyContextHolder.getDBContext();
    }
}

See the example in http://blog.springsource.org/2007/01/23/dynamic-datasource-routing/.
It worked fine for me.


text:
Q: Magento 2 custom mail template I have created custom mail template and successfully send mail to the customer upon order complete.
I created new mail template from admin based on the custom one I added in code, to let the marketing team edit the mail and change style.
Now I need to get marketing team changes using the new template name but it gives error this mail template not found when I do

$transport = $transportBuilder->setTemplateIdentifier('custom_email_template');
Error: Email template 'custom_email_template' is not defined

Can I use the ID instead and how to set fall back if the template was deleted to send the template base file in my custom module?
Another query how to get the mail template preview in code as html string?
Thanks in advance.

A: I have did some research in how the backend preview templates and I wrote helper for that purpose to be used in my custom module.
I used the id for that template not the identifier and I cannot set variables before rendering.
see code below:
namespace namespace\Module\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;

class Emailpreview extends \Magento\Framework\App\Helper\AbstractHelper {

public $store;

public function __construct(Context $context, StoreManagerInterface $store){
parent::__construct($context);
$this->store = $store;
}

public function previewSerialsMailTemplate($id = '26'){
    $storeId = $this->store->getStore()->getId();
    /** @var $template \Magento\Email\Model\Template */
    $om = \Magento\Framework\App\ObjectManager::getInstance();

    $emailFactory = $om->create('\Magento\Email\Model\TemplateFactory');
    $template = $emailFactory->create();//get_class_methods
    $template->load($id);

$postObject = new \Magento\Framework\DataObject();
$postObject->setData(['message' => 'message', 'subject' => 'subject', 'customername' => 'mgomma']);

    $template->setVars(['data' => $postObject]);
    $maliciousCode = $om->create('\Magento\Framework\Filter\Input\MaliciousCode');

    $template->setTemplateText($maliciousCode->filter($template->getTemplateText()));
    $profilerName = 'email_template_proccessing';

    \Magento\Framework\Profiler::start($profilerName);
    $template->emulateDesign($storeId);

    $appState = $om->create('\Magento\Framework\App\State');
    $templateProcessed = $appState->emulateAreaCode(
        \Magento\Email\Model\AbstractTemplate::DEFAULT_DESIGN_AREA,
        [$template, 'getProcessedTemplate']
    );

    $template->revertDesign();
    if ($template->isPlain()) {
        $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>";
    }

    \Magento\Framework\Profiler::stop($profilerName);
    return $templateProcessed;
}
}


text:
Q: Sort matrix with variable number of columns in R i would like to sort matrix MM based on column "summ" in ascending order, then descending order for column 1 til column before "summ". Thus if n = 4, then i need sort MM based on column "summ" in ascending order, then descending order for column 1 til 4. My code is:
n <- 4
M <- matrix(NA_integer_, nrow=2^n-1, ncol=n)
M <- as.matrix(M)
for (i in 1:(2^n-1))
   M[i, ] <- as.integer(intToBits(i)[1:n])
MM <- data.frame(M[-1,])
MM <- cbind(M,apply(M, 1, sum))
dimnames(MM)[[2]] <- c(paste("item",1:n,sep=""), "summ")

my result would like to be following code while i want general solution for n.
MMM <- MM[order(MM[,n+1],-MM[,1],-MM[,2],-MM[,3],-MM[,4]),]
      item1 item2 item3 item4 summ
 [1,]     1     0     0     0    1
 [2,]     0     1     0     0    1
 [3,]     0     0     1     0    1
 [4,]     0     0     0     1    1
 [5,]     1     1     0     0    2
 [6,]     1     0     1     0    2
 [7,]     1     0     0     1    2
 [8,]     0     1     1     0    2
 [9,]     0     1     0     1    2
[10,]     0     0     1     1    2
[11,]     1     1     1     0    3
[12,]     1     1     0     1    3
[13,]     1     0     1     1    3
[14,]     0     1     1     1    3
[15,]     1     1     1     1    4

Thanks for your help!

A: You can try to use a custom function along the lines of the following:
CustomOrder <- function(inTable) {
  n <- ncol(inTable)
  Order <- do.call(order, c(data.frame(inTable[, n], inTable[, 1:(n-1)] * -1)))
  inTable[Order, ]
}

I would suggest adding some error checking in there, though, and testing it on more than just the sample you've provided here.
Usage would be:
CustomOrder(MM)
#       item1 item2 item3 item4 summ
#  [1,]     1     0     0     0    1
#  [2,]     0     1     0     0    1
#  [3,]     0     0     1     0    1
#  [4,]     0     0     0     1    1
#  [5,]     1     1     0     0    2
#  [6,]     1     0     1     0    2
#  [7,]     1     0     0     1    2
#  [8,]     0     1     1     0    2
#  [9,]     0     1     0     1    2
# [10,]     0     0     1     1    2
# [11,]     1     1     1     0    3
# [12,]     1     1     0     1    3
# [13,]     1     0     1     1    3
# [14,]     0     1     1     1    3
# [15,]     1     1     1     1    4


text:
Q: json() on "requests" response raises UnicodeEncodeError I'm querying Github's Jobs API with python3, using the requests library, but running into an error parsing the response.
Library: http://docs.python-requests.org/en/latest/
Code:
import requests
import json

url = 'https://jobs.github.com/positions.json?'

response = requests.get(url)

print(response.json())

Error:

UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in
  position 321: ordinal not in range(128)

Using this API in the past with Ruby, I've never run into this issue.
I also tried converting it to a dictionary but it resulted in the same errors.
There's other questions on SO about the UnicodeEncodeError (mostly re: opening files), but I'm not familiar with Python and didn't find them helpful.

A: First, check that the response is actually JSON. Try printing response.text and see if it looks like a valid JSON object.
Assuming it is JSON: it's very "hack"-ey, but you can replace the non ASCII characters with their escaped Unicode representation:
def escape_unicode(c):
    return c.encode('ascii', 'backslashreplace').decode('ascii')

response = ...

text = response.text
escaped = re.sub(r'[^\x00-\x7F]', lambda m: escape_unicode(m.group(0)), text)
json_response = json.loads(escaped)


text:
Q: Retrieving common column data from two tables in a single column with out duplicates in MYSQL Below are the 2 tables from which i want to retrieve common column ie "location" from two tables in to a single column with out duplicates... I am using this query..
SELECT datan1.location,
       temp.location
FROM datan1
LEFT OUTER JOIN TEMP ON datan1.location=temp.location
UNION
SELECT datan1.location,
       temp.location
FROM datan1
RIGHT OUTER JOIN TEMP ON datan1.location=temp.location;

but i am not getting what i expected... any help is highly appreciated
Expected Output
Location
 1.Mysore
  2.Hyderabad 3. Chennai
Hyderabad should not come as it is repeated

A: if you want common locations between the two tables  you should use  inner  join
select location
from datan1
inner join temp on temp.location = datan1.location

if you want all the location in both the table  you could use a simply union  avoinding left and right join
select location
from datan1
union
select location
from temp


text:
Q: Select2 cannot Chained Dropdown? My code seems to work without select2 but I want to apply select2 in it, but code don't work. this is my full code:

And also the code for chained select that I want to apply with:

    Pet Type

        <select name="type"  class="input-sm form-control country" style="width: 100%;">
            <option selected="selected">--Select--</option>
            <?php
                    include('connect.php');
                    $sql=mysql_query("select * from pet_type");
                    while($row=mysql_fetch_array($sql)) {
                        $id=$row['pet_type_id'];
                        $data=$row['pet_type_name'];
                        echo '<option value="'.$id.'">'.$data.'</option>';
                    } ?>
        </select>

    Service

        <select name="service_id" class="input-sm city form-control"  style="width: 100%;>
                    <option selected="selected">
            --Select--
            </option>
        </select>

    Branch

        <select name="branch_id" class="input-sm br form-control"  style="width: 100%;>
                    <option selected="selected">
            --Select--
            </option>
        </select>

When I put Select2 on the class:nothing happens, I think the problem is on the change function, because when I don't select2 on 1st dropdown it can pass on 2nd dropdown with select2, but then I cannot pass on the 3rd dropdown, how should I code it?

A: A couple things might help. One in particular which is you have a syntax error in your .city and .br <select> lines. The style has no close quote, which likely invalidates those selection dropdowns. If this doesn't work with just .change(), try the $("#whatever").on("change", etc....) method:

    Pet Type

        <select id="country_id" name="type" class="input-sm form-control country" style="width: 100%;">
            <option selected="selected">--Select--</option>
            <?php
                    include('connect.php');
                    $sql=mysql_query("select * from pet_type");
                    while($row=mysql_fetch_array($sql)) {
                        $id=$row['pet_type_id'];
                        $data=$row['pet_type_name'];
                        echo '<option value="'.$id.'">'.$data.'</option>';
                    }
            ?>
        </select>

    Service

        <select id="service_id" name="service_id" class="input-sm city form-control"  style="width: 100%;">
                    <option selected="selected">
            --Select--
            </option>
        </select>

    Branch

        <select id="branch_id" name="branch_id" class="input-sm br form-control"  style="width: 100%;">
                    <option selected="selected">
            --Select--
            </option>
        </select>

On a side note, don't use mysql_ anymore but rather mysqli_ or PDO. The mysql_ library is deprecated and removed entirely from the latest versions of PHP.


text:
Q: Saving state from child component by pressing a button in parent component? I've been working on a project that requires me to set a number from a child component, and then grab said number by pressing a button that is located in the parent component.
to make this even more difficult for myself, the child component is repeated multiple times, and the button on the parent component needs to grab the value of the state from each of the child components.
How can i go about doing this? I've coded up a quick example that shows my problem in a simple and basic way, i am really lost.
Example code on codesandbox
for the example code, i am trying to grab the random generated number from Random.jsx, and save it to the state of ranNum1, and ranNum2 located in the parent component Example.jsx, the parent component has the button that needs to grab the data.
Parent Component
import React, { Component } from "react";
import Helmet from "react-helmet";
import Random from "./Random";
class Example extends Component {
  constructor(props) {
    super(props);
    this.state = { ranNum1: 0, ranNum2: 0 };
  }
  render() {
    return (
      <React.Fragment>
        <Helmet>
          <title>{this.state.title}</title>
        </Helmet>

              Grab Random Number

                Click the button to grab the 2 random generated number from the
                child components

              Catch is the button is located in the parent component

{" "}

            <Random stage="first" uid="num1" />
            <Random stage="second" uid="num2" />

              <button
                className="btn"
                id="save-num-button"
                onClick={this.handleGrabNums}
              >
                Grab both random numbers
              </button>

      </React.Fragment>
    );
  }
}

export default Example;

child component
import React, { Component } from "react";

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = { randomNumber: 0 };
  }
  render() {
    return (
      <React.Fragment>
        <button onClick={this.generateNumber}>
          Generate {this.props.stage} random number
        </button>
      </React.Fragment>
    );
  }

  generateNumber = () => {
    const generatedNumber = Math.floor(Math.random() * 1000);
    this.setState({ randomNumber: generatedNumber });
    alert(this.state.randomNumber);
  };
}

export default Example;

A: What you need to do is pass a function from the parent into the child as a prop. Then in the child you call the prop function.
What I have also done is a small edit to the Random Component prop where the uid now matches the name in state. So when the handleChange function gets called from the child, you pass in the number and the uid so you can easily change the state in the parent.

// Parent Component
class Example extends Component {
  constructor(props) {
    super(props);
    this.state = { ranNum1: 0, ranNum2: 0 };

    this.handleChange = (num, uid) => {
      this.state[uid] = num;
    };

    this.handleGrabNums = () => {
      console.log(this.state);
    };
  }

  render() {
    return (
      <React.Fragment>
        <Helmet>
          <title>{this.state.title}</title>
        </Helmet>

              Grab Random Number

                Click the button to grab the 2 random generated number from the
                child components

              Catch is the button is located in the parent component

{" "}

            <Random
              stage="first"
              uid="ranNum1"
              handleChange={this.handleChange}
            />
            <Random
              stage="second"
              uid="ranNum2"
              handleChange={this.handleChange}
            />

              <button
                className="btn"
                id="save-num-button"
                onClick={this.handleGrabNums}
              >
                Grab both random numbers
              </button>

      </React.Fragment>
    );
  }
}

// Child Component
class Example extends Component {
  constructor(props) {
    super(props);
    this.state = { randomNumber: 0 };
  }
  render() {
    return (
      <React.Fragment>
        <button onClick={this.generateNumber}>
          Generate {this.props.stage} random number
        </button>
      </React.Fragment>
    );
  }

  generateNumber = () => {
    const generatedNumber = Math.floor(Math.random() * 1000);
    this.setState({ randomNumber: generatedNumber });
    this.props.handleChange(generatedNumber, this.props.uid);
  };
}


text:
Q: PHP - Remove Shortcodes and Content in between with Regex Pattern I have the following string:
$text = My example text [shortcode_name]content of shortcode[/shortcode_name] is cool.

And the following pattern:
$pattern= '/\[(\/?shortcode_name.*?(?=\]))\]/';

It gives me the following result:
preg_replace($pattern,'',$text);
My example text content of shortcode is cool.

This works like a charm to remove the shortcode.
What I'm looking for is to remove the shortcode and all content in between.
The result that I'm looking for is:
My example text is cool.

A: Here you go:
$pattern= '/\[(shortcode_name)\].*?\[\/\1\] ?/';

Explanation:

*

*match [

*followed by "shortcode_name" (captured within (...) for reuse in a later step, see below)

*followed by ]

*followed by anything, non-greedily (important!)

*followed by [/

*followed by what was matched in (...) earlier, in this example "shortcode_name"

*followed by ]

*followed by 1 or zero space

A: This could maybe work as your regex:
/\[(\w+)\].*\[\/(\1)\]/

you find the first square bracket tag of any name, and grep the content in between, and then use lookback to find the closing square bracket. I only tested it with javascript, but it should work. Then you should use another regex to replace multiple whitespace for one whitespace :)

A: You just accepted another answer while I was working on my solution, no problem :) but I still want to post my answer, as it can be more flexible if you have multiple shortcodes:
<?php

$shortCodes = array("shortcode_name", "shortcode_name2", "shortcode_name3");

$text = <<< EOF
My example text [shortcode_name]content of shortcode[/shortcode_name] is cool.
another example text [shortcode_name2]content of shortcode[/shortcode_name2] is cool.
Yet another example  [shortcode_name3]content of shortcode[/shortcode_name3] is cool.
EOF;

foreach($shortCodes as $shortCode){
   $text = preg_replace("%\[$shortCode\].*?\[/$shortCode\]%i", '', $text);
   $text = preg_replace('/\s{2,}/i', ' ', $text); //remove 2 or more spaces

}

echo $text;

OUTPUT:
My example text is cool.
another example text is cool.
Yet another example is cool.

Demo:
http://ideone.com/VhL5vm

A: Try my version it will take care the newline as well.
$text = "My example text [shortcode_name]content of shortcode[/shortcode_name] is cool.";
$text = "My example text [shortcode_name]content of
shortcode[/shortcode_name] is cool.";

$pattern= '/\[(shortcode_name)\](.|\s)*?\[\/\1\]/';
echo preg_replace($pattern,'' ,$text);

Output
My example text is cool.


text:
Q: input search no iphone Estou com a seguinte marcação:
    <form class="area-search" action="">
      <input name="search" type="search" placeholder="O QUE ESTA PROCURANDO?">
      <button>Buscar</button>
    </form>

No iphone/ipad está arredondando os cantos da input de busca. Tentei resetar usando border-radius: 0 !important; mas sem resultados.

A: Para remover os estilos do input no Chrome e Safari do iPhone basta usar:
input {
-webkit-appearance: none;
}

Para versões anteriores do iOS use:
input {
-webkit-appearance: none;
border-radius: 0;
}


text:
Q: $\mathbb{E}[x|x>y]$ where both $x$ and $y$ are standard normally distributed variables. I am interested in finding $\mathbb{E}[x|x>y]$ given that $x \sim \mathcal{N}(0,1)$ and $y\sim \mathcal{N}(0,1)$. Furthermore I know that these variables are not correlated with each other. I know the result is $\frac{1}{\sqrt{\pi}}$ but I am not sure how to get there. What I have done so far is the following:
$\int_{-\infty}^{\infty}\frac{1}{1-F_{x}(y)}\int_{y}^{\infty}x f_x(x)dx f_y(y)dy$ however somehow this result does not give me $\frac{1}{\sqrt{\pi}}$, please help :).

A: Hint: Note that $\mathbb{E}[x | x > y] = \mathbb{E}[\max\{x,y\}]$.  Try to take it from here, if you can.  If you want to see the rest, hover below:

 Let $\phi$ be the p.d.f. of a standard normal and $\Phi$ be the c.d.f. Then the c.d.f. of $\max\{x,y\}$ is $\Phi(x)^2$, implying the p.d.f. is its derivative, $2\phi(x)\Phi(x)$.  This implies that the mean is 2\begin{align}\int_{-\infty}^\infty x\phi(x) \Phi(x) \,dx = 2\int_{-\infty}^\infty \phi(x)^2 \,dx \end{align} by integration by parts (with $u = \Phi(x)$ and $dv = x\phi(x) \,dx$).  Recalling $\phi(x) = \frac{1}{\sqrt{2\pi}}e^{-x^2 / 2}$ and integrating gives the answer.

Edit:  A solution adapting your work so far:
Note that $$\mathbb{E}[x | x > y] = \frac{\mathbb{E}[x \cdot \mathbf{1}_{x > y}]}{\mathbb{P}[x > y]}$$ where $\mathbb{1}_{x > y}$ is in the indicator random variable for the event $x > y$.  By symmetry, the denominator is $1/2$, so we have \begin{align}\mathbb{E}[x | x> y] = 2 \mathbb{E}[x \cdot \mathbf{1}_{x > y}] &= 2 \int_{-\infty}^\infty \int_{y}^\infty x \phi(x) \phi(y) dx dy \\&= 2 \int_{-\infty}^\infty x\phi(x)\int_{-\infty}^x \phi(y) dy dx \\
&= 2 \int_{-\infty}^\infty x\phi(x) \Phi(x) dx.\end{align}
Basically the $1/(1 - F_x(y))$ shouldn't be there; it should be one over a probability outside of the integrals entirely.


text:
Q: Getting JSON Data on Table on JSTL Page So I am using the amiibo api to pull data, and display what is returned in a table. For now, I'm just putting the series in the table to make sure it works, but it doesn't!
Here is my table:

                    #
                    Amiibo

            <c:forEach var="amiibo" items="${amiibos}" varStatus="status">

                    ${status.count}
                    ${amiibo.amiiboSeries}

            </c:forEach>

And here is my servlet that pulls that the api data and puts it into a list:
String json = callAmiiboApi(input.getAmiibo());

        // Check for valid json format.  If false, String contains an error message.
        if (json.startsWith("{") || json.startsWith("[")) {
            Gson gson = new Gson();
            ArrayList<Amiibo> amiibos = gson.fromJson(json, new TypeToken<ArrayList<Amiibo>>(){}.getType());

            //get list of elements
            if (!amiibos.isEmpty() && amiibos.size() > 0) {
                request.setAttribute("amiibos", amiibos);
            }
        }

Here is my object:
public class Amiibo implements Serializable
{
    public String amiiboSeries;
    public String character;
    public String gameSeries;
    public String head;
    public String image;
    public String name;
    public String[] release;
    public String tail;
    public String type;

    public Amiibo()
    {
        amiiboSeries = "";
        character = "";
        gameSeries = "";
        head = "";
        image = "";
        name = "";
        release = new String[0];
        tail = "";
        type = "";
    }

    public String getAmiiboSeries()
    {
        return amiiboSeries;
    }

This is the error I get:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Does anyone know what I am doing wrong in pulling this data? I think the api is accessed fine, I believe my issue is in how I am displaying it (potentially when I put it into a list?).
-- edit --
This is my input class to get the user input
import java.io.Serializable;

public class Input implements Serializable {
    private String amiibo;

    public Input() {
        this("");
    }

    public Input(String amiibo) {
        this.amiibo = amiibo;
    }

    public String getAmiibo() {
        return amiibo;
    }

    public void setAmiibo(String amiibo) {
        this.amiibo = amiibo;
    }
}

A: Crete wrapper object:
class AmiiboResponse {

    private List<Amiibo> amiibo;

    public List<Amiibo> getAmiibo() {
        return amiibo;
    }

    public void setAmiibo(List<Amiibo> amiibo) {
        this.amiibo = amiibo;
    }
}

and deserialise in this way:
List<Amiibo> amiibos = gson.fromJson(json, AmiiboResponse.class).getAmiibo();


text:
Q: Creating a matrix from table in c# With .Net MVC i am using DB First approach. I need a School Day Program, but I am not sure to use pivoting, DataTable or anything else?
The table in SQL is like that:
WeeklyProgram
Id RoomId Hour Day
1  1      9    1
2  1      12   1
3  2      14   1
4  2      12   2
5  3      11   1
6  4      10   2

And trying to convert it to a table in html with null cells like this:
For Day 1 My School Program is;
#     Room1 Room2 Room3
9:00  1     null  null
10:00 null  null  null
11:00 null  null  5
12:00 2     null  null
13:00 null  null  null
14:00 null  3     null

Tried pivoting but cant get what i thought.
Thanks all.
UPDATE: I'VE FOUND AN ANSWER
if (!date.HasValue)
            date = DateTime.Now;

        List<WeeklyProgram> modelBase = table
            .Where(b => b.Day == day)
            .ToList();

        int[] hours = { 9, 10, 11, 12, 13, 14};

        List<PivotTable> pivotTable = new List<PivotTable>();

        foreach (var hour in hours)
        {
            PivotTable pivotRow = new PivotTable() { Hour = hour };

            foreach (var item in modelBase)
                if (item.Hour == hour)
                    switch (item.RoomId)
                    {
                        case 1:
                            pivotRow.Room1 = item.Id;
                            break;
                        case 2:
                            pivotRow.Room2 = item.Id;
                            break;
                        case 3:
                            pivotRow.Room3 = item.Id;
                            break;
                    }
            pivotTable.Add(pivotRow);
        }

        return pivotTable;

--
    public class PivotTable
{
    public int Hour { get; set; }
    public int Room1 { get; set; }
    public int Room2 { get; set; }
    public int Room3 { get; set; }
    public int Room4 { get; set; }
    public int Room5 { get; set; }
}

A: First, you need to filter your WeeklyProgram down to the day of interest:
var dayProgram = from c in WeeklyProgram
                 where c.Day == 1
                 select c;

Then you can extract the hourly schedule rows from that data, leaving nulls for unscheduled rooms by converting Id into a nullable type, which is then converted to a Dictionary for lookup later:
var dayClasses = (from c in dayProgram
                  group c by c.Hour into cg
                  let cgd = cg.ToDictionary(c => c.RoomId, c => (int?)c.Id)
                  select new {
                      Hour = cg.Key,
                      Room1 = cgd.GetValueOrDefault(1),
                      Room2 = cgd.GetValueOrDefault(2),
                      Room3 = cgd.GetValueOrDefault(3)
                  }).ToDictionary(c => c.Hour, c => c);

Now you extract all the hours that are used during the WeeklyProgram:
var hoursInWeek = (from c in WeeklyProgram
                   orderby c.Hour
                   select c.Hour).Distinct();

Now you are ready to combine the hours used with the rooms scheduled:
var ans = from h in hoursInWeek
          select new {
              Hour = $"{h}:00",
              Room1 = dayClasses.GetValueOrDefault(h)?.Room1,
              Room2 = dayClasses.GetValueOrDefault(h)?.Room2,
              Room3 = dayClasses.GetValueOrDefault(h)?.Room3
          };

This uses a helper function to make looking up in dictionaries where the key might not exist easier (NOTE: This uses all features up to C# 7.1.)
static public class Ext {
    public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
}

For earlier versions of C#, you can use this version:
static public class Ext {
    public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default(TV)) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
}


text:
Q: What is this Gradle build Error after installing Fabric Crashlytics in my android firebase app? I tried to manually add Fabric Crashlytics and then tried to use the plugin but got the same error when I try to build:
Error:Execution failed for task ':app:processReleaseManifest'.
> Manifest merger failed : Attribute meta-data#io.fabric.ApiKey@value value=( my api key ) from AndroidManifest.xml:39:13-69
    is also present at [com.firebaseui:firebase-ui-auth:1.2.0] AndroidManifest.xml:20:13-60 value=(@string/twitter_consumer_secret).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:37:9-39:72 to override.

I added the line suggested (even though I don't really understand it or know if it will cause a conflict of some sort with firebase-ui-auth )
tools:replace="android:value"

and now I can build and run the app but when I force a crash like so:
throw new RuntimeException("This is a crash");

I get  crash reports though it took awhile for them to appear.
My gradle file looks like so:
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

// Create a variable called keystorePropertiesFile, and initialize it to your
// keystore.properties file, in the rootProject folder.
def keystorePropertiesFile = rootProject.file("keystore.properties")

// Initialize a new Properties() object called keystoreProperties.
def keystoreProperties = new Properties()

// Load your keystore.properties file into the keystoreProperties object.
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

android {
    signingConfigs {
        config {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }
    compileSdkVersion 25
    buildToolsVersion '25.0.3'
    defaultConfig {
        applicationId "aaa.bbb.ccc"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        signingConfig signingConfigs.config

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.config
        }
        debug {
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:design:25.1.1'
    compile 'com.android.support:support-v4:25.1.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.google.android.gms:play-services-auth:10.2.4'
    compile 'com.firebaseui:firebase-ui:1.2.0'
    compile 'com.firebaseui:firebase-ui-auth:1.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.4'
    compile 'com.google.firebase:firebase-core:10.2.4'
    compile 'com.google.firebase:firebase-database:10.2.4'
    compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    testCompile 'junit:junit:4.12'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true;
    }
}

apply plugin: 'com.google.gms.google-services'

and  in my manifest I have the internet permission which was working already and now:
<meta-data
        tools:replace="android:value"
        android:name="io.fabric.ApiKey"
        android:value=" my key " />

My Android Studio is version 2.3.2
So, is the manifest fix going to cause a problem down the road - is the initial build error still an issue?  Is there something I might be missing to avoid the initial build error?
Thanks
PS the full manifest file is:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="aaa.bbb.ccc"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-sdk tools:overrideLibrary="com.firebase.ui, com.firebase.ui.auth"/>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainNavDrawerActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="stateHidden|adjustResize">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            tools:replace="android:value"
            android:name="io.fabric.ApiKey"
            android:value=" my key " />
    </application>

</manifest>

A: I had the same issue,
Delete this from your manifest file:
tools:replace="android:value"

It's better to have the keys inside gradle like this :
manifestPlaceholders = [fabric_io_id: "key here "]

And add it to
       <meta-data
          android:name="io.fabric.ApiKey"
          android:value="${fabric_io_id}"
          tools:replace="android:value"/>


text:
Q: Cómo obtener el valor de una variable de sesión (y mostrar el nombre del usuario logueado) Estoy tratando de poner en un input el nombre de usuario de quien se logea en la página, pero no sé si se puede usar las mismas variables de un archivo PHP a otro distinto. Para el log in uso lo siguiente:
<?php
session_start();
require('scripts/connection.php');

if (isset($_POST['username']) and isset($_POST['password']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    $query = "SELECT * FROM `login` WHERE username='$username' and password='$password'";
    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);
    if ($count == 1)
    {
        $_SESSION['username'] = $username;
    }
    else
    {
        $fmsg = "Invalid Login Credentials.";
    }
}
if (isset($_SESSION['username']))
{
    $username = $_SESSION['username'];
        header("Location: dashboard.php");
}
else
{
}

?>,

Pero en donde quiero poner el nombre del username es en otro HTML distinto, una página independiente de esta tal que así:
<input class="inp1" type="text" id="usernamew" name="usernamew" value="<?php echo $username ?>">

Pero no funciona.

A: El nombre del usuario ya lo estás grabando dentro de una variable de sesión. Si se abre una nueva página, pero se mantiene la misma sesión, sólo se necesita:

*

*Inicializar la sesión con session_start().

*Obtener el valor se la variable $_SESSION.

*Opcionalmente, como medida de seguridad, usar htmlspecialchars() para escapar caracteres especiales.

<?php

    //Inicializar la sesión
    session_start();
    if (isset($_SESSION['username'])) {
        //asignar a variable
        $usernameSesion = $_SESSION['username'];
        //asegurar que no tenga "", <, > o &
        $username = htmlspecialchars($usernameSesion);

        //usarla donde quieras
        echo "<p>¡Hola $username!</p>";
?>

<!-- O dentro del HTML -->
<input type="text" value="<?php echo $username; ?>">

<?php
    } else {
        //No existe username en la sesión
        header('Location: http://url-de-tu-web.com/login.php');
    }

Te recomiendo leer acerca del Manejo de sesiones.

Comentarios sobre tu código:
Hay un problema importante de seguridad en cómo estás accediendo a la
  base de datos. Esto es muy importante que lo resuelvas, ya que toda tu
  base de datos corre peligro. Te recomiendo leer
  ¿Cómo evitar la inyección SQL en PHP?
Por otro lado, si bien header("Location: dashboard.php"); funciona,
  es incorrecto. Debería tener la URL completa.

A: Sobre esta misma pregunta, necesito que me muestre mas datos de usuario logueado con el mismo script el cual me trae el username pero recito que también me traiga el nombre, apellido y la fecha de registro en la db usuario, nombres, apellidos, aregistro.


text:
Q: Upload Picture from Phonegap to Google Cloud I am making an app in which I want to upload picture to Server.
I chose google cloud service where I created bucket and now have followed Video Instruction to upload file.
When I Used the code shown in video I could test it on localhost but later for my Cordova project google api doesn't seem to work. Do I need plugin for it? Or am I missing something here?
Thanks


text:
Q: Create new Azure Website from an exiting backup Azure website I have a running Azure website using Umbraco template. As per business requirement I need to host the same website to a newly created Azure Website.
For that I have backup the running Website using "cloudcellar". But not finding any options to deploy the backup to my newly created web site(Re-store options is available in cloudcellar but that restore in the old Website only).
I will continue to research but if any of you know the answer (how can I easily restore Azure website to newly created website ) please feel free to weigh in!

A: There is more info on it at Cloud Cellars site Restore from Backup
Basically there is a giant green 'Restore' button on the bottom of the Cloud Cellar Dashboard that you click. :)


text:
Q: how to pass image from view controller to tab bar with segue? I am at a loss as to how to pass a selected image in one view controller to a tab bar controller using a segue, i keep on getting "unrecognized selector sent to instance ...". Here is my prepare for segue in a ViewController3 :
 if ([[segue identifier]isEqualToString:@"tabbarGo"]) {

    UITabBarController *tabar=segue.destinationViewController;
    UINavigationController *navController = [tabar.viewControllers objectAtIndex:1];
    ViewController5 *fifthView=[navController.viewControllers objectAtIndex:0];

    fifthView.theImage = selectedImage.image;

    [tabar setSelectedIndex:1];
}

i have imported ViewController5 into ViewController3 as 5 is the tab bar controller and the m file for viewcontroller5 is as follows :
#import <UIKit/UIKit.h>
#import "ViewController5.h"
#import "ViewController3.h"
@interface ViewController5 ()
@end

@implementation ViewController5

@synthesize theImage;
-(void)setImage:(UIImage *)image
{
}
- (void)viewDidLoad {

[super viewDidLoad];

[_imageView setImage:theImage];

}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end

I do not understand what i am doing wrong and have gone through most of the posts, or should i go through a "NSUserDefaults *prefs" approach to this ?
Any help appreciated and thanks.

A: ok got it to work to send an image to a tab bar with navigation controller by adding one line of code, i was forgetting to specify the NSString value of the segue so here is the final full code for "prepare for segue" :
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSString * segueIdentifier = [segue identifier];
 UITabBarController *tabar=segue.destinationViewController;
UINavigationController *navController = [tabar.viewControllers objectAtIndex:1];
ViewController5 *fifthView=[navController.viewControllers objectAtIndex:0];
fifthView.theImage = selectedImage.image;
[tabar setSelectedIndex:1];
}


text:
Q: Unable to access camunda cockpit page I'm using spring boot camunda to build some wf.
All my process works fine, but I cannot access to camunda cockpit interface.
I added the url to WebConfig.java to disable auth by .antMatchers("/camunda/app/**").permitAll().
Now I have 200 OK but a white page and the following error:
GET http://localhost:8083/camunda/app/admin/default/setup/
net::ERR_CONTENT_LENGTH_MISMATCH 200

Any ideas why this may happen and how to solve it?

A: Can you try hitting "http://localhost:8080"
If context path provided then, "http://localhost:8080/${contextPath}", this should direct you to cockpit web UI.

A: You can create a default user with configuration like below :
camunda:
    bpm:
        admin-user:
            id: demo
            password: 1234
            firstName: Default

If you dont create user with config, camunda will forward you a setup page to create a user.
Could you try
http://localhost:yourport/camunda/app/cockpit/default/#/login
If you have context path use below
http://localhost:yourport/yourContextPath/camunda/app/cockpit/default/#/login


text:
Q: iOS - Index Out Of Range I've stumbled across an error in my application:

fatal error: Index out of range (lldb)

I think I may have an idea as to what the problem is, however, don't have a clue on how to amend the error.
I believe due to the fact I'm using section headers, this is causing the problem. I've proof read the coding as well as trying to fix it and searching online. Below I have posted a sample of my code (didn't want to include it all as it includes a few hundred lines of code).
Essentially, I am using a TableViewController in combination with SWReveal where the user selects an option and text will appear.
class BackTableVC: UITableViewController {

    struct Brands {
      var sectionName : String!
        var sectionBrands : [String]!
    }

    struct ThirdView {
        var ThirdViewArray = [String]()
    }

    var brandArray = [Brands]()

    var ThirdArray = [ThirdView]()

    var brandAnswerArray = [String]()

    override func viewDidLoad() {

        brandArray = [

            Brands(sectionName: "Bugatti", sectionBrands: ["EB 110","Veyron"])]

        ThirdArray = [ThirdView(ThirdViewArray: ["EB 110","Veyron"])]

 }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  brandArray[section].sectionBrands.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!

        cell.textLabel?.text = brandArray[indexPath.section].sectionBrands[indexPath.row]

        return cell

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        let DestVC = segue.destinationViewController as! CarDetailsVC

        let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!

        let ThirdAnswerArray : ThirdView

        ThirdAnswerArray = ThirdArray[indexPath.row]

        DestVC.brandAnswerArray = ThirdAnswerArray.ThirdViewArray

       DestVC.FirstString = brandAnswerArray[indexPath.row]

    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return brandArray.count
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return brandArray[section].sectionName

    }

}
    import Foundation

struct ThirdView {
    var ThirdViewArray = [String]()
}

    class CarDetailsVC: UIViewController {

       var FirstString = String()

    var brandAnswerArray = [String]()

    @IBOutlet var Label: UILabel!

    override func viewDidLoad() {

        Label.text = FirstString

    }

        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            _ = segue.destinationViewController as! CarDetailsVC
        }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
}

}

My ThirdView struct and CarDetailsVC are in separate .swift files.
The line which is giving me grief is:
       DestVC.FirstString = brandAnswerArray[indexPath.row]

P.S. if I was to do this:
DestVC.FirstString = "Hello World"

Hello World is shown when selecting only the first option, then the code/application breaks an I get the same error "index out of range" on the line:
        ThirdAnswerArray = ThirdArray[indexPath.row]

A: This simple answer is that your brandAnswerArray doesn't have enough values to give you the thing at index indexPath.row.  i.e. If you have an array with 5 values and you ask it for array[8], the app will crash because index 8 doesn't exist.
Specifically, you are telling your table that you have a certain number of cells/rows:
brandArray[section].sectionBrands.count
That means for every integer, from 0, to whatever brandArray[section].sectionBrands.count is, the table is going to ask you to generate a cell.  Therefore, that is the range that your indexPath.row can have.
BUT: In your prepareForSegue, you are accessing brandAnswerArray[indexPath.row], and brandAnswerArray simply doesn't have enough values to give you whatever is at that requested index (which is a risk, since you used a different portion of data to build the table).


text:
Q: Why won't Safari OSX play YouTube videos? When I display a video, I see this message:
When I click through to the message about HTML support I see:

Yet we know that Safari supports H.264.
Other notes - YouTube videos play in Chrome without trouble. Vimeo videos play in Safari no problem. This problem isn't version specific I've had it for eons. Disabling all extensions doesn't help.
OS version High Sierra 10.13.2
MacBook Pro - Early 2015
Graphics: Intel Iris Graphics 6100 1536 MB


text:
Q: How do you import a user model with strongloop arc database discovery The loopback application already comes equipped with a user model and CRUDs; however, I'm trying to hook an old database up to my loopback application that already contains a user model so the model discovery replies with:
ValidationError: The `ModelDefinition` instance is not valid. Details: `name` is not unique (value: "User").
at /home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/dao.js:264:12
at ModelConstructor.<anonymous> (/home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/validations.js:483:13)
at ModelConstructor.next (/home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/hooks.js:75:12)
at done (/home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/validations.js:480:25)
at /home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/validations.js:554:7
at ModelConstructor.<anonymous> (/home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/validations.js:353:5)
at allCb (/home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/dao.js:1374:7)
at /home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback-datasource-juggler/lib/connectors/memory.js:371:7
at /home/theory/.nvm/versions/v0.12.4/lib/node_modules/strongloop/node_modules/loopback/node_modules/continuation-local-storage/node_modules/async-listener/glue.js:188:31
at process._tickDomainCallback (node.js:381:11)

Can I rename the incoming model to something else using model discovery?  Is there a merge option for models?

A: This is because you're using a exiting model name (User) which belongs to loopback. Calling the model something like "UserAuth" would work.
Using slc arc if connected to the database when changing the model name you can migrate the old model to the new model.
To read more on why and how read their documentation here:
Using built-in models


text:
Q: Shipping & Payment based on Customer Groups in magento 2 Is there a way so that we can restrict payment and shipping for various customer group in magento 2.3.5.
if anyone have tried this and can provide some guidance on how to approach this will be great.
Thanks in Advance!

A: To restrict payment methods to specific customer groups I can recommend this module
https://github.com/galacticlabs/customer-group-payment-filters
It works with 2.3.x and I have used it in production without issues.
For shipping methods, depending on the shipping methods you use you may need to create your own plugin to achieve this.


text:
Q: Getting Page Load Progress with Ajax Well, i am new to Ajax and JQuery, I struggled to compile this. I'm trying to load URL with ajax navigation and with popstate retrieving back and front navigations. The below code works well but my problem is integrating the Progress Indicator of the page i'm trying to load when the link is clicked using Pace Page Progress Bar Plugin.

<meta charset="utf-8" />

<title>jQuery Ajax Test</title>

<link rel="stylesheet" href="https://www.gossipper.com/content/css/inspired-mob/styles/pace-theme-center-atom.css" />

Web page test.html

Get extern

Initial content in test.html

As i stated above, am a newbie to Ajax, JQuery and Javascript. I struggled to compile this, i need help getting this to work.

A: The problem in your code is your script source for pace, css source for pace and the proper placing of html elements.
I tried to go in the sources of your script and css for pace but it is not found.
You don't need to encapsulate all of your element in the
.
Based from https://www.w3schools.com/html/html_head.asp
The  element is a container for metadata (data about data) and is placed between the  tag and the  tag.
HTML metadata is data about the HTML document. Metadata is not displayed.
Metadata typically define the document title, character set, styles, links, scripts, and other meta information.
The following tags describe metadata: <title>,


text:
Q: Why Is Xcode Throwing Errors But Still Compiling? I am working on an iOS app that is using Firebase Firestore. In the project I am working on, I am receiving a number of errors related to Firebase Firestore code. When I create a new project and use the same code the errors do not exist. What's odd is that the code builds and compiles even with the errors. A simple example of what is happening is below.
User.swift
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift
import MapKit

struct User: Codable, Identifiable {
    @DocumentID var id: String?
    var email: String?
}

UserRepository.swift
import Foundation
import Firebase
import FirebaseFirestore
import FirebaseFirestoreSwift

class UserRepository: ObservableObject {
    let db = Firestore.firestore()

    @Published var users = [User]()

    init() {
        startSnapshotListener()
    }

func startSnapshotListener() {
        // Add a SnapshotListener to the User Collection.
        db.collection(FirestoreCollection.users).addSnapshotListener { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                // Check to make sure the Collection contains Documents
                guard let documents = querySnapshot?.documents else {
                    print("No Users.")
                    return
                }

                // Documents exist.
                self.users = documents.compactMap { user in
                    do {
                        //return try user.data(with: User.self)
                        return try user.data(as: User.self)
                    } catch {
                        print(error)
                    }
                    return nil
                }
            }
        }
    }

func createUser1() {
        let user1 = testUser1

        do {
            let _ = try self.db.collection(FirestoreCollection.users).document("testUser1").setData(from: user1)
        } catch {
            print("Error writing new User to Firestore in SeafoodRepository: \(error)")
        }
    }
}

The errors are coming from
return try user.data(as: User.self)

Error1: Argument passed to call that takes no arguments
Error2: Cannot convert return expression of type '[String: Any]' to return
type'User?'

and
let _ = try self.db.collection(FirestoreCollection.users).document("testUser1").setData(from: user1)

Error1: Cannot convert value of type 'User' to expected argument type'[String: Any]'

I've cleaned the project, restarted Xcode, etc and nothing quiets the errors. Any help would be appreciated.

A: The issue was my version of Firebase. I am using Swift Package Manager to manage Firebase. I thought this updated automatically. It doesn't.
File -> Swift Packages -> Update to Latest Package Versions
This silenced the errors.


text:
Q: What is meant by stream buffering? I had started learning C programming, so I'm a beginner, while learning about standard streams of text, I came up with the lines "stdout" stream is buffered while "stderr" stream is not buffered, but I am not able to make sense with this lines.
I already have read about "buffer" on this forum and I like candy analogy, but I am not able to figure out what is meant when one says: "This stream is buffered and the other one is not." What is the effect?
What is the difference?
Update: Does it affect the speed of processing?

A: Buffering is collecting up many elements before writing them, or reading many elements at once before processing them. Lots of information out there on the Internet, for example, this
and other SO questions like this
EDIT in response to the question update: And yes, it's done for performance reasons. Writing and reading from disks etc will in any case write or read a 'block' of some sort for most devices, and there's a fair overhead in doing so. So batching these operations up can make for a dramatic performance difference

A: Buffer is a block of memory which belongs to a stream and is used to hold stream data temporarily. When the first I/O operation occurs on a file, malloc is called and a buffer is obtained. Characters that are written to a stream are normally accumulated in the buffer (before being transmitted to the file in chunks), instead of appearing as soon as they are output by the application program. Similarly, streams retrieve input from the host environment in blocks rather than on a character-by-character basis. This is done to increase efficiency, as file and console I/O is slow in comparison to memory operations.
GCC provides three types of buffering - unbuffered, block buffered, and line buffered. Unbuffered means that characters appear on the destination file as soon as written (for an output stream), or input is read from a file on a character-by-character basis instead of reading in blocks (for input streams). Block buffered means that characters are saved up in the buffer and written or read as a block. Line buffered means that characters are saved up only till a newline is written into or read from the buffer.
stdin and stdout are block buffered if and only if they can be determined not to refer to an interactive device else they are line buffered (this is true of any stream). stderr is always unbuffered by default.
The standard library provides functions to alter the default behaviour of streams. You can use fflush to force the data out of the output stream buffer (fflush is undefined for input streams). You can make the stream unbuffered using the setbuf function.

A: A program writing to buffered output can perform the output in the time it takes to write to the buffer which is typically very fast, independent of the speed of the output device which may be slow.
With buffered output the information is queues and a separate process deals with the output rendering.
With unbuffered output, the data is written directly to the output device, so runs at the speed on the device.  This is important for error output because if the output were buffered it would be possible for the process to fail before the buffered output has made it to the display - so the program might terminate with no diagnostic output.


text:
Q: SSIS parameterized datasource from SQL table This is what I have been trying to do:
SSIS package : Items

With the following sql statement, using linked server:
USE [TARGET]
GO

INSERT INTO [dbo].[Item]
       ([No_]
       ,[Description]
       ,[Unit Price]
       )
SELECT [No_]
      ,[Description]
      ,[Unit Price]
FROM [SOURCE].[Database].[dbo].[Item]

What I want to do:

Store the datasource for both TARGET and SOURCE in sql table Datasource:
Data Source=localhost;Initial Catalog=TARGET;Provider=SQLNCLI.1;Integrated Security=SSPI;Auto Translate=False;

Data Source=localhost;Initial Catalog=SOURCE;Provider=SQLNCLI.1;Integrated Security=SSPI;Auto Translate=False;

And finally update the sql statement in the SSIS package pointing at a parameter.
INSERT INTO @SOURCE +'.[Item]'+
       ([No_]
       ,[Description]
       ,[Unit Price]
       )
SELECT [No_]
      ,[Description]
      ,[Unit Price]
FROM @SOURCE +'.[Item]'+

But not been successful so far, any suggestions?

Update:
Was missing one picture:

In the connection manager I would want to get the datasource information from the table Datasource (first picture after "what I want to do")

Update 2:
Is this possible??

A: You can try this in Execute SQL Task:-
DECLARE @query nvarchar(max)
DECLARE @TARGET nvarchar(200) = ?
DECLARE @SOURCE nvarchar(200) = ?
Set  @query ='INSERT INTO ' + @TARGET +'.[Item]
   ([No_]
   ,[Description]
   ,[Unit Price]
   )
   SELECT [No_]
  ,[Description]
  ,[Unit Price]
  FROM ' +  @SOURCE +'.[Item]'
EXEC(@query)

In the Parameter Mapping map the ? to the variables created ie Target and Source


text:
Q: Update only the specific field in cakephp I have a small problem. I have a table item_pictures that has 6 fields
img1 | img2 | img3 | ima4 | img5| that store  5 images. so it means one row of Batabases has 5 fields that store the path of the images. What i wanna do is that  to create kind of a button next to each image that when the user click it, it just update the field of the image making it empty, thats all i want. So that all i want to update or change only one speciffic field. is that possible and if so how??
Thats the code i have comme up so far:
$this->Form->postLink($this->Html->tag('i', '',
                array('class' => 'glyphicon glyphicon-remove')),
                array('controller' => 'item_pictures','action' => 'delete_current_img', $item['Item']['id'] .'-'. 'img'.$i .'-'. $pictures['img'.$i]) ,
                array('escape' => false), __('Are you sure you want to delete This Image?'))

So i want that in the controller to grab this variable and to update the row with the id => $item['Item']['id'] , on the column img.$i with the value $pictures['img'.$i], and make it empty...

A: I think you were pretty close, so I would cycle $i = 1 to $i = 5 with
$item_picture_id = $item['Item']['ItemPicture']['id'] //or something, im not sure how you have done your relations

echo $this->Form->postLink($this->Html->tag('i', '',
    array('class' => 'glyphicon glyphicon-remove')),
    array('controller' => 'item_pictures','action' => 'delete_current_img', $item_picture_id, 'img'.$i) ,
    array('escape' => false), __('Are you sure you want to delete This Image?'));

So for example image 5 ($i = 5) should resolve to the URL: item_pictures/delete_current_img/ID/img5/
Then for your controller just have (very simple example):
public function delete_current_img($id,$field){
    $this->ItemPicture->id = $id;
    $this->ItemPicture->saveField($field,'');
    //then just go back to where you come from
    $this->redirect(array('controller' => 'foo', 'action' => 'where_ever_the_delete_came_from'));
}

Hope it helps!


text:
Q: System tray missing in Ubuntu 13.04 and notifications show only an icon I just installed Gnome 3 on Ubuntu 13.04.
Usually the system tray used to appear at the bottom when I moved my mouse there, but now nothing appears. Also instead of the notification box appearing at the bottom just an icon appears, and then when the mouse is brought near it, it just vanishes.
Please help me out with this.

A: Sounds like the installation was corrupted.  Time to go back to stock.
Try this, it usually fixes and reverts any problems I've ever gone through.
Sudo apt-get install --reinstall lightdm unity