text:
Q: QGIS fails to load WMS layer I am trying to load WMS from the URL https://vedas.sac.gov.in/geoserver/vedas/wms/?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetCapabilities
While this URL works on the website https://vedas.sac.gov.in/desertification/index.html, it does not work when I use the URL in QGIS 3.22.12. QGIS throws an error: 'Failed to parse capabilities.'
The error report marks the error in the requested XML at line 27817. Is there any way to still access the layer without the server admin deleting the said layers?

Could not get WMS capabilities: invalid name for processing instruction at line 27817 column 21
This is probably due to an incorrect WMS Server URL.

A: This is a very large and horrible capability response document that generates a Java exception on output. But if you download the xml File and replace lines  27815-27820 with the following lines, it may be possible to load some layers if you drag the file into map canvas.
27815:    </Layer>
27816:  </Capability>
27817:</WMT_MS_Capabilities>

A: For WMS 1.3.0, take a copy of the XML output, delete the corrupted forest_biomass_karnataka layer and add </Layer></Capability></WMS_Capabilities> to the end of the file.  The file is still invalid at this point though.  Several Style sections are missing required Title elements, such as vedas:rh_forecast, vedas_dvi:aizwal_pie, India_wetland_2017_18, vedas:rh_forecast there are others... you can add in an empty element <Title/>
A couple of eastBoundLongitude elements have values greater the 180, which is not permitted, so change those to 180.
Now you have a valid capabilities response, but you should go further.
Change all http://192.168.2.17:8090/ references to https://vedas.sac.gov.in/ except the GetCapabilities URL at: /WMS_Capabilities/Capability[1]/Request[1]/GetCapabilities[1]/DCPType[1]/HTTP[1]/Get[1]/OnlineResource[1]/@*[namespace-uri()='http://www.w3.org/1999/xlink' and local-name()='href'] which should point to your saved capabilities file on your local server, for example I changed mine to http://localhost/test/verdas130.xml


text:
Q: Rails migration is always inserting whitespaces or changing the ordering of columns in the schema There is a frustrating issue where my rails migrations update the schema with whitespaces and the position of the table's columns.
So most times when I run bundle exec rake db:migrate it will do one of the below scenarios. When I merge this into our main branch and other developers work off this, then their rails migration reverts tabs and position ordering.
We have noticed that all three developers on the team have the same issue when running a migration if I have been the last committer of the schema.
I just updated postgres to v9.2.4 that is the same as the other devs. Any ideas of what else I could try?
Examples
Below are git diffs to demonstrate what is happening.
Example of re-ordering the schema:
   create_table "accounts", :force => true do |t|
     t.integer  "organisation_id"
-    t.boolean  "active",             :default => false
     t.text     "notes"
+    t.boolean  "active",             :default => false
   end

Example of adding tabs to the schema:
   create_table "comments", :force => true do |t|
-    t.integer  "commentable_id",   :default => 0
-    t.string   "commentable_type", :default => ""
+    t.integer  "commentable_id",     :default => 0
+    t.string   "commentable_type",   :default => ""
-    t.datetime "created_at",                       :null => false
-    t.datetime "updated_at",                       :null => false
+    t.datetime "created_at",                            :null => false
+    t.datetime "updated_at",                            :null => false

A: I built a gem to solve this problem.
It sorts columns, index names and foreign keys, removes excess whitespace and runs Rubocop for some formatting to unify the output of your schema.rb file.
https://github.com/jakeonrails/fix-db-schema-conflicts
After you add it to your Gemfile you just run rake db:migrate or rake db:schema:dump like normal.

A: Good news! Rails finally pushed out an update which solves exactly this. Starting from Rails v5.1.0, the default (and only option) is to remove any extra spaces between the columns.

A: You just should ignore schema.rb from your version control. It changes differently depending on th order of migrations and who generated them. You only need the migrations to generate the appropiated schema for each developer involved in the project.
Regards.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript get the text visible on the display I have a HTML page which is structured in two parts (div), a header and a container part in which some text is displayed.
The text in the container part is large, and it is scrollable.
I need to get the exact same text displayed on the window and to perform some actions on the displayed text, such as highlight an element.
I have found something about getting the scroll position, but what I need is the actual content starting at that position.
It is possible to obtain that?
Thanks.


text:
Q: Is it possible to disable Wrap-around for Numpy Number Types I would like for example uint types to hit 0 rather than wrap-around on subtraction - is it possible to alter this behaviour from python without writing a new c-type? (For example for subtracting two uint8 numpy arrays) ?

A: There is no integer overflow/underflow detection in Numpy, but you could test for this yourself either before or after the calculation.  m0 does this after the calculation, as shown below.
import numpy as np
import timeit

a = np.arange(0, 251, 50, dtype=np.uint8)
b = np.array(a[::-1])

def m0(a, b):
    x = (a-b)
    x[b>a] = 0

def m1(a, b):
    c = (a.astype(np.int16) - b).clip(0, 255).astype(np.uint8)

m0(a, b)
m1(a, b)

a = np.array(a.repeat(1000))  # repeat and copy (copy since I don't remember whether repeat is an indexing trick)
b = np.array(b.repeat(1000))

N = 1000000
print timeit.timeit("m0(a, b)", setup="from __main__ import m0, m1, a, b", number=N)
# 1.7734951973
print timeit.timeit("m1(a, b)", setup="from __main__ import m0, m1, a, b", number=N)
# 3.6973798275

I also compare the times to @Qlaus's approach, which is also good, and they are comparable (you shouldn't take the 50% speed gain here very seriously, but instead test them both for your specific application).  On the other hand, the subtraction itself takes about 0.6 of the times above, so with this removed, the m0 solution is about 3x faster.  But on the other hand, usually if you do one operation that will underflow or overflow you will be doing several, and for those cases, using int16 wil likely be fastest.  In the end, testing for your actual case will be the best approach to optimizing.

A: Numpy does not do overflow handling on array types. See this discussion or this related question.
If you do not care about speed so much you could save your results in an int16 first and then clip it and write it back to an uint8 array.
import numpy as np
a = np.arange(5, dtype=np.uint8)
b = np.ones(5, dtype=np.uint8) * 2
print(a-b)  # [254 255   0   1   2]

c = (a.astype(np.int16) - b).clip(0, 255).astype(np.uint8)
print(c)  # [0, 0, 0, 1, 2]


text:
Q: Reading component parameters and setting defaults I'm pulling my hair on this because it should be simple.
I'm trying to create a component and set its default properties.
<CustomComp text="Some text" color2="0x939202" value="4.5" />

But when  I initialize it, the parameters still don't register.
I do like this:
[Bindable] private var myColor2:uint = 0x000000;
[Bindable] private var myValue:Number = 10.0;

But it just gives me the default, all the time. What am I doing wrong?

A: For starters the private vars have different names than the vars in the CustomComp tag.


text: Q: Tensorflow: Diagonal of matrix of matrices / Diagonal of 4D tensor Given a 4D tensor x of shape (batch_size, batch_size, seq_len, feature_dim), I want to be able to retrieve the matrices along the diagonal entries, i.e. I need a way to fetch all x[diag_entry, diag_entry, :, :] slices for the values range(batch_size) producing a tensor of shape (batch_size, seq_len, feature_dim). However, I cannot explicitly loop over range(batch_size) as batch_size may vary since I work in Keras. Does Tensorflow have functionality supporting such an operation?


text:
Q: How to write the response to the text file I am trying to log the request response from the service into a text file. I am using log4net to log the response to a text file but it is logging only the request but not the response.
How can I do this?
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {

        if (log.IsErrorEnabled)
        {
        SaveResponseToLog("AfterReceiveReply" +"\n##### VisService SOAP Response #####\n");
        string filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Daimler AG\\Vis@\\" + "log.txt";
        System.Xml.XmlDictionaryWriter writer = null;
        MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
        reply = buffer.CreateMessage();
        System.ServiceModel.Channels.Message replyCopy = buffer.CreateMessage();
        try
        {
            FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            writer = System.Xml.XmlDictionaryWriter.CreateTextWriter(fs);
            replyCopy.WriteMessage(writer);

            MessageBox.Show("AfterReceiveReply" + writer.ToString());
            writer.Flush();
        }
        catch (Exception e)
        {
            //Something went wrong while writing the response
            MessageBox.Show(e.Message);
        }
        finally
        {
            writer.Close();
        }
  }

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
    {
        if (log.IsErrorEnabled)
        {
            string visServiceSOAPRequest = request.ToString();
            log.Error("Error:VisService SOAP Request >>>");
            log.Error(visServiceSOAPRequest);
            //For displaying the message in the mail confirmation box
            SaveResponseToLog("BeforeSendRequest" + "\nVisService SOAP Request >>>\n" + visServiceSOAPRequest);
        }
        return null;
    }

    private void SaveResponseToLog(string message)
    {
        System.IO.StreamWriter writer = null;
        //StreamReader rd = null;
        string filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My App\\Application\\" + "log.txt";
        if (!File.Exists(filename))
        {
            using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {

                 fs.Flush();
                 fs.Close();
            }
        }

        try
        {
            if (File.Exists(filename))
            {
                    writer = System.IO.File.AppendText(filename);
                    writer.Write(message);
                    writer.Flush();
            }
        }

        catch (Exception e)
        {
            // Wenn das loggen nicht funktioniert, kann der Fehler ja nicht geloggt werden..
            log.Error("Error saving the message in the log.txt file: " + e.Message);
        }
        finally
        {
            writer.Close();

        }
    }

A: Following code just work for me. Decorate your service implementation by attribute [MyServiceBehavior]
Requests can be seen in AfterReceiveRequest method.
Responses can be seen in BeforeSendReply method.
    public class MyServiceBehaviorAttribute : Attribute, IServiceBehavior
    {
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
            {
                foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
                {
                    epDisp.DispatchRuntime.MessageInspectors.Add(new Inspector());
                    foreach (DispatchOperation op in epDisp.DispatchRuntime.Operations)
                        op.ParameterInspectors.Add(new Inspector());
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }
    }

    public class Inspector : IDispatchMessageInspector, IParameterInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            Console.WriteLine("IDispatchMessageInspector.AfterReceiveRequest called.");
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            Console.WriteLine("IDispatchMessageInspector.BeforeSendReply called.");
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            Console.WriteLine(
              "IParameterInspector.AfterCall called for {0} with return value {1}.",
              operationName,
              returnValue.ToString()
            );
        }

        public object BeforeCall(string operationName, object[] inputs)
        {
            Console.WriteLine("IParameterInspector.BeforeCall called for {0}.", operationName);
            return null;
        }
    }


