text:
Q: WCF Concurrent requests piling up on the server when using WSHttpBinding I have a WCF client/server app which is communicating over HTTP using the WSHttpBinding.
Server Setup: self-hosting, using the standard WCF ServiceHost.
My actual service class is attributed as:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple,
 InstanceContextMode = InstanceContextMode.PerSession,
 UseSynchronizationContext = false)]

Client Setup: using a visual-studio generated client proxy using synchronous service calls (proxy.call_server_method blocks until such time as the server has responded in full.)
Scenario:
I have one particular method call which takes 20 seconds to execute on the server. The client calls this method in a separate thread, so it is not being held up, and the ConcurrencyMode.Multiple means WCF should execute it in a separate thread on the server as well.
This theory is supported by the fact that when I configure my app to use NetTcpBinding, everything works fine.
Problem:
If I configure the app to use WSHttpBinding, then this long method call causes the http requests to 'back up'. I have verified this behaviour both from inspecting my logs, and by debugging the HTTP requests using fiddler.
Example:

*

*Client initiates 20-second long request on a background thread

*Client initiates request B and C on foreground thread

*Requests B and C get sent to the server, which doesn't process them until it is done with the 20-second long request

But sometimes:

*

*Requests B and C do not get sent (they don't even appear in fiddler) until the 20-second request comes back  (this is rare).

*

*Note: setting <add address="*" maxconnection="100"/> in the client's app.config made this (appear to) stop happening.

*Request B gets sent and receives a response immediately, while request C is held back until the 20-second one completes (this is rare)

Here's a timeline from fiddler demonstrating the problem: (click for bigger version)

As you can see, the requests are all getting backed up at the server. Once the 20-second request completes, the responses all come flooding through, but note that there are some requests which aren't getting held up...
So, Questions:

*

*What the heck is going on here? Why does it work fine using NetTcpBinding and not work using WSHttpBinding?

*Why the inconsistent behaviour?

*What can I do to fix it?

Notes:

*

*It's not locking on the server. I've set breakpoints and used !syncblk and it consistently reports no locks are being held.

*It's not my threading (NetTcpBinding shouldn't work otherwise)

*I have <serviceThrottling maxConcurrentCalls="1000" maxConcurrentInstances="1000" maxConcurrentSessions="1000" /> set in the server's app.config

*The 20-second call is just waiting on a timer, it's not thrashing the CPU or disk or network

*I'd prefer a solution that didn't involve re-architecting the application to use asynchronous calls... it's a big bunch of legacy code and I really don't want to be messing with stuff I don't understand.

A: We saw exactly the same symptoms with a JSON service hosted in IIS/ASP.NET.
The root cause ended up being ASP.NET synchronizing the requests - not WCF. We had to disable session state (at the application level) to get concurrent WCF methods.
Web.config:
<system.web> <sessionState mode="Off" /> </system.web>
Please note that our service uses webHttpBinding, not wsHttpBinding. So, I'm not sure if this also solves Orion's problem.

A: [Self-answer to show other users what our eventual solution was]
In the end, I never managed to solve this.
Our final solution was to switch our app away from WSHttpBinding and onto NetTcpBinding in production - we had been planning on doing this eventually anyway for performance reasons.
This is rather unfortunate though, as it leaves a black mark on WSHttpBinding which may or may not be warranted. If anyone does ever come up with a solution which does not involve ditching WSHttpBinding, I'd love to know about it

A: I think you hit the protocol limit and to work around it you need to modify the standard settings on the client machine:
http://support.microsoft.com/kb/183110
http://support.microsoft.com/kb/282402
I guess WSHttpBinding uses WinINET settings when issuing the requests.

A: There is some throttle outside of WCF (a .Net or Windows thing) that defaults to only letting a maximum of two simultaneous outbound HTTP connections.  Unfortunately I can't remember for the life of me the name of the thing (and what you'd put in app.config or your app to override it).  Given that you're not seeing the requests leave the client, and that it's only HTTP, I think you're hitting "that thing".  I'll keep looking for its name.
Update: Found it - try this on the client (but change the '2' to a bigger number):
<configuration>
  <system.net>
    <connectionManagement>
      <add address = "*" maxconnection = "2" />
    </connectionManagement>
  </system.net>
</configuration>

A: If you change to BasicHttpBinding, does it work?
Is so, it sounds like this is your problem, Session throttling, something that bit me in the ass.

A: Consider using ConcurrencyMode.Multiple on per-call services to allow concurrent
calls.

A: I forget - could it be ordering?  I think maybe RM over http preserves order but maybe Tcp sessions don't (unless you explicitly request it)?  Is there an attribute on the Service Contract that described ordered/unordered sessions (I forget).

A: Not sure but sometimes the problem with the concurrent calls from silverlight application are related with browser connection management. For me the solution was to put that in our App.xaml.cs, Application_Startup method as descrive here: http://weblogs.asp.net/olakarlsson/simultaneously-calling-multiple-methods-on-a-wcf-service-from-silverlight
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);


text:
Q: Fullcalendar timeGridWeek and timeGridDay not loading correctly For my calendar, I'm trying to use the timeGridWeek and timeGridDay views. Instead of loading correctly like this:
it loads like this:
My calendar defaultview is dayGridMonth, which works fine. When I click the buttons that change the view to week or day, it doesn't render correctly AND also doesn't let me change the view further with button clicks (essentially I'm stuck in the view I selected).
Here is my code for the calendar element + imports:
import timeGridPlugin from "@fullcalendar/timegrid";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin, { Draggable } from "@fullcalendar/interaction";

          <FullCalendar
            ref={this.calendarRef}
            defaultView="dayGridMonth"
            height={"parent"}
            width={"parent"}
            droppable={true}
            drop={this.handleDrop}
            dateClick={this.handleDateClick}
            eventClick={this.handleEventClick}
            header={{
              left: "prev,next, today",
              center: "title",
              right: "dayGridMonth,timeGridWeek,timeGridDay"
            }}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            editable={true}
            events={this.state.events}
            eventLimit={true}
          />

Thanks in advance :)

A: Nevermind, it's fixed! it seems to just be wonky rendering on the local side. When I hosted the app on heroku the timeGridWeek and day both rendered fine. It seems to have just been a faulty installation.

A: make sure all minor versions of core and plugins are the same, like 4.4.2, not one 4.4.2 other 4.4.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change the background color on hover for a Monaco editor delta decoration? Looking at the playground example, I can create and apply delta decorations just fine:
var editor = monaco.editor.create(document.getElementById("container"), {
    value: "var a = true",
    language: "javascript"
});

var decorations = editor.deltaDecorations([], [
    { range: new monaco.Range(3,1,5,1), options: { isWholeLine: true, linesDecorationsClassName: 'myLineDecoration' }},
    { range: new monaco.Range(7,1,7,24), options: { inlineClassName: 'myInlineDecoration' }},
]);

However, the :hover variants of the css aren't respected at all for the decoration className at all.
The :hover variant for inlineClassName is respected, but only for the specific block I hover over, not the entire decoration:

I know Monaco's dom manipulation is very complex (and it's amazing it works in the browser so well!) so this may be expected.
Is there some way to affect the :hover background color of a Monaco editor delta decoration?


text:
Q: D3 selections based on json data Is there any way to style elements based on how deep they are in JSON? I want to grab the top most level of JSON data and second level and be able to style it different each level it goes in. As far as I know I can only style all elements like so:
d3.select('g').style({opacity:'0.5'})

