text:
Q: Run two Application on Same Port in Visual Studio I have run Two Applications in different ports.
One is : http://localhost:12345/
and another one is : http://localhost:50949/

Now I got a cors domain issue, So I want to run those applications on same port number in vs 2012

How can i do it?

A: I'm adding another answer with another option.  Using full-blown IIS has some advantages, but not everyone has it installed or even has the option to install it.  Visual Studio, by default, will assign ports to each project and create them in IIS Express.  However, you can easily override it in the project properties.
As an example, I might have two project that look like this:

*

*MyNamespace.Web (currently listening on port 12345)

*MyNamespace.Web.Api (currentlly listening on port 54321)

When I deploy these, I'll run them in different virtual directories like this:

*

*MyNamespace.Web on http://mysite/

*MyNamespace.Web.Api on http://mysite/api
To mimic this in Visual Studio with IIS Express, I can go to the Project Properties of MyNamespace.Web.Api and change the Project Url (under Servers, on the Web tab) to http://localhost:12345/api/ and click the "Create Virtual Directory" button.
My two projects are now running on IIS Express, using the same port, but in different virtual directories.

A: If you configure Visual Studio to use IIS you can configure both websites under a different Virtual Directory, which will allow you to run them side-by-side. It does require you to have your routing setup correctly to understand the difference between ApplicationRoot and WebRoot, and that you're using the HTML Helpers objects everywhere to setup your routs in links.
You can also configure virtual directories in IIS express if you want to, but I suspect you'll need to dive into the XML to make it work.


text:
Q: Media query for HDPI and MDPI Laptop screens not working I have to apply different property to an element for HDPI and MDPI screen.
I tried following code but it works only for HDPI not for MDPI.
@media screen and (min-width: 900px) {
  .myClass {
    margin-left: 34%;
  }
}
@media screen and (max-width: 899px) and (min-width: 500px) {
  .myClass {
    margin-left: 43%;
  }
}

Here media screen min-width 990px(HDPI) is working but for other it is not working. How should I do it?

A: /* (ldpi) Android*/
@media only screen and (-webkit-device-pixel-ratio:.75){
  /* CSS  */
}

/* (mdpi) Android*/
@media only screen and (min-device-width : 480px) and (max-device-width : 800px) {
  /* CSS  */
}

/* (hdpi) Android*/
@media only screen and (-webkit-device-pixel-ratio:1.5){
  /* CSS  */
}

Reference 1
Reference 2

A: Another solution is (.scss)
  @media only screen and (min-height: 500px) and (max-height: 800px) and (min-width: 600px) {
  margin-top: 0px;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: All 6-digit numbers consist of [6] which must contain 1,2,3 I'm required to find all possible numbers which consist of {1,2,3,4,5,6}, and include each of {1,2,3} at least once. For example: 113124 is good, but not 464612 because it's missing 3.
My approach was to first calculate all the sequences which contain 1,2,3 once. Which would be: $6\times5\times4\times3^3$. The reasoning is that you have 6 different places to place 3, then 5 for 2, and 4 for 1. Because I'm looking now for sequences which contain each digit only once I'd fill the 3 rest spots with {4,5,6} meaning $3^3$. Now for the case where you have a digit twice it would be: $3\times{6\choose2}\times4\times3\times3^2$. Using the same reasoning but this time you have $6\choose2$ ways to choose 2 positions for a number, then you are left with 4 places for the other number and so on. And you multiply by 3 for each number. So you carry on up to 4 times the same number, because if you would continue for 5 you don't have enough spots to fill in the other 2 numbers you must have, so the formula is:
$$ 6*5*4*3^3 + 3*{6\choose2}*4*3*3^2+3*{6\choose3}*3*2*3+3*{6\choose4}*2$$
Yet the answer is incorret, it's a question a friend asked me to do so I'm not aware of the exact solution, from what I recall he said the answer is roughly 11,000.

A: Let $A$ denote the set of $6$-digit numbers with digits in $\{1,2,3,4,5,6\}$.
For $i=1,2,3,4,5,6$ let $A_i$ denote the set of elements of $A$ that do not contain $i$ as digid.
Then with inclusion/exclusion and symmetry we find:$$|A_1\cup A_2\cup A_3|=3|A_1|-3|A_1\cap A_2|+|A_1\cap A_2\cap A_3|=3\cdot5^6-3\cdot4^6+3^6$$so that: $$|A|-|A_1\cup A_2\cup A_3|=6^6-3\cdot5^6+3\cdot4^6-3^6=11340$$


text:
Q: Qustion with contexts in chapter 3.3 book k&r In book is given to me function ----
/* binsearch find x in v[0] <= v[1] <= ... <= v[n-1] */
int bin( int x, int v[] , int n)
{
     int low, high , mid;

     low = 0;
     high = n -1;
     while( low <= high) {
            printf("LOL\n");
            mid = (low+high)/2;
            if( x < v[mid])
            high = mid + 1;
            else if ( x> v[mid])
            low = mid + 1;
            else return mid;

            }
return -1;
}

This is text for function:
Binary search first compares the input value x to the middle element of the array v. If x is less
than the middle value, searching focuses on the lower half of the table, otherwise on the upper
half. In either case, the next step is to compare x to the middle element of the selected half.
This process of dividing the range in two continues until the value is found or the range is
empty.
Why is it that when I put in int v[4] nexts elements = { 2,3,4,5} and for x = 2 the loop goes on forever?
Is this their mistake?

A: Your code has a typo.
Instead of
        if( x < v[mid])
        high = mid + 1;

there shall be
        if( x < v[mid])
        high = mid - 1;

Also it would be better if the function would be declared as
int bin( int x, const int v[] , int n);

because the algorithm does not change the array itself and could be applied to constant arrays.
Take into account that there is standard C function bsearch declared in header <stdlib.h>

A: You have made a slight error in the program... in the line 10 it should be
if(x<v[mid])
{
   high=mid-1;
}

...
rest is fine...thats why it was resulting in a forever loop


text:
Q: Can you force unreferenced code to be linked in from a static library? Here's the scenario - I have created a custom NSView subclass, and the implementation is in a static library. The class is never referenced from the final executable, only from the Interface Builder XML file. Since it's not referenced, it doesn't get included at link time, and as a result the class can't be found at runtime.
Is there any way to force it to be linked in, other thank link dynamically or compile the class directly into the executable itself?

A: You can use the class class method on it, which will mostly be a no-op, but will reference it from your code.
int main(int argc, const char** argv)
{
    [MyClass class]; // There you are! MyClass is now referenced from your code.

    /* ... rest of your main function ... */
}

A: Trying using -all_load or -force_load flags. See comments in the following post:
What does the -all_load linker flag do?

A: How about making a pointer to the offending class in the executable? That ought to force it and won't require you to allocate memory etc.


text:
Q: Is this proper English, 'who do you want to win'? Most of us know about the upcoming Mayweather and McGreggor match.
My friend asked me today
"Who do you want to win?"
That sounds so strange to me. I understand what he's saying but the English is just so strange sounding in that sentence.
Rather something like "Who do you want the winner to be? makes more sense, but the first sentence seems so odd to me. Is it properly formatted in English?

A: Neither your friend's question nor your version of it is correct; in both, the interrogatory pronoun should be the objective whom. Other than that, the two are both correct.
The construction in both sentences is an infinitive clause, consisting of a subject, an infinitive, and any modifiers. One possible source of confusion in both sentences is the fact that the infinitive clause is noncontiguous, with words not in the clause between parts of the clause.
In an infinitive clause, since there is no predicate (it is instead an infinitive), the subject takes case based on the clause's function in the sentence, not the subject's function in the clause. Because of this, the subjects of both infinitive clauses should be accusative, for both clauses are direct objects (You want whom to win).
Your revision made the infinitive that of a linking verb, which takes a predicate nominative (misleading name) of the same case as the subject. Because the subject (winner) is objective, the predicate nominative must be so as well; hence, whom.
With this replacement, both sentences would be correct, and they would have the same meaning.

A: Remember the sentence is a question.  Essentially question of preferred "fighter" .  A simple alternative might have been 'who is going to win ?'; however since the fight event has not occurred we don't know with certainty the answer.  The use of want here seems informative here as it implies the listener to give or form an opinion as too the likely outcome.


text:
Q: ARCore AnchorNode.setOnTapListener I am trying to add onTapListener to a node, but a code inside of it is never being called. Can someone spot a mistake I am doing?
private fun addNodeToScene(fragment: ArFragment, createAnchor: Anchor, renderable: ModelRenderable) {
    val anchorNode = AnchorNode(createAnchor)
    anchorNode.setOnTapListener{_,_ ->
        buttonasd.text = "asdasd" // this line is never called
    }

    val transformableNode = TransformableNode(fragment.transformationSystem)
    transformableNode.renderable = renderable
    transformableNode.setParent(anchorNode)
    fragment.arSceneView.scene.addChild(anchorNode)
    transformableNode.select()
}

A: to make it works you shold do following :
    private fun addNodeToScene(fragment: ArFragment, createAnchor: Anchor, renderable: ModelRenderable) {
    val anchorNode = AnchorNode(createAnchor)

    val transformableNode = TransformableNode(fragment.transformationSystem).apply {
        setOnTapListener { _, _ ->
            //TODO your action
            }

        }
        transformableNode.localPosition = Vector3(0f,0.3f,0f)
        transformableNode.renderable = renderable
        transformableNode.setParent(anchorNode)
        fragment.arSceneView.scene.addChild(anchorNode)
        transformableNode.select()
    }

A: Try a slightly different approach, like this:
private var grid = Array(ROW_NUM) {
    arrayOfNulls<TranslatableNode>(COL_NUM)
}

val anchorNode = AnchorNode(hitResult.createAnchor())
anchorNode.setParent(arFragment.arSceneView.scene)

grid.matrixIndices { col, row ->
    val renderableModel = droidRenderable?.makeCopy() ?: return@matrixIndices
    TranslatableNode().apply {
        setParent(anchorNode)
        renderable = renderableModel
        addOffset(x = row * spacing, z = col * spacing)
        grid[col][row] = this
        this.setOnTapListener { _, _ ->
            // button.text = "asdasd"
        }
    }
}

Hope this helps.


text:
Q: MVC 5 Ajax form with field updates asynchronously and still supporting a Full form post So I have been using MVC for a while but not a lot of Ajax.
So the issue i have is that I have a create view where the first field of the create view is a Date picker which on change i want ajax to change the selection dropdown of another field on the form. I have the Ajax update working , but the form Post (Create button), now only calls into the Ajax method on the controller. I want the Ajax post back to call the default method Create method on the Controller. So the Create form contains 3 fields

*

*A date (which has the OnChange Ajax submit)

*A drop down list of id's and text

*other fields as required

I have included the model and cshtml view files (one the partial). The controller is just simply a method taking either the datetime value or the entire model.
So I have the code working where, when the date changes it updates the relevant LocalIds field, but because the 'create' button is inside the Ajax.BeginForm tags, when the create button is pressed, it generates an Ajax call, and I want it to generate a Form Post. What am i missing
CreateModel
public class IdsSelection
{
    public string Id { get; set; }
    public List<SelectListItem> Selections { get; set; }
}

public class CreateModel
{
    [Display(Name="Local Id's")]
    public IdsSelection LocalIds;
    [Display(Name="Day")]
    [Required, DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode=true)]
    public DateTime Date { get; set; }
    [Required, Display(Name = "Other Value")]
    [Range(1.0, 1000000.0, ErrorMessage ="Value must be greater than zero")]
    public decimal OtherValue { get; set; }

    public CreateModel()
    {
        Date = DateTime.Today;
    }
}