text:
Q: Comparison of Asp.net (MVC) and WPF (MVVM) - Is There a Data Binding Equivalent? I am considering a transition form WPF (mvvm) to asp.net (MVC). I thought it might be useful for sanity sake to draw a lose comparison of asp.net(MVC) and WPF(MVVM).
What would a MVC equivalent of the following WPF Example look like? To be specific, I am curious as to how the separation of UI and application logic is maintained and perhaps more importantly, if there is a data binding equivalent. How would the two different design patterns accomplish the same scenario.
Viewmodel
In your view model, you would have a class in which a component in the view will bind too. Something to the tune of:
namespace solution.ViewModels
{
    public class MainViewModel : BaseViewModel
    {
        private DateTime _fromDate;

        public DateTime FromDate
        {
            get { return _fromDate; }
            set { _fromDate = value; OnPropertyChanged("FromDate"); }
        }

        private DateTime _toDate;

        public DateTime ToDate
        {
            get { return _toDate; }
            set { _toDate = value; OnPropertyChanged("ToDate");}
        }
    }
}

Where BaseViewModel is:
public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

View
<Window .......>
    <Grid>
       <DatePicker SelectedDate = "{Binding ToDate}">
       <DatePicker SelectedDate = "{Binding FromDate}">
    </Grid>
</Window>

A: I think some of the comments on this question so far are a little unfair...Yes the two technologies (ASP.Net MVC and WPF) are used to build for completely different platforms, but there are comparisons that can be made between the architectures (MVC and MVVM) being used in each of those platforms.
In WPF you have a ViewModel that exposes your Model to your View. In your example, MainViewModel exposes a model that contains a from and a to date via the FromDate and ToDate properties. The view can then choose to display those values as it pleases.
In ASP.Net MVC, you still have a Model and a View and something that connects the two - a Controller. The action invoked on your controller by some HTTP request is responsible for populating a model to be rendered by a view and returned to the client as an HTTP response.
public class MainController : Controller
{
  public ActionResult ShowMeTheModel()
  {
    SimpleModel model = new SimpleModel
    {
      FromDate = DateTime.Today,
      ToDate = DateTime.Today.AddDays(7)
    };

    return View(model);
  }

  [HttpPost]
  public ActionResult UpdateTheModel(SimpleModel model)
  {
    // use the model parameter to persist changes or otherwise

    return Redirect("ShowMeAllTheModels");
  }
}

And a basic View

A Simple Model

<% using(Html.BeginForm("UpdateTheModel", "Main")) %>
<% { %>

      From Date
      To Date

        <%= Html.DatePickerFor(model => model.FromDate) %>

        <%= Html.DatePickerFor(model => model.ToDate) %>

<% } %>

Databinding occurs in the post back - put very simply, an [HttpPost] action with a parameter of type SimpleModel will populate that model with the values contained in the HTTP post. That action can then use that values in that model to persist changes or trigger some action.
So yes the platforms are very different and you need to be fully aware of these differences, but there are definitely comparisons that can be made as I have outlined above.

A: No, No, No and...NO
WPF is run at client side and everything is happening on the client side. It keeps all the states and data in the same machine's memory.
MVC on the other hand runs on both the client and server side where the server does NOT store the state (you can read more about HTTP stateless) and the client/server does not share the same piece of memory or data.
So those are completely different technology targeting completely different use cases.
Classic ASP on the other hand is trying to simulate the behavior you described by using post back. Basically it is sending back all the user's action back to the server and the server can act correspondingly (such as change the value, disable button ect).
I would not recommend using it anymore since it is putting lots of unnecessary pressure on the server


text:
Q: Referring to a Enumeration Value type in a method signature I would like to add a method to scala.Enumeration.  My first approach was to try to extend it, but was bitten by this.  My second approach was to try to define a method, and pass in the Enumeration - if that worked, I hoped to use an implicit conversion.  I'm having a hard time preserving type with the return type of the method, however.
object EnumExample {
  object SampleEnum extends Enumeration {
    val include, exclude = Value
  }

  def parse[T <: Enumeration](name:String, enum:T):T#Value =
    enum.valueOf(name) match {
      case Some(x) => x
      case x => throw new RuntimeException("No field named '" + name + "' found on enum " + enum + ", legal values = " + enum.values)
    }

  def main(args:Array[String]) = {
    //compiles fine, and preserves custom type
    val withNameExample:SampleEnum.Value = SampleEnum.withName("include")

    //also fine, but we lost type info
    val enumWithHash:Enumeration#Value = parse("include", SampleEnum)

  /**
  error: type mismatch;
   found   : Main.$anon.EnumExample.SampleEnum#Value
   required: Main.$anon.EnumExample.SampleEnum.Value
      val parseExample:SampleEnum.Value = parse("include", SampleEnum)
   *
   */
    val customTypeWithHash:SampleEnum.type#Value = parse("include", SampleEnum)

    //same error
    val customTypeWithDot:SampleEnum.Value = parse("include", SampleEnum)
  }
}

One obvious fix would be to just remove the return type declaration from the parse method, but that gives me a "illegal dependent method type".  This leaves me with lots of questions:

*

*Is this possible to specify?  One way or another, I'd like to get a nice error message when parsing an enumeration field in from a String.

*Why do I get the "illegal dependent method type"?

*What precisely is the "#" operator(?) in this case?

A: This looks like a bug to me (at least in 2.8.0 Beta1 where I've tested it).
Particularly instructive is the following:
scala> var x: SampleEnum.type#Value = null
x: SampleEnum.Value = null

Here, we're requesting the arbitrary inner type but we're actually getting the specific inner type.  That's just broken (and I will file a bug report if there is not already one, unless someone else swiftly explains why this is not a bug).
So, what to do?  Well, first, let's understand the original method signature of parse:
def parse[T <: Enumeration](name:String, enum:T):T#Value

We have T which is a subclass of Enumeration, enum which is an instance of T, and--since there is no way to express that the Value must be from that particular instance of T, we have to resort to T#Value (i.e. an inner type of T, without regard to which particular T it comes from).
Now we have to pass in a specific object, get back a generic inner object, and do it in the face of ExampleObject.type#Value being the same as ExampleObject.Value even though they type differently.
So we have to write our own object from scratch:
class SampleWorkaroundClass extends Enumeration {
  val include, exclude = Value
}
lazy val SampleWorkaround = new SampleWorkaroundClass

Here we have a single instantiation of a specially defined class.  Now we can get around the bug in Object:
scala> val typeWorks:SampleWorkaroundClass#Value = parse("include",SampleWorkaround)
typeWorks: SampleWorkaroundClass#Value = include

(The lazy val is just to get exactly the same behavior as with objects where they're not instantiated until they're used; but a val alone would be fine.)

Edit: Outer#Inner means "any inner class of type Inner coming from this outer class" as opposed to myOuter.Inner which means "only that class of type Inner that has this instance of Outer, myOuter, as its enclosing class".  Also, I don't get the dependent type error in 2.8.0 Beta1--but not being able to specify the type makes things quite awkward.

Edit: update on bug report--the way it works now is apparently intentional.  To use types in this fashion, you are intended to explicitly specify the type in the function call (as it is not inferred to be what you want), like so
val suggested: SampleEnum.type#Value = parse[SampleEnum.type]("include",SampleEnum)

This way is easier if you only have to do this a few times.  If you have to do it many times, creating your own class with a val (or lazy val) instantiation probably makes things easier / more compact.


text:
Q: [UE4 error]The project could not be compiled. Would you like to open it in Visual Studio? I saw many many people ask this question and apparently there is no absolute answer to this question.
this happened for me when I uninstall my visual studio 2015 cause unreal 4.18 no matter I do use VS 2015 and I want to use 2017 and I saw some people solve this problem with uninstalling VS 2015.
when I uninstall VS 2015 receive this error when I want to create a new C++ project:
The project could not be compiled. Would you like to open it in Visual Studio?
Running f:/Program Files/Epic Games/UE_4.19/Engine/Binaries/DotNET/UnrealBuildTool.exe MyProject451 Development Win64 -project="F:/c++ New/New folder/MyProject451/MyProject451.uproject" -editorrecompile -progress -NoHotReloadFromIDE
Performing full C++ include scan (building a new target)
Creating makefile for MyProject451 (no existing makefile)
@progress push 5%
Parsing headers for MyProject451Editor
  Running UnrealHeaderTool "F:\c++ New\New folder\MyProject451\MyProject451.uproject" "F:\c++ New\New folder\MyProject451\Intermediate\Build\Win64\MyProject451Editor\Development\MyProject451Editor.uhtmanifest" -LogCmds="loginit warning, logexit warning, logdatabase error" -Unattended -WarningsAsErrors -installed
Reflection code generated for MyProject451Editor in 7.2801937 seconds
@progress pop
Performing 9 actions (4 in parallel)
[2/9] Resource ModuleVersionResource.rc.inl
[3/9] Resource PCLaunch.rc
SharedPCH.Engine.cpp
MyProject451GameModeBase.cpp
MyProject451.init.gen.cpp
MyProject451.cpp
MyProject451GameModeBase.gen.cpp
[8/9] Link UE4Editor-MyProject451.dll
[9/9] Link UE4Editor-MyProject451.lib
LINK : fatal error LNK1181: cannot open input file 'ws2_32.lib'
   Creating library F:\c++ New\New folder\MyProject451\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-MyProject451.lib and object F:\c++ New\New folder\MyProject451\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-MyProject451.exp
ERROR: UBT ERROR: Failed to produce item: F:\c++ New\New folder\MyProject451\Binaries\Win64\UE4Editor-MyProject451.dll
Total build time: 34.18 seconds (Local executor: 0.00 seconds)

image of error (i copy notes in above as you can see ):enter image description here
many peoples mention its relate to Windows SDK and there is windows SDK in installing if I add more let me know.
enter image description here
I thought if I install unreal 4.19 its maybe get fixed but it didn't.
it seens ue4 genrate C++ files for VS 2015.
enter image description here
I hope there is anyone known how to solve this problem and guide me how.

A: I fix it with downloading this cleaner form this link https://github.com/Microsoft/VisualStudioUninstaller/releases .
after that UE4  when you want to create new project sends a message and it says you don't have VS2017 don't panic just download the installer and modify it after that it downloading about 350 mg and after that, everything will get fixed.
for more info :
https://answers.unrealengine.com/questions/597939/new-c-project-fails-to-compile-using-ue-415-and-vs.html


text:
Q: Angular JS hide first element of ng-repeat How would I hide the first element of an ng-repeat?

{{ item.value }}

This works in that the whole ng-repeat block is hidden, but how would I hide only the first item in items? I want to display it completely differently using more prominent html/etc, so it's useful to have it in that list of data.

A: No need to hide, just use a filter to exclude the first item from the list:

0">

{{ item.value }}

A: You can do this

{{ item.value }}

Here are the docs: http://docs.angularjs.org/api/ng.directive:ngRepeat

A: There's a simpler solution in more recent versions of Angular.
The filter "limitTo" now supports a "begin" argument (docs):
{{ limitTo_expression | limitTo : limit : begin}}

So you can use it like this in a ng-repeat:
ng-repeat="item in items | limitTo: items.length : 1"

This means that ng-repeat will begin at index 1 (instead of the default index 0) and will continue for the rest of the items array's length (which is less than items.length, but limitTo will handle that just fine).

A: In case you need to skip last, use ng-if='!$last'.


text:
Q: How do I upgrade mysql 5.5.24 to 5.5.27 on Ubuntu 12.04? I've bee running around for about 1 1/2 hours now trying to figure out how to do an upgrade. Can anyone direct me to a tutorial on this?

A: Unfortunately, the most recent mysql version in the official repositories is 5.5.24. Even Ubuntu 12.10, which is in the testing phase, only has 5.5.25.
If you want to upgrade to 5.5.27, you have two options, neither of which will probably successfully "upgrade" your existing installation, may break future official Ubuntu mysql updates, and may or may not work:

*

*Install the 5.5.27 deb packages (for Debian) from the official website.

*Build 5.5.27 from source (also available at the MySQL website).

A: I wrote a script to assist you in upgrading to the latest release of MySQL.
Please see my post here: http://ubuntuforums.org/showthread.php?t=1933991


text:
Q: Showing $6x^3 - 3x - 18 $ is irreducible The techniques I know right now to show a polynomial f(x) in Q[x] is irreducible are to show it is irreducible in some $F_p$ with p a prime f(x) has the same degree in $F_p$ as in Q[x], and the Eisenstein criteria.
I know that $6x^3-3x-18$ is irreducible in Q[x], but I don't see how to show it. The prime divisors of 18 are 2 and 3, both of which divide 6 so a simple Eisenstein doesn't work. And I've tried roots of the polynomial in $F_p$ for many p's, but it always seems to have roots. I'm guessing there is a simple way to solve this problem, does anyone know?

A: If a cubic polynomial is reducible, it has a linear factor, which corresponds to a  root, which your polynomial does not have in $\mathbb Q$ by the rational root theorem.
Alternatively, you could show that your polynomial has no root in $\Bbb F_{11}$.


text:
Q: How to create a "loop" statement within an {expect} script? Assumption is, this is the script
#!/usr/bin/expect
set a "__test__"

i would like to create a loop inside this script so it can print the value for
 $a

with the a number infront of it based on the loop.
so if i wanted it to loop 3 times.. end product would become:
 1:__test__
 2:__test__
 3:__test__

A: You can use for
#!/usr/bin/expect
set a "__test__"
for {set x 0} {$x<3} {incr x} {
   puts "$x:$a"
}

See more info in tcl commands because expect is an extension to tcl language.


text:
Q: Question about Kotlin Coroutine Cancellation I have a code something like the following in my app
class MyFragment : Fragment(), CoroutineScope by MainScope() {

    override fun onDestroy() {
        cancel()
        super.onDestroy()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        doSomething()
    }

    private fun doSomething() = launch {
        val data = withContext(Dispathers.IO) {
            getData()
        }

        val pref = context!!.getSharedPreferences("mypref", MODE_PRIVATE)
        pref.edit().putBoolean("done", true).apply()
    }
}

In production, I get many NPEs in doSomething() while accessing context.
My assumption was that the coroutine gets cancelled after calling cancel() in onDestroy(), so I didn't bother to check the context for a null value. But it looks like continues to execute even after cancel() is called. I think it happens if the cancel() is called after completing the withContext and before resuming the coroutines.
So I replaced doSomething() with the following.
    private fun doSomething() = launch {
        val data = withContext(Dispathers.IO) {
            getData()
        }

        if (isActive) {
            val pref = context!!.getSharedPreferences("mypref", MODE_PRIVATE)
            pref.edit().putBoolean("done", true).apply()
        }
    }

This fixes the crash.
However, Is this an expected behavior or am I doing something wrong? Kotlin's documentation isn't very clear about this. And most of the examples online are like my original code.

A: Your code assumes that the withContext() will stop execution when it returns, if the scope is cancelled, but actually it didn't, till version 1.3.0 of kotlin coroutines. Here is GitHub issue. I guess that you are using an earlier version of the library.
I also recommend you use LifecycleScope instead of a custom scope. It's part of lifecycle-runtime-ktx library. So, simplified solution looks like:
// build.gradle
dependencies {
    ...
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-rc02"
}

class MyFragment : Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        doSomething()
    }

    private fun doSomething() = viewLifecycleOwner.lifecycleScope.launch {
        val data = withContext(Dispathers.IO) {
            getData()
        }

        val pref = context!!.getSharedPreferences("mypref", MODE_PRIVATE)
        pref.edit().putBoolean("done", true).apply()
    }
}