not sure how I would do this based on JSON children.
example would be here http://bl.ocks.org/mbostock/4063550
If I wanted to style "flare" different from analytics:
{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 3938},
      {"name": "CommunityStructure", "size": 3812},
      {"name": "HierarchicalCluster", "size": 6714},
      {"name": "MergeEdge", "size": 743}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "BetweennessCentrality", "size": 3534},
      {"name": "LinkDistance", "size": 5731},
      {"name": "MaxFlowMinCut", "size": 7840},
      {"name": "ShortestPaths", "size": 5914},
      {"name": "SpanningTree", "size": 3416}
     ]
    },
    {
     "name": "optimization",
     "children": [
      {"name": "AspectRatioBanker", "size": 7074}
     ]
    }
   ]
  },
  {
   "name": "animate",
   "children": [
    {"name": "Easing", "size": 17010},
    {"name": "FunctionSequence", "size": 5842},
    {
     "name": "interpolate",
     "children": [
      {"name": "ArrayInterpolator", "size": 1983},
      {"name": "ColorInterpolator", "size": 2047},
      {"name": "DateInterpolator", "size": 1375},
      {"name": "Interpolator", "size": 8746},
      {"name": "MatrixInterpolator", "size": 2202},
      {"name": "NumberInterpolator", "size": 1382},
      {"name": "ObjectInterpolator", "size": 1629},
      {"name": "PointInterpolator", "size": 1675},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
    },
    {"name": "ISchedulable", "size": 1041},
    {"name": "Parallel", "size": 5176},
    {"name": "Pause", "size": 449},
    {"name": "Scheduler", "size": 5593},
    {"name": "Sequence", "size": 5534},
    {"name": "Transition", "size": 9201},
    {"name": "Transitioner", "size": 19975},
    {"name": "TransitionEvent", "size": 1116},
    {"name": "Tween", "size": 6006}
   ]
  },
  {
   "name": "data",
   "children": [
    {
     "name": "converters",
     "children": [
      {"name": "Converters", "size": 721},
      {"name": "DelimitedTextConverter", "size": 4294},
      {"name": "GraphMLConverter", "size": 9800},
      {"name": "IDataConverter", "size": 1314},
      {"name": "JSONConverter", "size": 2220}
     ]
    },
    {"name": "DataField", "size": 1759},
    {"name": "DataSchema", "size": 2165},
    {"name": "DataSet", "size": 586},
    {"name": "DataSource", "size": 3331},
    {"name": "DataTable", "size": 772},
    {"name": "DataUtil", "size": 3322}
   ]
  },
  {
   "name": "display",
   "children": [
    {"name": "DirtySprite", "size": 8833},
    {"name": "LineSprite", "size": 1732},
    {"name": "RectSprite", "size": 3623},
    {"name": "TextSprite", "size": 10066}
   ]
  },
  {
   "name": "flex",
   "children": [
    {"name": "FlareVis", "size": 4116}
   ]
  },
  {
   "name": "physics",
   "children": [
    {"name": "DragForce", "size": 1082},
    {"name": "GravityForce", "size": 1336},
    {"name": "IForce", "size": 319},
    {"name": "NBodyForce", "size": 10498},
    {"name": "Particle", "size": 2822},
    {"name": "Simulation", "size": 9983},
    {"name": "Spring", "size": 2213},
    {"name": "SpringForce", "size": 1681}
   ]
  },
  {
   "name": "query",
   "children": [
    {"name": "AggregateExpression", "size": 1616},
    {"name": "And", "size": 1027},
    {"name": "Arithmetic", "size": 3891},
    {"name": "Average", "size": 891},
    {"name": "BinaryExpression", "size": 2893},
    {"name": "Comparison", "size": 5103},
    {"name": "CompositeExpression", "size": 3677},
    {"name": "Count", "size": 781},
    {"name": "DateUtil", "size": 4141},
    {"name": "Distinct", "size": 933},
    {"name": "Expression", "size": 5130},
    {"name": "ExpressionIterator", "size": 3617},
    {"name": "Fn", "size": 3240},
    {"name": "If", "size": 2732},
    {"name": "IsA", "size": 2039},
    {"name": "Literal", "size": 1214},
    {"name": "Match", "size": 3748},
    {"name": "Maximum", "size": 843},
    {
     "name": "methods",
     "children": [
      {"name": "add", "size": 593},
      {"name": "and", "size": 330},
      {"name": "average", "size": 287},
      {"name": "count", "size": 277},
      {"name": "distinct", "size": 292},
      {"name": "div", "size": 595},
      {"name": "eq", "size": 594},
      {"name": "fn", "size": 460},
      {"name": "gt", "size": 603},
      {"name": "gte", "size": 625},
      {"name": "iff", "size": 748},
      {"name": "isa", "size": 461},
      {"name": "lt", "size": 597},
      {"name": "lte", "size": 619},
      {"name": "max", "size": 283},
      {"name": "min", "size": 283},
      {"name": "mod", "size": 591},
      {"name": "mul", "size": 603},
      {"name": "neq", "size": 599},
      {"name": "not", "size": 386},
      {"name": "or", "size": 323},
      {"name": "orderby", "size": 307},
      {"name": "range", "size": 772},
      {"name": "select", "size": 296},
      {"name": "stddev", "size": 363},
      {"name": "sub", "size": 600},
      {"name": "sum", "size": 280},
      {"name": "update", "size": 307},
      {"name": "variance", "size": 335},
      {"name": "where", "size": 299},
      {"name": "xor", "size": 354},
      {"name": "_", "size": 264}
     ]
    },
    {"name": "Minimum", "size": 843},
    {"name": "Not", "size": 1554},
    {"name": "Or", "size": 970},
    {"name": "Query", "size": 13896},
    {"name": "Range", "size": 1594},
    {"name": "StringUtil", "size": 4130},
    {"name": "Sum", "size": 791},
    {"name": "Variable", "size": 1124},
    {"name": "Variance", "size": 1876},
    {"name": "Xor", "size": 1101}
   ]
  },
  {
   "name": "scale",
   "children": [
    {"name": "IScaleMap", "size": 2105},
    {"name": "LinearScale", "size": 1316},
    {"name": "LogScale", "size": 3151},
    {"name": "OrdinalScale", "size": 3770},
    {"name": "QuantileScale", "size": 2435},
    {"name": "QuantitativeScale", "size": 4839},
    {"name": "RootScale", "size": 1756},
    {"name": "Scale", "size": 4268},
    {"name": "ScaleType", "size": 1821},
    {"name": "TimeScale", "size": 5833}
   ]
  },
  {
   "name": "util",
   "children": [
    {"name": "Arrays", "size": 8258},
    {"name": "Colors", "size": 10001},
    {"name": "Dates", "size": 8217},
    {"name": "Displays", "size": 12555},
    {"name": "Filter", "size": 2324},
    {"name": "Geometry", "size": 10993},
    {
     "name": "heap",
     "children": [
      {"name": "FibonacciHeap", "size": 9354},
      {"name": "HeapNode", "size": 1233}
     ]
    },
    {"name": "IEvaluable", "size": 335},
    {"name": "IPredicate", "size": 383},
    {"name": "IValueProxy", "size": 874},
    {
     "name": "math",
     "children": [
      {"name": "DenseMatrix", "size": 3165},
      {"name": "IMatrix", "size": 2815},
      {"name": "SparseMatrix", "size": 3366}
     ]
    },
    {"name": "Maths", "size": 17705},
    {"name": "Orientation", "size": 1486},
    {
     "name": "palette",
     "children": [
      {"name": "ColorPalette", "size": 6367},
      {"name": "Palette", "size": 1229},
      {"name": "ShapePalette", "size": 2059},
      {"name": "SizePalette", "size": 2291}
     ]
    },
    {"name": "Property", "size": 5559},
    {"name": "Shapes", "size": 19118},
    {"name": "Sort", "size": 6887},
    {"name": "Stats", "size": 6557},
    {"name": "Strings", "size": 22026}
   ]
  },
  {
   "name": "vis",
   "children": [
    {
     "name": "axis",
     "children": [
      {"name": "Axes", "size": 1302},
      {"name": "Axis", "size": 24593},
      {"name": "AxisGridLine", "size": 652},
      {"name": "AxisLabel", "size": 636},
      {"name": "CartesianAxes", "size": 6703}
     ]
    },
    {
     "name": "controls",
     "children": [
      {"name": "AnchorControl", "size": 2138},
      {"name": "ClickControl", "size": 3824},
      {"name": "Control", "size": 1353},
      {"name": "ControlList", "size": 4665},
      {"name": "DragControl", "size": 2649},
      {"name": "ExpandControl", "size": 2832},
      {"name": "HoverControl", "size": 4896},
      {"name": "IControl", "size": 763},
      {"name": "PanZoomControl", "size": 5222},
      {"name": "SelectionControl", "size": 7862},
      {"name": "TooltipControl", "size": 8435}
     ]
    },
    {
     "name": "data",
     "children": [
      {"name": "Data", "size": 20544},
      {"name": "DataList", "size": 19788},
      {"name": "DataSprite", "size": 10349},
      {"name": "EdgeSprite", "size": 3301},
      {"name": "NodeSprite", "size": 19382},
      {
       "name": "render",
       "children": [
        {"name": "ArrowType", "size": 698},
        {"name": "EdgeRenderer", "size": 5569},
        {"name": "IRenderer", "size": 353},
        {"name": "ShapeRenderer", "size": 2247}
       ]
      },
      {"name": "ScaleBinding", "size": 11275},
      {"name": "Tree", "size": 7147},
      {"name": "TreeBuilder", "size": 9930}
     ]
    },
    {
     "name": "events",
     "children": [
      {"name": "DataEvent", "size": 2313},
      {"name": "SelectionEvent", "size": 1880},
      {"name": "TooltipEvent", "size": 1701},
      {"name": "VisualizationEvent", "size": 1117}
     ]
    },
    {
     "name": "legend",
     "children": [
      {"name": "Legend", "size": 20859},
      {"name": "LegendItem", "size": 4614},
      {"name": "LegendRange", "size": 10530}
     ]
    },
    {
     "name": "operator",
     "children": [
      {
       "name": "distortion",
       "children": [
        {"name": "BifocalDistortion", "size": 4461},
        {"name": "Distortion", "size": 6314},
        {"name": "FisheyeDistortion", "size": 3444}
       ]
      },
      {
       "name": "encoder",
       "children": [
        {"name": "ColorEncoder", "size": 3179},
        {"name": "Encoder", "size": 4060},
        {"name": "PropertyEncoder", "size": 4138},
        {"name": "ShapeEncoder", "size": 1690},
        {"name": "SizeEncoder", "size": 1830}
       ]
      },
      {
       "name": "filter",
       "children": [
        {"name": "FisheyeTreeFilter", "size": 5219},
        {"name": "GraphDistanceFilter", "size": 3165},
        {"name": "VisibilityFilter", "size": 3509}
       ]
      },
      {"name": "IOperator", "size": 1286},
      {
       "name": "label",
       "children": [
        {"name": "Labeler", "size": 9956},
        {"name": "RadialLabeler", "size": 3899},
        {"name": "StackedAreaLabeler", "size": 3202}
       ]
      },
      {
       "name": "layout",
       "children": [
        {"name": "AxisLayout", "size": 6725},
        {"name": "BundledEdgeRouter", "size": 3727},
        {"name": "CircleLayout", "size": 9317},
        {"name": "CirclePackingLayout", "size": 12003},
        {"name": "DendrogramLayout", "size": 4853},
        {"name": "ForceDirectedLayout", "size": 8411},
        {"name": "IcicleTreeLayout", "size": 4864},
        {"name": "IndentedTreeLayout", "size": 3174},
        {"name": "Layout", "size": 7881},
        {"name": "NodeLinkTreeLayout", "size": 12870},
        {"name": "PieLayout", "size": 2728},
        {"name": "RadialTreeLayout", "size": 12348},
        {"name": "RandomLayout", "size": 870},
        {"name": "StackedAreaLayout", "size": 9121},
        {"name": "TreeMapLayout", "size": 9191}
       ]
      },
      {"name": "Operator", "size": 2490},
      {"name": "OperatorList", "size": 5248},
      {"name": "OperatorSequence", "size": 4190},
      {"name": "OperatorSwitch", "size": 2581},
      {"name": "SortOperator", "size": 2023}
     ]
    },
    {"name": "Visualization", "size": 16540}
   ]
  }
 ]
}

A: While using hierarchical layouts, including tree layout, d3 conveniently adds a depth field to the transformed data.
You can make the attributes depend on this data by providing an accessor method which is called with the element's data and index and return a value from it instead of providing a constant.
Example:

d3.json("flare.json", function(error, root) {
  var nodes = tree.nodes(root);

  var node = svg.selectAll(".node")
      .data(nodes)
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; });

  // The radius is now dependent on how deep the node is.
  node.append("circle")
      .attr("r", function (d, idx) { return 5 / d.depth; });

  // ...

});


text:
Q: What is happening while printing even odd numbers using interrupt method? I am trying to print even odd numbers using two threads with interrupt method.
I refereed code from internet and wrote a code showing below.It prints properly but after prints 20,program is continuing it's execution.

*

*What change do i have to make in the code to stop the execution of the program?

*Without oldNum check code is working fine. Is there any logic to provide oldNum check ?

*If I remove Thread.sleep(1000L) from Line-a then it only prints "Even Thread  prints 20" and continue execution.What is happening here?