CreateView.cshtml
@Model Demo.Models.CreateModel
....
@using (Ajax.BeginForm("ChangeDate", "Process", new AjaxOptions()
{
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET",
    UpdateTargetId = "changeid",
}))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Date, new
           {
               htmlAttributes = new
               {
                   autofocus = "autofocus",
                   @class = "form-control",
                   @Value = Model.Date.ToString("yyyy-MM-dd"),
                   onchange = "$(this.form).submit();"
               }
           })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })

        @Html.Partial("_ShowIds", Model.LocalIds)

            @Html.LabelFor(model => model.OtherValue, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.OtherValue, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.OtherValue, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {

}

_ShowIds.cshtml
@model Demo.Models.IdsSelection

    @Html.Label("Local Id", htmlAttributes: new { @class = "control-label col-md-2" })

        @if(Model.Selections.Count == 1)        // one
        {
            @Html.HiddenFor(model => model.Id)
            @Html.EditorFor(model => model.Selections[0].Text, new
            {
                htmlAttributes = new
                {
                    @class = "form-control",
                    @readonly = "readonly",
                }
            })
        }
        else            // more entries so show a dropdown
        {
            @Html.DropDownListFor(model => model.Id, Model.Selections, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model, "", new { @class = "text-danger" })
        }

A: You have not shown you controller methods, but assuming the method which generates this view is named Create(), then create a corresponding POST method
[httpPost]
public ActionResult Create(CreateModel model)

for saving the data. The remove @using (Ajax.BeginForm("ChangeDate", "Process", new AjaxOptions() { ..... ])) and replace with a normal form to post back to the server (and you can remove jquery.unobtrusive-ajax.min.js)
@using (Html.BeginForm())
{
    ....

Next create a controller method that returns your partial view based on the selected date
public PartialViewResult FetchLocalIds(DateTime date)
{
  IdsSelection model = // populate model based on selected date
  return PartialView("_ShowIds", model);
}

Next, in the view, wrap the current @Html.Partial() in a placeholder element

    @Html.Partial("_ShowIds", Model.LocalIds)

Then use jquery to handle the datepickers .change() event and call the FetchLocalIds() method to update the DOM using the .load() function.
$('#Date').change(function() {
  $('#localids').load('@Url.Action("FetchLocalIds")', { date: $(this).val() })
})

Note also to remove onchange = "$(this.form).submit();" from the @Html.EditorFor(model => model.Date, new { ... })


text:
Q: TypeError: Network request failed fetch in react native Iam trying to get data from url but getting this error "Network request failed", the URL is working correctly in postman, here is the output of postman

my code:
  const getCategories = async () => {
try {
  const url = "*******/api/categories/getRandomCategories/4"
  await fetch(url, {
    method: 'GET'
  }).then((res) => console.log(res.json()))
    .then((resJson) => {
      console.log(resJson)
    }).catch((e) => console.log(e))
} catch (error) {
  console.log(error)

}

}

A: We can't test your API endpoint because you do not provide it. You should try to see if an other endpoint is working properly with your code, you can use a random one for example.
Also your code is a bit messy, you are returning a console.log instead of your response as json in the first then. Try to simplify it like this:
const getCategories = async () => {
   try {
     const url = "..."
     const response = await fetch(url, {
       method: 'GET'
     })
     .then(response => response.json())
     .then(responseJson => console.log(responseJson))
   }
   catch (error) {
     console.log(error)
   }
}

Since you get a Network request failed you should verify that your url is the same as the one you use in Postman, e.g. if you use a base url constant make sure it is correct:
const baseUrl = 'https://yourdomain.com' // Be sure there is no "/" at the end.
const url = baseUrl + '/api/categories/getRandomCategories/4'

Finally you should verify you use the correct headers to when fetching.


text:
Q: Does electromagnetic induction moves the body or it just makes an induced current? If I approched a magnet to a coil does it moves it by the effect of induced electric current so it repells away from the magnet or it just induces the current in the coil without the coil making a flux that makes a repulsion force that can make the coil move away?

A: you can think of the repulsion due to a coil and a magnet in two ways
way 1: a coil and a magnet both have a magnetic field.A magnetic pressure force between them causes a force of repulaion/attraction
or 2, the lorentz force on each of the e.g  moving  charges in the coil q( vxb) cause it to repell
You are over complicating it, yes technically there is an induced electric field if i were to MOVE a magnet near a coil of current. however there is still a repulsion force in a magnostatic case


text:
Q: Is there a way to restore or re-link an active directory user with a local cached version of the user from a corrupted domain? I used to run an Active Directory installation.  The AD server had died a few years back and I'd just been running on cached credentials since I didn't have hardware available to rebuild on and hadn't been using AD for that many services.
I recently got a new server and am trying to get AD set back up.  I am unable to boot the old system and don't know where backups are of the old AD tree.  I was able to associate the computer to the new domain, but presumably since SIDs don't match up, it recreated new users with the same name (but a .000 on the user directory) for my user.  I'm trying to figure out a good way to merge the old local user with the new AD account.  I'm aware that it can be done by moving registry entries and files from one set of user files to the other such as is described here, but I wasn't sure if there might be a simpler, more direct way to force a re-association despite the change in SID.  The domain name and username are the same for both.

A: As others said, you can't really do this. The cached credentials wouldn't be of much use anyway - as far as I know the only thing of much interest are the usernames and passwords and they are held using a different hash from the one on the directory so you can't reimport them.
User SIDS will be recreated in the new directory anyway, sort of by definition. If you want to import users from another domain so they keep their security rights you need to use the regular import tools. But you won't have those cached on the PC anyway. So you will need to (re)grant your users access to whatever domain resources they need.

A: You should know that questions about home networks are off topic here, but I'll throw you a bone since this is easy.
You can't "force a re-association despite the change in SID" whatever that means. What you can do is use the User State Migration Tool, or simply use the Copy Profile feature to copy your old account's profile to your new one.


text:
Q: Center divs inside div I have two tables inside divs inside another div:
HTML

Example

Example

CSS
.container {
    width: 100%;
    overflow: hidden;
    float: left;
    border: 1px solid red;
    text-align: center;
}
.tabel {
    border: 1px solid black;
    border-collapse: collapse;
    padding: 5px;
}
.thing {
    width: 50%;
    float: left;
    min-width: 230px;
}

.center {
   margin: 0 auto;
}

The two cells are centered correctly
[Image deleted by host]
but when the width of the screen gets too small, the cells go underneith each other (what I want), but they no longer get centered:
[Image deleted by host]
So what I want them to look like:
[Image deleted by host]

A: You have to remove float: left;, set display: inline-block; and eliminate white space between them.
.thing {
    width: 50%;
    display: inline-block;
    /* float: left; */
    min-width: 230px;
    vertical-align: top;
}

fiddle: http://jsfiddle.net/3g7xk0sj/1/

A: Just use media query http://jsfiddle.net/3g7xk0sj/3/
@media all and (max-width: 480px) {
    .thing {
        width: 100%;
    }
}

A: The problem you are facing is that you are telling each floating DIV (class thing) to be 50% width a minimum of 230px, but it will never span to 100% of the container's width (unless the container is also 230px wide). So the auto margin will only be applied within class .thing's width, which is 230px. Now add to that your table that is ALSO 230px wide, no margin will ever be rendered and consequently you tables will never float in the center.
Try using a CSS media query instead to force a 100% width on class thing when the screen size goes below 460px (230px*2).
Alternatively, use display: inline-block instead of floating, as emmanuel suggested.

A: Remove float:left & use margin:0 auto in thing class

A: Demo http://jsfiddle.net/3g7xk0sj/4/
.container {
    width: 100%;
    overflow: hidden;
    float: left;
    border: 1px solid red;
    text-align: center;
}
.tabel {
    border: 1px solid black;
    border-collapse: collapse;
    padding: 5px;
}
.thing {
    margin: 0 auto;
    width: 50%;
}

Example

Example


text:
Q: iPad Safari reloads main page constantly Our Webapp site has strange problem where we get occasionally huge number of page reloads from Apple iPad Safari.
What happens is that Safari opens keep alive HTTP 1.1 connection to our server and issue streams of GETs to it. The requests can arrive only tens of milliseconds from each other and it seems Safari is reloading the page as soon as it gets response to previous request. After sending 4-5 requests, Safari closes socket, opens new and same thing repeats for several minutes until it suddenly stops.
Things checked

*

*Happens only with main page root url /

*Page has no window.location.reload call on load that could cause this

*Confirmed with tcpdump and wireshark that problem is real and happens between iPad device and our server. (i.e. not problem with haproxy, our servers or buggy logging)

*Problem seems to be mainly with iOS 4.3.3

*I can not ask the users and we have not repeated this locally with testing devices

*All problem requests come from single IP that seems like VPN gateway of a school but from different random users (based on cookies same users may use webapp days successfully until problem repeats)

Has anyone idea what might be happening here?

*

*Broken proxy somehwere?

*iOS HomeScreen webapp bookmark gone haywire?

*DoS attempt, though lame one

*People turn zombies while using our webapp and instead of Brainsss they crave Reloadss?


text:
Q: How can I get the names of name-value pairs in Handlebars? I have this data structure:
flavors": {
            "sour": 0.16666666666666666,
            "salty": 0.16666666666666666,
            "sweet": 0,
            "meaty": 0.16666666666666666,
            "bitter": 0.16666666666666666
        }

My html is this:

Flavors:

     {{#Flavors}}

{{Flavours.Name}}
  // doesn't work  //
        {{/Flavors}}

What I'm trying to do is get at the name of the flavour: i.e. salty, sour, etc. I want to be able to cater for arbitrary values is the JSON, and not code them in the html block.

A: You may iterate over the object in this way:
{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

For details check this post: Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

A: the answer to my question is on this page:
Handlebars/Mustache - Is there a built in way to loop through the properties of an object?
it's Ben's answer. Works very well indeed!

A: Iterate over json and use key to get property names.
for (var key in obj) {
   alert(' name=' + key + ' value=' + obj[key]);
   // do some stuff here
}

A: Your template should be like the following:

Flavors:

 {{#each flavours}}

{{@key}}

    {{/each}}

according with the documentation on the website.


text:
Q: Error while updating item from datasheet view There is a problem while updating any item in datasheet view of discussion list. While editing any item I get error as "you must specify non-blank value for Name". even though there is no column named 'Name' ?
I checked type conflicts as well. but there is not any.!
Any idea?

A: Please check if you had set any hidden fields to non-blank. If so, you need to change the option "Require that this column contains information" of them to "no".
See the following article:
http://www.alexangas.com/blog/2009/07/the-rows-you-modified-could-not-be-saved-to-the-server-due-to-validation-errors/


text:
Q: How can I validate select input in RShiny app? I want to ask, can somebody help me how to validate select input like this ? We assume that there is no factor in iris. Is there some way how to validate it ?
Server:
output$choose_y = renderUI({
    is_factor <- sapply(iris, FUN = is.factor)
    y_choices <- names(iris) [is_factor]
    selectInput('choose_y', label = 'Choose Target Variable', choices = y_choices)
})

Ui:
uiOutput('choose_y')

A: To illustrate our discussion in comments, you could check if any factor is present in dataset:
# With iris
is_factor <- sapply(iris, FUN = is.factor)
y_choices <- names(iris) [is_factor]
validate(need(any(is_factor),"No factor in dataset"))
print(paste('OK to use iris'))

#[1] "OK to use iris"

# With mtcars
is_factor <- sapply(mtcars, FUN = is.factor)
y_choices <- names(mtcars) [is_factor]
validate(need(any(is_factor),"No factor in dataset"))

Error: No factor in dataset


text:
Q: How to grab the year from a string with php I have a couple of strings which look like this:
$string1 = '03 Aug 2020 00:49'
$string2 = '15 Sep 2019 23:02'
$string3 = '21 Jul 2018 22:48'
How can i grab the year only out of the string? ( so 2020 or 2019 or 2018)

A: Try This
echo date("Y", strtotime($string1));
echo date("Y", strtotime($string2));
echo date("Y", strtotime($string3));

A: Easiest solution if the format is allways like you described:
echo substr($string1, 7,4);


text:
Q: How to get the next date when click on button in android? In my application i have a text view to set the current date and two buttons for next date and previous date.
When click on next button i need to set the next date to text view without opening the date picker and similarly to previous button also.
Please can any one help me.

A: You could use the Calendar to get the current date. And then if you want the previous date you could use c.add(Calendar.DATE, -1) where -1 is the number of days you want to decrement from current date. In your case we want the previous date so used -1.Similarly, to get the next date use c.add(Calendar.DATE, 1). You can get the number of days previous or before just by altering the integer.
First of all to set current date to textview.
Calendar c = Calendar.getInstance();

System.out.println("Current time => " + c.getTime());

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());

textview.setText(formattedDate);

Then on previous button click:
previous.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                c.add(Calendar.DATE, -1);
                formattedDate = df.format(c.getTime());

                Log.v("PREVIOUS DATE : ", formattedDate);
                textview.setText(formattedDate);
             }
});

On Next Button click:
next.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                c.add(Calendar.DATE, 1);
                formattedDate = df.format(c.getTime());

                Log.v("NEXT DATE : ", formattedDate);
                textview.setText(formattedDate);
            }
});