There are other helpful utilities which simplifies coroutines usage, take a look at Use Kotlin coroutines with Architecture components documentation section.

A: This is the expected behaviour since Coroutine Cancellation is cooperative in nature.
See https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#cancellation-is-cooperative
While suspend functions will check for the state of coroutine in your case you will have to do this yourself.
A cleaner way is to have these operations in a viewmodel and just cancel the coroutine in ViewModel onCleared; if you are using ViewModel

A: The latest coroutine updates have introduced the possibility of working safe with scopes. Basically if you are doing async work in Fragments or Activities you use lifecycleScope and if you are going async work in ViewModel you need to use viewModelScope. There is also a GlobalScope that can be used in any class but it was proved to have many stability flaws and should be avoided. In any case scenario you should use either lifecycleScope or viewModelScope and use suspend functions in other classes.
So here is the way to do it:
 override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    lifecycleScope.launch {
        doSomething()
    }
 }

 private suspend fun doSomething(){
    withContext(Dispatchers.IO){
        getData()
        if (isActive) {
            val pref = context!!.getSharedPreferences("mypref", MODE_PRIVATE)
            pref.edit().putBoolean("done", true).apply()
        }
    }
 }

As you can see in the code above, there is no need for a scope or launch in the doSomething function because that acts as a task that gets executed in the already launched coroutine above in onActivityCreated. Launching a new coroutine in the doSomething() function is pointless. Also, you can encapsulate your entire code in your withContext() statement because getting shared preferences is also a transaction that works best on Dispatchers.IO. Alternatively you can change the context to the desired context anytime you want, like:
   withContext(Dispatchers.IO){
        getData()
        if (isActive) {
            val pref = context!!.getSharedPreferences("mypref", MODE_PRIVATE)
            pref.edit().putBoolean("done", true).apply()
        }
        withContext(Dispatchers.Default){
            // Heavy computing
        }
    }

Always remember that Dispatchers.IO is optimised best for database transactions, shared preferences and networking calls. If you do heavy computing like forEach in forEach and stuff like that, use Dispatchers.Default and if you need to do view work, use Dispatchers.Main.
These scopes make sure your task gets executed without interruption from other activity components, and if it is interrupted by something like activity destruction, it prevents exceptions and uses garbage collector properly on everything that's inside the scope. Since I started using the scopes, there were no more crashes for me.


text:
Q: how can I Highlight words but avoid a specific sentence? I'm making a highlighting on a solr field that is storing a JSON string. The problem comes when the word I'm searching for is part of the key. I would like to know if its a way to avoid this. For Example, I search the word Body on this json:
{"Opponents Argue - Article Body":"Argue: The U.S. House of Representatives Was Not Right to Imp.."}
and the result is
{"Opponents Argue - Article <b class="highlight">Body":"Argue: The U.S. House of Representatives Was Not Right to <b class="highlight">Body"}
I would like to avoid the exact sentence "Opponents Argue - Article Body" that is the key and this is what I'm doing
 options.Highlight = new HighlightingParameters()
        {
            Fields = new[] { "bodyText", "title", "description", "hlnamedDetails" },
            BeforeTerm = "<b class=\"highlight\">",
            AfterTerm = "</b>",
            Snippets = 100000,
            MaxAnalyzedChars = _highlightingConfig.Value.MaxAnalyzedChars,
            MergeContiguous = true,
            Query = new SolrQuery("(hlnamedDetails:Body) AND -(hlnamedDetails:\"Opponents Argue - Article Body\")")
        };


text:
Q: Why isn't my application entering my if statement I'm trying to write a console client-server application in Java; using sockets, I currently have a simple login system and a simple command system. The login system appears to work, although it prints the "Invalid username and password" line to the client, regardless whether the user inputs correct credentials. - The connection is definitely working.
However, the command system does not seem to function at all, when the command is received by the server, it does not appear to send anything back.
So my main question is why doesn't my server send anything back to the client when the command is received?
Here is my Server:
import java.io.*;
import java.net.*;

class TCPServer2
{
public static void main(String argv[]) throws Exception
{

    ServerSocket welcomeSocket = new ServerSocket(6789);
    String[][] Login = {{"MATT","UNCP"},{"JOHN","UNCP"},{"CARL","UNCP"}};
    String Command;
    String username;
    String username1;
    String password;
    String password1;
    String cmd;
    while(true)
    {
        Socket connectionSocket = welcomeSocket.accept();
        BufferedReader inFromClient =
           new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
        username = inFromClient.readLine();
        System.out.println("\nUsername received: " + username);
        password = inFromClient.readLine();
        System.out.println("\nPassword received: " + password);
        username1=username.toUpperCase();
        password1=password.toUpperCase();

        for(int i = 0; i<Login.length; i++)
        {
            if(Login[i][0].equals(username1) && Login[i][1].equals(password1))
            {
                outToClient.writeBytes("Hello " + username1);
                outToClient.writeBytes("\nOther users registered on the server currently include: \n");

                for(int k = 0; k<Login.length; k++)
                {
                    outToClient.writeBytes(Login[k][0]);
                    }
            }
            else {
                outToClient.writeBytes("Invalid Username and/or password.\n");
            }
            }
                        BufferedReader inFromClient2 =
           new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient2 = new DataOutputStream(connectionSocket.getOutputStream());
        Command = inFromClient2.readLine();
        System.out.println("\nCommand received: " + Command);

if(Command.equals("listTranslations"))
{
outToClient2.writeBytes("English,Thai,Geordie,etc.");
}
else
{
if(Command.equals("getCost"))
{
outToClient2.writeBytes("£100\n");
}
else
{
outToClient2.writeBytes("Invalid Command");
}
}

}

    }
}