*Provided break points inside run() method and inside for loop of main method ,run() methods break points are not hitting.Why this is happening?
In short I want to know what is the code flow here.
Thanks
Vikash
public class PrintOddEvenUsingInterrupt {

public static volatile int count;
  public static void main(String[] args) throws InterruptedException {
    Thread oddThread = new Thread(new OddInterruptThread(), "Odd Thread ");
    Thread evenThread = new Thread(new EvenInterruptThread(),"Even Thread ");

    oddThread.start();
    evenThread.start();
    for (int i = 0; i < 20; i++) {
        count++;
        oddThread.interrupt();//Break points works here
        evenThread.interrupt();
        Thread.sleep(1000L);// Line-a
    }
}

static class OddInterruptThread implements Runnable {
    public void run() {
        int oldNum = 0;//Break points doesn't works here
        while (true) {
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
            }

            if (oldNum != count && count % 2 == 1) {
                System.out.println(Thread.currentThread().getName()
                        + " prints " + count);
                oldNum = count;
            }
        }
    }
}

static class EvenInterruptThread implements Runnable {
    public void run() {
        int oldNum = 0;//Break points doesn't works here
        while (true) {
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
            }

            if (oldNum != count && count % 2 == 0) {
                System.out.println(Thread.currentThread().getName()
                        + " prints " + count);
                oldNum = count;
            }
        }
    }
}
}

A: The reason your program is not stopping is: while your main thread exits, your odd and even threads sleeps in infinite loop.
You will need to define a stopping condition for your threads to come out.
One way to achieve this is via using conditions.
Eg:
public volatile static boolean oddFinished = false;
public volatile static boolean evenFinished = false;

Then in your threads, instead of looping infinitely, loop against condition
    while (! oddFinished){
        // also change your thread sleep to sleep for fewer time interval (say 1000L or whatever your program wants to wait for)
    }
Do the same for even thread...
while (! evenFinished){
    // also change your thread sleep to sleep for fewer time interval (say 1000L or whatever your program wants to wait for)
}

And in the main thread, you can add the following code after your for loop ends...
oddFinished = true;
evenFinished = true;

oddThread.join();
evenThread.join();

This will allow your code to stop gracefully.

A: I think the simplest solution will be to make your threads demons.
Just add the following lines before starting your thteads.
oddThread.setDaemon(true);
evenThread.setDaemon(true);

And your program will exit immediately after exiting from main.


text:
Q: How to plot RS chart using Matlab I am working with some video data and I expected to see some self similarity when plotting the RS chart, instead I got zigzagy lines. I would like some of you to check my code segment & tell me if I did something wrong in it.
The video file has 114 frames & I have a seperate function that computes the R over sigma and returns that value plus the no of pixels.
points=zeros(7,5,1);
RS=zeros(7,5,1);
for l=1:7
    x= floor(rand()*240);
    y=floor(rand()*320);
im_frame=image_data(x,y,1,:);
im_frame=im_frame(:);

for i=1:5
        N=floor(length(im_frame)/2^(i-1));
    for j=1:2^(i-1)
        [pt,RSt]=calcRSrange(im_frame((i-1)*N+1:i*N));
        points(l,i) = pt+points(l,i);
        RS(l,i)=RSt+RS(l,i);
    end
    points(l,i)=points(l,i)/j;
    RS(l,i)=RS(l,i)/j;
end
end
log_RS=log(RS);
log_points=log(points);
figure
plot(log_points',log_RS')
xlabel('log no. of pixels')
ylabel('Log RS value')

Thank you in advance:)


text:
Q: How to make sure only one instance of a bash script runs? A solution that does not require additional tools would be prefered.

A: Although you've asked for a solution without additional tools, this is my favourite way using flock:
#!/bin/sh