A: Try this,
private static SimpleDateFormat  dateFormat  = new SimpleDateFormat("dd -MM-yyyy", Locale.US);

int dayShift = n; // Positive for next days, negative for previous days
Calendar c = Calendar.getInstance();
if (dayShift  != 0) {
        c.add(Calendar.DAY_OF_YEAR, dayShift);
}
mdate.setText(dateFormat.format(c.getTime());

A: Use the following code:
Calendar mCalendar  = new GregorianCalendar(year, month, day);
mCalendar.add(Calendar.DAY_OF_YEAR, 1);
Date mDate          = mCalendar.getTime();

start of by initializing you calendar, add  mCalendar.add(Calendar.DAY_OF_YEAR, 1); or substract mCalendar.add(Calendar.DAY_OF_YEAR, -1); a day, get the current date, then format it to your needs


text:
Q: Computing trace of matrix Let A be a n×n matrix such that $$[a_{ij}]_{n×n}=\frac{((-1)^i)(2i^2+1)}{4j^4+1}$$ then what is
$$1+ \lim_{n\to {\infty}}\left(tr(A^n)^{1/n}\right)$$
I cannot figure out how to calculate trace of $$A^n$$

A: If $\{\lambda_k\}$ are the eigenvalues of $A$, then $A^m$ has eigenvalues $
\{\lambda_k^m\}$ and so:
$$\text{trace} A^m = \sum_{i=1}^n\lambda_k^m.$$
If these eigenvalues are non-negative reals, then you can easily show that:
$$\lim\limits_{m\to\infty}\sqrt[m]{\lambda_1^m+\dots \lambda_n^m} = \max\limits_k \lambda_k.$$
what remains to be done is to find the eigenvalues of your matrix which I do not see an immediate formula for.

A: Answer complementing the answer of @dezdichado.
In fact this matrix is the product of the (column) vector $U$ with coordinates:
$$(-1)^i(2i^2+1), \ \ \ \ i=1 \cdots n$$
with the line vector $V^T=$ with coordinates
$$\frac{1}{4j^4+1}, \ \ \ \ j=1 \cdots n$$
Therefore $A=UV^T$ is a rank 1 matrix. As such, it has eigenvalue $0$ with multiplicity $n-1$, and a nonzero eigenvalue that is plainly the trace, therefore the real number:
$$\lambda=\sum_{i=1}^n a_{ii}=\sum_{i=1}^n \frac{(-1)^i(2i^2+1)}{4i^4+1}$$
which has a closed form expression due to its alternate signs yielding a telescoping behavior (observation made by Dezdichado):
$$\lambda=\dfrac{-2n^2-2n-1+(-1)^n}{(2n+1)^2+1}$$
Remark: the result obtained is the square of the so-called spectral norm of $A$.


text:
Q: Pandas concat multi level index dataframes and merge same name columns within same level I have two multi-level index dataframes. When I concat them, the same name columns become duplicated.
df1
Column
  col1 col2
     1    3
     2    4

I want to merge this with another df,
df2
Column
  col3
     5
     6

When I merge both using
pd.concat([df1, df2], axis=1)

The result comes:
Column      Column
  col1 col2   col3
     1    3      5
     2    4      6

What I want to get is:
Column
  col1 col2 col3
     1    3    5
     2    4    6

Any help would be much appreciated. Thanks

A: Use DataFrame.sort_index:
pd.concat([df1, df2], axis=1).sort_index(axis=1)

EDIT:
print (df1)
  Column
    col5 col2
0      1    3
1      2    4

print (df2)
  Column
    col1
0      5
1      6

df = pd.concat([df1, df2], axis=1)

c = df.columns.tolist()
df = df.reindex(c[:1] + sorted(c[1:]), axis=1)
print (df)
  Column
    col5 col1 col2
0      1    5    3
1      2    6    4

EDIT1: Use DataFrame.xs with DataFrame.sort_index, add original non selected caolumns values by Index.union and last change order by DataFrame.reindex:
print (df)
  Column              a
    col2 col1 col5 col1 col3
0      1    5    3    5    4
1      2    6    4    7    7

cols = (df.xs('Column', drop_level=False, axis=1, level=0)
          .sort_index(ascending=False, axis=1).columns)
print (cols)
MultiIndex([('Column', 'col5'),
            ('Column', 'col2'),
            ('Column', 'col1')],
           )

df = df.reindex(cols.union(df.columns, sort=False), axis=1)
print (df)
  Column              a
    col5 col2 col1 col1 col3
0      3    1    5    5    4
1      4    2    6    7    7

A: We can also use DataFrame.combine_first:
df3 = df1.combine_first(df2)


text:
Q: Using better-sqlite3 in an Angular + Electron app: Module parse failed: Unexpected character In my Angular + Electron app I'm trying to install some sqlite library in order to read contents from an sqlite database file.
I've installed better-sqlite3 using:
npm install --save better-sqlite3
npm install --save-dev @types/better-sqlite3

And I've tried to use it doing:
import * as sqlite from 'better-sqlite3';

// ...

const myDb = sqlite('/path/to/file.sqlite');

However when the application builds it fails with:

ERROR in ./node_modules/better-sqlite3/build/better_sqlite3.node 1:0
  Module parse failed: Unexpected character '' (1:0) You may need an
  appropriate loader to handle this file type, currently no loaders are
  configured to process this file. See
  https://webpack.js.org/concepts#loaders (Source code omitted for this
  binary file) ERROR in ./node_modules/integer/build/integer.node 1:0
  Module parse failed: Unexpected character '' (1:0) You may need an
  appropriate loader to handle this file type, currently no loaders are
  configured to process this file. See
  https://webpack.js.org/concepts#loaders (Source code omitted for this
  binary file)

It looks like I'm not the first experiencing this issue when using Electron. Infact, the issue has been discussed here and and here however I couldn't find a solution that works for me.

A: Have you tried to use @angular-builders/custom-webpack?
npm i @angular-builders/custom-webpack --save-dev

in your angular.json file, set this under your architect:
"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./angular.webpack.js"
      },

and then add a custom config file angular.webpack.js at the root of your project:
module.exports = {
  externals: {
    'better-sqlite3': "require('better-sqlite3')"
  }
};


text:
Q: Where are Django directories created? I installed Django 1.8.4 for Python 3.4 and whenever I type into the command prompt:
django-admin.py startproject newsite

a new window opens up in Python IDLE with the following inside of it:
#!C:\Python34\python.exe
from django.core import management

if __name__ == "__main__":
    management.execute_from_command_line()

I know there is supposed to be a new directory with manage.py and url.py etc. inside of it but I can't find it. I opened up C:\python34\Scripts and there is no new directory.
I've also tried typing into the command prompt:
python C:\python34\Scripts\django-admin.py startproject newsite

and then nothing happens, no window or anything.

A: Per the documentation (emphasis mine):

startproject <projectname> [destination]
django-admin startproject
Creates a Django project directory structure for the given project
  name in the current directory or the given destination.
By default, the new directory contains manage.py and a project
  package (containing a settings.py and other files). See the template
  source for details.
If only the project name is given, both the project directory and
  project package will be named <projectname> and the project
  directory will be created in the current working directory.
If the optional destination is provided, Django will use that existing
  directory as the project directory, and create manage.py and the
  project package within it. Use . to denote the current working
  directory.
For example:
django-admin startproject myproject /Users/jezdez/Code/myproject_repo


text:
Q: How to export and import an array with dynamic values in it, in javascript? I have an array that take dynamically objects as values.
I want to export it (with all values, of course) to another js file and have access to all the elements (actually objects) of the array from there but, can't find how...
Any ideas will be very appreciated.

A: You can do this in 2 ways
1) Persist the data into a file as json. When you have all your data collected write it to a .json file. Then you can read it in another file and access the data. (Note: only in Node.js environment)
// file1.js
const fs = require('fs')
const data = [your_ready_data]
const stringified = JSON.stringify(data)
fs.writeFileSync("store.json", stringified, {encoding: "utf8"});