Here is my client:
import java.io.*;
import java.net.*;

class TCPClient2
{
public static void main(String argv[]) throws Exception
{
     String userName;
     String passWord;
     String loginInfo;
     String loginInfo2;
     String loginInfo3;
     String command;
     String commandInfo;
     String commandInfo2;

     BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
     Socket clientSocket = new Socket("localhost", 6789);
     DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
     BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

     System.out.println("Username: ");
     userName = inFromUser.readLine();
     outToServer.writeBytes(userName + "\n");

     System.out.println("Password: ");
     passWord = inFromUser.readLine();
     outToServer.writeBytes(passWord + "\n");

     loginInfo = inFromServer.readLine();
     System.out.println(loginInfo);
     loginInfo2 = inFromServer.readLine();
     System.out.println(loginInfo2);
     loginInfo3 = inFromServer.readLine();
     System.out.println(loginInfo3);

     System.out.println("Please enter a command: ");
     command = inFromUser.readLine();
     outToServer.writeBytes(command);

     commandInfo = inFromServer.readLine();
     System.out.println(commandInfo);
     commandInfo2 = inFromServer.readLine();
     System.out.println(commandInfo);

     clientSocket.close();
 }
}

This is my first time asking a question on stackoverflow, but i've browsed it a lot in the past. So I just wanted to also say thank you for the great community you provide.

A: Im not sure if this will help you but check if you don't have to flush after each writeBytes call to really outputs data to the client.
try to add  outToClient.flush();

A: This is a continuation from my comment:
This is how I would do it, first I would replace this: String[][] Login = {{"MATT","UNCP"},{"JOHN","UNCP"},{"CARL","UNCP"}}; by something like so:
Map<String, String> userDetails = new HashMap<String, String>();
userDetails.put("MAT", "UNCP");
userDetails.put("JOHN","UNCP");
userDetails.put("CARL", "UNCP");

Then, instead of this:
 for(int i = 0; i<Login.length; i++)
        {
            if(Login[i][0].equals(username1) && Login[i][1].equals(password1))
            {
                outToClient.writeBytes("Hello " + username1);
                outToClient.writeBytes("\nOther users registered on the server currently include: \n");

                for(int k = 0; k<Login.length; k++)
                {
                    outToClient.writeBytes(Login[k][0]);
                    }
            }
            else {
                outToClient.writeBytes("Invalid Username and/or password.\n");
            }
        }