[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :

echo "servus!"
sleep 10

This comes from the examples section of man flock, which further explains:

This is useful boilerplate code for shell scripts.  Put it at the top of the shell script you want to lock and it'll automatically lock itself on the first run.  If the env var $FLOCKER is not set to the shell script that is  being  run,  then execute  flock and grab an exclusive non-blocking lock (using the script itself as the lock file) before re-execing itself with the right arguments.  It also sets the FLOCKER env var to the right value so it doesn't run again.

Points to consider:

*

*Requires flock, the example script terminates with an error if it can't be found

*Needs no extra lock file

*May not work if the script is on NFS (see https://serverfault.com/questions/66919/file-locks-on-an-nfs)

Update: If your script may get called through different paths (e.g. through its absolute or relative path) or in other words if $0 differs in parallel invocations then one needs to use realpath as well:
[ "${FLOCKER}" != "`realpath '$0'`" ] && exec env FLOCKER="`realpath '$0'`" flock -en "$0" "$0" "$@" || :

A: This may be too simplistic, please correct me if I'm wrong. Isn't a simple ps enough?
#!/bin/bash

me="$(basename "$0")";
running=$(ps h -C "$me" | grep -wv $$ | wc -l);
[[ $running > 1 ]] && exit;

# do stuff below this comment

A: This is a modified version of Anselmo's Answer. The idea is to create a read only file descriptor using the bash script itself and use flock to handle the lock.
script=`realpath $0`     # get absolute path to the script itself
exec 6< "$script"        # open bash script using file descriptor 6
flock -n 6 || { echo "ERROR: script is already running" && exit 1; }   # lock file descriptor 6 OR show error message if script is already running

echo "Run your single instance code here"

The main difference to all other answer's is that this code doesn't modify the filesystem, uses a very low footprint and doesn't need any cleanup since the file descriptor is closed as soon as the script finishes independent of the exit state. Thus it doesn't matter if the script fails or succeeds.

A: I would use a lock file, as mentioned by Marco
#!/bin/bash

# Exit if /tmp/lock.file exists
[ -f /tmp/lock.file ] && exit

# Create lock file, sleep 1 sec and verify lock
echo $$ > /tmp/lock.file
sleep 1
[ "x$(cat /tmp/lock.file)" == "x"$$ ] || exit

# Do stuff
sleep 60

# Remove lock file
rm /tmp/lock.file

A: If you want to make sure that only one instance of your script is running take a look at:
Lock your script (against parallel run)
Otherwise you can check ps or invoke lsof <full-path-of-your-script>, since i wouldn't call them additional tools.

Supplement:
actually i thought of doing it like this:
for LINE in `lsof -c <your_script> -F p`; do
    if [ $$ -gt ${LINE#?} ] ; then
        echo "'$0' is already running" 1>&2
        exit 1;
    fi
done

this ensures that only the process with the lowest pid keeps on running even if you fork-and-exec several instances of <your_script> simultaneously.

A: Almost like nsg's answer: use a lock directory. Directory creation is atomic under linux and unix and *BSD and a lot of other OSes.
if mkdir -- "$LOCKDIR"
then
    # Do important, exclusive stuff
    if rmdir -- "$LOCKDIR"
    then
        echo "Victory is mine"
    else
        echo "Could not remove lock dir" >&2
    fi
else
    # Handle error condition
    ...
fi

You can put the PID of the locking sh into a file in the lock directory for debugging purposes, but don't fall into the trap of thinking you can check that PID to see if the locking process still executes. Lots of race conditions lie down that path.

A: To add to Bruce Ediger's answer, and inspired by this answer, you should also add more smarts to the cleanup to guard against script termination:
#Remove the lock directory
cleanup() {
    if rmdir -- "$LOCKDIR"; then
        echo "Finished"
    else
        echo >&2 "Failed to remove lock directory '$LOCKDIR'"
        exit 1
    fi
}

if mkdir -- "$LOCKDIR"; then
    #Ensure that if we "grabbed a lock", we release it
    #Works for SIGTERM and SIGINT(Ctrl-C) as well in some shells
    #including bash.
    trap "cleanup" EXIT

    echo "Acquired lock, running"

    # Processing starts here
else
    echo >&2 "Could not create lock directory '$LOCKDIR'"
    exit 1
fi

A: One other way to make sure a single instance of bash script runs:
#! /bin/bash -

# Check if another instance of script is running
if pidof -o %PPID -x -- "$0" >/dev/null; then
  printf >&2 '%s\n' "ERROR: Script $0 already running"
  exit 1
fi

...

pidof -o %PPID -x -- "$0" gets the PID of the existing script¹ if it's already running or exits with error code 1 if no other script is running

¹ Well, any process with the same name...

A: I am using cksum to check my script is truly running single instance, even I change filename & file path.
I am not using trap & lock file, because if my server suddenly down, I need to remove manually lock file after server goes up.
Note: #!/bin/bash in first line is required for grep ps
#!/bin/bash

checkinstance(){
   nprog=0
   mysum=$(cksum $0|awk '{print $1}')
   for i in `ps -ef |grep /bin/bash|awk '{print $2}'`;do
        proc=$(ls -lha /proc/$i/exe 2> /dev/null|grep bash)
        if [[ $? -eq 0 ]];then
           cmd=$(strings /proc/$i/cmdline|grep -v bash)
                if [[ $? -eq 0 ]];then
                   fsum=$(cksum /proc/$i/cwd/$cmd|awk '{print $1}')
                   if [[ $mysum -eq $fsum ]];then
                        nprog=$(($nprog+1))
                   fi
                fi
        fi
   done

   if [[ $nprog -gt 1 ]];then
        echo $0 is already running.
        exit
   fi
}

checkinstance

#--- run your script bellow

echo pass
while true;do sleep 1000;done

Or you can hardcoded cksum inside your script, so you no worry again if you want to change filename, path, or content of your script.
#!/bin/bash

mysum=1174212411

checkinstance(){
   nprog=0
   for i in `ps -ef |grep /bin/bash|awk '{print $2}'`;do
        proc=$(ls -lha /proc/$i/exe 2> /dev/null|grep bash)
        if [[ $? -eq 0 ]];then
           cmd=$(strings /proc/$i/cmdline|grep -v bash)
                if [[ $? -eq 0 ]];then
                   fsum=$(grep mysum /proc/$i/cwd/$cmd|head -1|awk -F= '{print $2}')
                   if [[ $mysum -eq $fsum ]];then
                        nprog=$(($nprog+1))
                   fi
                fi
        fi
   done

   if [[ $nprog -gt 1 ]];then
        echo $0 is already running.
        exit
   fi
}

checkinstance

#--- run your script bellow

echo pass
while true;do sleep 1000;done

A: This handy package does what you're looking for.
https://github.com/krezreb/singleton
once installed, just prefix your command with singleton LOCKNAME
e.g. singleton LOCKNAME PROGRAM ARGS...

A: Another approach not mentioned here that does not use flock is to rely on the fact that creating a link is atomic.
Given this script:
#!/bin/bash

touch /var/tmp/singleton.$$.lock
if ( link /var/tmp/singleton.$$.lock /var/tmp/singleton.lock 2>/dev/null ) ; then
  echo 'Lock Acquired By: ' $$
  sleep 2
  echo 'Lock Released By: ' $$
  rm /var/tmp/singleton.lock /var/tmp/singleton.$$.lock
else
  echo 'Failed Lock Acquistion Attempt By: ' $$
  rm /var/tmp/singleton.$$.lock
fi

When you try to run multiple instances simultaneously, only one of them acquires the "lock":
§ for i in {1..3}; do (./singleton.sh &) ; done ; sleep 3
Lock Acquired By:  3816
Failed Lock Acquistion Attempt By:  3820
Failed Lock Acquistion Attempt By:  3818
Lock Released By:  3816

You can modify this script to add the appropriate trap statements to make it robust in the event that your script does not exit gracefully.
The basic idea is that when two instances of the script run, they try to create a link at the same path (i.e., /var/tmp/singleton.lock) that points to something, but only one of them will succeed and the other one will get the error code for the error:
ln: failed to create hard link '/var/tmp/singleton.lock': File exists

In this script, the something happens to be an empty file that has the PID of the executing script. You could use other schemes for what something could be but the important bit is that the two instances of the script try to create a link at the same path.

A: You can use this: https://github.com/sayanarijit/pidlock
sudo pip install -U pidlock

pidlock -n sleepy_script -c 'sleep 10'

A: My code to you
#!/bin/bash

script_file="$(/bin/readlink -f $0)"
lock_file=${script_file////_}

function executing {
  echo "'${script_file}' already executing"
  exit 1
}

(
  flock -n 9 || executing

  sleep 10

) 9> /var/lock/${lock_file}

Based on man flock, improving only:

*

*the name of the lock file, to be based on the full name of the script

*the message executing
Where I put here the sleep 10, you can put all the main script.

A: Easiest one liner script rather than writing complex PID or lock statements
flock -xn LOCKFILE.lck -c SCRIPT.SH

where x denotes exclusive lock
and n denotes non-blocking which fails rather than wait for the lock to be released.
c runs the script that you want to launch.


text:
Q: How to stop button from moving I have a button that, when pressed, is supposed to expand the element behind it (.nav which contains .work and .contact) out in both directions. However, I can't seem to keep the button in the center.

$(function() {
  var nav = $('.nav');
  var button = $('.nav button');
  button.on('click', function(){
    nav.toggleClass('active');
    if(nav.hasClass('active'))
      button.text('');
    else
      button.text('');
  });
});
html {
  background: #f1f1f1;
}
.nav {
  display: block;
  margin: auto;
  margin-top: 80px;
  margin-bottom: 200px;
  background: #ccc;
  color: black;
  text-align: center;
  width: 350px;
  height: 330px;
  transition: width 0.5s;
}
.nav.active {
  width: 1000px;
  transition: width 0.5s;
}
.navigation button {
  position: absolute;
  width: 350px;
  Height: 350px;
  margin: 0 auto;
  display: block;
  background-color: #2e0513!important;
  background: url(TransplantAltFontbackgroundvector.png) 12px 15px;
  background-repeat: no-repeat;
  background-size: 325px 325px;
  border: none;
  transition: 0.5s ease-in-out;
}
.navigation.active button {
  transform: scale(1.1);
  transition: 0.5s ease-in-out;
}
.navigation:hover button {
  box-shadow: 0px 0px 20px black;
  transform: scale(1.01);
  transition: 0.1s ease-in-out;
}
.navigation.active:hover button {
  box-shadow: none!important;
  transform: scale(1.1)!important;
  transition: 0.5s ease-in-out;
}
.navigation button img {
  position: relative;
  right: 30px;
  bottom: 40px;
}
.work,
.contact {
  position: relative;
  visibility: hidden;
}
.work a {
  font-family: arapey;
  font-size: 30px;
  font-style: italic;
  text-decoration: none;
}
.contact a {
  font-family: arapey;
  font-size: 30px;
  font-style: italic;
  text-decoration: none;
}
.nav.active > .work {
  visibility: visible!important;
  display: table;
  margin: auto;
  position: relative;
  float: left;
  left: 125px;
  top: 150px;
}
.nav.active > .contact {
  visibility: visible!important;
  display: table;
  margin: auto;
  position: relative;
  float: right;
  right: 125px;
  top: 150px;
}

    <button>
    </button>

      work

      contact

A: Give the nav a style of position: relative. Then, toggle a class (or just add the styling, should work as well) to the button on click that does the following:
button.my-pressed-class {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

This should keep it in the middle.
Edit: Keep in mind you already have a transform set on the button on hover. Just, add the translateX to hover when the button has the aforementioned class, to avoid it from moving around on hover.

A: add postion relative to .navigation and position absolute to .nav with left value

$(function() {
  var nav = $('.nav');
  var button = $('.nav button');
  button.on('click', function(){
    nav.toggleClass('active');
    if(nav.hasClass('active'))
      button.text('');
    else
      button.text('');
  });
});
html {
  background: #f1f1f1;
}

.navigation {
   position: relative;
}

.nav {
  display: block;
  margin: auto;
  margin-top: 80px;
  margin-bottom: 200px;
  background: #ccc;
  color: black;
  text-align: center;
  width: 350px;
  height: 330px;
  transition: width 0.5s;
  position: absolute;
  left: 100px;
}
.nav.active {
  width: 1000px;
  transition: width 0.5s;
}
.navigation button {
  position: absolute;
  width: 350px;
  Height: 350px;
  margin: 0 auto;
  display: block;
  background-color: #2e0513!important;
  background: url(TransplantAltFontbackgroundvector.png) 12px 15px;
  background-repeat: no-repeat;
  background-size: 325px 325px;
  border: none;
  transition: 0.5s ease-in-out;
}
.navigation.active button {
  transform: scale(1.1);
  transition: 0.5s ease-in-out;
}
.navigation:hover button {
  box-shadow: 0px 0px 20px black;
  transform: scale(1.01);
  transition: 0.1s ease-in-out;
}
.navigation.active:hover button {
  box-shadow: none!important;
  transform: scale(1.1)!important;
  transition: 0.5s ease-in-out;
}
.navigation button img {
  position: relative;
  right: 30px;
  bottom: 40px;
}
.work,
.contact {
  position: relative;
  visibility: hidden;
}
.work a {
  font-family: arapey;
  font-size: 30px;
  font-style: italic;
  text-decoration: none;
}
.contact a {
  font-family: arapey;
  font-size: 30px;
  font-style: italic;
  text-decoration: none;
}
.nav.active > .work {
  visibility: visible!important;
  display: table;
  margin: auto;
  position: relative;
  float: left;
  left: 125px;
  top: 150px;
}
.nav.active > .contact {
  visibility: visible!important;
  display: table;
  margin: auto;
  position: relative;
  float: right;
  right: 125px;
  top: 150px;
}

    <button>
    </button>

      work

      contact


text:
Q: How to disable default day-off in Team Foundation Server capacity calender? I want to add capacity of my team members to sprint capacity, But Sat & Sun aren't days off in my country. Can I disable day-off for this calender?

A: You'll need TFS 2013 Update 2 or later:

*

*Hit the admin page for the project (usually
http://server:8080/tfs/collection/project/_admin)

*Select the team that you need to configure

*Beside "Members" there is a "Settings" tab.

*Choose the working days for the team.

Configure and customize Agile planning tools for a team project
https://msdn.microsoft.com/en-us/library/hh543813.aspx


text:
Q: How to use preg variable in SQL query I'm using a userid in my bbcode, but I want to display the username!
So I want a query to do something like
SELECT username
FROM users
WHERE id = "$1"';

How is this possible? Or is there any other solution?
I want the output to be "John said" instead of "2 said".
<?php
$str = "[quote=2]Foobar[/quote]";

$match = "/\[quote=(.*?)\](.*?)\[\/quote\]/is";
$replace = "
$1 said:
>$2
";
$bbcode = preg_replace($match, $replace, $str);
?>

A: You need preg_replace_callback to modify the replacement/to replace the user id with the correct user name before its inserted into your string.

A: You do it using preg_replace_callback function,
$bbcode = preg_replace_callback($match, function($matches){
       // execute query
       $query = "SELECT username FROM users WHERE id = '{$matches[1]}'";
       // get user name
       $username = $row['username']; // just for illustration.
       // return formatted string.
       return "
$username said:
>$matches[2]
";
}, $str);

Oh there is a better way. Running SQL query for each of them is not a good idea. So first get all the User ids an contents. Then get all the corresponding name from db.
$match = "/\[quote=(.*?)\](.*?)\[\/quote\]/is";
preg_match_all($match, $str, $matches);

$query = "SELECT id, username from tbl1 where id IN (".implode(",", $matches[1]).")";
// run the query. get all the row in a hash.
$hash[$row['id']] = $hash[$row['username']];

$bbcode = preg_replace_callback($match, create_function(
    '$m',
    'global $hash;return "
{$hash[$m[1]]} said:
$m[2]
";'
    ), $str);


text:
Q: Laravel, How to get result from controller using ajax by sending multiple values from checkboxes I have select box which is working fine and sending values to controller but I want to use checkboxes instead of this select box and without using any submit button so this is what I need to do
I tried to use ajax and checkboxes but cant get html data as its working now with my code when Im using the select box
     <select class="offer-multiple" style="width: 100%" name="categories[]" id="categories" multiple="multiple">
                                @foreach($categories as $item)
                                    @if(in_array($item->id,$categoryArray))
                                        <option value="{{ $item->id }}" selected="selected">  {{ $item->title }} - {{ $item->num_offer }} Offer</option>
                                    @else
                                        <option value="{{ $item->id }}">   {{ $item->title }} - {{ $item->num_offer }} Offer</option>
                                    @endif
                                @endforeach
                            </select>

Jquery:
$("#categories").change(function() {

//console.log(locationUrl);
var dataArray = [];

var dataString = JSON.stringify($("#categories").val());

var urlCall = '/getOfferCategory/'+locationUrl[5];

console.log(urlCall);

var loadingSection = 'result';
//call ajax
makeAjaxCall(urlCall,dataString,'',loadingSection);
});

A: Not sure that is an appropriate way to use checkboxes.  You can have checkboxes having the same name if you use name[] as the name so it submits an array to the server (PHP anyways).
The markup would be something like below, but that includes a submit button.  With the checkbox option, how are you suppose to know when the user is done making selections ?  The user would have to click a submit button or something when they are done making selections ?
<form action="" method="" class="form" id="form">

    <fieldset>
        <legend>Check Boxes with Same Name</legend>

        <input type="checkbox" name="category[]" value="1" />1
        <input type="checkbox" name="category[]" value="2" /> 2
        <input type="checkbox" name="category[]" value="3" /> 3
        <input type="checkbox" name="category[]" value="4" /> 4
        <input type="checkbox" name="category[]" value="5" /> 5
        <input type="checkbox" name="category[]" value="6" /> 6

    </fieldset>
    <button type="submit">
    Submit
    </button>

</form>

The jQuery would be something like:
$("#form").submit(function(e) {

e.preventDefault();

var urlCall = '/getOfferCategory/action';

$.ajax({
    url: "/echo/html/",
    type: "POST",
    dataType:  "HTML",
    data:  $('#form').serialize()
}).done(function (result, status, xhr) {
    alert(result);
}).fail(function (xhr, status, error) {
    alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
});
});

/echo/html/ is for Fiddle.


text:
Q: When are those polynomials irreducible? Let $f_n (x) := x^n - x^{n-1} - x^{n-2} - ... - x^2 - x - 1$, which is an irreducible polynomial by corollary 2.2 of https://www.sciencedirect.com/science/article/pii/S0022404903002457.

Question: For which $m,n \geq 2$ is the polynomial $f_n(x^m)$ irreducible over the integers?

Especially interesting is the case when $n$ (or $m$) is a prime.

Question 2: Is $f_n(x^m)$ irreducible whenever $n$ is a prime?

Computer experiments found no counterexample so far.

A: We show that for all $m, n \geq 2$ the polynomial $f_n \left( x^m \right)$ is irreducible.
This answer is based on a wonderful technique I learnt a few years ago from an answer on MSE by Keith Conrad, and I encourage the reader to look at that answer first (it is not very long), as it shows the key ideas in a much nicer setup. I do here a lot of casework which can probably be shortened, but I didn't really attempt to streamline it. If
$$p(x) = \sum_{i = 0}^{n} a_i x^i$$
is a polynomial of degree $n$, then we define
$$\tilde{p} (x) = \sum_{i = 0}^{n} a_{n - i} x^i$$
that is the polynomial with coefficients reversed. Algebraically, $\tilde{p} (x) = x^{\mathrm{deg} (P)} p \left( \frac{1}{x} \right)$. Notice that
$$(x - 1) f_n (x) = x^{n + 1} - 2 x^n + 1$$
Therefore, to understand the factorization of $f_n \left( x^m \right)$, it suffices to understand the factorization of
$$x^{n m + m} - 2 x^{n m} + 1$$
Fix $n, m$ and from now on we will call this polynomial $f(x)$. Throughout, we will assume that $n > 2$: if $n = 2$ the method that we use shows that for all $m$ the polynomial $f_{n} \left( x^m \right)$ is irreducible.
Suppose that there was a factorization into nonconstant monic polynomials $g, h$
$$f = g h$$
Then, taking $k = g \tilde{h}$ or $k = - g \tilde{h}$ (according to whether $g(0) = 1$ or $- 1$ respectively), we see that $k$ is a monic polynomial such that
$$f \tilde{f} = k \tilde{k}$$
We will show that this implies that $k = f$ or $k = \tilde{f}$. Write
$$k(x) = \sum_{i = 0}^{n m + m} a_i x^i$$
and then
$$\tilde{k} (x) = \sum_{i = 0}^{n m + m} a_{n m + m - i} x^i$$
We know that $a_{n m + m} = 1$, and by looking at the constant coefficient of $k \tilde{k} = f \tilde{f}$ we see that $a_0 = 1$. Now, the key point: compare the coefficient of $x^{n m + m}$ in $f \tilde{f} = k \tilde{k}$: it is the sum of the squares of the coefficients of $f$ and $k$ respectively, therefore
$$\sum_{i = 0}^{n m + m} a_{i}^2 = 6$$
It will be useful in the cases below to see explicitly what $f \tilde{f}$ is:
$$f \tilde{f} = x^{2 m n + 2 m} - 2 x^{2 m n + m} - 2 x^{m n + 2 m} + 6 x^{m n + m} - 2 x^{m n} - 2 x^{m} + 1$$
From the coefficients of $k$ we already now, there are two possibilities:
Case 1: There exist $m n + m > a > b > c > d > 0$ such that
$$k(x) = x^{n m + m} \pm x^a \pm x^b \pm x^c \pm x^d + 1$$
Looking at the coefficient of $x^{2 n m + 2 m - 1}$ in $k \tilde{k}$ we see that we must have $a = n m + m - 1, \ d = 1$ and $x^a, x^d$ must both come with a minus sign. We must have $k(1) = 0$, and so without loss of generality (otherwise we look at $\tilde{k}$) $x^b$ comes with a plus sign and $x^c$ with a minus. Now,
$$k \tilde{k} = \left( x^{m n + m} - x^{m n} + x^b - x^c - x^m + 1 \right) \times \\ \left( x^{m n + m} - x^{m n} - x^{m n + m - c} + x^{m n + m - b} - x^m + 1 \right)$$
Looking at the coefficient of $x^{2 m n}$, since $n > 2$ the positive contribution of $\left( - x^{m n} \right) \left( x^{- m n} \right)$ must cancel out, and the only options are $c = 2 m, m n - m$. In particular $c$ is divisible by $m$. Substituting $x$ to be a primitive $m$-th root of unity, we get that $x^b = 1$, and therefore $b$ is divisible by $m$ as well. Since $m n > b > c$, this rules out the option of $c$ being $m n - m$, and therefore we have $c = 2 m$. Now looking at the coefficient of $x^{m n}$ we see that we must have $b = m n - m$, but this means that the coefficient of $x^{2 m n}$ is wrong, and so we get a contradiction. Therefore, what happens is
Case 2: for some $m n + m > a > 0$, we have $k(x) = x^{m n + m} \pm 2 x^a + 1$. It is immediate to see in this case that $a = mn, m$ and $x^a$ comes with a minus sign, that is $k = f, \tilde{f}$ and without loss of generality, $k = f$.
Therefore $g h = \pm g \tilde{h}$, that is $h = \pm \tilde{h}$. However, notice that
$$\gcd \left( f, \tilde{f} \right) = \gcd \left( x^{m n + m} - 2 x^{m n} + 1, x^{m n - m} - 1 \right) = \\ = \gcd \left( x^{2 m} - 2 x^{m} + 1, x^{m n - m} - 1 \right)$$
It is easy to see that the only roots of $x^{2 m} - 2 x^m + 1$ which are on the unit circle are the $m$-th roots of unity, and they each appear with multiplicity $1$, therefore $\gcd \left( f, \tilde{f} \right) = x^m - 1$. Since $h | f, \ \tilde{h} | \tilde{f}$ we have $h | \gcd \left( f, \tilde{f} \right) = x^m - 1$.
Over all, we have shown that in every nontrivial factorization of $\left( x^m - 1 \right) f_n \left( x^m \right) = g h$, one of the factors on the right hand side divides $x^m - 1$, which immediately implies that $f_n \left( x^m \right)$ is irreducible: if there was a factorization $f_n \left( x^m \right) = u(x) v(x)$ then $g(x) = u(x), \ h(x) = \left( x^m - 1 \right) v(x)$ would be a counterexample. QED


text:
Q: How to place ImageView half overlapped on top boundary of ConstraintLayout in a Fragment? I am trying to make a Login screen where my LoginActivity contains a LoginFragment which is used to get user input for display picture, username, and password. Now, I want to display my circular ImageView centered and half-overlapping the top boundary of the ConstraintLayout which is the root Layout of my Fragment (as shown in the attached image). How can I achieve this? Everything is working fine except for the placement of the ImageView. I have also attached the code of my fragment layout xml.
I have already seen How to half overlap images in android constraint layout and how to half overlap imageview on another imageview in android, but none of these achieve the desired result.
Here is the LoginFragment XML
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_card"
    android:elevation="6dp"
    android:padding="24dp"
    android:layout_margin="24dp">

<androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintGuide_percent="0.5"/>

<ImageView
        android:id="@+id/imageview_profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/circle"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintTop_toTopOf="@id/guideline"
        app:layout_constraintBottom_toBottomOf="@id/guideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

<androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/edittext_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/tinBlue"
        app:backgroundTint="@color/colorPrimaryDark"
        android:hint="@string/hint_username"
        android:textColorHint="@color/colorPrimaryDark"
        android:textCursorDrawable="@null"
        app:layout_constraintTop_toBottomOf="@+id/imageview_profile"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:maxLength="20"/>

<androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/edittext_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/tinBlue"
        app:backgroundTint="@color/colorPrimaryDark"
        android:hint="@string/hint_password"
        android:textColorHint="@color/colorPrimaryDark"
        android:textCursorDrawable="@null"
        app:layout_constraintTop_toBottomOf="@id/edittext_username"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:inputType="textPassword"
        android:maxLength="20"/>

<TextView
        android:id="@+id/textview_forgot_password"
        android:text="@string/text_forgot_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:layout_marginVertical="24dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/edittext_password"/>
<Button
        android:id="@+id/button_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="12dp"
        android:layout_marginVertical="24dp"
        android:background="@color/tinBlue"
        android:textColor="@color/white"
        android:text="@string/login_button_label"
        app:layout_constraintTop_toBottomOf="@id/textview_forgot_password"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Here is the LoginActivity XML
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                               xmlns:app="http://schemas.android.com/apk/res-auto"
                                               android:layout_height="match_parent"
                                               android:layout_width="match_parent"
                                               android:background="@color/darkGray">
<TextView
        android:id="@+id/textview_tin_account"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_tin_account"
        android:textSize="24sp"
        android:textColor="@color/white"
        android:layout_gravity="center_horizontal"
        android:layout_marginVertical="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/login_ui_container"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        app:layout_constraintTop_toBottomOf="@id/textview_tin_account"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">
</androidx.constraintlayout.widget.ConstraintLayout>

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_new_user"
        android:textSize="12sp"
        android:textColor="@color/white"
        android:layout_gravity="center_horizontal"
        android:layout_marginVertical="4dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

Here is the required result
]1

A: You can constrain the ImageView to the middle of the top edge of your Fragment layout as shown in the questions you referenced (you don't need the Guideline):
<ImageView
    android:id="@+id/imageview_profile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/circle"
    android:src="@mipmap/ic_launcher"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

Then, allow children to draw outside their bounds by setting android:clipChildren="false" and android:clipToPadding=false in each of the parent layouts i.e. all the parent ConstraintLayouts layouts.


text:
Q: How to transfer data between two pages react native navigation I'm trying to transfer data between two pages of react. I have data on newMood.js where I can create a new Mood, and I want to add the information from that to the Home.js page. How can I do that?
Here is the simplified code from newMood.js. There are some commented out lines of my attempts.
export default class newMood extends Component{
  static navigationOptions = {
    title: 'New Entry',
    headerStyle: {
      backgroundColor: 'white',
    },
    headerTintColor: '#00b3b3',
  };

  constructor(props){
    super(props)
    this.state={
      mood: '',
      energy: '',
      activity: '',
      sleep: '',
      journal:'',
    }
  }

  //saveData = () => {
   // const {mood, energy, activity, sleep, journal} = this.state;
   // let myArray={
   //   mood: mood,
   //   energy: energy,
   //   activity: activity,
   //   sleep: sleep,
   //   journal: journal
    //}
    //alert("mood: " + mood + "\nenergy: " + energy + "\nactivity: " + activity + "\nsleep: " + sleep + "\njournal: " + journal)
    //return (mood, energy, activity, sleep, journal);
  //};

  render() {
    const { navigate } = this.props.navigation;
    const currentMood = this.state.mood;
    const currentJournal = this.state.journal;
    return(
          <View style={styles.container}>
            <Text style={styles.mood}>Mood</Text>
            <View style={styles.container2}>
            <TouchableOpacity
              disabled={currentMood.length !== 0 && currentMood !== 'excited'}
              style={styles.button}
              onPress={() => this.setState({mood: 'excited'})}
            >
             <Text style={styles.answer}></Text>
            </TouchableOpacity>
            <TouchableOpacity
              disabled={currentMood.length !== 0 && currentMood !== 'happy'}
              style={styles.button}
              onPress={() => this.setState({mood: 'happy'})}
            >
             <Text style={styles.answer}></Text>
            </TouchableOpacity>
            </View>
            <Text style={styles.energy}>Journal</Text>
            <View style={styles.container3}>
            <TextInput
              multiline
              numberOfLines={3}
              color="white"
              style={styles.textInput}
              onChangeText={journal => this.setState({journal})}
            />
            <TouchableOpacity
              style={styles.submit}
              //onPressIn={this.saveData}
              onPressOut={() => navigate('Home')}
              //onPressOut={() => navigate('Home', { currentMood, currentEnergy, currentActivity, currentSleep, currentJournal })}
            >
             <Text style={styles.answer}>Submit</Text>
            </TouchableOpacity>
            </View>
          </View>
      );
    }
  }

Here is the code from Home.js, where I have attempted to retrieve the information, but get an error due to an undefined object:
export default class Home extends Component {
  static navigationOptions = {
    title: 'Entries',
    headerStyle: {
      backgroundColor: 'white',
    },
    headerTintColor: '#00b3b3',
  };

  render() {
    const { navigate } = this.props.navigation;
    //const { currentMood, currentJournal } = this.props.route.params
    return (
      <View style={styles.container}>
      <TouchableOpacity
        style={styles.button}
        onPress={() => navigate('newMood')}
      >
      <Text style={styles.plus}>+</Text>
      </TouchableOpacity>
      </View>
    );
  }
}

I would appreciate any help!

A: in class newMood , send data as a object with key-value pair, and on other page get the value by the key
<TouchableOpacity
  style={styles.submit}
  //onPressIn={this.saveData}
  onPressOut={() => navigate('Home', { 'data': { currentMood,
  currentEnergy, currentActivity, currentSleep, currentJournal }})}>
       <Text style={styles.answer}>Submit</Text>
   </TouchableOpacity>

in class Home
componentDidMount(){
  // prints the transfered data
  console.log(this.props.navigation.getParam('data'));
}


text:
Q: Retrieve all models that are not associated with another model through pivot I have three tables: users, organizations, organization_user. organization_user is a pivot table for the many-to-many relationship between users and organizations. The many-to-many relationships have been setup correctly in the corresponding models.
I need to obtain all users who are not associated with a given organization. How should this be done using eloquent. Below is what I have tried, but it is returning no results:
public function associate_user($organization_id){

        $data = [
            'organization'      => \App\Organization::find($organization_id),
            'users'             => \App\User::whereDoesntHave('organizations', function($query) use ($organization_id){
                $query->where('organization_id', $organization_id);
            })
        ];

        return view('admin.associateUser', $data);

    }

A: You are never actually executing the query.
You need to call get() at the end of the query builder.
public function associate_user($organization_id) {
    $data = [
        'organization' => \App\Organization::find($organization_id),
        'users'        => \App\User::whereDoesntHave('organizations', function($query) use ($organization_id){
            $query->where('organization_id', $organization_id);
        })->get(); // Add the call to get()
    ];
    return view('admin.associateUser', data);
}


text:
Q: Accessing the session on socket requests with sails.js When making a client request using io.socket such as;
io.socket.post('activity/subscribe')

There is no session information appended to the request object in sails causing my authentication policies to fail.
This is not a cross-domain request and the sails.sid cookie has been set. I'm using redis as a session store and for XHR requests the session is populated correctly.
My understanding is that sails handles the integration of sockets so that when a requests reached the app's routes it can be treated like any other request?
I've had a look at the answer in Sails.js authorization for socket requests but that fails as req.socket.manager is not defined.
Maybe that's for an older version of sails? Am in v0.11.0.
After sending the post request, I see the following in the console:
verbose: Receiving incoming message from Socket.io:  { method: 'post',
  headers: {},
  data: {},
  url: 'activity/subscribe' }
verbose: Interpreting socket.io message as virtual request to "post activity/subscribe"...
error: policy error here as no session..

A: We figured it out eventually...
'activity/subscribe' - no good
'/activity/subscribe' - yay


text:
Q: Iphone OpenGL : gluLookAt X,Z to rotation (360) : Heading angle The OpenGL program I am writing uses a port of glULookat to control the camera
To rotate I have the following code
case ActionTurnLeft:
center[0] = eye[0] + cos(-SPEED_TURN)*v[0] - sin(-SPEED_TURN)*v[2];
center[2] = eye[2] + sin(-SPEED_TURN)*v[0] + cos(-SPEED_TURN)*v[2];

break;

case ActionTurnRight:
    center[0] = eye[0] + cos(SPEED_TURN)*v[0] - sin(SPEED_TURN)*v[2];
    center[2] = eye[2] + sin(SPEED_TURN)*v[0] + cos(SPEED_TURN)*v[2];
My question is how do I get the rotation angle in degrees?
Updated :  Tried this and it gave me -572 ish to 572
float rotAngleDegs;
float PI = 3.1415926535897;
rotAngleDegs = (cos(-SPEED_TURN)*v[0] - sin(-SPEED_TURN)*v[2]) * 180 / PI;
NSLog(@"%f", rotAngleDegs);

A: To get an angle in degrees just multiply the angle in radians by 180 / PI where PI = 3.1415926535897. In this case, the rotation angle in radians is the entire piece of code after eye[] part.
rotAngleDegs = (cos(-SPEED_TURN)*v[0] - sin(-SPEED_TURN)*v[2]) * 180 / PI

A: It looks like you are using a rotation matrix. Wikipedia Rotation Matrix entry
-SPEED_TURN is the angle of rotation in radians which can be converted to degrees by multiplying the factor 180 / PI.

A: Incrementing a float by rotation +=2.865; seemed to actually work lol


text:
Q: Create-react-app doesn't support relay compiler's --artifactDirectory option In the relay docs, they nudge you to use the --artifactDirectory option for the relay compiler. This causes all the generated files to be placed in a single directory, which sounds like a very good idea to me! However, using this option causes a bunch of errors like this:
Failed to compile

./src/path/to/component/Component.tsx
Module not found: Can't resolve './__generated__/Component_field.graphql' in '/Users/me/path/to/project/src/path/to/component'

How do I use relay-compiler's --artifactDirectory option in create-react-app?

A: You can't. babel-plugin-relay/macro (or babel-plugin-relay) needs to be configured with the same option, or it will look for the generated files in a ./__generated__/ directory next to the source file. There is a description of how to do that in this stackoverflow answer, but configuring babel-plugin-macros is not possible in create-react-app.


text:
Q: Ember Data Nested Resources Tree Structure I have a slightly peculiar problem with loading my tree structure into Ember.
My models are:
book.js
  - parts: DS.hasMany('part', {inverse: 'book', async: true})

part.js
  - subparts: DS.hasMany('part', {inverse: 'parent_part', async: true}),

With the following API responses:
GET /api/books:
{
  books: [
    {id: 1, links: {parts: "/api/books/1/parts"}},
    ...
  ]
}

GET /api/books/1/parts:
{
  parts: [
  {
    id: 1,
    subparts: [10, 11]
  },
  {
    id: 2,
    subparts: []
  }
  ]
}

The problem is in the tree nature of the parts: The book only has direct descendants id 1 and 2, but these have sub-parts on their own.
The structure as it is works but results in multiple sub-queries for each part that was not included in the /books/1/parts result. I want to avoid these queries, not only because of performance reasons but also because I will need additional query parameters which would get lost at this step... I know about coalesceFindRequests but it introduces new problems.
To rephrase the problem, Ember Data thinks that every part that is included in the /books/1/parts response should be added directly to the book:parts property. How can I still load all records of the parts tree at the same time?
I tried renaming the fields, but Ember Data assigns the records based on the model name, not the field name.
I fear that some creative adapter overriding will be necessary here. Any idea appreciated. The backend is completely under my control, so I could change things on that end, too.

A: You need to use a process called sideloading, which should work as you expect (I've had issues in the past with sideloading data). As mentioned in this issue, you want to split your parts into two separate arrays.
{
    // These are the direct children
    "parts": [{...}, {...}],
    // These are the extra records
    "_parts": [{...}, {...}]
}


text:
Q: Run-length encoding program have number come before letter I'm making a program for run-length encoding which is used to shorten words.
i.e. aaabbc becomes 3a2bc
My program works so far but instead of outputting 3a2bc it does a3b2c. So how can I make my current program switch?
Code:
public class Compress {
       public static void main(String[] args) {
          String word = "aaabbc";
          System.out.println(compress(word));
       }

       public static String compress (String original){
              String compressed = "";

              char ch = original.charAt(0);
              int counter = 1;
              for (int i = 1; i < original.length(); i++) {
                 if (ch == original.charAt(i)) {
                    counter = counter + 1;
                 }
                 else {
                     compressed = compressed + ch;
                    if(counter != 1){
                       compressed = compressed + counter;
                    }
                    ch = original.charAt(i);
                    counter = 1;
                 }
              }
              compressed = compressed + ch;
              if(counter != 1){
                 compressed = compressed + counter;
              }
              return compressed;
       }
}

A: where you have:
             else {
                 compressed = compressed + ch;
                if(counter != 1){
                   compressed = compressed + counter;
                }
                ch = original.charAt(i);
                counter = 1;
             }

you should switch the first two statement blocks, like
             else {
                if(counter != 1){
                   compressed = compressed + counter;
                }
                 compressed = compressed + ch;
                ch = original.charAt(i);
                counter = 1;
             }

BTW, its much more efficient to use StringBuilder for this rather than String


text:
Q: Handling arrays in C I'm just a beginner with C language.
I want to determine elements of array, but it failed.
I'd like to insert index(row=x, column=y). Is this possible?
Here's my code.
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS

int main(void)
{
    int x, y;
    char coords[3][3] = { NULL };

    printf("x, y: ");
    scanf("%d %d", &x, &y);

    coords[x][y] = 'O';

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
            printf("%c ", coords[i][j]);
        printf("\n");
    }

    return 0;
}

If x=2, y=2, I expect the outcome to be printed
␠␠␠
␠␠␠
␠␠O

(Where ␠ is a space)
I think coords[x][y] = 'O'; is the problem, but i can't fix it.

A: You have not initialized your coords array as you perhaps think! The line:
char coords[3][3] = { NULL };

actually gives all 9 elements the value of zero - which is the nul (unprintable) character. (If there are less initializers in the list than array elements, all 'extra' elements will be given the value of zero.)
What you perhaps want (to set all 9 elements to the blank space) is:
char coords[3][3] = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} };

Or something similar, like using the ASCII value for the space (32) if you know your system uses ASCII encoding (which it is not obliged to).
Better would be to define your desired initial value as a constant, then use that as the initializer:
const char X = ' ';
char coords[3][3] = { {X, X, X}, {X, X, X}, {X, X, X} };

as this makes it easier to change things (less typing) if you need to use a different initial character.

A: First:
char coords[3][3] = { NULL };

The NULL makes little sense in here, although the compiler will most probably compile the code and initialize all elements to zero. Let's fix it to something more "correct":
char coords[3][3] = { { 0 } };

The array elements not initialized explicitly are initialized to 0. For a reference, you could read array initialization on cppreference.
Now we know that all out array elements are initialized with 0. So you can check them before printing:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (coords[i][j] == 0) {
            printf(" ");
        } else {
            printf("%c", coords[i][j]);
        }
        printf(" ");
    }
    printf("\n");
}

Alternatively, you could initialize all array elements to ' ' character as suggested in the other answer.


text:
Q: Proof of vanishing vector expression If I expand the following expression for the 3 components I see that the expression vanishes, $|\mathbf{n}|=1$:
$$
\left(\mathbf{n}\times (\mathbf{n}\times \mathbf{x})\right)\cdot \mathbf{x}
+\left(\mathbf{n}\times (\mathbf{n}\times \mathbf{x})\right)\cdot \left(\mathbf{n}\times \left(\mathbf{n}\times \mathbf{x}\right)\right)=\mathbf{0}
$$
Is there a more elegant proof?
EDIT A simple picture also give a proof. I'm looking for a algebraic proof, like some manipulation using vector-algebra.

A: Hint:
Let ${\bf a}\bot {\bf n}$ with $|{\bf a}|=1$ and ${\bf b}={\bf n}\times {\bf a}$. Then if the expression vanishes for ${\bf x}\in\{ {\bf a},{\bf b},{\bf n}\}$ then you are done since they constitue a basis of $\mathbb{R}^3$


text:
Q: DOMDocument->saveXML() taking too long So, I've created a 34MB XML file.
When I try to get the output from DOMDocument->saveXML(), it takes 94 seconds to return.
I assume the code that generates this XML is irrelevant here, as the problem is on the saveXML() line:
$this->exportDOM = new DOMDocument('1.0');
$this->exportDOM->formatOutput = TRUE;
$this->exportDOM->preserveWhiteSpace = FALSE;
$this->exportDOM->loadXML('<export><produtos></produtos><fornecedores></fornecedores><transportadoras></transportadoras><clientes></clientes></export>');

[...]

$this->benchmark->mark('a');
$this->exportDOM->saveXML();
$this->benchmark->mark('b');
echo $this->benchmark->elapsed_time('a','b');
die;

This gives me 94.4581.
What am I doing wrong? Do you guys know any performance-related issues with DOMDocument when generating the file?
If you need additional info, let me know. Thanks.

I tried removing formatOutput. It improves the perfomance by 33%.
Still taking too long. Any other tips?

A: One thing that helped - although it isn't the perfect solution - was setting $this->exportDOM->formatOutput = FALSE;.
It improved the performance by ~33%.


text:
Q: Why can't I kill thread? Dear All I have this type of code:
public class Testimplements Runnable  {

    public static void main(String[] args) {

        InTheLoop l= new InTheLoop();
        Thread th = new Thread(l);
        th.start();
        th.interrupt();
    }

    @Override
    public void run() {

        int count = 0;
        for (Integer i = 0; i <=10000000000000000000; i++) {
        }
    }
}

I know there is ways to kill thread. For instance:
 // Example 1
 if (Thread.interrupted()){
                 return;
 }

// Example 2
   if(flag){ // volatile
   return;
    }

but can't I kill the thread without if statement?

A: You can use the stop() method if you really have to, but be aware that it is inherently unsafe and deprecated.
See http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html for details.

A: As far as I know you have to implement the interruption policy for your thread yourself, how it handles the interrupt call and when it stops etc.
See: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

A: Instead of thread better use ExecutorService for more control on threads.
Read more in oracle documentation and here is tutorial

A: This subject is very important and I could not find any clear answer for That so I write a sample code with OOP form to explain that
import threading
import time
import tkinter as tk

class A(tk.Tk):
    def __init__(self ,*args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.count = 0
        self._running = True
        self.Do = 0
        A.Run(self)

    def Thread_Terminate(self):                     # a method for killing the Thread
        self._running =False
        self.T.join()

        self.Btn2.config (state='normal')
        self.Btn1.config (state='disabled')

    def Thread_Restart(self):                       # a thred for Start and Restart the thread
        self.Btn1.config (state='normal')
        self._running = True

        self.T = threading.Thread(target=self.Core) # define Thread

        if (self.T.is_alive() != True):             # Cheak the Thread is that alive
            self.T.start()

        self.Btn2.config (state='disabled')

    def Window (self):
        self.title(" Graph ")
        self.geometry("300x300+100+100")
        self.resizable(width=False, height=False)

        self.Lbl1 = Label(self,text = '0' ,font=('Times', -50, 'bold'), fg='Blue')
        self.Lbl1.pack()
        self.Lbl1.place(x=130, y=30 )

        self.Btn1 = Button(self,text= 'Thread OFF',width=25,command = self.Thread_Terminate)
        self.Btn1.pack()
        self.Btn1.place(x=50,y=100)
        self.Btn1 ['state'] = 'disable'

        self.Btn2 = Button(self, text='Thread ON', width=25, command=self.Thread_Restart)
        self.Btn2.pack()
        self.Btn2.place(x=50, y=140)

        self.Ent1 = Entry(self, width  = 30, fg='Blue')
        self.Ent1.pack()
        self.Ent1.place(x=50, y=180)

    def Core(self):                                 # this method is the thread Method
        self.count = 0
        i = self.Ent1.get()
        if (i==''):
            i='10'

        while (self._running and self.count<int(i)):
            self.count +=1

            self.Lbl1.config(text=str(self.count))

            print(str (self.count)+'Thread Is ON')
            time.sleep(0.5)

    def Run(self):
        A.Window(self)
        self.mainloop()

if __name__ == "__main__":
    Obj1 = A()


text:
Q: webpack cache option not working in esm module I have my package.json set as type="module".
I am trying to use filesystem cache provided in webpack 5 like
cache: {
        type: 'filesystem' //  Use file caching
    },

but keep getting warning as
<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: Can't resolve 'url' in 'C:\vbrick\rev-avenger-old'
<w> while resolving 'url' in C:\vbrick\rev-avenger-old as file
<w>  at resolve esm file url

I tried to use chaceLocation and cacheDirectory but still having same issue.
Any help highly appreciated!!!


text:
Q: how to install a downloaded theme to magento? I am using magento 1.8. I downloaded a theme,
http://www.templatemela.com/new-style-magento-theme.html

Now I have the theme zip file. I searched over the internet but I couldn't find any solution. I replaced the folders app, js, skin of magento root folder with the folders from theme folder. After that to activate the theme I open the admn dashboard I got an error,
The page isn't redirecting properly

Which is the correct way to install a new theme to magento?
Any one provide the step by step installation.

A: After you install the theme, go to System -> Configuration -> Design.
For the Themes section, set everything to modern, since that's the name of the theme.
The theme will now be applied.
If you're running the default install, you can make the front page look how the demo store on here does. For that you'll need to update the CMS blocks, so go to CMS -> Manage Pages. Click on the Home Page.
You'll be in the General Information section. Under Content, put the following:
{{block type="core/template" template="sample/home.phtml"}}
You can either comment out what's already there, or just remove it completely.
Then you need to go to Custom Design and set the Layout to 1 column.
That's it! Hope It will help you.

A: there are 3 steps to install a downloaded Magento theme. I followed this tutorial: http://magentoexplorer.com/how-to-manually-install-a-downloaded-magento-theme and successfully to install ultimo theme downloaded from Themeforest
Step 1: Extract/unzip template file
Step 2: Upload theme to Magento root folder
Step 3: Activate your new Magento theme
see the screenshot
Hope this helps


text:
Q: Getting Pandas DataFrame label indices from multiple columns I am figuring out how to get the indices of labels in Pandas DataFrame based on column values. I have the following DataFrame:
d = {'col1': ['label1', 'label2', 'label3'],
     'col2': ['label2', 'label3', 'label1'],
     'col3': ['label2', 'label1', 'label3'],
     'col4': ['label3', 'label1', 'label2']}

df = pd.DataFrame(data = d)

which formats as:
     col1    col2    col3    col4
0  label1  label2  label2  label3
1  label2  label3  label1  label1
2  label3  label1  label3  label2

I am trying to get it to the following form:
       label1 label2 label3
col1      0      1      2
col2      2      0      1
col3      1      0      2
col4      1      2      0

This tells the index of each label in the corresponding column in the original DataFrame df. For example, in col3, the indices of labels 1-3 are 1, 0 and 2, respectively.

A: You can transpose and then argsort:
res = pd.DataFrame(df.T.values.argsort(1),
                   columns=np.sort(df.iloc[:, 0].values),
                   index=df.columns)

print(res)

      label1  label2  label3
col1       0       1       2
col2       2       0       1
col3       1       0       2
col4       1       2       0

A: Use stack with reset_index and pivot:
df1 = df.stack().reset_index(name='v').pivot('level_1','v','level_0')
print (df1)
  v        label1  label2  label3
level_1
col1          0       1       2
col2          2       0       1
col3          1       0       2
col4          1       2       0

Or reset_index with melt and pivot:
df1 = df.reset_index().melt('index').pivot('variable','value','index')
print (df1)
 value     label1  label2  label3
variable
col1           0       1       2
col2           2       0       1
col3           1       0       2
col4           1       2       0

Last step is remove index and columns names:
df1.index.name = None
df1.columns.name = None
print (df1)
      label1  label2  label3
col1       0       1       2
col2       2       0       1
col3       1       0       2
col4       1       2       0


text:
Q: Getting results for multi_match cross_fields query in elasticsearch with custom analyzer I have an elastic search 5.3 server with products.
Each product has a 14 digit product code that has to be searchable by the following rules. The complete code should match as well as a search term with only the last 9 digits, the last 6, the last 5 or the last 4 digits.
In order to achieve this I created a custom analyser which creates the appropriate tokens at index time using the pattern capture token filter. This seems to be working correctly. The _analyse API shows that the correct terms are created.
To fetch the documents from elastic search I'm using a multi_match cross_fields bool query to search a number of fields simultaneously.
When I have a query string that has a part that matches a product code and a part that matches any of the other fields no results are returned, but when I search for each part separately the appropriate results are returned. Also when I have multiple parts spanning any of the fields except the product code the correct results are returned.
My maping and analyzer:
PUT /store
{
    "mappings": {
        "products":{
            "properties":{
                "productCode":{
                    "analyzer": "ProductCode",
                    "search_analyzer": "standard",
                    "type": "text"
                },
                "description": {
                    "type": "text"
                },
                "remarks": {
                    "type": "text"
                }
            }
        }
    },
    "settings": {
        "analysis": {
            "filter": {
                "ProductCodeNGram": {
                    "type": "pattern_capture",
                    "preserve_original": "true",
                    "patterns": [
                        "\\d{5}(\\d{9})",
                        "\\d{8}(\\d{6})",
                        "\\d{9}(\\d{5})",
                        "\\d{10}(\\d{4})"
                    ]
                }
            },
            "analyzer": {
                "ProductCode": {
                    "filter": ["ProductCodeNGram"],
                    "type": "custom",
                    "preserve_original": "true",
                    "tokenizer": "standard"
                }
            }
        }
    }
}

The query
GET /store/products/_search
{
    "query": {
        "bool": {
            "must": [
               {
                   "multi_match": {
                      "query": "[query_string]",
                      "fields": ["productCode", "description", "remarks"],
                      "type": "cross_fields",
                      "operator": "and"
                   }
               }
            ]
        }
    }
}

Sample data
POST /store/products
{
    "productCode": "999999123456789",
    "description": "Foo bar",
    "remarks": "Foobar"
}

The following query strings all return one result:
"456789", "foo", "foobar", "foo foobar".
But the query_string "foo 456789" returns no results.
I am very curious as to why the last search does not return any results. I am convinced that it should.

A: The problem is that you are doing a cross_fields over fields with different analysers. Cross fields only works for fields using the same analyser. It in fact groups the fields by analyser before doing the cross fields. You can find more information in this documentation.
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html#_literal_cross_field_literal_and_analysis

A: Although cross_fields needs the same analyzer across the fields it operates on, I've had luck using the tie_breaker parameter to allow other fields (that use different analyzers) to be weighed for the total score.
This has the added benefit of allowing per-field boosting to be calculated in the final score, too.
Here's an example using your query:
GET /store/products/_search
{
    "query": {
        "bool": {
            "must": [
               {
                   "multi_match": {
                      "query": "[query_string]",
                      "fields": ["productCode", "description", "remarks"],
                      "type": "cross_fields",
                      "tie_breaker": 1   # You may need to tweak this
                   }
               }
            ]
        }
    }
}

I also removed the operator field, as I believe using the "AND" operator will cause fields that don't have the same analyzer to be scored inappropriately.


text:
Q: What is starting the artisan queue:work process I have a laravel 9.x project which has several queue jobs.
I am running on multiple AWS EC2 servers, meaning I simply load the same source code (repo) to both servers which are basically configured the same. (Same php, same MySQL connection, etc). I just have different subdomains mapped to each of the different servers. My queue driver/connection is configured for "database".
What I am trying to do is allow only server #1 to run/process the queue jobs as they are dispatched. So on Server #1 I have supervisor installed which has a .conf file to run the php artisan queue:work commands.
I have a total of 3 queues, two are for specific jobs and the 3rd is the default (unnamed) queue that handles all jobs that are not dispatched to a specific queue.
What I am finding is all the jobs for the 2 named queues are only running on server #1 as desired. However the jobs that do not specify a queue are sometimes being ran on server #2.
I just can't understand how this is if I never run the command: php artisan queue:work on server #2? Supervisor is not even installed on server #2 and I have never manually run the command on that server.
Is there anything in Laravel 9.x or composer that would automatically run the queue worker process?
As a second question is there still no command to cause the queue worker to stop?
Just as an example here is a line of code where I dispatch a job that creates a GIF from a video file:
GIFCreatorJob::dispatch($video->id);
This job often is ran on server #2 which is the server that calls the above line of code to dispatch.
TIA


text:
Q: I am trying to create a table of 8x8 squares in HTML using script I thought maybe doing this with a for loop like that

This code doesn't seem to work. Please understand that I am not at all fluent in js, so a solution with an explenationn will really help.

A: document.write would not work as you have tried here, it won't write the
 tags at the place you've mentioned either.
You need to modify the DOM, specifically the table element.
Below code, takes a reference of table and appends the 8 rows and 8 cols in it.

document.querySelector("table").innerHTML = new Array(8).fill("
" + new Array(8).fill("	").join("") + "
").join("");
td {
  border: 1px solid;
  padding: 5px;
}

PS: This is a basic example to get you started, there are better ways to achieve this. you should look more into DOM Manipulation in JS.

A: document.write() will never create a child element inside the
 element, you can create a child element for a parent with appendChild().
Here an example with pure JavaScript:

for (var i = 0; i < 8; i++) {
  var row = document.createElement("tr");
  document.getElementById('tbl').appendChild(row).setAttribute("id", 'row_' + i);
  for (var j = 0; j < 8; j++) {
    var column = document.createElement("td");
    document.getElementById('row_' + i).appendChild(column);
  }
}
table {
  border: 1px solid black;
}

td {
  border: 1px solid blue;
  padding: 3px;
  margin: 2px;
}

Here, the script will create a child
 for the
, then you can create child  for the
.

A: Use DOM manipulation methods and make sure to put


text:
Q: Error in database query I am trying to create table in MySql through Java program. There seems to be a error in the database query for creating table which I am not able to figure out. This is my java program
package Registration;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class StartBatch
{

    public void startBatch(String batch)

    {

    Connection connection=null;

        String connectionURL = "jdbc:mysql://localhost:3306/Batches";

        Statement stmt;

        ResultSet rs1;

        try

        {

            Class.forName("com.mysql.jdbc.Driver");

        connection = DriverManager.getConnection(connectionURL, "root", "");

             stmt=connection.createStatement();

         rs1=stmt.executeUpdate("CREATE TABLE IF NOT EXISTS `"+batch+"` (\n" +"  `id` int(11) NOT NULL AUTO_INCREMENT,\n" +"  `student` text NOT NULL,\n" +"  `fees` bigint(20) NOT NULL,\n" +"  PRIMARY KEY (`id`)\n" +") ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;");

   //The error is in above query
    }

                     catch(ClassNotFoundException e){

                            e.printStackTrace();

            }

            catch(SQLException e){

                            e.printStackTrace();

            }

            catch (Exception e){

                            e.printStackTrace();

            }

            finally {

            // Always close the database connection.

            try {

            if (connection != null) connection.close();

            }

            catch (SQLException ignored){

            }

        }

    }

}

Error:
java.lang.RuntimeException: Uncompilable source code - incompatible types: int cannot be converted to java.sql.ResultSet
    at Registration.StartBatch.startBatch(StartBatch.java:39)
    at org.apache.jsp.CreatedBatch_jsp._jspService(CreatedBatch_jsp.java:83)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

I am using Netbeans to run this class.

A: Try this :
int updt;
    updt=stmt.executeUpdate("CREATE TABLE IF NOT EXISTS " + batch + " (id int(11) NOT NULL AUTO_INCREMENT, student text NOT NULL, fees bigint(20) NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1");

http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)

A: First of all executeUpdate() is used for insert,delete and update queries so you should not use this for creating a table.
If you want to create a table using execute() of Statement or
PreparedStatement(mostly recommended) whose return type is void.
Moreover your stmt.executeUpdate(query) returns int type not ResultSet type please go through the Documentation


text:
Q: Android - ActionBar - How to get color of hold event There's a way to know the color of hold event on action bar? Like image below:
The theme is Theme.AppCompat.Light

I just want the color value... but, how?

A: you can achieve it by using custom action bar.
Add in onCreate methode:
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);

// create xml in layout and inflate into view.
View v = getLayoutInflator().inflate(R.layout.search, null);

// here you can find id add listener on add button.
Button addBtn = (Button)v.findViewById(R.id.addBtn);

addBtn.setonClickListener(this);

//Now add view in your action bar.
actionBar.setCustomView(v);

I think it will help.

A: This color is defined in xml file. you can create your own style by using:
actionbar style generator
or you can see the source code of
Theme.AppCompat
in summary this value is set statically and you can find it without needing to get it at the runtime because it is what you have styled.
for other part of your app you can create theme with
android holo colors
if you want the color value here it is:
The color is


text:
Q: How can I create a MediaSession in Nativescript? I'm trying to create an Android application with Nativescript. So far I'm doing great, except for one thing (and - considering this is an app for listening podcast - maybe the most important one).
To reproduce mp3 files in my app, I'm using a plugin quite famous, named nativescript-audio. It works great, except that doesn't show any control when phone is in Lock Screen. Which is something I want to give to user.
Reading some android developer documentation, I found out I might need a MediaSession, and then add some icons with actions and write some callback functions to manipulate the player.
Problem is: in Nativescript, how can I do that?
this.session = new android.media.session.MediaSession(
    android.content.Context,
    'My Media Session'
)

This is the snippet I used in my player TypeScript class. But not working, because I receive this error:
Error: Cannot marshal JavaScript argument function () { [native code] } at index 0 to Java type.

Anyone with this problem before willing to help me? Thanks a bunch!

A: You should pass a valid context, you are passing the context class definition itself.
import { android as androidApp } from "tns-core-modules/application";

this.session = new android.media.session.MediaSession(
  androidApp.context,
  'My Media Session'
)


text:
Q: What does Alex's mom say to her in Spanish at the end? What did Alex's mom say to her in Spanish at the end of Wizards of Waverly Place the Movie?

A: She says

"Te quiero, mi hijita"

which would be "I love you, my little girl." Or more idiomatically in English, perhaps "I love you, dear."