// file2.json
const dataString = fs.readFileSync("store.json", { encoding: "utf8" });
const data = JSON.parse(dataString) //
// ...

2) send as argument.
//file1.js
const mainFunction = (list) => {
  //....
}

// file2.js
import mainFunction from 'file1.js'
const collectDate = () => {
  //....
  const data = [your_ready_data]

  mainFunction(your_ready_data)
  //....
}


text:
Q: how to auto precompile asset when client upload images in production in Rails 5 My rails' app has uploading images function.
Precompiled assets will be created in public/assets When I deploy rails app in production and run
RAILS_ENV=production rake assets:precompile

I will get below error messages every time user upload images successfully in admin platform and request showing that created image.
    ActionView::Template::Error (The asset "course/main_photo/XXXX/Course_ss12344.png" is not present in the asset pipeline.):
In those messages, I found that images created by user didn't precompile in the public/assets.
config.assets.compile = true # when I set true for config.assets.compile, server will response assets slowly that is not good choice.

config/environments/production.rb  # below is my relative code in production's config
config.assets.compress = true
config.assets.compile = false
config.assets.digest = true
config.serve_static_assets = true

Can anyone give me some advice on how to auto precompile assets or other advice when user upload images online?

A: Try this
Remove previous pre-compiled assets by running
"rake assets:clobber"
than do "rake assets:precompile" and Restart your server


text:
Q: Spring MVC 3.2 - XStreamAlias Ignored Person.java:
@XStreamAlias("person")
public class Person {
    @XStreamAlias("id")
    private Long personProfileId;
    private String lastName;
    private String firstName;
    private String middleName;
    private String nameSuffix;
    private String namePrefix;

    // etc ...
}

Spring configuration:
<bean id="contentNegotiationManager"
    class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="useJaf" value="false" />
    <property name="defaultContentType" value="application/xml" />

    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
        </map>
    </property>
</bean>

<bean
    class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="order" value="1" />
    <property name="contentNegotiationManager" ref="contentNegotiationManager" />

    <property name="defaultViews">
        <list>
            <bean
            class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />

            <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                <constructor-arg>
                    <bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
                </constructor-arg>
            </bean>
        </list>
    </property>
</bean>

<mvc:annotation-driven
    content-negotiation-manager="contentNegotiationManager" />

A call to http://mycompany.com:8080/myapp/persons?format=xml returns:
<?xml version="1.0" encoding="UTF-8"?>
<list>
<com.example.myapp.model.Person>
    <personProfileId>1</personProfileId>
    <lastName>McCartney</lastName>
    <firstName>James</firstName>
    <middleName>Paul</middleName>
</com.example.myapp.model.Person>
<com.example.myapp.model.Person>
    <personProfileId>2</personProfileId>
    <lastName>Lennon</lastName>
    <firstName>John</firstName>
    <middleName>Winston</middleName>
</com.example.myapp.model.Person>
<com.example.myapp.model.Person>
    <personProfileId>3</personProfileId>
    <lastName>Starkey</lastName>
    <firstName>Richard</firstName>
</com.example.myapp.model.Person>
<com.example.myapp.model.Person>
    <personProfileId>4</personProfileId>
    <lastName>Harrison</lastName>
    <firstName>George</firstName>
</com.example.myapp.model.Person>
</list>

I would expect it to return:
<?xml version="1.0" encoding="UTF-8"?>
<list>
<Person>
    <id>1</id>
    <lastName>McCartney</lastName>
    <firstName>James</firstName>
    <middleName>Paul</middleName>
</Person>
<Person>
    <id>2</id>
    <lastName>Lennon</lastName>
    <firstName>John</firstName>
    <middleName>Winston</middleName>
</Person>
<Person>
    <id>3</id>
    <lastName>Starkey</lastName>
    <firstName>Richard</firstName>
</Person>
<Person>
    <id>4</id>
    <lastName>Harrison</lastName>
    <firstName>George</firstName>
</Person>
</list>

It seems like XStream is correctly being called to marshall the object to XML, but that the @XStreamAlias annotations are being ignored. Is there some further configuration needed to get this to work?

A: I was trying to figure out this same thing (though with a Spring Boot project) and found an alternative: autodetectAnnotations.
xstreamMarshaller.setAutodetectAnnotations(true);

See this project, add the above line to the Application.java.

A: Figured it out. The annotated classes need to be explicitly identified to the XStreamMarshaller.

<property name="defaultViews">
    <list>
        <bean
        class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />

        <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
            <constructor-arg>
                <bean class="org.springframework.oxm.xstream.XStreamMarshaller">
                    <property name="annotatedClasses">
                        <array>
                            <value>com.example.myapp.model.Person</value>
                        </array>
                    </property></bean>
            </constructor-arg>
        </bean>
    </list>
</property>

A: As per XStream documentation https://x-stream.github.io/annotations-tutorial.html
you have to use xstream.processAnnotations(MyPOJO.class);


text:
Q: can we build for Symbian^3 same code done in s60 3rd edition using lwuit I have made application in j2me using lwuit and successfully built on S60 3d edition FP2, now to make wide compatibility i want to make build for Symbian^3, so is it possible?

A: Yeah its possible. Because LWUIT supports both touch and non touch mobiles and no need to change the code for this. AFAIK you have to check following steps,

*

*Resolution: Because resolution of symbian s60 3rd edition not more than 240x320 or 320x240. But symbian^3 smartphone having 640x360 or 360x640.

*MenuBar: Look on this blog

*Drag and Drop: You can enable drag and drop the components If you needs.

Just test the LWUITDemo application from repository on symbian s60 3rd editon and symbian^3 mobiles. Then you can find the what are all the changes have to do. Also look on this wiki information about Symbian.

A: You should be able to use the same jar file on the Symbian^3 devices, unless some of the APIs have changed. At least this was true for S60 5th edition, I've never used j2me on Symbian^3 myself.


text:
Q: Sortable column headers based off dynamic input? Firstly I'd like to apologize for the topic question... I simply couldn't think of a question. Mainly because I don't know what I am looking for. I just need a hint or a pointer to the general direction of how to solve my problem. I think this is where my inexperience with the web shows a little... Anyway!
So what I have right now is a drop down with users in it. Select the user, and info comes up in 4 columns. That info needs to be sortable from the column headers. I can do both things independently from each other (the selection and the sorting), but I think the post/submit of the dropdown happens before I can save the variables to be passed in the URL, so I can't get it to behave properly.
So here's the code:
<form action="" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
  User: <select name="user_id">
<?php foreach($users as $user): ?>
<option value="<?php echo $user['id']; ?>" <?php echo ($user_id == $user['id'] ? 'selected' : ''); ?>><?php echo $user['name']; ?></option>
<?php endforeach ?>
</select>
<input type="submit" name="submit" value="Select">
</form>

Name
Priority
Date Created
Age

What I think is happening is that the submit happens before the variables can be set to send to the database file. If I have a user selected and click on the column header to sort it, it takes me back to the default where there is no user selected.
Any ideas, tips or help?
Thanks


text:
Q: WAMP Virtual Host Not Working with Personal Project I have virtual machine running windows 2012 server in a LAN that is connected to the internet. There is also a wamp server in the windows server.. I have configure a wamp virtual host in the machine with the following details
Apache version is 2.4.18
Mysql version is 5.7.11
PHP version is 5.6.19

The project folder is datacentre
This is the path.
C:\wamp\www\datacentre

When I type localhost into the url I get the wamp home page
when I type localhost/datacentre into the url I get the datacentre homepage
But when I type datacentre into the url it rather it serches the net.
this is the path to the host file
C:\Windows\System32\drivers\etc

This is the host file from the windows server.
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#ne
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

   127.0.0.1 localhost
   127.0.0.1 datacentre

  ::1 localhost
  ::1 datacentre

This is the path for the httpd.conf file
C:\wamp\bin\apache\apache2.4.18\conf

Uncommented the virtual host line.
    # Virtual hosts
    Include conf/extra/httpd-vhosts.conf

this is the path to the httpd-vhost file
C:\wamp\bin\apache\apache2.4.18\conf\extra

This is the httpd-vhost.conf file
#
# Virtual Hosts
#

<VirtualHost *:80>
    ServerName localhost
     ServerAlias localhost
    DocumentRoot c:/wamp/www
    <Directory  "c:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName datacentre
     ServerAlias datacentre
    DocumentRoot "c:/wamp/www/datacentre"
    <Directory  "c:/wamp/www/datacentre">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>


text:
Q: Multi-location entity query solution with geographic distance calculation in my project we have an entity called Trip. This trip has two points: start and finish. Start and finish are geo coordinates with some added properties like address atc.
what i need is to query for all Trips that satisifies search criteria for both start and finish.
smth like
select from trips where start near 16,16 and finish near 18,20 where type = type

So my question is: which database can offer such functionality?
what i have tried
i have explored mongodb which has support for geo indexes but does not support this use case. current solution stores the points as separate documents which have a reference to a Trip. we run two separate quesries for starts and finishes, then extract ids of their associated trips and then select trip ids that are found both in starts and finishes and finally return a collection of trips.
on a small sample it works fine but with a larger collection it gets slow and it's like scratching my left ear with my right hand.
so i am looking for a better solution.
i know about neo4j and its spatial plugin but i couldn't even make it work on windows. would it support our use case?
or are there any better solutions? preferably with a object mapper written in php.

A: like edze already said Postgres (PostGIS) or SQLite(SpatiaLite) is what your looking for
SELECT
  *
FROM
  trips