I would do this:
if (userDetails.get(username1).equals(password1))
{
    outToClient.writeBytes("Hello " + username1);
                outToClient.writeBytes("\nOther users registered on the server currently include: \n");

    for (String str : userDetails.keySet()
    {
         outToClient.writeBytes(str);
    }

}
else
{
    outToClient.writeBytes("Invalid Username and/or password.\n");
}

The way I am seeing it, the system is both working and printing the Invalid credentials string is because, assuming you provide these log in details: CARL and UNCP, you are passing the 2nd set of credentials, so your loop will check the credentials by comparing them with the first set and since they do not match, it will print the message. On the second iteration, it will see that the credentials match and will log you in.
For more information take a look at the JavaDoc. HashMap is a collection which is usually a good thing to know about, besides the usual List and Set.


text:
Q: Count unique elements in mutidimensional array with Jquery Mapping? Any ideas on JQuery mapping that will return an array of duplicates names, and titles, with their count. So I can create a bar graph in D3 or Chart JS (Chart JS seems easier so far)...
ie, I have (example, using JSON)
 obj = {"Chocolate":"Organic", "Chocolate":"Fresh", "Chocolate":"Organic",
    "Vanilla":"Regular",
    "Vanilla":"Organic","Strawberry":"Fresh","Vanilla":"Regular"};

I want this
    var data = {
    labels: ["Chocolate", "Strawberry", "Vanilla"],
    datasets: [
        {
            label: "Fresh",
            fillColor: "blue",
            data: [1,0,1] //(1 Fresh chocolate, 1 Fresh Strawberry, No fresh Vanilla)
        },
        {
            label: "Regular",
            fillColor: "red",
            data: [0,0,2] //(0 regular chocolate, 0 regular Strawberry, 2 regular Vanilla)
        },
        {
            label: "Organic",
            fillColor: "green",
            data: [2,1,0] //(2 organic chocolate, 1 organic Vanilla, 0 organic strawberry)
        }
    ]
};

http://jsfiddle.net/u25c7gtj/2/
What have I tried? Well so far I have been able to group the items by Chocolate, Vanilla, or Strawberry, but the next step of getting a count of the items that have matching properties... I don't even know where to begin comparing them. I tried only pulling the "Flavor and Type", to compare those as objects but the comparison only yielded the groups with the individual flavor and type key and value pairs.
function groupBy(propertyName, array) {
    var groupedElements = {};

    for(var i = 0; i < array.length; i++) {
        var element = array[i];
        var value = element[propertyName];

        var group = groupedElements[value];
        if(group == undefined) {
            group = [element];
            groupedElements[value] = group;
        } else {
            group.push(element);
        }
    }

    return groupedElements;
}

var result = groupBy("flavor", obj)
console.log(result);
$("#results").html(JSON.stringify(result, null, 4));

I also tried the code below which only seems to count the total
 <script type="text/javascript">
 $.ajax({

    url: "/_api/web/lists/getbytitle('Ice Cream List')/items?$select=ID,Flavor,Type",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function(data){
       // $.each(data.d.results, function(index, item){
           // console.log(item.Id);
//  console.log(item.Title);
//  console.log(item.m4gs);
 //       });

var  counts = [];

jQuery.each(data.d.results, function(index, item) {
  if (!counts.hasOwnProperty(item)) {
    counts[item] = 1;
  } else {
    counts[item]++;
  }
});
console.log(counts[]);


text:
Q: Addition and Multiplication in Combinations How can we determine when are we supposed to use addition or multiplication in combinations?
Consider the question:
What is the number of ways of choosing 4 cards from a pack of 52
playing cards? In how many of these
(A) four cards are of the same suit?
(B) four cards belong to four different suits?
In the solution for A, addition between all $4$ combinations have been taken into consideration, whereas for facecards, multiplication has been done. How can we determine which to use when?
Also, in the question:
"two are red cards and two are black cards"
My solution is:
Since there are $26$ red and black cards, to select two red and two black, we will do:
$$52C26 \cdot 26C2+ 52C26 \cdot 26C2$$
But this is wrong why?

A:
What is the number of ways of choosing four cards of the same suit when four cards are selected from a standard deck of $52$ playing cards?

Method 1:  To be successful, we must choose four of the thirteen clubs or four of the thirteen diamonds or four of the thirteen hearts or four of the thirteen spades, which can be done in
$$\binom{13}{4} + \binom{13}{4} + \binom{13}{4} + \binom{13}{4} = 4\binom{13}{4}$$
ways.
Why do we add?
The Addition Principle states that if there are $m$ ways of performing one task and $n$ ways of performing another task that cannot be done at the same time, then the number of ways of performing one of the tasks is $m + n$.
In this case, we may choose four clubs or four diamonds or four hearts or four spades.  Since these tasks are mutually exclusive (cannot be performed at the same time), we add the number of ways each task can be performed.
The word or is an indication that you need to add.
Method 2: To be successful, we must choose one of the four suits and four of the thirteen cards of that suit in
$$\binom{4}{1}\binom{13}{4}$$
ways.
Why do we multiply?
The Multiplication Principle states that if one task can be performed in $m$ ways and a second task can be performed independently of the first in $n$ ways, then there are $mn$ ways of performing both tasks.
In this case, we choose a suit and then choose four cards of that suit.  Since the number of ways we can select four cards of the chosen suit is independent of the choice of suit, we multiply the number of ways each task can be performed.
The word and is an indication that you have to multiply.

What is the number of ways of choosing four cards of different suits when four cards are selected from a standard deck of $52$ cards?

We must choose one of the thirteen clubs and one of the thirteen diamonds and one of the thirteen hearts and one of the thirteen spades, which can be done in
$$\binom{13}{1}\binom{13}{1}\binom{13}{1}\binom{13}{1}$$
ways.
Notice that each of the four tasks is performed independently of the others, so we multiply the number of ways each task can be performed.

What is the number of ways of choosing two red and two black cards when four cards are selected from a standard deck of $52$ playing cards?

We must select two of the twenty-six red cards and two of the twenty-six black cards, which can be done in
$$\binom{26}{2}\binom{26}{2}$$
ways.
Notice that each task is performed independently of the other, so we multiply the number of ways each task can be performed.
Why is your answer wrong?
You first selected $26$ of the $52$ cards in the deck, then multiplied by the number of ways to select two of those $26$ cards of one of the colors.  However, $\binom{52}{26}$ is the number of ways of selecting any $26$ cards in the deck (which do not all need to be the same color).  Instead, you should have chosen all $26$ cards of that color and then chosen two cards of that color for each color, which can be done in
$$\binom{26}{26}\binom{26}{2} = \binom{26}{2}$$
ways.
Moreover, you have to this for the red cards and the black cards, so you have to multiply the number of ways of doing this for each color.

A: For every selection of $2$ red cards there are $^{26}C_2$ ways to match them with $2$ black cards. As there are also $^{26}C_2$ ways of choosing $2$ red  cards, the number of ways of choosing $2$ red and $2$ black is:
$$n = ^{26}C_2\cdot ^{26}C_2 = 105625$$
For (A) $$n = ^{13}C_4 + ^{13}C_4 + ^{13}C_4 + ^{13}C_4\ \text{or}\  4\cdot ^{13}C_4$$
For (B) $$n = 13\cdot 13\cdot 13\cdot 13 = 13^4$$


text:
Q: Loading specific json message_ids according to the selected indexPath Goal:
When I select a message from the list of chat messages in the MessageListController with didSelectRowAt, I want the opened chat session in the next ChatDetailController to match the same conversation that was selected. Obviously.
I'm working with WatchKit but it's the same thing in this iOS image. The message with Sophia is selected and the chat with Sophia opens.

I want to pass the json "message_id" i.e. the chatMessageId property from my model. I'm already passing the chatMessageId from the MessageModelto the ChatDetailController with this line presentController(withName: "ChatDetailController", context: messageContext)
Here is a print out of the passed data using messageContext.

Passed context: Optional(HTWatch_Extension.MessageModel(partner: "9859", nickname: "Marco", message: "Have you seen is dog?", city: "Madrid", countryBadgeImageURL: https://i.imgur.com/PJcyle7.jpg, messageListImageURL: https://i.imgur.com/PJcyle7.jpg, chatMessageId: "Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ", status: "offline"))

What's the next step? How do I tell the ChatDetailController to populate its table with the conversation that matches the row that was selected?
MessageListController
// ...code...

let messageObject = [MessageModel]()
//var chatObject = [ChatModel]()

// ...code...

override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {

    var messageContext = messageObject[rowIndex]
    var chatContext = chatObject[rowIndex]

    do {
        guard let fileUrl = Bundle.main.url(forResource: "Chats", withExtension: "json") else {
            print("File could not be located")
            return
        }
        let data = try Data(contentsOf: fileUrl)
        let decoder = JSONDecoder()

        let msg = try decoder.decode([ChatModel].self, from: data)
        self.chatObject = msg

    } catch let error {
        print(error)
    }

    // I got part of this line from a previous question, but these property types do not match.
    // No matter what chatObject I create I cannot access it/assign it.
    // Also I do not want to mutate messageContext which Xcode is telling me to do.
    messageContext.chatMessageId = (chatObject as AnyObject).filter { (dictionaryTemp:[String:String]) -> Bool in
        return dictionaryTemp["message_id"] == chatContext.chatMessageId
    }

    // WatchKit's model presentation method.
    presentController(withName: "ChatDetailController", context: messageContext)
}

ChatDetailController
var chats: [ChatModel] = []

    var messageModel: MessageModel? {
        didSet {
            guard let model = messageModel else { return }
            partnerLabel.setText(model.nickname)
        }
    }

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        if let message = context as? MessageModel {

            self.messageModel = message
            print("Passed context: \(String(describing: messageModel))")
        } else {
            print("Passed context error: \(String(describing: context))")
        }

        do {
            guard let fileUrl = Bundle.main.url(forResource: "Chats", withExtension: "json") else {
                print("File could not be located")
                return
            }
            let data = try Data(contentsOf: fileUrl)
            let decoder = JSONDecoder()

            let msg = try decoder.decode([ChatModel].self, from: data)
            self.chats = msg

        } catch let error {
            print(error)
        }

        DispatchQueue.main.async(execute: {

            self.setupTable(chatMessageArray: self.chats as [AnyObject])
        })
    }

ChatModel
public struct ChatModel: Codable {
// ... other properties
public var chatMessageId: String

enum CodingKeys: String, CodingKey {
    // ... other cases
    case chatMessageId = "message_id"
}

init (message:String , fromId:String, toID : String, imgUrl : URL?, chatMessageId : String) {
    // ... other properties
    self.chatMessageId = chatMessageId
   }
  }
 // .... decoders etc
}

MessageModel
public struct MessageModel: Codable {
    // ...
    public var chatMessageId: String

enum CodingKeys: String, CodingKey {
    // ... other cases
    case chatMessageId = "message_id"
}
// ... init/decoders etc
}

Messages.json
[
  {
    "userid": "4444",
    "nickname": "Marco",
    "online_status": "offline",
    "message": "Have you seen his dog?",
    "city": "Madrid",
    "flag_url": "https://i.imgur.com/PJcyle7.jpg",
    "creationDate": "2016-02-22 15:18:40",
    "avatar_url": "https://i.imgur.com/PJcyle7.jpg",
    "message_id": "Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ" // different id
  },
  {
      "userid": "12121",
      "nickname": "Tom",
      "online_status": "online",
      "message": "Where is the pizza shop?",
      "city": "Kyoto",
      "flag_url": "https://i.imgur.com/PJcyle7.jpg",
      "creationDate": "2016-02-22 15:18:40",
      "avatar_url": "https://i.imgur.com/PJcyle7.jpg",
      "message_id": "EnotMkk8REEd0DHGvUgnd45wBap80E" // different id
  }
]

Chats.json
2 conversations containing 2 messages each. Each conversation has a unique fromId (partner), toID (myself), and unique message_id.
[
  {
    "fromId": "zz1234skjksmsjdfwe2zz",
    "toId": "qq43922sdkfjsfmmxdfqq",
    "messageText": "Have you seen is dog?",
    "imageUrl": "https://i.imgur.com/PJcyle7.jpg",
    "message_id": "Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ", // conversation 1  - same message id as the 1st message in Messages.josn with nickname Marco.
    "read": "true"
  },
  {
      "fromId": "zz1234skjksmsjdfwe2zz",
      "toId": "qq43922sdkfjsfmmxdfqq",
      "messageText": "Yes I have. It's cute.",
      "imageUrl": "https://i.imgur.com/PJcyle7.jpg",
      "message_id": "Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ", // conversation 1
      "read": "true"
  },
  {
      "fromId": "bb888skjaaasjdfwe2333",
      "toId": "qq43922sdkfjsfmmxdfqq",
      "messageText": "What kind of pizza do you want?",
      "imageUrl": "https://i.imgur.com/PJcyle7.jpg",
      "message_id": "EnotMkk8REEd0DHGvUgnd45wBap80E", // conversation 2 - same message id as the 2nd message in Messages.josn with nickname Tom.
      "read": "true"
  },
  {
      "fromId": "bb888skjaaasjdfwe2333",
      "toId": "qq43922sdkfjsfmmxdfqq",
      "messageText": "I like ham & pineapple pizza.",
      "imageUrl": "https://i.imgur.com/PJcyle7.jpg",
      "message_id": "EnotMkk8REEd0DHGvUgnd45wBap80E", // conversation 2
      "read": "true"
  }
]

A: let msg = try decoder.decode([ChatModel].self, from: data)
self.chats = msg

You are storing all chat data contained in Chats.json into chats property.
To filter chats, try replacing second line like below
self.chats = msg.filter { chat in
    return chat.chatMessageId == self.messageModel.chatMessageId
}

or, while I don't know why all chats are contained in single json file, it will be better to separate json file into multiple files for each chat like Chat-Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ.json.
I hope this will help.

A: Your MessageListController didSelectRowAt method should be as simple as this.
 //MessageListController

    // ...code...

    let messageObject = [MessageModel]()
//    var chatObject = [ChatModel]()

    // ...code...

    override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {

        //creating a context with the message object at selected row.
        var messageContext = messageObject[rowIndex]
        // WatchKit's model presentation method. passing the context along.
        presentController(withName: "ChatDetailController", context: messageContext)

//        Rest of the codes not required in your MessageListController
    }

    // ...code...

Your MessageListController will be like this.
// ChatDetailController
    var chats: [ChatModel] = []

    var messageModel: MessageModel? {
        didSet {
            guard let model = messageModel else { return }
            partnerLabel.setText(model.nickname)
        }
    }

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        if let message = context as? MessageModel {

            self.messageModel = message
            print("Passed context: \(String(describing: messageModel))")
        } else {
            print("Passed context error: \(String(describing: context))")
        }

        do {
            guard let fileUrl = Bundle.main.url(forResource: "Chats", withExtension: "json") else {
                print("File could not be located")
                return
            }
            let data = try Data(contentsOf: fileUrl)
            let decoder = JSONDecoder()

            //msg holds all chat messages in the file
            let msg = try decoder.decode([ChatModel].self, from: data)
            // We should filter the chats in the msg array with the selected message content
            self.chats = msg.filter({
                $0.chatMessageId == messageModel?.chatMessageId
            })

//            self.chats only holds the chats with chatMessageId

        } catch let error {
            print(error)
        }

        DispatchQueue.main.async(execute: {

            self.setupTable(chatMessageArray: self.chats as [AnyObject])
        })

Hope this will resolve your issue. Happy Coding :)


text:
Q: Proper way to program a Microsoft Access Backend Database in a Multiuser Environment There is a prevailing opinion that regards Access as an unreliable backend database for concurrent use, especially for more than 20 concurrent users, due to the tendency of the database being corrupted.
There is a minority opinion that says an Access database backend is perfectly stable and performant, provided that:

*

*Your network has no problems, and

*You write your program correctly.

My question is very specific: what does "Write your program correctly" mean?  What are the requirements that you have to follow in order to prevent the database from being corrupted?
Edit: To be clear: The database is already split.  Assume less than 25 users.  I'm not interested in performance considerations, only database stability.

A: If you're looking for great example of what programming practices you need to avoid, number one on the list is generally that of NOT running a split database. Number two is not placing the front end on each computer.
For example the above poster had all kinds of problems, but you can darn your bet that their failing was either that they didn't have the databae split, or they weren't placing the software (front end) on each computer.
As for the person having to resort to some weird locking mechanism, that's kind of strange and not required. Access (actually the JET data engine, now called ACE) has had a row locking feature built in since office 2000 came out.
I've been deploying applications written access commercially for about 12 years now. In all those years I had one corruption occur from ONE customer.
Keep in mind that before Microsoft started pushing and selling SQL server, they rated the JET database engine for about 50 users.  While my clients don't have problems, in 9 out of 10 cases when someone has a probem you find number one on the list is that they failed to split the database, or they're not installing the front in part on each computer.
As for coding Techniques or tips? Any program design that you build and make it in which a reduced number of records are loaded into the form is a great start in your designs. In other words you never want to just simply throw up a form attached to a large table without restricting the the records to be loaded into the form. This is probably the number one tip I can give here.
For example, it makes no sense to load up an instant teller machine with everybody's account number, and THEN ask the user what account number to work on.  In fact I asked a 80 year old grandmother if this idea made any sense, and even she could figure that out. It makes far more sense to ask the user what account to work on, and then simply load in the one customer.
The above same concept applies to a split database on a network. If you ask a user for the customer account number, and THEN open up the form to the one record with a where clause, then even with 100,000 records in the back end, the form load time will be near instant because only ONE RECORD will be dragged from the customers table down the network wire.
Also keep in mind that there is a good number of commercial applications in the marketplace such as simply accounting that use a jet back end ( you can actually open simply accounting files with MS access, they renamed the extensions to hide this fact, but it is an access mdb file).
Some of my clients have 3-5 users with headsets on, and they're running my reservation software all day long. Many have booked more then 40,000+ customers and in a 10 year period NONE of them have had a probem. (the one corruption example above was actually on a single user system believe it or not).
So, I never had one service call due to reliability of my access products. On the other hand this application only has 160 forms, and about 30,000 lines of code.  It has about 65 highly related and noralized tables (relations enforced, and also cascade deletes).
So there's no particular programming approach needed here for multi user applications, the exception being good designs that reduce bandwidth requirements.
At the end of the day it turns out that good applications are ones that do not load unnecessary records into a form. It turns out that when you design your applications this way then when you change your backend part to SQL server you find this approach results in very little work needed to make your access front end work great with a SQL server back end.
At last count I think here's an estimate of close to 100 million access users around the world. Access is by far the most popular desktop database engine out there and for the most part users find they have trouble free operation.
The only people who have operational problems on networks are those that not split, and not placed the front end on each computer.

A: Also see Corrupt Microsoft Access MDBs FAQ    Which I've compiled over the years based on newsgroup postings and predates Allen's page.  That said my clients have had very few corruptions over the years and have never lost data nor had to restore from backup.
I'm not sure what "write your program correcly" means in this context.   I've read a few postings indicating this but it's more the implementation aspects.  As Albert has pointed out you have to split the database and give each user their own copy of the FE MDB/MDE.   You can't access a backend MDB over a wireless network card as they are too unstable.   Same with a WAN unless the WAN is very fast/wide and very stable.    We then suggest upszing to SQL Server or using Terminal Services/Citrix.
I have several clients running 20 to 25 users all day long into the system. One MDB has 120 tables while another has 160 tables.    A few tables have over 600,000 to 800,000 records.   The one client had 4 or 5 corruptions in five or seven years.   We figured out the cause of all but two of those.   And they were hardware related in one way or another. At least one of these apps should've been upsized to SQL Server. However that was cancelled on me by a Dilbert's PHB (Pointy Haired Boss).

A: The only compelling answers so far seem to be to reduce network traffic, and make sure your hardware cannot fail.
I find these answers unsatisfactory for a number of reasons.

*

*The network traffic position is contradictory.  If the database can only handle a certain amount of network traffic, then people need sensible guidelines to gauge this, so they can intelligently choose a database that is appropriate.

*Blaming Access database crashes on hardware failures is not a defensible position.  Users will (rightly) claim that their other software doesn't suffer from these kinds of problems.
Access database corruption is not an imaginary problem.  The people who regularly suggest that 5 to 20 users is the upper practical limit for Access applications are speaking from experience.

A: Very good code (wrapped in trasactions with rollbacks) we had a call center with over 100 very active users at a time back in Access 97 days.
Another one with VB 5 front-end, Access Jet on portables that RAS (yes the old dial up days) to a SQL Server 6 database - 250 concurrent users.
People using the wizard to link a form directly to a table where the form is used to make edits ... might be a problem.

A: Uncompleted transactions e.g a recordset that does not get closed properly and a break in network connection for any reason while a database is open (have seen the power saving features of NIC causing corruption) are my number one causes

A: I don't believe the number of users is a limitation with MS-Access Jet Engine.
My understanding is that the Jet Engine queues up concurrent maintenance transactions to apply them 1 at a time (like a printer queue does to print print jobs). Via ODBC connectivity, and an intelligent user-application program that manages the record set sizes, locking of records open for edit, and only maintains DB connections long enough to retrive a record and save a record, that puts little strain on the jet engine. I look at mdb file as tables. You can conceivably have 100s of these in one database, or more. The SQL querying to these tables would be by random access, and the naming convention of the mdb files lets the SQL query built in the applciations program which table (mdb file) to access. MS-Access databases can be 10s 100s or 1000s of Gigabytes this way and run smoothly. Proper indexing and normalizing of data to revent storing of redundant data also helps. I've never run into a database crash or concurrency issue with MS-Access and ODBC and Win32 Perl GUI interface driving the applciation.  I use no MS-Access Objects other than tables, indexes, and perhaps views/queries. And yes, I store the database on a dedicated PC and install my applications software on each workstation PC.


text:
Q: Synthesis getting stuck and not finishing due to this block of verilog code... any ideas why? This is the block of code causing the synthesis to get stuck
always @ (posedge M_AXIS_ACLK) begin
       if(force_enable && !stop_signal) begin
           for (j=0; j <31; j = j+2)begin
               buffer_data[j+buffer_counter]   <= (eqed_valid[j/2]) ? {23'b0 , eqed_vals[j]} : 64'b0 ;
               buffer_data[j+buffer_counter+1] <= (eqed_valid[j/2]) ? {23'b0 , eqed_vals[j+1]} : 64'b0 ;
           end
           buffer_counter <= buffer_counter + 32;
       end
    end

This is the block of code that sets up the force_enable and stop_signal which stops the buffer counter and the loop from running
/*
   SET THE BUFFER WIDTH FOR THE AXI STREAM. LETS HAVE 1024 BE DEFAULT VAL.
   Set the reset as well
*/
reg [31:0] buffer_max_counter;

always @ (posedge M_AXIS_ACLK) begin
   if(!M_AXIS_ARESETN) begin
       buffer_max_counter <= 32'b0;
   end
   buffer_max_counter <= ( buffer_width > 16384 || buffer_width < 1024) ? buffer_width_default: buffer_width;
end

always @ (posedge M_AXIS_ACLK) begin
   if(!M_AXIS_ARESETN) begin
       counter_to_force_enable <= 0;
       stop_signal <= 0;
       force_enable <= 0;
       for (i=0; i < 8192; i = i+1)begin
           buffer_data[i] <= 0 ;
       end
       valid_counter <= 0;
       eq_counter <= 0;
       buffer_counter <=0;
   end
   else begin
       if (M_AXIS_TLAST)begin
           stop_signal <= 0;
           buffer_counter <= 0;
       end
       if (enable_generator && !force_enable && !stop_signal) // staart the counter delay
           counter_to_force_enable <= counter_to_force_enable + 1;
       if (counter_to_force_enable >= 10 && (buffer_counter+32) < buffer_max_counter )begin //begin filling buffer
           force_enable <=1;
           stop_signal  <=0;
       end else if (counter_to_force_enable >= 10 && (buffer_counter+32) >= buffer_max_counter )  begin
            force_enable <= 0;
            stop_signal  <= 1;
            counter_to_force_enable <= 0 ;
       end else begin
            //do nothing
            force_enable <= force_enable;
       end
   end
end

I am guessing that the buffer_counter is the issue here since I am using it to index the array buffer_data and its not a constant.


text:
Q: getting bitmap null even though declared i am using fragments to open camera using intents.But when ever i set my ImageView using the bitmap,i get an null pointer exception.
CODE
public class UploadDocument extends MasterFragment implements View.OnClickListener {

    private TextView label;
    private Button btChooseDoc, btDocumentType, btUpload, btCancel;
    private EditText etTitle;
    private String[] chooseDocumentArray;
    private String userSelection = "";
    ImageView image;
    private Intent intent;
    Bitmap camera;

    public void onClick(View view) {

        setUp();

        switch (view.getId()) {

            case R.id.bt_choose_file:

                displayPopup(getActivity(), "Choose File", chooseDocumentArray, btChooseDoc, false, new GetNamePosition() {
                    @Override
                    public void getName(String name) {
                        userSelection = name;
                        if (userSelection.equals("Gallery")) {
                          intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, 0);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Camera")) {
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 1);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Other")) {
                            intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("file/*");
                            startActivityForResult(intent, 2);
                            btChooseDoc.setText("Choose File");
                        }
                    }

                    @Override
                    public void getPosition(int position) {

                    }
                });

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==1 && resultCode==getActivity().RESULT_OK){

            camera= (Bitmap) data.getExtras().get("data");
            camera.compress(Bitmap.CompressFormat.JPEG,100,null);
            image.setImageBitmap(camera);

        }

    }

LOGCAT
Caused by: java.lang.NullPointerException
            at android.graphics.Bitmap.compress(Bitmap.java:890)
            at example.com.pocketdocs.UploadDocument.UploadDocument.onActivityResult(UploadDocument.java:108)
            at android.app.Activity.dispatchActivityResult(Activity.java:5315)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3529)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3576)
            at android.app.ActivityThread.access$1100(ActivityThread.java:165)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
            at android.os.Handler.dispatchMessage(Handler.java:107)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5370)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)

i am using fragments to open camera using intents.But when ever i set my ImageView using the bitmap,i get an null pointer exception.
I have declared the bitmap above but still i am null pointer

A: You can try this -
image.post(
new Runnable(){
    image.setImageBitmap(camera)
});

need logcat data to give specific solution.

A: As you didn't post the log cat. I think the problem occurred
camera= (Bitmap) data.getExtras().get("data");

camera is null.So, you get NPE. This should be
camera= (Bitmap) data.getExtra("data");

also change the condition in onActivityResult(...)
if(requestCode==1 && resultCode==getActivity().RESULT_OK && data != null)

Try to recycle the bitmap you have used otherwise it cause outofmemoryexception
image.setImageBitmap(camera);
camera.recycle();


text:
Q: Can't create Jar via eclipse or manually I'm at my wits end.  I can't create a jar file (manually or through Eclipse).  I've followed instructions for creating the manifest and jar file manually.  The end result is that I get an error saying "The JavaJAR file 'widgetSamples.jar' could not be launched. Please check the console for possible errors."  The console doesn't register anything when I launch the jar file or when the error message pops.
In eclipse when I create the jar I do get warnings:
Exported with compile warnings: SWT Resources/src/widgetSamples.java
I created a separate simple program to see if it might have been something with my code but I can't even get a simple SWT display to open; I get the same error.  The code executes properly in Eclipse.
I have the 64 bit SWT installed as far as I know.  Any help is much appreciated.  Thanks.

A: Creating jar file using eclipse IDE
http://www.tutorialspoint.com/eclipse/eclipse_create_jar_files.htm
Creating jar using CMD
http://www.wikihow.com/Create-JAR-File


text:
Q: Can't encrypt Instagram requests using Charles Proxy Last year Facebook rolled out setting that allowed community to entrypt traffic using user installed certificates. I've successfully enabled whitehat settings for instagram account associated to my facebook account, and set them as seen on image.

I'm using Charles Proxy to monitor HTTPS traffic, however after applying these Instagram settings and enabling SSL proxying in Charles I can't read any requests and every action on Instagram app results in error like can't update feed. Disablind SSL proxying let's me use the app without errors, but all requests seen in Charles from Instagram are encrypted.

*

*I'm able to read requests from sites that doesn't use pinned
certificates like stackoverflow.com.

*On my mobile phone I
downloaded Charles certificate from chls.pro/ssl.

*tutorial I've followed, however I didn't understand  and did not do part past How to Find Version, VersionCode and Signature Key
Is there something I forgot to do or have done wrong way? Thanks in advance for any advises.


text:
Q: C# Sum values in a List with multiple columns Was following tutorial here https://www.tutorialspoint.com/chash-linq-sum-method to Sum up values in a list. But I have multiple columns so code fails at:
            double res = ProductList.AsQueryable().Sum();
            Console.WriteLine(res);