WHERE
  ST_Distance(ST_StartPoint(way), ST_GeomFromText('POINT(16 16)',4326) < 5
  AND ST_Distance(ST_EndPoint(way), ST_GeomFromText('POINT(18 20)',4326) < 5
  AND type = 'type'


text:
Q: How to copy a character array into another character array in 'c' using pointers and without using string library How do I copy a character array into another character array in C using pointers and without using string library?
I've tried this:
Header File:
char strconcat(char a[100], char b[100]) {
    int i=0,j=0;
    while(a[i] != '\0'){
        i++;
    }
    while(b[j] != '\0'){
        a[i] = b[j];
        j++;
        i++;
    }
    return a[100];
}

A:  char *strconcat(char *dst, const char *src)
 {
     char *bak = dst;
     while (*dst) dst++;
     while (*dst = *src)
     {
          dst++;
          src++;
     }
     return bak;
 }

Note you cannot have char a[100] as your function parameters. In C this notation is automatically converted to char a[] that is equivalent to char *a.
You also don't have to compare things to 0. Omitting a comparison will make that happen by default.

A: void strconcat(char *a, char *b)
{

 int i=0,j=0;
 while(a[i++]!='\0')
         ;
 while(b[j]!='\0')
       a[i++]=b[j++];
 a[i] = '\0';
}

A: The first version naively assumes enough space in destination,
char *
my_strcat(char *destp, char *srcp)
{
    if(!destp) return(destp); //check that dest is valid
    if(!srcp) return(destp);  //check that src is valid
    char *dp=destp; //save original destp
    while(*dp) { dp++; }      //find end of destp
    while(*srcp)
    {
        *dp++ = *srcp++;      //copy src to dest, then increment
    }
    return(destp);
}

The second version allows you to specify maximum size for destination,
char *
my_strncat(char *destp, char *srcp, long max)
{
    if(!destp) return(destp); //check that dest is valid
    if(!srcp) return(destp);  //check that src is valid
    char *dp=destp; //save original destp
    long x=0;
    while(*dp && (x<max)) { dp++; ++x; }      //find end of destp
    while(*srcp && (x<max))   //copy from src while more space in dst
    {
        *dp++ = *srcp++; ++x; //copy src to dest, then increment
    }
    *dp = '\0'; //ensure destination null terminated
    return(destp);
}


text:
Q: How can I override Resharper's GetHashCode generation routine After selecting Generate > Equality members ReSharper generates a GetHashCode() method with body
public override int GetHashCode()
{
    unchecked
    {
        var hashCode = (int) Property1;
        hashCode = (hashCode * 397) ^ Property2;
        hashCode = (hashCode * 397) ^ Property3.GetHashCode();
...
        return hashCode;
    }
}

according to several articles
What is the best algorithm for an overridden System.Object.GetHashCode?
https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash
I'd like to generate my own GetHashCode() method
(inspired by first SO answer)
public override int GetHashCode()
{
    unchecked
    {
        int hash = (int) 2166136261;
        hash = (hash * 16777619) ^ Property1.GetHashCode();
        hash = (hash * 16777619) ^ Property2.GetHashCode();
        hash = (hash * 16777619) ^ Property3.GetHashCode();
...
        return hash;
    }
}

Is it possible ? How ?


text:
Q: Image Carousel Codepen Images not loading I have been trying to implement this codepen [https://codepen.io/LokeshNagarajan/pen/apRmZe?editors=1111] on my website but like in the codepen the images do not load even if I assign an https src and i believe the issue stems from the javascript but not sure exactly what to do to fix it.
(function ($) {
  'use strict';

  $.fn.waterwheelCarousel = function (startingOptions) {

// Adds support for intializing multiple carousels from the same selector group
if (this.length > 1) {
  this.each(function () {
    $(this).waterwheelCarousel(startingOptions);
  });
  return this; // allow chaining
}

var carousel = this;
var options = {};
var data = {};

function initializeCarouselData() {
  data = {
    itemsContainer: $(carousel),
    totalItems: $(carousel).children().length,
    containerWidth: $(carousel).width(),
    containerHeight: $(carousel).height(),
    currentCenterItem: null,
    previousCenterItem: null,
    items: [],
    calculations: [],
    carouselRotationsLeft: 0,
    currentlyMoving: false,
    itemsAnimating: 0,
    currentSpeed: options.speed,
    intervalTimer: null,
    currentDirection: 'forward',
    leftItemsCount: 0,
    rightItemsCount: 0,
    performingSetup: true
  };
  data.itemsContainer.children().removeClass(options.activeClassName);
}

/**
 * This function will set the autoplay for the carousel to
 * automatically rotate it given the time in the options
 * Can clear the autoplay by passing in true
 */
function autoPlay(stop) {
  // clear timer
  clearTimeout(data.autoPlayTimer);
  // as long as no stop command, and autoplay isn't zeroed...
  if (!stop && options.autoPlay !== 0) {
    // set timer...
    data.autoPlayTimer = setTimeout(function () {
      // to move the carousl in either direction...
      if (options.autoPlay > 0) {
        moveOnce('forward');
      } else {
        moveOnce('backward');
      }
    }, Math.abs(options.autoPlay));
  }
}

/**
 * This function will preload all the images in the carousel before
 * calling the passed in callback function. This is only used so we can
 * properly determine the width and height of the items. This is not needed
 * if a user instead manually specifies that information.
 */
function preload(callback) {

  var $imageElements = data.itemsContainer.find('img'),
      totalImages = $imageElements.length,
      loadedImages = 0;

  if (options.preloadImages === false || $imageElements.length === 0) {
    callback();
    return;
  }

  $imageElements.each(function () {
    $(this).bind('load', function () {
      // Add to number of images loaded and see if they are all done yet
      loadedImages += 1;
      if (loadedImages === totalImages) {
        // All done, perform callback
        callback();
        return;
      }
    });
    // May need to manually reset the src to get the load event to fire
    // http://stackoverflow.com/questions/7137737/ie9-problems-with-jquery-load-event-not-firing
    $(this).attr('src', $(this).attr('src'));

    // If browser has cached the images, it may not call trigger a load. Detect this and do it ourselves
    if (this.complete) {
      $(this).trigger('load');
    }
  });
}

/**
 * Makes a record of the original width and height of all the items in the carousel.
 * If we re-intialize the carousel, these values can be used to re-establish their
 * original dimensions.
 */
function setOriginalItemDimensions() {
  data.itemsContainer.children().each(function () {
    if ($(this).data('original_width') == undefined || options.forcedImageWidth > 0) {
      $(this).data('original_width', $(this).width());
    }
    if ($(this).data('original_height') == undefined || options.forcedImageHeight > 0) {
      $(this).data('original_height', $(this).height());
    }
  });
}

/**
 * Users can pass in a specific width and height that should be applied to every image.
 * While this option can be used in conjunction with the image preloader, the intended
 * use case is for when the preloader is turned off and the images don't have defined
 * dimensions in CSS. The carousel needs dimensions one way or another to work properly.
 */
function forceImageDimensionsIfEnabled() {
  if (options.forcedImageWidth && options.forcedImageHeight) {
    data.itemsContainer.children().each(function () {
      $(this).width(options.forcedImageWidth);
      $(this).height(options.forcedImageHeight);
    });
  }
}

/**
 * For each "visible" item slot (# of flanking items plus the middle),
 * we pre-calculate all of the properties that the item should possess while
 * occupying that slot. This saves us some time during the actual animation.
 */
function preCalculatePositionProperties() {
  // The 0 index is the center item in the carousel
  var $firstItem = data.itemsContainer.children().eq(0);

  data.calculations[0] = {
    distance: 0,
    offset: 0,
    opacity: 1
  }

  // Then, for each number of flanking items (plus one more, see below), we
  // perform the calcations based on our user options
  var horizonOffset = options.horizonOffset;
  var separation = options.separation;
  for (var i = 1; i <= options.flankingItems + 2; i++) {
    if (i > 1) {
      horizonOffset *= options.horizonOffsetMultiplier;
      separation *= options.separationMultiplier;
    }
    data.calculations[i] = {
      distance: data.calculations[i - 1].distance + separation,
      offset: data.calculations[i - 1].offset + horizonOffset,
      opacity: data.calculations[i - 1].opacity * options.opacityMultiplier
    }
  }
  // We performed 1 extra set of calculations above so that the items that
  // are moving out of sight (based on # of flanking items) gracefully animate there
  // However, we need them to animate to hidden, so we set the opacity to 0 for
  // that last item
  if (options.edgeFadeEnabled) {
    data.calculations[options.flankingItems + 1].opacity = 0;
  } else {
    data.calculations[options.flankingItems + 1] = {
      distance: 0,
      offset: 0,
      opacity: 0
    }
  }
}

/**
 * Here we prep the carousel and its items, like setting default CSS
 * attributes. All items start in the middle position by default
 * and will "fan out" from there during the first animation
 */
function setupCarousel() {
  // Fill in a data array with jQuery objects of all the images
  data.items = data.itemsContainer.children();
  for (var i = 0; i < data.totalItems; i++) {
    data.items[i] = $(data.items[i]);
  }

  // May need to set the horizon if it was set to auto
  if (options.horizon === 0) {
    if (options.orientation === 'horizontal') {
      options.horizon = data.containerHeight / 2;
    } else {
      options.horizon = data.containerWidth / 2;
    }
  }

  // Default all the items to the center position
  data.itemsContainer
      .css('position', 'relative')
      .children()
      .each(function () {
        // Figure out where the top and left positions for center should be
        var centerPosLeft, centerPosTop;
        if (options.orientation === 'horizontal') {
          centerPosLeft = (data.containerWidth / 2) - ($(this).data('original_width') / 2);
          centerPosTop = options.horizon - ($(this).data('original_height') / 2);
        } else {
          centerPosLeft = options.horizon - ($(this).data('original_width') / 2);
          centerPosTop = (data.containerHeight / 2) - ($(this).data('original_height') / 2);
        }
        $(this)
          // Apply positioning and layering to the images
            .css({
              'left': centerPosLeft,
              'top': centerPosTop,
              'visibility': 'visible',
              'position': 'absolute',
              'z-index': 0,
              'opacity': 0
            })
          // Give each image a data object so it remembers specific data about
          // it's original form
            .data({
              top: centerPosTop,
              left: centerPosLeft,
              oldPosition: 0,
              currentPosition: 0,
              depth: 0,
              opacity: 0
            })
          // The image has been setup... Now we can show it
            .show();
      });
}

/**
 * All the items to the left and right of the center item need to be
 * animated to their starting positions. This function will
 * figure out what items go where and will animate them there
 */
function setupStarterRotation() {
  options.startingItem = (options.startingItem === 0) ? Math.round(data.totalItems / 2) : options.startingItem;

  data.rightItemsCount = Math.ceil((data.totalItems - 1) / 2);
  data.leftItemsCount = Math.floor((data.totalItems - 1) / 2);

  // We are in effect rotating the carousel, so we need to set that
  data.carouselRotationsLeft = 1;

  // Center item
  moveItem(data.items[options.startingItem - 1], 0);
  data.items[options.startingItem - 1].css('opacity', 1);

  // All the items to the right of center
  var itemIndex = options.startingItem - 1;
  for (var pos = 1; pos <= data.rightItemsCount; pos++) {
    (itemIndex < data.totalItems - 1) ? itemIndex += 1 : itemIndex = 0;

    data.items[itemIndex].css('opacity', 1);
    moveItem(data.items[itemIndex], pos);
  }

  // All items to left of center
  var itemIndex = options.startingItem - 1;
  for (var pos = -1; pos >= data.leftItemsCount * -1; pos--) {
    (itemIndex > 0) ? itemIndex -= 1 : itemIndex = data.totalItems - 1;

    data.items[itemIndex].css('opacity', 1);
    moveItem(data.items[itemIndex], pos);
  }
}

/**
 * Given the item and position, this function will calculate the new data
 * for the item. One the calculations are done, it will store that data in
 * the items data object
 */
function performCalculations($item, newPosition) {
  var newDistanceFromCenter = Math.abs(newPosition);

  // Distance to the center
  if (newDistanceFromCenter < options.flankingItems + 1) {
    var calculations = data.calculations[newDistanceFromCenter];
  } else {
    var calculations = data.calculations[options.flankingItems + 1];
  }

  var distanceFactor = Math.pow(options.sizeMultiplier, newDistanceFromCenter)
  var newWidth = distanceFactor * $item.data('original_width');
  var newHeight = distanceFactor * $item.data('original_height');
  var widthDifference = Math.abs($item.width() - newWidth);
  var heightDifference = Math.abs($item.height() - newHeight);

  var newOffset = calculations.offset
  var newDistance = calculations.distance;
  if (newPosition < 0) {
    newDistance *= -1;
  }

  if (options.orientation == 'horizontal') {
    var center = data.containerWidth / 2;
    var newLeft = center + newDistance - (newWidth / 2);
    var newTop = options.horizon - newOffset - (newHeight / 2);
  } else {
    var center = data.containerHeight / 2;
    var newLeft = options.horizon - newOffset - (newWidth / 2);
    var newTop = center + newDistance - (newHeight / 2);
  }

  newTop -= heightDifference / 2;
  newLeft -= widthDifference / 2;

  var newOpacity;
  if (newPosition === 0) {
    newOpacity = 1;
  } else {
    newOpacity = calculations.opacity;
  }

  // Depth will be reverse distance from center
  var newDepth = options.flankingItems + 2 - newDistanceFromCenter;

  $item.data('width', newWidth);
  $item.data('height', newHeight);
  $item.data('top', newTop);
  $item.data('left', newLeft);
  $item.data('oldPosition', $item.data('currentPosition'));
  $item.data('depth', newDepth);
  $item.data('opacity', newOpacity);
  $item.data('distanceFactor', distanceFactor);
}

function moveItem($item, newPosition) {
  // Only want to physically move the item if it is within the boundaries
  // or in the first position just outside either boundary
  if (Math.abs(newPosition) <= options.flankingItems + 1) {
    performCalculations($item, newPosition);

    data.itemsAnimating++;

    $item
        .css('z-index', $item.data().depth)
      // Animate the items to their new position values
        .animate({
          'left': $item.data().left,
          'top': $item.data().top,
          'opacity': $item.data().opacity
        }, data.currentSpeed, options.animationEasing, function () {
          // Animation for the item has completed, call method
          itemAnimationComplete($item, newPosition);
        });

    TweenMax.to($item, data.currentSpeed / 1000, {
      scaleX: $item.data('distanceFactor'),
      scaleY: $item.data('distanceFactor'),
      ease: options.animationEasing
    });

  } else {
    $item.data('currentPosition', newPosition)
    // Move the item to the 'hidden' position if hasn't been moved yet
    // This is for the intitial setup
    if ($item.data('oldPosition') === 0) {
      $item
          .css({
            'left': $item.data().left,
            'top': $item.data().top,
            'opacity': $item.data().opacity,
            'z-index': $item.data().depth
          });

      TweenMax.to($item, 0, {
        scaleX: $item.data('distanceFactor'),
        scaleY: $item.data('distanceFactor')
      });
    }
  }

}

/**
 * This function is called once an item has finished animating to its
 * given position. Several different statements are executed here, such as
 * dealing with the animation queue
 */
function itemAnimationComplete($item, newPosition) {
  data.itemsAnimating--;

  $item.data('currentPosition', newPosition);

  // Keep track of what items came and left the center position,
  // so we can fire callbacks when all the rotations are completed
  if (newPosition === 0) {
    data.currentCenterItem = $item;
  }

  // all items have finished their rotation, lets clean up
  if (data.itemsAnimating === 0) {
    data.carouselRotationsLeft -= 1;
    data.currentlyMoving = false;

    // If there are still rotations left in the queue, rotate the carousel again
    // we pass in zero because we don't want to add any additional rotations
    if (data.carouselRotationsLeft > 0) {
      rotateCarousel(0);
      // Otherwise there are no more rotations and...
    } else {
      // Reset the speed of the carousel to original
      data.currentSpeed = options.speed;

      data.currentCenterItem.addClass(options.activeClassName);

      if (data.performingSetup === false) {
        options.movedToCenter(data.currentCenterItem);
        options.movedFromCenter(data.previousCenterItem);
      }

      data.performingSetup = false;
      // reset & initate the autoPlay
      autoPlay();
    }
  }
}

/**
 * Function called to rotate the carousel the given number of rotations
 * in the given direciton. Will check to make sure the carousel should
 * be able to move, and then adjust speed and move items
 */
function rotateCarousel(rotations) {
  // Check to see that a rotation is allowed
  if (data.currentlyMoving === false) {

    // Remove active class from the center item while we rotate
    data.currentCenterItem.removeClass(options.activeClassName);

    data.currentlyMoving = true;
    data.itemsAnimating = 0;
    data.carouselRotationsLeft += rotations;

    if (options.quickerForFurther === true) {
      // Figure out how fast the carousel should rotate
      if (rotations > 1) {
        data.currentSpeed = options.speed / rotations;
      }
      // Assure the speed is above the minimum to avoid weird results
      data.currentSpeed = (data.currentSpeed < 100) ? 100 : data.currentSpeed;
    }

    // Iterate thru each item and move it
    for (var i = 0; i < data.totalItems; i++) {
      var $item = $(data.items[i]);
      var currentPosition = $item.data('currentPosition');

      var newPosition;
      if (data.currentDirection == 'forward') {
        newPosition = currentPosition - 1;
      } else {
        newPosition = currentPosition + 1;
      }
      // We keep both sides as even as possible to allow circular rotation to work.
      // We will "wrap" the item arround to the other side by negating its current position
      var flankingAllowance = (newPosition > 0) ? data.rightItemsCount : data.leftItemsCount;
      if (Math.abs(newPosition) > flankingAllowance) {
        newPosition = currentPosition * -1;
        // If there's an uneven number of "flanking" items, we need to compenstate for that
        // when we have an item switch sides. The right side will always have 1 more in that case
        if (data.totalItems % 2 == 0) {
          newPosition += 1;
        }
      }

      moveItem($item, newPosition);
    }
  }
}

/**
 * The event handler when an image within the carousel is clicked
 * This function will rotate the carousel the correct number of rotations
 * to get the clicked item to the center, or will fire the custom event
 * the user passed in if the center item is clicked
 */
$(this).children().bind("click", function () {
  var itemPosition = $(this).data().currentPosition;

  if (options.imageNav == false) {
    return;
  }
  // Don't allow hidden items to be clicked
  if (Math.abs(itemPosition) >= options.flankingItems + 1) {
    return;
  }
  // Do nothing if the carousel is already moving
  if (data.currentlyMoving) {
    return;
  }

  data.previousCenterItem = data.currentCenterItem;

  // Remove autoplay
  autoPlay(true);
  options.autoPlay = 0;

  var rotations = Math.abs(itemPosition);
  if (itemPosition == 0) {
    options.clickedCenter($(this));
  } else {
    // Fire the 'moving' callbacks
    options.movingFromCenter(data.currentCenterItem);
    options.movingToCenter($(this));
    if (itemPosition < 0) {
      data.currentDirection = 'backward';
      rotateCarousel(rotations);
    } else if (itemPosition > 0) {
      data.currentDirection = 'forward';
      rotateCarousel(rotations);
    }
  }
});

function nextItemFromCenter() {
  var $next = data.currentCenterItem.next();
  if ($next.length <= 0) {
    $next = data.currentCenterItem.parent().children().first();
  }
  return $next;
}

function prevItemFromCenter() {
  var $prev = data.currentCenterItem.prev();
  if ($prev.length <= 0) {
    $prev = data.currentCenterItem.parent().children().last();
  }
  return $prev;
}

/**
 * Intiate a move of the carousel in either direction. Takes care of firing
 * the 'moving' callbacks
 */
function moveOnce(direction) {
  if (data.currentlyMoving === false) {
    data.previousCenterItem = data.currentCenterItem;

    options.movingFromCenter(data.currentCenterItem);
    if (direction == 'backward') {
      options.movingToCenter(prevItemFromCenter());
      data.currentDirection = 'backward';
    } else if (direction == 'forward') {
      options.movingToCenter(nextItemFromCenter());
      data.currentDirection = 'forward';
    }
  }

  rotateCarousel(1);
}

/**
 * Navigation with arrow keys
 */
$(document).keydown(function (e) {
  if (options.keyboardNav) {
    // arrow left or up
    if ((e.which === 37 && options.orientation == 'horizontal') || (e.which === 38 && options.orientation == 'vertical')) {
      autoPlay(true);
      options.autoPlay = 0;
      moveOnce('backward');
      // arrow right or down
    } else if ((e.which === 39 && options.orientation == 'horizontal') || (e.which === 40 && options.orientation == 'vertical')) {
      autoPlay(true);
      options.autoPlay = 0;
      moveOnce('forward');
    }
    // should we override the normal functionality for the arrow keys?
    if (options.keyboardNavOverride && (
            (options.orientation == 'horizontal' && (e.which === 37 || e.which === 39)) ||
            (options.orientation == 'vertical' && (e.which === 38 || e.which === 40))
        )) {
      e.preventDefault();
      return false;
    }
  }
});

/**
 * Public API methods
 */
this.reload = function (newOptions) {
  if (typeof newOptions === "object") {
    var combineDefaultWith = newOptions;
  } else {
    var combineDefaultWith = {};
  }
  options = $.extend({}, $.fn.waterwheelCarousel.defaults, newOptions);

  initializeCarouselData();
  data.itemsContainer.children().hide();
  forceImageDimensionsIfEnabled();

  preload(function () {
    setOriginalItemDimensions();
    preCalculatePositionProperties();
    setupCarousel();
    setupStarterRotation();
  });
}

this.next = function () {
  autoPlay(true);
  options.autoPlay = 0;

  moveOnce('forward');
}
this.prev = function () {
  autoPlay(true);
  options.autoPlay = 0;

  moveOnce('backward');
}

this.reload(startingOptions);

return this;
  };

  $.fn.waterwheelCarousel.defaults = {
// number tweeks to change apperance
startingItem: 1,   // item to place in the center of the carousel. Set to 0 for auto
separation: 175, // distance between items in carousel
separationMultiplier: 0.6, // multipled by separation distance to increase/decrease distance for each additional item
horizonOffset: 0,   // offset each item from the "horizon" by this amount (causes arching)
horizonOffsetMultiplier: 1,   // multipled by horizon offset to increase/decrease offset for each additional item
sizeMultiplier: 0.7, // determines how drastically the size of each item changes
opacityMultiplier: 0.8, // determines how drastically the opacity of each item changes
horizon: 0,   // how "far in" the horizontal/vertical horizon should be set from the container wall. 0 for auto
flankingItems: 3,   // the number of items visible on either side of the center

// animation
speed: 300,      // speed in milliseconds it will take to rotate from one to the next
animationEasing: 'linear', // the easing effect to use when animating
quickerForFurther: true,     // set to true to make animations faster when clicking an item that is far away from the center
edgeFadeEnabled: false,    // when true, items fade off into nothingness when reaching the edge. false to have them move behind the center image

// misc
linkHandling: 2,                 // 1 to disable all (used for facebox), 2 to disable all but center (to link images out)
autoPlay: 0,                 // indicate the speed in milliseconds to wait before autorotating. 0 to turn off. Can be negative
orientation: 'horizontal',      // indicate if the carousel should be 'horizontal' or 'vertical'
activeClassName: 'carousel-center', // the name of the class given to the current item in the center
keyboardNav: false,             // set to true to move the carousel with the arrow keys
keyboardNavOverride: true,              // set to true to override the normal functionality of the arrow keys (prevents scrolling)
imageNav: true,              // clicking a non-center image will rotate that image to the center

// preloader
preloadImages: true,  // disable/enable the image preloader.
forcedImageWidth: 0,     // specify width of all images; otherwise the carousel tries to calculate it
forcedImageHeight: 0,     // specify height of all images; otherwise the carousel tries to calculate it

// callback functions
movingToCenter: $.noop, // fired when an item is about to move to the center position
movedToCenter: $.noop, // fired when an item has finished moving to the center
clickedCenter: $.noop, // fired when the center item has been clicked
movingFromCenter: $.noop, // fired when an item is about to leave the center position
movedFromCenter: $.noop  // fired when an item has finished moving from the center
  };

})(jQuery);

   /*--water_wheel_carousel--*/
var carousel = $("#carousel").waterwheelCarousel({
     flankingItems: 2,
     separation:200,
     sizeMultiplier:0.8,
     separationMultiplier:0.9,
     speed:250,
 });

 $("#carousel").swipe( {
    swipeStatus:function(event, phase, direction, distance)
    {
        if (phase=="end"){
            if(direction == "right") {
                carousel.prev();
            }
            else if(direction =="left") {
                carousel.next();
            }else { return false;}
        }
    },
    triggerOnTouchEnd:false,
    threshold:100
});
$('#prev').on('click', function (){
    carousel.prev();
    return false;
});
$('#next').on('click', function (){
    carousel.next();
    return false;
});
/*--water_wheel carousel_script_end--*/

Kindly help me fix the javascript so as to apply the solution to my code. Thanks

A: Your images are loading, but there are DIVs with a white background on top of them that are visually blocking the images. If you remove the background-color CSS declaration on those DIVs, then your images will show up. Just update this:
#carousel .caption {
    position: absolute;
    background-color:#FFF;
    top: 0px;
    left: 0px;
    height:100%;
    width:100%;
}

to this:
#carousel .caption {
    position: absolute;
    top: 0px;
    left: 0px;
    height:100%;
    width:100%;
}


text:
Q: Tailor forced casts conflicts let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell

It's standard sentence that implements the table view's cell's properties. But Tailor (it's a Swift analyzer/linter) warns about you shouldn't forced the CustomTableViewCell as as! If I used to as as?, I have to implement cell's properties as cell!. But Tailor don't warn about [forced-type-cast] Force casts should be avoided. What's the reason of this? How can I implement cell's without unwrap of cell as cell! What's the correct programming paradigms for forced casts operations in Swift?

A: I am not familiar with "Tailor" but most likely the reason it is giving you this warning is because if a force cast fails then obviously your program will crash and thats never good.
The as! operator does have its place if you are 100% sure that what you are casting is of that type. But, even then its better to be safe than sorry and you should use a guard or if let statement instead in order to handle a failed cast.
if let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? CustomTableViewCell {
  //do what you like with cell
}

or
guard let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? CustomTableViewCell else {
  //abort current scope, return, break, etc. from scope.
}
//do what you like with cast cell


text:
Q: Files (Nautilus) in 19.10 - drag-n-drop on desktop doesn't work If I insert a flash drive and try to drag any files onto desktop - nothing happens.
Or from any other folder.
Drag 'n copy only works if you open desktop in nautilus ("show desktop in files").
I already ran the command:
gsettings set org.gnome.nautilus.preferences use-experimental-views false

It didn't help. How to fix this?

A: Since Ubuntu 19.04, Nautilus doesn't handle desktop icon management, rather it is handled by a GNOME Shell Extension called 'Desktop Icons' (package name: gnome-shell-extension-desktop-icons). The extension doesn't support the drag-and-drop feature yet.
However, you can replace Nautilus with Nemo as your file manager and get the traditional desktop icon management back. Follow this Q&A to replace Nautilus by Nemo: Make nemo the default file browser.
You should disable/remove the Desktop Icons extension to avoid any potential incompatibility. You may also have to add Nemo manually to the list of (auto-) startup programs.