see end of the file here https://dotnetfiddle.net/vmtTuP for issue.

A: In a simple case, if you want to Sum some value, say, Qty, just specify it:
  double res = ProductList.Sum(item => item.Qty);

If you want to sum several values (say, both Qty and Tax) in one go you can use Aggregate:
  (double Qty, double Tax) res = ProductList
    .Aggregate((Qty : 0.0, Tax : 0.0), (s, a) => (s.Qty + a.Qty, s.Tax + a.Tax));

  Console.Write($"Qty = {res.Qty}; Tax = {res.Tax}");

A: You don't need AsQueryable() and all you need to do is specify the field of your object you wish to sum - for example if you wanted to sum Tax:
double res = ProductList.Sum(x => x.Tax);
Console.WriteLine(res);


text:
Q: Approximation of Sets of Finite Perimeter Fix an open set $\Omega \subset \mathbb{R}^n$. If $E$ is a measurable subset of $\Omega$, we may define the perimeter of $E$ in $\Omega$, denoted by $P(E;\Omega)$, to be
$$P(E;\Omega) = \sup_{\underset{||\phi||_{\infty} \leq 1}{\phi \in C^1_c(\Omega;\mathbb{R}^n)}} \int_E \mbox{div} \phi \, dx,$$
and when $P(E;\Omega) < +\infty$ we say that $E$ has finite perimeter in $\Omega$.
A basic property of any set of finite perimeter is that it may be approximated by sets with smooth boundary, in the following sense: for $E$ with $P(E;\Omega) < + \infty$, there exists a sequence $E_n$ such that $$\chi_{E_n} \xrightarrow{L^1} \chi_E$$ $$P(E_n; \Omega) \to P(E;\Omega),$$
where the $E_n = G_n \cap \Omega$ and the $G_n$ have smooth boundaries.
This is shown in Theorem 3.42 and Remark 3.43 of "Functions of Bounded Variation and Free Discontinuity Problems" by Ambrosio, Fusco, and Pallara. The basic argument involves first considering $\Omega = \mathbb{R}^n$, approximating $\chi_E$ by a sequence $\{u_n\}$ of smooth functions, and then defining $E_n = \{ u_n > t\}$ for an appropriate choice of $t$. The coarea formula, together with the lower-semicontinuity of the perimeter functional, can combine to prove that $P(E_n;\Omega) \to P(E;\Omega)$. The precise choice of $t$ is mostly irrelevant -- Sard's theorem implies that for almost every $0 < t < 1$ the resulting $E_n$ have smooth boundary. For more general $\Omega$, one needs some sort of extension operator (so there are some modest regularity conditions on $\Omega$ for this to be true).
My question is this: is it possible to do the same sort of approximation, but with the additional constraint $$m(E_n) = m(E),$$ where $m$ denotes Lebesgue measure? More specifically, are you aware of a result of this sort in the literature?


text:
Q: Know username who is working on remote desktop We are a team of 20 people we have a machine that is used by everyone. We take remote desktop of that machine to work on. so if somebody is working and i want to take that i have to ask everyone  in the team who is using it so that i can take the remote desktop of it. Is there any way so that i can directly know who is using remote desktop of that machine so that i don't have to ask everybody in the team.

A: If you can logon to that PC via remote desktop, you can use Task Manager and Users tab to view all users (active/disconnected).
If you cannot logon, then you can remotely issue the following command:
query session /server:hostnamehere
to get the same list of users.


text:
Q: WPF C# DataBinding List Finalization I have implemented a user control that contains a ListBox that is bound to a List:
listBox1.ItemsSource = list;

I have implemented a method that removes the (only) reference to the list:
listBox1.ItemsSource = null;

Having called this method, I force garbage collection:
GC.Collect();

The destructor of my list class is not being called. There is obviously some hidden reference to the list.
Any explanation of this behavior would be gratefully received.

A: list is not null, so it's still alive.
list = null;

A: The solution is to derive the list class from ObservableCollection(or something that implements INotifyCollectionChanged) rather than List.


text:
Q: Update Etsy listing via API Using DevDefined.OAuth I'm trying to update existing listing on Etsy.
Here is my code:
_consumerContext = new OAuthConsumerContext
        {
            ConsumerKey = _apiKey,
            ConsumerSecret = _apiSecret,
            SignatureMethod = SignatureMethod.HmacSha1
        };

_session = new OAuthSession(_consumerContext, "https://openapi.etsy.com/v2/oauth/request_token?scope=transactions_r%20email_r%20listings_r%20transactions_w%20listings_w",
            "https://www.etsy.com/oauth/signin",
            "https://openapi.etsy.com/v2/oauth/access_token");

            _accessToken = new TokenBase();
            _accessToken.ConsumerKey = _apiKey;
            _accessToken.Token = token;
            _accessToken.TokenSecret = tokenSecret;

            IConsumerRequest request = _session.Request(_accessToken)
                .Put()
                .ForUri(new Uri(string.Format("https://openapi.etsy.com/v2/listings/{0}", listing_id)));

            request.Context.QueryParameters.Add("listing_id", listing_id.ToString());
            request.Context.QueryParameters.Add("title", "New title");

            string response = ConsumerRequestExtensions.ReadBody(request);

But I receive 403 response all the time with message "signature_invalid".
When I create listing on Etsy using the same way (except method is POST, not PUT), everything works fine.
Am I missing something?

A: It depends what you mean by Update...  Much simplified response below, to create the initial listing on Etsy call:
...
request.Resource = "/listing"
request.Method = Method.POST;
...

Then, to update a listing including stock and price, you must ensure that you have the listing's offering id and product identifier from Etsy, and ensure that this is set in the request data.
To get the product_identifier and offering id, make a GET call:
...
request.Resource = "/listings/my-etsy-listing-id/inventory"
request.Method = Method.GET;
...

To make further changes for eg Stock or Price, make the following call:
...
request.Resource = "/listings/my-etsy-listing-id/inventory"
request.Method = Method.PUT;
...

To update title/description... call
...
request.Resource = "/listing/my-etsy-listing_id"
request.Method = Method.PUT;
...

As I said at the beginning, this is very much simplified. There is an awful lot of data that you need to send to do stuff in Etsy.

A: You can use the ETSY API method updateInventory to get your product listings updated on ETSY
$oauth = new OAuth(API KEYSTRING, API SHARED STRING);
$oauth->setToken($oauth_token, $oauth_token_secret);
$data = $oauth->fetch(
"https://openapi.etsy.com/v2/listings/$listing_id/inventory", [
'products' => $product_data
  'sku_on_property'      => ''
 ],
 OAUTH_HTTP_METHOD_PUT
 );

You can pass the product data as JSON in the $product_data fields to get your products updated on ETSY


text:
Q: Need to change the date format by using tuples in python def problem3_3(month, day, year):
months = ('January','February','March','April','May',"June",'July','August',
          'September','October','November','December')
new_date = months[5] + " " + str(day), str(year)

print(new_date)

The output is
('June 17', '2016') instead of June 17 , 2016
how do i remove these commas
Thank you.

A: The comma should be an string also, try something like this
months = ('January','February','March','April','May',"June",'July','August',
          'September','October','November','December')
new_date = months[5] + " " + str(day)+','+ str(year)

print(new_date)


text:
Q: convolution of nearly periodic data Suppose I have two vectors $x,y\in\mathbb{C}^n$. I am interested in efficient calculation of the convolution
$$z(k) = \sum_{i=0}^{n-1}x(i)y(i+k)$$
for $k=0,...,n-1$. Note that $y$ is taken nearly periodic i.e. $y(n+i)=\alpha y(i)$. For the simple case $\alpha=1$, this can be calculated efficiently using a Fourier-Transform as $x*y=\mathcal{F}^{-1}(\mathcal{F}(x)\mathcal{F}(y))$. Is there a generalization of this method to other values of $\alpha$?
(If general $\alpha\in\mathbb{C}$  are too tricky, pure phase factors, i.e. $\alpha=e^{i\phi}$ are probably enough for my usecase)


text:
Q: How to format text in input box with css I'm trying to change the font color of the placeholder text that appears in the input boxes before the visitor types any text.
Here's my example http://santa.parseapp.com/
See the text boxes at the bottom of the page. I think it's using a user agent stylesheet at the moment, which means the form elements dont have styles created?
I'm not sure which element I need to target with CSS. Here's what I've go:
form input[type=text] {
  width: 300px;
  margin-bottom: 7px;
  font-size: 20px;
  border: 0;
  padding: 5px 7px;
  background-color: #FF2950;
  color: #fff;
  }

A: It sounds like you're looking to style the placeholder text, yeah?
Generally speaking, placeholder text gets the same styling as the element itself, apart from the colour. So in your example, the placeholder text will be color: grey and font-size: 20px.
If you want to target the placeholder text specifically, you need to use the :placeholder psuedo-class:
::-webkit-input-placeholder {
   color: blue;
}

::-moz-placeholder {
   color: blue;
}

:-ms-input-placeholder {
   color: blue;
}

A: Check this fiddle:
http://jsfiddle.net/7r2d9/1/
form input[type=text]:focus {
  color: black;
}


text:
Q: Define a custom AndroidManifest property to fastlane I have a custom variable on both build.gradle and AndroidManifest.xml:
android {
   defaultConfig {
      manifestPlaceholders.myCustomProperty = "#"
   }
}

and
<meta-data
   android:name="CUSTOM_PROPERTY"
   android:value="${myCustomProperty} />

I want to define myCustomProperty in Fastfile. None of the following work:
gradle(
    task: "assemble"
    ...
    properties {
        "manifestPlaceholders.myCustomProperty" => "Value 1",
        "myCustomProperty" => "Value 2",
        "android.defaultConfig.manifestPlaceholders.myCustomProperty" => "Value 3"
    }
)

I always get # when using myCustomProperty in the app (after building it with Fastfile).


text:
Q: Android firebase dynamic link I have created a dynamic link in firebase console, this dynamic link points to an app in Play Store (i.e. I use this link to share this app with other users via WhatsApp). Also I receive the deep link in my app through getDynamicLink method.
When I append a query parameter(?invite=494556) to dynamic link the Play Store page appears but I cannot receive the deep link in getDynamic link method it's null. How to do I append query parameters to dynamic link and recieve it when is installed?
I cannot use firebase invite as I want to share via WhatsApp.

A: In the getDynamicLink() success listener of Firebase we get the deeplink url and means we get the data which we put in deeplink url while creating dynamic link from the firebase console. So in your case, you need to provide  data(invite=494556) in the deeplink url like this: https://INVITE/494556. On the app side you can listen for the string "INVITE" and, whenever your deeplink url contains this string, it means the number at first index is what you are looking for. You can implement different deeplinks in this way, you need to just change the string and provide whichever data you need.