A: Support of icons on the desktop in Ubuntu 19.10 is still limited for reasons outlined here. Thus, you currently cannot (yet) drag and drop files from Nautilus to the desktop. For the moment, your workarounds are:

*

*Copying using the keyboard (Ctrl+c, then click on desktop and Ctrl+v).

*(As you mentionned:) You can drag files in Nautilus to the Desktop folder in your home directory. These files will appear on the desktop.

A: Another possibility is to uninstall the "Desktop Icons" extension and install this one:
https://extensions.gnome.org/extension/2087/desktop-icons-ng-ding/?c=80141

I lightly tested it, and for now drag and drop works as supposed to do and moving icons in different screens also.
Additionally, it's much more configurable:

A: Yes it works, Nautilus has to be uninstalled after Nemo installation and it needs an extra start application command: nemo-desktop. This is to avoid the desktop getting filled by duplicated dragged icons etc if Nautilus is still present. Then it needs gnome-shell-extension-dekstop-icons to be installed.


text:
Q: Difference between hvplot and holoplot So for a while now I have been migrating from Matplotlib to holoviews for my plotting needs, and mostly enjoying what I have experienced. Then i notice hvplot, which seems to make the holviews workflow way easier, by tying it closer together with Pandas. All good so far. But now I discover holoplot, which seems to do the same thing? I am quite confused, so hopefully someone could please try to explain to me the difference between hvplot and holoplot. Please...
Kind regards,
Rasmus

A: HoloPlot was the predecessor of hvPlot, even the logo is the same :)
I think it got renamed hvPlot in later versions.
It was developed by exactly the same developers.
So for high-level plotting use hvPlot.
https://hvplot.holoviz.org/index.html


text:
Q: What are the main differences between Ubuntu Desktop and Ubuntu Touch? Now that Ubuntu for phones is mature enough and established, can someone intimately familiar can explain what are the main differences between the two.
Where the two diverge to the point of being incompatible?

A: The desktop currently runs Unity 7 on top of Compiz and X.org
Mobile runs Unity 8 on top of Mir.
Almost everything else is the same.  Soon, desktop will also be Unity 8 and Mir, then there will be no difference.

A: There's not much different on the terms of the layout, also you still have command line accessibility, however the biggest difference in the apps, not all apps available on Computer are available on mobile and Vice Versa. Another major difference is the ease of use with HTML 5 and easily being able to turn your web page into an Ubuntu touch app. The mobile SDK does a lot of the work for you.


text:
Q: Script Inside Php Loop So guys i have this script:
$('input[type="file"].fileupdate').on('change', function (event, files, label) {
var file_name = $(this).val().replace(/\\/g, '/').replace(/.*\//, '')
$('input[type="text"].filenameupdate').val(file_name);
});

And i would like to use inside a loop where i have a form:

<input class="fileupdate" type="file" style="text-align:center;" name="file" value="'.htmlentities($row_dados['imagem'], ENT_COMPAT, 'utf-8').'" />

<input class="filenameupdate" type="text" readonly style="text-align:center;" name="imagem" placeholder="'.htmlentities($row_dados['imagem'], ENT_COMPAT, 'utf-8').'" />

But since its a loop when i choose the inopt file it changes all the input text on the loop and not one the specific one i would like to.
Example:
inputfile1 - inputext1
inputfile2 - inputext2
...
And when i choose a file with the inputfile1 it changes the inputext1 and inputext2 and i would like only to change the inputext1.
Dont know how to do it and already tried to make a search on internet but dont know how to search with the proper keywords.
Cumps.

A: Try changing the text file name with a simple counter in the loop
$i=1;

//loop start

{

$filename = filename$i

//run code

$i++;

}


text:
Q: Trying to understand pthread_cond_lock and pthread_cond_signal So I'm trying to understand exactly how pthread_mutex_lock works.
My current understanding is that it unlocks the mutex and puts whatever thread is going though it to sleep.  Sleep meaning that the thread is inactive and consuming no resources.
It then waits for a signal to go from asleep to blocked, meaning that the thread can no longer change any variables.
thread 1:
    pthread_mutex_lock(&mutex);
    while (!condition){
        printf("Thread wating.\n");
        pthread_cond_wait(&cond, &mutex);
        printf("Thread awakened.\n");
        fflush(stdout);
   }
   pthread_mutex_unlock(&mutex);

   pthread_cond_signal(&condVar);
   pthread_mutex_unlock(&mutex);

So basically in the sample above, the loop runs and runs and each iteration pthread_cond_wait checks if the condition of the loop is true.  If it is then the cond_signal is sent and the thread is blocked so it can't manipulate any more data.
I'm really having trouble wrapping my head around this, I'd appreciate some input and feedback about how this works and whether or not I am beginning to understand this based on what I have above.
I've gone over this post but am still having trouble

A: First, a summary:

*

*pthread_mutex_lock(&mutex):
If mutex is free, then this thread grabs it immediately.
If mutex is grabbed, then this thread waits until the mutex becomes free, and then grabs it.

*pthread_mutex_trylock(&mutex):
If mutex is free, then this thread grabs it.
If mutex is grabbed, then the call returns immediately with EBUSY.

*pthread_mutex_unlock(&mutex):
Releases mutex.

*pthread_cond_signal(&cond):
Wake up one thread waiting on the condition variable cond.

*pthread_cond_broadcast(&cond):
Wake up all threads waiting on the condition variable cond.

*pthread_cond_wait(&cond, &mutex):
This must be called with mutex grabbed.
The calling thread will temporarily release mutex and wait on cond.
When cond is broadcast on, or signaled on and this thread happens to be the one woken up, then the calling thread will first re-grab the mutex, and then return from the call.
It is important to note that at all times, the calling thread either has mutex grabbed, or is waiting on cond. There is no interval in between.

Let's look at a practical, running example code.  We'll create it along the lines of OP's code.
First, we'll use a structure to hold the parameters for each worker function. Since we'll want the mutex and the condition variable to be shared between threads, we'll use pointers.
#define  _POSIX_C_SOURCE  200809L
#include <stdlib.h>
#include <pthread.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

/* Worker function work. */
struct work {
    pthread_t        thread_id;
    pthread_mutex_t *lock;      /* Pointer to the mutex to use */
    pthread_cond_t  *wait;      /* Pointer to the condition variable to use */
    volatile int    *done;      /* Pointer to the flag to check */
    FILE            *out;       /* Stream to output to */
    long             id;        /* Identity of this thread */
    unsigned long    count;     /* Number of times this thread iterated. */
};

The thread worker function receives a pointer to the above structure. Each thread iterates the loop once, then waits on the condition variable. When woken up, if the done flag is still zero, the thread iterates the loop. Otherwise, the thread exits.
/* Example worker function. */
void *worker(void *workptr)
{
    struct work *const work = workptr;

    pthread_mutex_lock(work->lock);

    /* Loop as long as *done == 0: */
    while (!*(work->done)) {
        /* *(work->lock) is ours at this point. */

        /* This is a new iteration. */
        work->count++;

        /* Do the work. */
        fprintf(work->out, "Thread %ld iteration %lu\n", work->id, work->count);
        fflush(work->out);

        /* Wait for wakeup. */
        pthread_cond_wait(work->wait, work->lock);
    }

    /* *(work->lock) is still ours, but we've been told that all work is done already. */
    /* Release the mutex and be done. */
    pthread_mutex_unlock(work->lock);
    return NULL;
}

To run the above, we'll need a main() as well:
#ifndef  THREADS
#define  THREADS  4
#endif

int main(void)
{
    pthread_mutex_t  lock = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t   wait = PTHREAD_COND_INITIALIZER;
    volatile int     done = 0;
    struct work      w[THREADS];

    char            *line = NULL, *p;
    size_t           size = 0;
    ssize_t          len  = 0;

    unsigned long    total;
    pthread_attr_t   attrs;
    int              i, err;

    /* The worker functions require very little stack, but the default stack
       size is huge. Limit that, to reduce the (virtual) memory use. */
    pthread_attr_init(&attrs);
    pthread_attr_setstacksize(&attrs, 2 * PTHREAD_STACK_MIN);

    /* Grab the mutex so the threads will have to wait to grab it. */
    pthread_mutex_lock(&lock);

    /* Create THREADS worker threads. */
    for (i = 0; i < THREADS; i++) {

        /* All threads use the same mutex, condition variable, and done flag. */
        w[i].lock = &lock;
        w[i].wait = &wait;
        w[i].done = &done;

        /* All threads output to standard output. */
        w[i].out = stdout;

        /* The rest of the fields are thread-specific. */
        w[i].id = i + 1;
        w[i].count = 0;

        err = pthread_create(&(w[i].thread_id), &attrs, worker, (void *)&(w[i]));
        if (err) {
            fprintf(stderr, "Cannot create thread %d of %d: %s.\n", i+1, THREADS, strerror(errno));
            exit(EXIT_FAILURE);  /* Exits the entire process, killing any other threads as well. */
        }
    }

    fprintf(stderr, "The first character on each line controls the type of event:\n");
    fprintf(stderr, "    e, q    exit\n");
    fprintf(stderr, "    s       signal\n");
    fprintf(stderr, "    b       broadcast\n");
    fflush(stderr);

    /* Let each thread grab the mutex now. */
    pthread_mutex_unlock(&lock);

    while (1) {
        len = getline(&line, &size, stdin);
        if (len < 1)
            break;

        /* Find the first character on the line, ignoring leading whitespace. */
        p = line;
        while ((p < line + len) && (*p == '\0' || *p == '\t' || *p == '\n' ||
                                    *p == '\v' || *p == '\f' || *p == '\r' || *p == ' '))
            p++;

        /* Do the operation mentioned */
        if (*p == 'e' || *p == 'E' || *p == 'q' || *p == 'Q')
            break;
        else
        if (*p == 's' || *p == 'S')
            pthread_cond_signal(&wait);
        else
        if (*p == 'b' || *p == 'B')
            pthread_cond_broadcast(&wait);
    }

    /* It is time for the worker threads to be done. */
    pthread_mutex_lock(&lock);
    done = 1;
    pthread_mutex_unlock(&lock);

    /* To ensure all threads see the state of that flag,
       we wake up all threads by broadcasting on the condition variable. */
    pthread_cond_broadcast(&wait);

    /* Reap all threds. */
    for (i = 0; i < THREADS; i++)
        pthread_join(w[i].thread_id, NULL);

    /* Output the thread statistics. */
    total = 0;
    for (i = 0; i < THREADS; i++) {
        total += w[i].count;
        fprintf(stderr, "Thread %ld: %lu events.\n", w[i].id, w[i].count);
    }
    fprintf(stderr, "Total: %lu events.\n", total);

    return EXIT_SUCCESS;
}

If you save the above as example.c, you can compile it to example using e.g. gcc -Wall -O2 example.c -lpthread -o example.
To get the correct intuitive grasp of the operations, run the example in a terminal, with the source code in a window next to it, and see how the execution progresses as you provide input.
You can even run commands like printf '%s\n' s s s b q | ./example to run a sequence of events in a quick succession, or printf 's\ns\ns\nb\nq\n' | ./example with even less time in between events.
After some experimentation, you'll hopefully find out that not all input events cause their respective action. This is because the exit event (q above) is not synchronous: it does not wait for all pending work to be done, but tells the threads to exit right then and there. That is why the number of events may vary even for the exact same input.
(Also, if you signal on the condition variable, and immediately broadcast on it, the threads tend to only get woken up once.)
You can mitigate that by delaying the exit, using e.g. (printf '%s\n' s s b s s s ; sleep 1 ; printf 'q\n' ) | ./example.
However, there are better ways.  A condition variable is not suitable for countable events; it is really flag-like.  A semaphore would work better, but then you should be careful to not overflow the semaphore; it can only be from 0 to SEM_VALUE_MAX, inclusive.  (So, you could use a semaphore to represent the number of pending job, but probably not for the number of iterations done by each/all thread workers.)  A queue for the work to do, in thread pool fashion, is the most common approach.

A: pthread_cond_wait() simply means that the current thread shall release the mutex and then waits on a condition. The trick here is that both happens atomically, so it cannot happen, that the thread has released the mutex and is not yet waiting on the condition or is already waiting on the condition and has not yet released the mutex. Either both has happened or none has happened.
pthread_cond_signal() simply wakes up any thread that is currently waiting on the signaled condition. The first thing the woken up thread will do is obtaining the mutex again, if it cannot obtain it (e.g. as the signaling thread is currently owning the mutex), it will block until it can. If multiple threads are waiting on the condition, pthread_cond_signal() just wakes up one of them, which one is not defined. If you want to wake up all the waiting threads, you must use pthread_cond_broadcast() instead; but of course they won't run at the same time as now each of them first requires to obtain the mutex and that will only be possible one after another.
pthread_cond_t has no state. If you signal a condition no thread is waiting for, then nothing will happen. It's not like this will set a flag internally and if later on some thread calls pthread_cond_wait(), it will be woken up immediately as there is a pending signal. pthread_cond_signal() only wakes up threads that are already waiting, that means these threads must have called pthread_cond_wait() prior to you calling pthread_cond_signal().
Here's some simple sample code. First a reader thread:
// === Thread 1 ===

// We want to process an item from a list.
// To make sure the list is not altered by one
// thread while another thread is accessing it,
// it is protected by a mutex.
pthread_mutex_lock(&listLock);

// Now nobody but us is allowed to access the list.
// But what if the list is empty?
while (list->count == 0) {
    // As long as we hold the mutex, no other thread
    // thread can add anything to the list. So we
    // must release it. But we want to know as soon
    // as another thread has changed it.
    pthread_cond_wait(&listCondition, &listLock);

    // When we get here, somebody has signaled the
    // condition and we have the mutex again and
    // thus are allowed to access the list. The list
    // may however still be empty, as another thread
    // may have already consumed the new item in case
    // there are multiple readers and all are woken
    // up, thus the while-loop. If the list is still
    // empty, we just go back to sleep and wait again.
}

// If we get here, the list is not empty.
processListItem(list);

// Finally we release the mutex again.
pthread_mutex_unlock(&listLock);

And then a writer thread:
// === Thread 2 ===

// We want to add a new item to the list.
// To make sure that nobody is accessing the
// list while we do, we need to obtain the mutex.
pthread_mutex_lock(&listLock);

// Now nobody but us is allowed to access the list.
// Check if the list is empty.
bool listWasEmpty = (list->count == 0);

// We add our item.
addListItem(list, newItem);

// If the list was empty, one or even multiple
// threads may be waiting for us adding an item.
// So we should wake them up here.
if (listWasEmpty) {
    // If any thread is waiting for that condition,
    // wake it up as now there is an item to process.
    pthread_cond_signal(&listCondition);
}

// Finally we must release the mutex again.
pthread_mutex_unlock(&listLock);

The code is written so that there can be any number of reader/writer threads. Signaling only if the list was empty (listWasEmpty) is just a performance optimization, the code would also work correctly if you always signal the condition after adding an item.


text:
Q: Swift : Add image to scopebar in uiSearchbar instead of titles I am trying to set an image to scope bar in uisearch bar. I know that is possible to do it in segmented control, but I can't figure out how to do it in scope bar.

A:
Duplicate: This has been answered HERE:

searchBar.setImage(UIImage(named: "your image"), forSearchBarIcon: .Search, state: .Normal)


text:
Q: How to add parameter to wp_enqueue_script? I have the situation that I need to include special scripts only in case a parameter in a macro is used. For the background, see the following:

*

*My plugin ChessTempoViewer which wraps a JavaScript library for usage in WP.

*There I add the necessary libraries by using wp_enqueue_script.

*I would like to internationalize the output of the viewer, which is described here.

So to use that internationalization, I should have to include the relevant script depending on the locale that should be used. This should be of course defined by the user, so the user should have the option to do something like:
[ctlocale locale="de_DE"][/ctlocale]
[ctpgn] 1. e4 e5 2. Nf3 ... [/ctpgn]

which should result in an output for the moves:
1. e4 e5 2. Sf3

S for Springer in German instead of N for Night in English.
My code currently looks like that:
function pgnviewer_js_and_css(){
  wp_enqueue_script("jquery");
  wp_enqueue_script('pgnyui', 'http://chesstempo.com/js/pgnyui.js');
  wp_enqueue_script('pgnviewer', 'http://chesstempo.com/js/pgnviewer.js');
  wp_enqueue_style('pgnviewer-css', 'http://chesstempo.com/css/board-min.css');
  wp_enqueue_style('ctpgn', plugins_url('ctpgn.css', __FILE__));
}

add_action('wp_enqueue_scripts', 'pgnviewer_js_and_css');

function chessTempoViewer($attributes, $content = NULL) {
  ..
}

How could I include an additional tag ctlocale as in the example above (as the first entry) to ensure that the script is included before the other scripts?

A: Shortcodes are inconvenient for such things, because they are processed in content, way after site's header. However since you don't need to deal with styles, only a script, it's a little easier by moving stuff to footer.
Your logic would be something like following:

*

*Locale shortcode stores requested locale in some way.

*At some point between content and footer you register and enqueue scripts, making locale script dependency of main script.

*WP reaches footer, resolved enqueued scripts, and prints them out for you.