text:
Q: How to monitor website status with AWS Lambda and CloudWatch? I have to monitor a website if it works - response looks like following:
{"response":
  {"time": 1457564305},
  "stat": "OK"
}
And need sending mail alert to me if stat is not OK.
Seems this can be done with Lambda using node.js and CloudWatch.
I tried to create Lambda function and execute through CloudWatch but only see the function was triggered.   Seems I need to push some metrics?
I'm newbie to node.js and Lambda (handler, metrics, etc.).
Would anyone share some hints on where I should start with?
Thanks a lot.

A: Not sure what you mean by "only see the function was triggered".
Yes, you can cause a Lambda function to be invoked on a schedule. That Lambda function could issue a request to the website and trigger a notification to an SNS topic if it believes the site to be down. You would subscribe (by email address or SMS) to the SNS topic for notifications. Here's an example of how to do this.


text:
Q: what is the difference between servlet container and spring container? What are the roles and responsibility of servlet container and spring container? Please someone clarify my doubts.

A: Spring container is responsible for creating the objects, wiring them together, configuring them, and managing their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application. These objects are called Spring Beans.
While Servlet container is basically web server or application server one who is responsible for creating and maintaining life cycle of a servlet like init, service, destroy in a nut shell. It has other functionalities as well in addition to maintaining lifecycle of a servlet.

A: They are very different concepts also if their names are similar.
A Servlet Container or Web Container (like Tomcat) is an implementation of various Java EE specifications like Java Servlet, JSP, etc. Put in a simple way, it is an environment where Java web applications can live. A web server + Java support.
A Spring Container on the other hand, is the core and the engine of the Spring Framework. It is an IoC Container that handles Spring applications lifecycle creating new beans and injecting dependencies.
Because a Spring application can be a web application, a Spring Container can "live" inside a Web Container.
For further information:

*

*about Servlet Container: http://en.wikipedia.org/wiki/Web_container

*about Spring Container: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html


text:
Q: Best way to insert values multiple times from data layer to stored procedure? Hi
I have DAL Layer, from where invoking a stored procedure to insert values into the table.
E.g.:-
CREATE PROCEDURE [dbo].[DataInsert]
    @DataName nvarchar(64)
AS
BEGIN
    INSERT INTO
         table01 (dataname)
        VALUES
    (@dataname)
END

Now as requirement changed, per client request i have to add values 5 times. So what is the best practice?
Do i call this Stored Procedure 5 times from my DAL?
or
Pass all the values (may be comma separated) to storedprocedure in one go and then let the stored procedure add it for 5 times?
BTW. Its not always 5 times. It is changeable.

A: You could create a user-defined table type;
CREATE TYPE [dbo].[SomeInfo] AS TABLE(
[Id] [int] NOT NULL,
[SomeValue] [int] NOT NULL )

Define your stored proc as such;
CREATE PROCEDURE [dbo].[AddSomeStuff]
    @theStuff [SomeInfo] READONLY
AS
BEGIN
    INSERT INTO SOMETABLE ([...columns...])
    SELECT [...columns...] from @theStuff
END

Then you'll need to create a datatable (called table below) that matches the schema and call the stored proc as so;
var cmd = new SqlCommand("AddSomeStuff", sqlConn) {CommandType = CommandType.StoredProcedure};

var param = new SqlParameter("@theStuff", SqlDbType.Structured) {Value = table};
cmd.Parameters.Add(param);

cmd.ExecuteNonQuery();

A: btw this proc works - I've just written and tested it see results below!
CREATE PROCEDURE [dbo].[DataInsert]
     @DataName nvarchar(max) AS
BEGIN
DECLARE @pos SMALLINT, @str VARCHAR(max)

WHILE @DataName <> ''
BEGIN
    SET @pos = CHARINDEX(',', @DataName)
    IF @pos>0
        BEGIN
            SET @str = LEFT(@DataName, @pos-1)
            SET @DataName = RIGHT(@DataName, LEN(@DataName)-@pos)
        END
    ELSE
        BEGIN
            SET @str = @DataName
            SET @DataName = ''
        END

   INSERT INTO table01 VALUES(CONVERT(VARCHAR(100),@str))

END
END
GO

then run it: -
EXEC    @return_value = [dbo].[DataInsert]
        @DataName = N'five, bits, of, your, data'
*rows from table01: *
five
bits
of
your
data
(5 row(s) affected)

A: I'd either call your proc repeatedly(that would be my choice), or else you could use XML to pass in a list of values as a single parameter.
http://support.microsoft.com/kb/555266

A: Instead of fancy SQL code that is difficult to maintain and is not scalable, I would simply go to invoking your stored procedure multiple times.
If performance or transactional behavior is an issue, you can consider to send the commands in a single batch.
You talked about 5 insert. If the number of record to insert is much greater, you could consider bulk insert as well.


text:
Q: create UML Diagrams with netbeans 7.1.2 I am using netbeans 7.1.2 to create my GUI application. I would like to know how to create a class diagram from my source code (reverse engineering) because i do not see any plug in information on the web. If anyone has any experience with this software please let me know

A: The latest version of NetBeans does not have this feature. Version 6.7 and earlier included this feature. If I remember correctly you had the ability to sync changes both ways.
More here: http://netbeans.org/features/uml/


text:
Q: Show that $\limsup |s_n|=0$ iff $\lim s_n=0$. First suppose $\lim s_n = 0$. then from the definition we know that for all $\epsilon>0$ there exist an $N\in\mathbb{N}$ such that for all $n\in\mathbb{N}$ with $n>N$ we have,
\begin{align*}
|s_n-0| = |s_n|<\epsilon.
\end{align*}
It follows then that for $\epsilon$, $N$, and $n$ as before we have,
\begin{align*}
|s_n| = ||s_n|-0|<\epsilon.
\end{align*}
So $\lim |s_n|=0$. It follows from a theorem discussed in class that $\limsup|s_n|=\lim|s_n|=0$.
Now conversely suppose that $\limsup |s_n| = 0$. We know that,
\begin{align*}
\liminf|s_n|\le\limsup|s_n| = 0.
\end{align*}
However $|s_n|\ge 0$ for all $n\in\mathbb{N}$. So it follows that $\liminf|s_n|=0$.  Since $\liminf|s_n|=\limsup|s_n|=0$ it follows that $\lim|s_n|=0$. Now since $\lim|s_n|=0$, we know that for every $\epsilon>0$ there is an $N\in\mathbb{N}$, such that for all $n>N$ we have,
\begin{align*}
||s_n|-0|=|s_n|<\epsilon.
\end{align*}
Which implies that for $\epsilon$, $N$, and $n$ as above we have
\begin{align*}
|s_n-0|<\epsilon.
\end{align*}
Hence $\lim s_n=0$ as needed.
indent Therefore $\limsup |s_n| = 0$ if and only if $\lim s_n=0$. Q.E.D.
Is this proof correct, if not can I get a hint as to whats wrong with it.


text:
Q: How to rollback database in case of an IntegrityError in Django? The following static method (taken from flasky) is a way to populate the database with fake data, and I want to import it to Django.

models.py

class User(UserMixin, db.Model):

    # ......

    @staticmethod
    def generate_fake(count=100):
        from sqlalchemy.exc import IntegrityError
        from random import seed
        import forgery_py

        seed()
        for i in range(count):
            u = User(email=forgery_py.internet.email_address(),
                     username=forgery_py.internet.user_name(True),
                     password=forgery_py.lorem_ipsum.word(),
                     confirmed=True,
                     name=forgery_py.name.full_name(),
                     location=forgery_py.address.city(),
                     about_me=forgery_py.lorem_ipsum.sentence(),
                     member_since=forgery_py.date.date(True))
            db.session.add(u)
            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()

The problem is, while I can do something like User.objects.create(...), I don't know how to rollback the database in case an IntegrityError happens (presumable due to a duplicate primary key).

A: By default, Django makes SQL queries in auto-commit mode, where every query is wrapped in a transaction, so you should not worry about an integrity error messing up your database. If an integrity error happens, Django won't insert the data.
To be extra-safe, you can wrap the creation code in a transaction, that in Django, is implemented as a python context handler:
from django.db import transaction

with transaction.atomic():
    User.objects.create(...)

But that would be unnecessary! You can read more about Transactions and how Django handles them in this documentation page.


text:
Q: Why did the station only have non-lethal guns? In season 2 episode 2, "Doors and Corners" while boarding the space station, guards attack the boarding party with non-lethal gel rounds.
Its mentioned that they're fitted up more like prison guards.
Later on the scientists they find seem to not be aware of their situation, and although initially violent, the only surviving scientist seems proud of the work they were doing.
Based on this I assume some of the other scientists might not have been as willing to work voluntarily, and potentially some would get unplugged every now and then and become violent.
This answer seems a bit odd to me given that they didn't seem aware of the outside world. Is there any more explanation to this?

A: A bit on insight on the topic from The Vital Abyss, the novelette from James Corey

Everyone in research had undergone the treatment, which admittedly posed some problems. Singh in computational biology held forth on her theory of the protomolecule as a Guzman-style quantum computer one night over dinner, and when Kibushi used the information without citing her, she snuck into the showers at the gymnasium and beat him to death with a ceramic workbench cap. After that, security kept a closer eye on us all, but they also switched to nonlethal weapons. Singh, while formally reprimanded by Dresden, kept her status on her team. It only tended to confirm what we all already knew: Morality as we had known it no longer applied to us.

A: In the book, Dresden explains that

"We modified our science team to remove ethical restraints."
Half a dozen clues clicked into place in Holden's head.
"Sociopaths," he said. "You turned them into sociopaths."
"High-functioning sociopaths," Dresden said with a nod. He seemed pleased to explain it. "And extremely curious ones. As long as we kept them supplied with interesting problems to solve and unlimited resources, they remained quite content."
"And a big security team armed with riot control rounds for when they aren't," Fred said.
"Yes, there are occasional issues," Dresden said.
Leviathan Wakes, Chapter Forty-One: Holden

In the following episode of the TV show ("Static") it is revealed that as in the book an operation was performed on the scientists -- including the surviving scientist, Paolo Cortázar -- to remove their empathy so that they could carry out their research. While the TV show does not provide an explicit explanation like the book, presumably the use of non-lethal gel rounds was for the same reason as in the book (to end occasional riots by crazy scientists). The problem was not that some of the scientists were unwilling to work voluntarily.