OpenDesign Specification for .dwg files

Question: I've been working with OpenDesign Specification for .dwg files about two weeks. And now, i've got all information except non-entity object and entity object. Maybe i can't understand how this information written. Concretely i need to know how to differ non-entity object and entity object. Work on C#. http://opendesign.com/files/guestdownloads/OpenDesign_Specification_for_.dwg_files.pdf on the page 98.
This is how i found out non-entity object format:
<code>private bool ReadNonEntityObject(FileReader fileReader, DWGVersion version, long handle, long fileLoc)
    {
        long oldPos = fileReader.BufferPosition;

        BaseTypes bReader = new BaseTypes(fileReader);
        fileReader.SeekAbsolute(fileLoc);

        var size = bReader.GetModularShort();

        if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2010))
        {
            var HandleSize = bReader.GetModularChar(false);
        }

        var objectType = bReader.GetObjectType(version);
        Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(objectType), 0).Substring(0, 2));
        if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2000) && version.IsEarlier(DWGVersion.VersionEnum.R2010))
        {
            var ObjectSize = bReader.GetLongRaw();
        }

        var handl = bReader.GetHandle();

        if (handl != handle)
            throw new Exception("DWG file is corrupted or incorrect");

        var extendedSize = bReader.GetShort();
        int size1 = 0;
        bool isGraphic = fileReader.GetBits(1, true)[0];
        if (isGraphic)
            size1 = bReader.GetLongRaw();
        if (extendedSize != 0)
        {
            var appHandle = bReader.GetHandle();
            var endPos = fileReader.BufferPosition + extendedSize;

            string data = "";//DEBUG for testing

            while (fileReader.BufferPosition < endPos)
            {
                int byteCode = bReader.GetByteRaw();
                object val = null;
                switch (byteCode) //TODO add all byteCode
                {
                    case 0:
                        {
                            if (version.IsEarlier(DWGVersion.VersionEnum.R2007))
                            {
                                int N = bReader.GetByteRaw();
                                var codePage = bReader.GetShortRaw();
                                val = bReader.GetStringAscii(N);
                            }
                            if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2007))
                            {
                                //TODO
                            }
                        }
                        break;
                    case 1:
                        val = bReader.GetText();
                        break;
                    case 8:
                        {
                            break;
                        }
                    case 2:
                        val = bReader.GetCharAscii() == 0 ? '{' : '}';
                        break;
                    case 40:
                        bReader.Get3DDouble();
                        break;
                    case 145:
                        {
                            val = bReader.GetDouble();
                            break;
                        }
                    case 70:
                        val = bReader.GetShortRaw();
                        break;
                    case 71:
                        val = bReader.GetLongRaw();
                        break;
                    default:
                        val = "";
                        break;

                }
                data += val + " ";
                //Console.WriteLine(data);
            }
        }

        if (version.Equals(DWGVersion.VersionEnum.R13_R14))
        {
            var DataSize = bReader.GetLongRaw();
            var persistentNum = bReader.GetByteRaw();
        }
        if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2004))
        {

        }

        fileReader.SeekAbsolute(oldPos);
        return true;
    }
</code>
Comment: What exactly is your question @Denish Kosov??????? Is it coading related??????
Answer: There is no isGraphic bit in non-entity object.
Extended data only. it is loop-like, see page 254.
in my experience most types - are entity objects.
i have base class for object and some heder reader in it. Many types extends from each other.
Use crc check, where it is for check you proof.

OpenDesign Specification for .dwg files


Schur complement condition for positive definiteness still for complex matrices

Question: Say that we're given the following matrices: $S\in M_{m,m}$ symmetric positive definite, $A\in M_{n,n}$, $X\in M_{n,m}$ and $Y\in M_{n,m}$.
Actually I need to use a program that doesn't accept matrix equalities and it only accepts the matrix inequality. Moreover this program does not accept the following matrix $(Y-AX)^T(Y-AX)$.
The equality that I need to set is $S=(Y-AX)^T(Y-AX)$ so I thought to reformulate the problem in the following manner:$\{S-(Y-AX)^T(Y-AX)\geq0\}\cup\{(Y-AX)^T(Y-AX)-S\geq0\}$ which means that $S-(Y-AX)^T(Y-AX)$ is at the same time positive and negative semidefinite hence a zero matrix. To avoid the use of the form $(Y-AX)^T(Y-AX)$ we can replace the two sets by the schur inequalityas follows
$\{S-(Y-AX)^T(Y-AX)\geq0\}\cup\{(Y-AX)^T(Y-AX)-S\geq0\}$ is equivalent to have
$$\left\{
\begin{bmatrix}S & (Y-AX)\\(Y-AX)^T & I_{n,n}\end{bmatrix}\geq0
\right\}\cup\left\{
\begin{bmatrix}I_{n,n} & j\times(Y-AX)  \\j\times(Y-AX)^T & -S\end{bmatrix}
\geq0\right\}.$$
So my question here is as follow: are the two last sets equivalent to have $S=(Y-AX)^T(Y-AX)$. I'm wondering also if the second set remains true since we're using a complex number.
Answer: No. The matrix
$$
B=\begin{bmatrix}I_{n,n} & j\times(Y-AX)  \\j\times(Y-AX)^T & -S\end{bmatrix}
$$
is not Hermitian in general (unless $Y-AX=0$). Even if it is, since $S$ is positive definite, $B$ is certainly not positive semidefinite.
Comment: The lemma for the schur compliment states that if the matrix block in the upper left side, which is $I_{n,n}$ in this case, is positive definite then B is positive definite if and only if $(Y-AX)^T(Y-AX) - S$ is positive definite. And as far as I know if B is positive definite it doesn't imply that $B$ must be positive element-wise. Therefore there is no restriction to choose the matrix block in the lower right side as a negative definite matrix, i.e. $-S$.
Comment: @Bel Please clarify the meaning of $\ge0$ in your question. Does it mean entrywise $\ge0$ or "positive semidefinite"?
Comment: In addition in a hermitian matrix the main diagonal entries should be real not the antidiagonal entries. So why we should set $Y-AX=0$?
Comment: It means positive semidefinite and I'm trying to prove that the matrix $S-(Y-AX)^T(Y-AX)$ is at the same time positive and negative semidefinite hence zero matrix.
Comment: @Bel OK, then my answer remains unchanged. In that answer I am not saying that you should set $Y-AX=0$. What I'm saying is that, since $Y-AX\not=0$ in general, the matrix $B$ is not Hermitian *and hence* it is not positive semidefinite (all positive semidefinite matrices, be they real or complex, must be Hermitian). Also, since your question states that $S$ is positive definite, it follows that $-S$ and in turn, $B$, are not positive semidefinite.


Chrome driver value gets null after extends to other class

Question: I have test class "Test" and a configuration class "Base", in the configuration class I set the driver instance it has been extends to test class "Test"
The value of driver get null for chrome driver but getting value for firefox driver
in the test class "Test"
Chrome driver set up:
System.setProperty("webdriver.chrome.driver", "D:\\Eclipse workspace_POC\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

Firefox driver set up:
WebDriver driver = new firefoxDriver();

can anyone sort the issue.
Comment: Neither of those two calls can return null, if actually executed. Can you clarify where you're calling them (different classes, different methods?) and by posting some actual code?
Comment: in different classs i am calling
Comment: Can you share error-log and source code?
Answer: Try using Static Instances.. Something like,
// In Test Class
public static WebDriver driver = null;

// Config Class [Works only if u extend Test. If not try Test.driver]
driver = new ChromeDriver();

Comment: Introducing a static (and widening the scope) will only compound the OP's problem of not understanding how inheritance works.
Comment: You are right, however the other option is to make the driver "Final" and access the driver in child class using a helper class. This will only complicate things more !! So, static driver implementation may be fine as long as u understand the implications


Idea on expansion and collaboration of the Drupal community

Question: Would it be possible to speak with the moderators of drupal.org into merging their Q&A + Forum with stackexchange's system? Combining the user base of drupal.org with the usability of the stackexchange system would benefit the Drupal community 10 fold. It's a win-win situation.
What do you think are the pros and cons of this idea? Is this even feasible?
Comment: Drupal.org doesn't have any Q&A, so far.
Answer: There is an open issue in the Drupal.org webmasters queue: http://drupal.org/node/1236290


How to check with decorator if user has access to some objects in Django

Question: I'm working on a project, with structure as below. And I was trying to check if user is a member of the requested team and is allowed to see it's details. So I was trying to achieve this by decorators, but i'm still getting http 500 error.
I'm not sure if it's right solution and just bad implementation or it's better to make it in different way.
I'll be gratefull for Your help.
Team/Models.py
roles = (('admin', 'admin'), ('member', 'member'), ('guest', 'guest'))

class Team(models.Model):
    name = models.CharField(max_length=150)
    description = models.TextField(blank=True)
    members = models.ManyToManyField(User, through='Membership')
    cppTables = models.JSONField(default=list, blank=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return f'teams/{self.pk}/'

    def has_user(self, user_id):
        return self.members.get(pk=user_id).exists()

class Membership(models.Model):
    member = models.ForeignKey(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    role = models.CharField(max_length=15, choices=roles, default='member')

    def __str__(self):
        return str(self.member)

    class Meta:
        unique_together = [['member', 'team']]

Team/Decorators.py
def required_membership(view_func):
    def wrapper(request, *args, **kwargs):
        team_id = kwargs['team_id']
        team = Team.objects.get(pk=team_id)
        if team.has_user(request.user.id):
            return view_func(request, *args, **kwargs)
        else:
            raise HttpResponseForbidden
    return wrapper

Team/Views.py
@method_decorator(required_membership, name="dispatch")
class TeamDetail(APIView):
    def get_object(self, pk):
        try:
            return Team.objects.get(pk=int(pk))
        except Team.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        team = self.get_object(pk)
        serializer = TeamSerializer(team, many=False)
        return Response(serializer.data)

Answer: in you decorator put wrapper inside inner function. your code will look something like this and plus no need to put it inside method decorator simple use like this @required_membership()
from django.core.exceptions import PermissionDenied
def required_membership():
    def inner(view_func):
        def wrapper(request, *args, **kwargs):
            team_id = kwargs['team_id']
            team = Team.objects.get(pk=team_id)
            if team.has_user(request.user.id):
                return view_func(request, *args, **kwargs)
            else:
                raise PermissionDenied
        return wrapper

    return inner

UPDATE
put decorator above get or post method instead of class
Comment: Worked like magic. I was trying to get the user id in the custom decorator and this comment update helped!
Answer: The simplest way is probably to just filter in the view:
from django.shortcuts import get_object_or_404

class TeamDetail(APIView):

    def get_object(self, pk):
        return get_object_or_404(Team, pk=pk, members=self.request.user)

    def get(self, request, pk, format=None):
        team = self.get_object(pk)
        serializer = TeamSerializer(team, many=False)
        return Response(serializer.data)
This will return a 404 in case the user is not a member of a team, which gives less information to exploit when the user aims to visit a team for which he is not a member.
You can also raise a HttpResponseForbidden instead by checking membership with:
from django.shortcuts import get_object_or_404

class TeamDetail(APIView):

    def get_object(self, pk):
        team = get_object_or_404(Team, pk=pk)
        if not team.members.filter(pk=self.request.user.pk).exists():
            raise HttpResponseForbidden
        return team

    def get(self, request, pk, format=None):
        team = self.get_object(pk)
        serializer = TeamSerializer(team, many=False)
        return Response(serializer.data)
Your has_user(…) method has a bug: it should use .filter(…) since a model object has no .exists() method, and .get(…) will raise an error in case it can not find the item:
class Team(models.Model):
    # …

    def has_user(self, user_id):
        return self.members.filter(pk=user_id).exists()


laravel vue 'supported methods: DELETE' when POSTing to 'store' method

Question: I get that we need to match the method to the action when submitting forms, but this has me baffled. I'm trying to store a new category to my database using
<form @submit.prevent="form.post('categories.store')">

I have no mention of 'destroy' or 'delete' anywhere on the page, so I don't understand why laravel thinks I'm trying to delete something.
My routes are:
Route::resource('categories', CategoryController::class)
    ->only(['create', 'store', 'edit', 'destroy'])
    ->middleware(['auth', 'verified']);

the vue is:

<template>

    <AuthenticatedLayout>
        <template #header>

                Create Category

        </template>

                    <form @submit.prevent="form.post('categories.store')">

                                        <InputLabel for="name" value="Category Name"></InputLabel>
                                        <TextInput
                                            v-model="form.name"
                                            id="name"
                                            type="text"
                                            class="mt-1 block w-full font-medium shadow-sm sm:text-sm border-gray-300 rounded-md"
                                            required
                                            autofocus
                                            autocomplete="form.name" />
                                        <InputError class="mt-2" :message="form.errors.name" />

                                        <InputLabel for="name" value="Game"></InputLabel>
                                        <select v-model="form.game" class="border-gray-300 rounded-md w-full">
                                            <option v-for="game in $page.props.games" :key="game.id"> {{ game.name }}</option>
                                        </select>
                                        <InputError class="mt-2" :message="form.errors.game" />

                                        <InputLabel for="name" value="Language"></InputLabel>
                                        <select v-model="form.language" class="border-gray-300 rounded-md w-full">
                                            <option v-for="language in $page.props.languages" :key="language.id"> {{ language.name }}</option>
                                        </select>
                                        <InputError class="mt-2" :message="form.errors.language" />

                                    <PrimaryButton class="mt-4">Create</PrimaryButton>

                    </form>

    </AuthenticatedLayout>
</template>

and my CategoryController is:
<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Language;
use App\Models\Game;
use Inertia\Inertia;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */

        // query categories details
        $words = \DB::table('memory_words')
            ->select('category_id', \DB::raw('COUNT(id) AS words'))
            ->groupby('category_id');
        $sentences = \DB::table('match_sentences')
            ->select('category_id', \DB::raw('COUNT(id) AS sentences'))
            ->groupby('category_id');
        $categories = auth()->user()->categories()
            ->join('games', 'categories.game_id', '=', 'games.id')
            ->join('languages', 'categories.language_id' ,'=', 'languages.id')
            ->joinSub($words, 'words', function($join) {
                $join->on('categories.id', '=', 'words.category_id');
            })
            ->joinSub($sentences, 'sentences', function ($join) {
                $join->on('categories.id', '=', 'sentences.category_id');
            })
            ->select('categories.id', 'categories.name', 'categories.user_id', 'games.name as game', 'languages.name as language', 'words.words', 'sentences.sentences')
            ->get();

        return Inertia::render('Manage', [
            'categories' => $categories,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return Inertia::render('Category/Create', [
            'games' => Game::all(),
            'languages' => Language::all()
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        dd($validated);
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'game' => 'required|integer',
            'language' => 'required|integer',
        ]);

        // check game and language exist
        if(is_null(Game::find($request->game))) {
            return;
        }
        if(is_null(Language::find($request->language))) {
            return;
        }

        Category::create([
            'name' => $request->name,
            'game' => $request->game,
            'language' => $request->language,
        ]);

        return redirect(route('manage'));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function edit(Category $category)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        //
    }
}

Laravel definitely thinks that I'm requesting a 'destroy' because when I remove that option from the routes, I get a 404 error. Yet a search for 'destroy' only brings up the empty functions in each of my models and the files created by Breeze to delete users or sessions.
What could cause this?
Answer: I think you need mention the route if you are using Ziggy route in your Inertia js app
<form @submit.prevent="form.post(route('categories.store'))">

Comment: I could have sworn I already did that, but you're exactly right. Thanks.


How to get pre-signed url with AWS.ManagedUpload

Question: I'm uploading file to AWS S3 with AWS.S3.ManagedUpload. Everything was simple until I want to obtain pre-signed URL for uploaded file.
I'm creating AWS.S3.ManagedUpload, and fire send method.
   const params = {
        Bucket: process.env.S3_BUCKET_NAME,
        Key: fileKey,
        Body: fileStream,
      }

     const upload = new AWS.S3.ManagedUpload({ params })

      upload.send((err, data) => {
        if (err) {
          console.log(err)
        }
        // handle successful upload
      })
    }

As a result I receive object with non-singed url. So it is accessible only if bucket is public which I want avoid.
Comment: Sorry the off-topic, but how do you send credentials to ManagedUpload ? I'm trying to use it, but can't find any working example.
Answer: I found simple solution. You need to use AWS.S3.getSignedUrl when upload is done.
upload.send((err, data) => {
  if (err) {
    // handle error
  }
  const signedUrl = s3.getSignedUrl('getObject', params)
  ...

Where params is { Bucket, Key, Expires }


How do I get back a strongly typed collection that queries multiple entities with Castle's ActiveRecord?

Question: I'm trying to get a specific set of data while joining 4 different entities together to do so.  What I've done is setup a DTO to try to get this working:
public class LatestThread
{
    private readonly string comment;
    private readonly DateTime posted;
    private readonly string userName;
    private readonly int reputation;
    private readonly int threadId;
    private readonly string topic;
    private readonly int userId;
    private readonly string avatar;

    public LatestThread(string comment, DateTime posted, string userName, int reputation, int threadId, string topic, int userId, string avatar)
    {
        this.comment = comment;
        this.avatar = avatar;
        this.userId = userId;
        this.topic = topic;
        this.threadId = threadId;
        this.reputation = reputation;
        this.userName = userName;
        this.posted = posted;
    }

    public string Comment
    {
        get { return comment; }
    }

    public DateTime Posted
    {
        get { return posted; }
    }

    public string UserName
    {
        get { return userName; }
    }

    public int Reputation
    {
        get { return reputation; }
    }

    public int ThreadId
    {
        get { return threadId; }
    }

    public string Topic
    {
        get { return topic; }
    }

    public int UserId
    {
        get { return userId; }
    }

    public string Avatar
    {
        get { return avatar; }
    }
}

Now I thought I could use SimpleQuery like so:
string hql = string.Format("select new LatestThread(m.Comment, m.Posted, u.UserName, u.Reputation, t.Id, t.Topic, u.Id, u.Avatar) from Thread as t inner join Message as m on t.Id = m.ThreadId inner join User as u on u.Id = m.PostedById inner join Activity as a on a.Id = t.ActivityId where a.Lineage like '{0}%' order by t.LastPosted desc", activityLineage);

return repository.SimpleQuery(0, 10, hql);
My repository method looks like:
    public virtual IList<T> SimpleQuery<T>(int firstResult, int maxResults, string hql, params object[] parameters)
    {
        var query = new SimpleQuery<T>(hql, parameters);
        query.SetQueryRange(firstResult, maxResults);
        return query.Execute();
    }

Now it's asking for me to put [ActiveRecord] at the top of my LatestThread class. When I do that it wants a primary key, and that just seems to be the wrong route.
I've also read bits that refer to the Import attribute given to classes that aren't the DTO.  In all the examples though it's just two entities being joined, not the 4 I have.  Do I need to add Import to all 4?  Or is there something to tell AR that it's a readonly DTO class?  OR am I doing this all wrong and there's a really easy way to do what I'm trying to do.
TIA!
Comment: Thinking what I want to do isn't that easy.  Looks like if you want to eager load items you have to select all the columns which kinda blows...
              from Post p
  join fetch p.Comments
  join fetch p.Blog
 where p.Id = 1
Comment: http://trappedinaworldofcode.wordpress.com/2008/03/19/strongly-typed-results-from-nhibernate-hql-projection-query/
Answer: Add the Import attribute to your new Thread class
[Import(typeof(LatestThread), "LatestThread")]
[ActiveRecord("Thread")]
public class Thread : ActiveRecordBase<Thread> { /* blah blah */ }

And then, query magic happens :)
string hql = string.Format("select new LatestThread(m.Comment, m.Posted, u.UserName, u.Reputation, t.Id, t.Topic, u.Id, u.Avatar) from Thread as t inner join Message as m on t.Id = m.ThreadId inner join User as u on u.Id = m.PostedById inner join Activity as a on a.Id = t.ActivityId where a.Lineage like '{0}%' order by t.LastPosted desc", activityLineage);

SimpleQuery<LatestThread> query = new  SimpleQuery<LatestThread>(typeof(Thread), hql );
LatestThread[] results = query.Execute()

Source : http://www.kenegozi.com/Blog/2006/10/08/projection-using-activerecords-importattribute-and-hqls-select-new-clause.aspx
Comment: I did actually see this post before, but wasn't sure where the heck to put the import.  It seems that you just need to put it on one of the entities? Then back on my LatestThread I shouldn't need any attributes right? It looks like from your example that I was close, but my exe was wrong at the end
Comment: Adding the Import to the Thread class and then trying to do it with my SimpleQuery still doesn't work.  It wants me to put ActiveRecord attribute on my LatestThread again...sigh...
Comment: I think this is close...I was just in a rush over lunch.  I'll retry tonight.
Comment: ahhh, yeah I think I have to have that typeof(Thread).  Thanks for posting an update!
Comment: Nice. I didn't know you could do that in HQL that way - as below, we've been doing it via simple projection.
Answer: You can't query a type that isn't mapped (which is what the [ActiveRecord] attribute does). AFAIK you can't get NHibernate to create a new arbitrary object instance like that via HQL (I stand to be corrected if someone knows otherwise).
Your best bet is to do a projection query and then have a method to map the tuples returned into instances of your type.
My answer here shows how to do a projection query and map it to an anonymous type; what you want to do is not much different. You could then put a method to do this in a type-specific repository or a strongly-typed extension method to the generic repository.
Comment: Crap, really new to nhib and castle's ar. I'm starting to understand "projection"s but tuples?  :P  I'll check it out.


I can't understand rotation mechanism in iOS6

Question: My app has view controllers subclassing shouldautorotateToInterfaceOrientation. And in it, I decides each view's rotation. This works correctly. But in iOS6, though I read documents provided Apple, I can't understand it.
My app has navigation controller as root view controller. This navigation controller has tab controller. And the tab controller has some view controllers. I want the first view controller (in tab controller) viewed only as portrait mode and the second view controller (in tab controller) viewed both portrait and landscape mode. It works correctly in iOS5.
But I don't know how to make it in iOS6. Although I know I should subclass supportedInterfaceOrientations, it doesn't work when rotation happen. To my surprise it is called when a view is showing.
How to make what I want?
Thank you for reading.
Comment: you should define the supported orientation for you application in `-application:supportedInterfaceOrientationsForWindow:` of the `AppDelegate.m` file or in the `Info.plist` and the your views would response only the `-shouldAutorotate:` method with a `BOOL` value, if your view supports the predefined orientations or not. the `- shouldAutorotateToInterfaceOrientation:` is deprecated in iOS6.
Answer: The following link might steer you to the right direction: http://code.shabz.co/post/32051014482/ios-6-supportedorientations-with-uinavigationcontroller
Basically, you need to subclass UINavigationController and have it listen to changes in -supportedInterfaceOrientations of its topViewController. There is a sample class you can download in the blog post and also explains what code to add.
Answer: When you use UINavigationController or UITabbarViewController - application always does what they say in their shouldAutorotate, supportedInterfaceOrientations methods.
You can add a category for them to redirect these methods to the controller they currently display.
Like this:
 @implementation UINavigationController (Rotation_IOS6)
-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}
@end

Similar for UITabbarViewController.
Comment: This may have unintended side effects. Think about it if you do that then that's the behavior of ALL navigation controllers system-wide, even if they're presented by the OS. I got a crash because of that. Subclassing is better because you remain in control of who gets the special behavior and who doesn't.
Answer: In my opinion, this is the best explaination i have found : http://www.widemann.net/wp-fr/?p=662 but it's in french.
Maybe it makes sense with google traduction in english


how to uninstall Linux dual boot with Windows?

Question: I installed Kali Linux (Debian distro) dual boot with Windows 7 but there were some damages with the ISO file i downloaded so Kali didn't install correctly,
please how do I uninstall Kali dual boot with Windows?and how to completly uninstall grub?i mean when I boot my PC computer directly boots into Windows cuz i'm gonna redownload the ISO file and reinstall Kali on my PC Thank you in advance
Comment: Kali is not Ubuntu. It's offtopic here I am afraid.
Answer: Go to Windows partition manager and delete the partition where you installed Linux and then format it. Start fresh installation.
Comment: well I actually already tried to delete the Linux partiton with diskmgmt.msc but when rebooting the PC rescue_grub appears and says no such partition when I trype rescue_grub>help an error occurs i couldn't log in to windows so i had to get the linux DVD and reinstall it so i can log in to windows


No styles in wp_admin

Question: Welcome,
I have a huge problem. Everything's fine on localhost. But when I upload my page to the server (site88.net), wp_admin styles don't load. The page itself is alright although.

I have tried what this guy wrote:
http://manovotny.com/fix-wordpress-admin-styles-not-loading/
I have also added define('SCRIPT_DEBUG', true); to wp-config.php and the result is following:

Please help :)
Comment: have you checked permission of directory where you have put css ? it must be 755.
Comment: I have just checked and yes, it is 755.
Comment: Please check jquery main file have loaded or not and have you changed home_url and site_url in wp_options table?
Comment: Yes, I have just checked `if (typeof jQuery != 'undefined') { alert("jQuery library is loaded!"); }else{ alert("jQuery library is not found!"); }` and I have also updated home_url and site_url in wp_options table.
Answer: Try the following:
1) Clear your browser cache.
2) Re-install WordPress (keep wp-content and your database, just reinstall the core files)
3) Check homeurl and siteurl form phpmyadmin
4)  rename .htaccess file form root.
5) Always user private browser remove cache issue.
That's it.
Comment: Thank you. It worked after reinstallation. That simple :D
Comment: Yes,sometime some files are missing while upload or may corrupt.Thanks for appreciation.

No styles in wp_admin


How can I set keyboard layout for the guest session?

Question: First, my ultimate goal is the same as in this question. I am a Dvorak user, but I want QWERTY, not Dvorak, to be the default keyboard layout in a guest session. If you know a direct answer to that instead of to the question below, that will also be appreciated.

I can change the keyboard layout to QWERTY with setxkbmap -layout us.
Some googling tells me that if I create a shell script /etc/guest-session/prefs.sh, it will be run when the guest session starts.
So I created a prefs.sh file containing just that command:
setxkbmap -layout us

What I expected to happen was to be able to run a guest session and automatically have the keyboard layout set to QWERTY. What actually happened was that when I tried running a guest session, it simply failed and brought me back to the login screen.
I must be misunderstanding something, but I don't know what. Any ideas?
If relevant: I'm using Ubuntu 12.04.
Answer: The way you did it, the command was run prematurely, i.e. before the actual start of the guest-session. Try this instead:
echo 'setxkbmap -layout us' >> $HOME/.profile

I just rewrote the tutorial about customizing guest sessions. It might help you understand it better.
Edit:
This has become more tricky on later Ubuntu versions. These lines in /etc/guest-session/prefs.sh work for me on Ubuntu 15.10:
echo "gsettings set org.gnome.desktop.input-sources sources \"[('xkb', 'se'), ('xkb', 'us')]\"" >> $HOME/.profile
echo "gsettings set org.gnome.desktop.input-sources current 1" >> $HOME/.profile

The ('xkb', 'se') value is my system default (a Swedish keyboard layout). So basically I set a list with my system default and the keyboard layout I want to use in the guest sessions - English (US). Then I tell the system to make the second value in the list the current keyboard layout. 0 (zero) would have been the first value.
Comment: Hmm this did not work for me. I can open a guest session but Dvorak is still the keyboard layout.
Comment: @zorkerz: Not for me either. I just edited my answer.
Comment: Your update worked for me (Ubuntu 16.04 beta).
Comment: @zorkerz: Great. :)


has to redirect to the website when I type a URL in the input field

Question: I have a simple search input box in my webpage that has google search action to it.This is the code.

        <form action="https://www.google.com/search" method="GET">
          <input type="search" id="search" name="q" placeholder="Search Google or type URL" />
          <button className="icon" type="submit">search</button>
        </form>

This is the image of search box
So if i type anything for example like apple, it searches google for apple and displays the content. But if I type a url like http://facebook.com, it again searches google and displays the search result for facebook.
But I need it to redirect to that particular website when I enter a url. If i enter http://facebook.com and press enter, It must redirect me to the facebook website and not to the google search results page for facebook.
Please help me out in this. Thanks in advance.
Comment: can you please explain me how to do that. @Pavitra
Comment: you have to use js for that
Answer: Effectively what you want here is for the one button to do two different things (search via google, or redirect to a URL). Because you want one element to do two different things, I would recommend using Javascript so that the page can decide which thing to do.
The following code will take in a string from an input box and either redirect if it starts with "HTTP://" or searches google if it doesn't:

        Enter a URL or search query
        <input type="text" name="search" id="search">
        <button type="submit" onclick="search(document.getElementById('search').value)">search</button>

Answer: You can add JS to check whether the input value is a URL.

function go() {
  const val = document.getElementById('input').value
  window.open(
    (isURL(val) ? '' :
      'https://google.com/search?q=') + val,
    '_blank')
}

function isURL(url) {
  try {
    new URL(url)
    return true
  } catch (e) {
    return false
  }
}
<input type="text" id="input" placeholder="Search Google or type URL" />
<button onclick="go()">Search</button>


Terminator terminal fail to launch

Question: For some reason my terminator terminal stopped working yesterday. This is the error I get when I try to run it:
/usr/share/terminator/terminatorlib/terminator.py:87: Warning: Attempt to add property GnomeProgram::default-icon after class was initialised
self.gnome_program = gnome.init(APP_NAME, APP_VERSION)

I have tried a remove and reinstall but that did nothing for the issue. A solution would be appreciated. Thank you.
Comment: and you're saying it doesn't start?
Comment: It does start. The terminal flashes for a split second and then immediately closes.
Answer: In my case commenting every line in ~/.config/terminator/config fixed the problem.
It seems like newer version cannot understand old config.
It is also weird that even if you do aptitude purge terminator it leaves this config file ;/

Terminator terminal fail to launch


Proving $\lim_{x\to \infty} xe^{-x^2} = 0$ using definition

Question: I am trying to prove that $\displaystyle\lim_{x\rightarrow \infty} xe^{-x^2} = 0$ using the formal definition of limits as $x$ approaches infinity. The definition I am using is as follows:
$$\lim_{x\rightarrow \infty} f(x) = L$$ if the following is satisfied:
for every number $\varepsilon >0$ there exists a number $R$, possibly depending on $\varepsilon$, such that if $x>R$, then $x$ belongs to the domain of $f$ and $$\vert f(x) - L \vert < \varepsilon.$$
My attempt has been to set up $\vert xe^{-x^2} \vert < \varepsilon$ and try to find a value of $x$ that satisfies the definition. However I am stuck. I tried rewriting it as $$e^{-x^2} < \frac{\varepsilon}{x}$$ so that $$x > \sqrt{\ln(\frac{\varepsilon}{x})}.$$ I am not able to solve for an explicit x-value though. I also tried writing $$x^2-\ln(x) > \varepsilon.$$ Is it possible to argue that any "nicer" expression than $x^2-\ln(x)$ could replace $x^2-\ln(x)$ and then find a value which $x$ must satisfy such that when $x>R$ we are guaranteed that $\vert f(x) \vert< \varepsilon$ ? Any input to this question would be appreciated!
Comment: If you want to prove that $x^2-\ln x>\epsilon$ for big enough $x$, you can use the inequality $\ln x\geq x-1\epsilon$, which should be easier since it's a polynomial.
Answer: By $e^{x^2}>1+x^2$ then
$$xe^{-x^2}<\dfrac{x}{1+x^2}<\dfrac1x$$
Comment: So since $xe^{-x^2} >0$ for all $x>0$ it would suffice that I apply the epsilon-delta definition to $\frac{1}{x}$  and show that the limit is $0$ as $x$ approaches infinity?
Answer: Note that
$$xe^{-x^2} < xe^{-x}$$
for $x>1$. Working out the epsilon-delta argument for this function should be much easier.
For example $e^x>\frac{x^2}{2}$ since this is only one of the positive terms of the power series of $e^x$. It follows that $\frac{x}{e^x}<\frac{2}{x}$ so if you give me a positive $\epsilon$, $xe^{-x}<\epsilon$ for all $x>\frac{2}{\epsilon}$ QED.
Comment: Then work it out...
Comment: @Shalop There you have it! I said it was going to be easy!
Answer: It seems you are specifically interested in getting an "easy" $x_{\epsilon}$ for given $\epsilon > 0$.
In such a case it is often helpful to estimate the given expression by others which are easier to handle. A possible way which plays it down to only elementary facts uses

$e > 2 \Rightarrow e^{-x} < 2^{-x}$
For $x>1$ we have $e^{-x^2} < e^{-x}$
$2^x \geq 2^{\lfloor x\rfloor} = (1+1)^{\lfloor x\rfloor} \stackrel{x>2}{>} \binom{\lfloor x\rfloor}{2}= \frac{\lfloor x\rfloor\cdot (\lfloor x\rfloor-1)}{2}$

Let $x>2$ and $\epsilon >0$:
$$\frac{x}{e^{x^2}} < \frac{x}{2^x} < \frac{2 \lfloor x\rfloor}{\lfloor x\rfloor\cdot (\lfloor x\rfloor-1)} = \frac{2 }{ \lfloor x\rfloor-1} < \frac{2 }{ \lfloor x\rfloor}\stackrel{!}{<}\epsilon$$
Obviously, the requested inequality is satisfied for $\boxed{\lfloor x_{\epsilon}\rfloor > \frac{2}{\epsilon}}$


How to print from Xamarin application?

Question: Is it possible to print from a xamarin application to a pos printer?
I search in xamarin docs about printing but i only found a microsoft UWP sample. Is this for xamarin development also? Probably i miss something so can anyone guide me how to print from a xamarin application silently to a ECS/POS printer?
Comment: You need to read the printer manual.  There is no general solution for this - you need to connect to the printer with bluetooth, then the specific details of printing will depend on the printer
Answer: Xamarin supports .NET Core technology. Xamarin.Forms is the user interface technology. Printing is something that is not covered with either of those.
You can print with Xamarin.Forms as each platform (iOS, Android, UWP etc) supports printing and Xamarin supports 100% of APIs of each platform, however you need to write the code separately, for example for UWP you can use the link you found above, but it will work only on UWP.

How to print from Xamarin application?


Does Linux x86 64 have both 2M and 4K page together?

Question: My kernel is
<code>Linux localhost.localdomain 2.6.30 #5 SMP Tue Aug 10 00:56:36 CST 2010 x86_64 x86_64 x86_64 GNU/Linux
</code>
My kernel module find a 2M page while nr_hugepages is disabled.
<code> [root@localhost ~]# cat /proc/sys/vm/nr_hugepages
0

[root@localhost ~]# cat /proc/meminfo
...
Hugepagesize:       2048 kB
DirectMap4k:        9856 kB
DirectMap2M:     2052096 kB
</code>
I wonder whether linux64 kernel can have both 2M and 4K page together? And what's the condition?
Answer: Yes.  I believe you need to build with a special kernel setting in order to support huge page size, then allocate the #/huge pages you wish (the rest of memory will be regular, 4K pages).
Here's are links:

http://unixfoo.blogspot.com/2007/10/hugepages.html
http://dbakerber.wordpress.com/2012/03/14/configuring-hugepages-for-oracle-on-linux/
http://lwn.net/Articles/374424/


Pulseaudio audio problems

Question: I have had this problem for quite some time now, before it worked by just inputting  pulseaudio --start, but now it doesn't work anymore. Usually when i use my web browser i start hearing crackling sounds, usually for the first 10 seconds of the audio playing it's fine, and then these noises begin, affecting not only the browser but the whole computer. I also tried reinstalling pulseaudio but the problem doesn't seem to go away.I'm on 20.04.03 LTS
Answer: I had the same and was able to fix it. It may be related to speech-dispatcher (some text-to-speech utility), so you can try:
killall speech-dispatcher

If the sound comes back to normal you can remove it completely (if you don't need it) with:
sudo apt remove speech-dispatcher

Don't forget to restart your web browser.
source: https://tqdev.com/2021-firefox-ubuntu-crackling-sound
Comment: Not happening anymore, but if it will happen again  i will try, thanks

Pulseaudio audio problems


Is there a way to add a new line after every ']' in Python?

Question: I originally had a string containing BBCode in which I wanted to format it better so it can be readable.
I had something like
['"9-5[centre][notice][url=https:\\/\\/www.youtube.com\\/playlist?list=PL3OTylWB5pG7s7JowIUEYBiPkKR0GRRRG][b]\\u25ba osu! Mapping Theory[\\/b][\\/url]\\n[url=https:\\/\\/youtu.be\\/0uGeZzyobSY]Linear Momentum[\\/url] | [url=https:\\/\\/youtu.be\\/zOzi8Q655vs]Linear Momentum 2[\\/url] | [url=https:\\/\\/youtu.be\\/Rm5l0UDJLcQ]Angular Momentum and Circular Flow[\\/url] | [url=https:\\/\\/youtu.be\\/hRc3Xm0wI7s]Active and Passive Mapping[\\/url]\\n[url=https:\\/\\/youtu.be\\/OgNhsZpKRYc]Slider Flow[\\/url] | [url=https:\\/\\/youtu.be\\/e05hOKXfWOk]Stream Flow[\\/url] | [url=https:\\/\\/youtu.be\\/zYAujNMPVbY]Slider Mechanics[\\/url] | [url=https:\\/\\/youtu.be\\/ZOtkAQ3MoNE]Aesthetics by Symmetry[\\/url] | [url=https:\\/\\/youtu.be\\/WnLG31LaQx0]Aesthetics by Complexity[\\/url] | [url=https:\\/\\/youtu.be\\/i323hh7-CAQ]Defining Flow[\\/url]\\n[url=https:\\/\\/youtu.be\\/hNnF5NLoOwU]Flow and Aesthetics[\\/url] | [url=https:\\/\\/youtu.be\\/tq8fu_-__8M]Angle Emphasis[\\/url] | [url=https:\\/\\/youtu.be\\/6ilBsa_dV8k]Strain[\\/url] | [url=https:\\/\\/youtu.be\\/KKDnLsIyRp0]Pressure[\\/url] | [url=https:\\/\\/youtu.be\\/jm43HilQhYk]Tension[\\/url] | [url=https:\\/\\/youtu.be\\/-_Mh0NbpHXo]Song Choice[\\/url] | [url=https:\\/\\/youtu.be\\/BNjVu8xq4os]Song Length[\\/url]\\n\\n[url=https:\\/\\/www.youtube.com\\/playlist?list=PL3OTylWB5pG6t5MCwGnq87iYZnE5G7aZL][b]\\u25ba osu! Rambling[\\/b][\\/url]\\n[url=https:\\/\\/youtu.be\\/-Beeh7dKyTk]Storyboards[\\/url] | [url=https:\\/\\/youtu.be\\/i6zzHMzwIzU]Why[\\/url]\\n\\n[url=https:\\/\\/youtu.be\\/_sBP7ttRQog]0 BPM[\\/url] | [url=https:\\/\\/youtu.be\\/UgtR6WnuTT8]ppv2 Pt.1[\\/url] | [url=https:\\/\\/youtu.be\\/Bx14u5tltyE]ppv2 Pt.2[\\/url] | [url=https:\\/\\/youtu.be\\/-095yuSLE4Y]Super high star rating[\\/url][\\/notice][url=https:\\/\\/amo.s-ul.eu\\/oApvJHWA][b]Skin v3.4[\\/b][\\/url]\\n[size=85]Personal edit of [url=https:\\/\\/osu.ppy.sh\\/forum\\/t\\/481314]Re:m skin by Choilicious[\\/url][\\/size]\\n\\n[img]http:\\/\\/puu.sh\\/qqv6C\\/0aaca52f51.jpg[\\/img][url=https:\\/\\/osu.ppy.sh\\/u\\/Satellite][img]http:\\/\\/puu.sh\\/qqv6K\\/94681bed3f.jpg[\\/img][\\/url][url=https:\\/\\/osu.ppy.sh\\/u\\/Sellenite][img]http:\\/\\/puu.sh\\/qqv6T\\/c943ed1703.jpg[\\/img][\\/url][url=https:\\/\\/osu.ppy.sh\\/u\\/Morinaga][img]http:\\/\\/puu.sh\\/qqv70\\/cfbdb2a242.jpg[\\/img][\\/url][url=https:\\/\\/osu.ppy.sh\\/u\\/-Mo-][img]http:\\/\\/puu.sh\\/qqv77\\/ca489f2d00.jpg[\\/img][\\/url]\\n[notice]I don\'t really do nomination stuff often anymore. \\nHowever, please do show me your map if it\'s any of the following:[box=][b]Bounty[\\/b]\\n[size=50]High priority modding for these artists\\/songs (maybe a GD, just ask).\\nPreferably non-cut versions and songs that have no ranked maps yet.[\\/size]\\n\\nYuuhei Satellite\\nYuuhei Catharsis\\nShoujo Fractal\\nHoneyWorks (non-vocaloid)\\nTrySail\\nClariS\\n\\nClariS - CLICK (Asterisk DnB Remix), [size=85]either version.[\\/size]\\nfhana - Outside of Melancholy, [size=85]a version that isn\'t cut pls[\\/size]\\nAny cover of \\u7832\\u96f7\\u6483\\u6226\\u3001\\u59cb\\u3081![\\/box]I also do storyboard checks for any map.\\n\\nPMs are open for anything. Ask me anything. \\nAsk me what my favourite colour is if you really want even.[\\/notice][box=Guests][b]Ranked[\\/b]\\n[url=https:\\/\\/osu.ppy.sh\\/b\\/1575100][img]http:\\/\\/s.ppy.sh\\/images\\/insane.png[\\/img] senya - Terasareru kurai no Shiawase [Lunatic][\\/url]\\n[url=https:\\/\\/osu.ppy.sh\\/b\\/1794557][img]http:\\/\\/s.ppy.sh\\/images\\/insane.png[\\/img] senya - Arehateta Chijou no Uta [Collab Insane][\\/url]\\n[url=https:\\/\\/osu.ppy.sh\\/b\\/1592915][img]http:\\/\\/s.ppy.sh\\/images\\/insane.png[\\/img] Tanaka Hirokazu - C-TYPE [TetriS-TYPE] [S-TYPE][\\/url]\\n[url=https:\\/\\/osu.ppy.sh\\/b\\/1490130][img]http:\\/\\/s.ppy.sh\\/images\\/insane.png[\\/img] TrySail - adrenaline!!! [Insane][\\/url] [size=85]Slightly ruined version.[\\/size]\\n[url=https:\\/\\/osu.ppy.sh\\/b\\/1401096][img]http:\\/\\/s.ppy.sh\\/images\\/insane.png[\\/img] senya - Shunkan Everlasting [Insane][\\/url]\\n[url=https:\\/\\/osu.ppy.sh\\/b\\/795269][img]

Basically unreadable currently.
I tried making it look like
['"9-5[centre][notice][url=https:\\/\\/www.youtube.com\\/playlist?list=PL3OTylWB5pG7s7JowIUEYBiPkKR0GRRRG]
[b]
\\u25ba osu! Mapping Theory[\\/b]
[\\/url]\\n[url=https:\\/\\/youtu.be\\/0uGeZzyobSY]
Linear Momentum[\\/url]
 | [url=https:\\/\\/youtu.be\\/zOzi8Q655vs]
Linear Momentum 2[\\/url]
 | [url=https:\\/\\/youtu.be\\/Rm5l0UDJLcQ]
Angular Momentum and Circular Flow[\\/url]
 | [url=https:\\/\\/youtu.be\\/hRc3Xm0wI7s]
Active and Passive Mapping[\\/url]
\\n[url=https:\\/\\/youtu.be\\/OgNhsZpKRYc]
Slider Flow[\\/url]
 | [url=https:\\/\\/youtu.be\\/e05hOKXfWOk]
Stream Flow[\\/url]
 | [url=https:\\/\\/youtu.be\\/zYAujNMPVbY]
Slider Mechanics[\\/url]
 | [url=https:\\/\\/youtu.be\\/ZOtkAQ3MoNE]
Aesthetics by Symmetry[\\/url]
 | [url=https:\\/\\/youtu.be\\/WnLG31LaQx0]
Aesthetics by Complexity[\\/url]
 | [url=https:\\/\\/youtu.be\\/i323hh7-CAQ]
Defining Flow[\\/url]
\\n[url=https:\\/\\/youtu.be\\/hNnF5NLoOwU]
Flow and Aesthetics[\\/url]
 | [url=https:\\/\\/youtu.be\\/tq8fu_-__8M]
Angle Emphasis[\\/url]
 | [url=https:\\/\\/youtu.be\\/6ilBsa_dV8k]
Strain[\\/url]
 | [url=https:\\/\\/youtu.be\\/KKDnLsIyRp0]
Pressure[\\/url]
 | [url=https:\\/\\/youtu.be\\/jm43HilQhYk]
Tension[\\/url]
 | [url=https:\\/\\/youtu.be\\/-_Mh0NbpHXo]
Song Choice[\\/url]
 |

Where there's a new line after every ']'
I've tried tweaking re.sub("[\(\[].*?[\)\]]", "", str(x)) to fit what I need but it just deletes everything inside of them. (I have no idea how regex works)
How can I go about this?
Answer: There's no need for a regular expression, just use the simple str.replace() function.
x = x.replace(']', ']\n')

Answer: It really depends on exactly what you want your output to look like.
I interpreted your output as wanting a newline after each url= tag, which would require the following regex:
output = re.sub(r"(\[url.*?\])", r"\1\n", input)

The brackets () form a capture group which is then used in the replace statement as \1 since its the first  unnamed capture group.
You can change the regex to your will but just keep the stuff you want to keep within the capture group.
If you want to experiment with regex you can use https://regexr.com/ which is an amazing resource when fiddling around with regex.


How can an R variable be passed to a system call for a python function?

Question: I have written a function in python that takes two arguments one of which is a file path name. I have wrapped the call to this python function within a loop in R. I want to be able to update a variable in this R for loop and pass the value of this variable to the python function as the file path name. How can I do this?
R code:
for (file in filenames) {
     file <- paste("/home/yyy/xx", file, sep="/")
     system('python pylib/filefunction.py <TODO: file> divide') # divide is the 2nd argument
}

Comment: what about converting divide to a string and concatenating it onto the end of the system call? (maybe with paste?)
Answer: I believe you can just use paste again:
for (file in filenames) {
  file <- paste('/home/yyy/xx', file, sep='/')
  system(paste('python', 'pylib/filefunction.py', file, 'divide'))
}

Or, better yet, sprintf:
for (file in filenames) {
  system(sprintf('python pylib/filefunction.py /home/yyy/xx/%s divide', file))
}

Comment: If this is not the correct answer, then I don't understand the question. (+1)


Implication and Interpretation of Banach Tarski

Question: As I understand, the Banach-Tarski paradox says a ball in 3-space
may be decomposed into finitely many pieces and reassembled into two balls each of
the same size as the original. Despite being called a paradox it is of course a theorem.
Looking at the proof, it seems to rely heavily on the Axiom of Choice. However since the consequences of not accepting the Axiom of Choice seem even more weird, I am wondering whether the more experienced Mathematicians here find the implication of Banach-Tarski a perfectly acceptable Theorem, or whether it shows that ZF with Choice is actually ultimately pathological ? ( i.e. does it just seem a weird from a perspective that is not mathematically mature enough ?)
Comment: The "sum" $1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\cdots$ can be rearranged to give an result we want, like $\pi^e$, or $-22/7$. Disturbing if our intuition is based on finite sums.  Same with Banach-Tarski, if we think decomposition is like cutting up an apple.
Comment: "Paradox" means "contrary to expectation, common sense, or received opinion" in its main meaning, though it is often mistaken to mean "logically contradictory". Nothing wrong with theorems being paradoxical.
Comment: Note: you can't use banach-tarski to tease physicists because it would require subatomic splits of your apple/ball/other real world object
Comment: related question http://math.stackexchange.com/questions/103743/foundation-for-analysis-without-axiom-of-choice
Comment: Let me just note that, long before you get to Banach-Tarski, there are already results that the man-in-the-street might call paradoxical, e.g., there are as many even integers as integers, and as many integers as rationals, but fewer rationals than reals. That's math.
Comment: What would be really disturbing would be if Banach-Tarski could be
carried out by an explicit construction. Since it can't, it's not
exactly a geometrical crisis.
Comment: @Arturo: I understand, the question is not based on the fact, that it *happens* to be called a paradox, but rather that independent of what people call it, the consequence seems pathological (perhaps due to a lack of mathematical maturity, granted !)
Comment: @PeeJay: I understand that as well; it's (i) a pet peeve of mine; and (ii) the final sentence of your first paragraph, that made that peeve rear its ugly head.
Comment: lol, I see :) perhaps in the context of this site it was a little superflous to state the obvious...
Comment: To me, AC has the flavor of one of
those statements about sets that at first seems like it should obviously be valid in
any formalization of our naive ideas about sets, but in fact becomes less obvious
the more you know about it.
Mathematicians in the 19th century had
other statements about sets that they thought were obviously
desirable, but which most mathematicians today would reject, e.g.,
the statement P that there exists a set which contains all sets. There are
theories like New Foundations in which P true.
ZFC vs NF vs ... is a matter of taste, that's all.
Comment: Just wanted to point you to an excellent article on Good Math / Bad Math about this "paradox":
http://scientopia.org/blogs/goodmath/2012/01/06/the-banach-tarski-non-paradox/ (also read the comments)
Answer: The reason the Banach-Tarski paradox seems paradoxical is because of the following naive argument: surely the volume of a ball is the same as the sum of the volume of any possible decomposition of that ball into finitely many pieces, which is in turn not the same as the volume of two balls. More precisely, surely the total measure ought to remain invariant.
And the reason the Banach-Tarski paradox is a theorem is that the intermediate pieces it uses are very weird: in particular, they do not have volume. (More precisely, they are non-measurable.) So the naive argument breaks down completely, but naive arguments break down all the time in mathematics.
A more focused version of your question might be: how weird or pathological should I regard a non-measurable set as being? Well, of course they are weird, but they aren't weird to the point that they're a good reason (in my opinion) to reject the axiom of choice. One can construct non-measurable sets using the weaker ultrafilter lemma, which I happen to be extremely fond of, so I embrace them out of necessity.
Edit: You might also be interested in hearing Terence Tao's thoughts; he's written about Banach-Tarski several times and has enlightening things to say.
Comment: This particular "naive argument" does not break down, if you allow random picking, in other words, if you can choose real numbers at random in the interval [0,1]. The concept of picking real numbers at random is equivalent to saying all sets are measurable, and losing the ability to speak about random real numbers is not acceptable. This is a case where the mathematicians are stupid and brainwashed, not the critics.
Answer: It seems that the vast majority of mathematicians consider Banach-Tarski an acceptable price to pay for having the Axiom of Choice available. Its practical consequences are at least twofold, one general and one more specific:

Be wary of your intuition about sets that are so weird that you need the axiom of choice to construct them. The general consensus seems to be that the Banach-Tarski components behave non-intuitively, but not paradoxically.
In the presence of the Axiom of Choice one has to accept that there is no well-behaved measure on all subsets of $\mathbb R^n$ (where "well-behaved" means something like being invariant under isometries, at least finitely additive, and assigning a nonzero finite measure to an ball of finite radius). This entails a plethora of "assume such-and-such is measurable" premises in many theorems, but again this is generally treated as an acceptable price to pay for having choice.

Arguably, it even leads to a more general and useful theory that the main example of a measure is not defined on the full power set. Otherwise, the standard development of everything would just assume that all subsets are measurable, and then one would have trouble applying the theory to special measures that one wanted, for one reason or another, to be partial.
Comment: @AsafKaragila: Borel sets are not dependent on the kind of axiom of choice one is talking about here. They have nothing to do with uncountable continuum choice.
Comment: Borel sets are somewhat dependent on the axiom of choice, should we be wary of those? :-)
Comment: Of course the Banach Tarski pieces behave non-paradoxically, because the axiom of choice is consistent! But this is not the same as saying that they are not paradoxical, because they contradict the concept of "randomly chosen real number", and require you to formulate the concept of "random real" differently, as a "random variable", for which you cannot do certain operations. For example, you cannot speak about the probability that a random chosen real lands in a non-measurable set, the concept is incoherent. So this means random reals are forbidden in your universe.
Comment: @Ron: It is consistent without the axiom of choice that every set of real numbers is Borel. So when talking about sets which are not Borel sets, we have to make appeal to the axiom of choice. Roughly countable choice suffices.
Answer: Qiaochu's answer is great, and reflects exactly what a mathematician should feel about the Banach-Tarski theorem.
I would like to add another opinion, as someone who works mostly in a choiceless context I can assure you that mathematics has many surprises in store for you once you give up the choice needed for Banach-Tarski.
You might end up with the bizarre universe in which there are no free ultrafilters on $\mathbb N$; the real numbers might be a countable union of countable sets; or it might be possible to cut the real numbers into more non-empty parts than elements.
There is always a "paradox", which is really just a counter-intuitive theorem, hiding in the dark corners of the universe. It tells you, in the philosophical level, just one thing:
Our intuition is completely developed by history and the axioms we are used to work with. Once you are completely used to the axiom of choice there is no surprise in the Banach-Tarski theorem, much like there is no surprise in Gödel's incompleteness theorems or in Cantor's theorem about the uncountability of the real numbers.
These are all theorems that shook the foundations of mathematics and caused people to shake their heads in disbelief, but eventually these theorems were accepted and nowadays people don't fuss about Banach-Tarski because it's one of the first thing presented in a course about measure theory: You can't measure everything in a translation-invariant way and with countable completeness.
The main issue is that in any strong enough theory there will be unexpected results, which is why the Banach-Tarski theorem - while very surprising - should not deter you from the axiom of choice, which makes infinitary things easier to deal with.
Comment: I would consider a universe without ultrafilters less bizarre than one with ultrafilters.
Comment: @Ben: I'd hardly think this is the case for most mathematicians.
Answer: The result points to the fact that it makes no sense to try to apply a geometric notion of measuring volume to all subsets of $\mathbb{R}^3$. But why should that be the case in the first place?
We measure volumes of sets by approximating them by sets that have a natural notion of volume, like disjoint unions of cubes. So we use mathematical methods to extend a notion of volume defined for simple objects to more complex objects. But there is no reason why the notion should apply to arbitrary sets of points.
And, intuitively, if there are sets of points somewhere that can not be approximated by objects with a natural notion of volume, the axiom of choice helps us to find them. Given that "set of points" and "geometric object" are in general quite different, it shouldn't be surprising that we can do that.
Answer: As something of an aside: it's important to remember that Banach--Tarski is not merely some artifact of choice.  Assuming choice, the BT paradox holds for some group actions (e.g. $SO(3)$ acting on $\mathbb R^3$), but not for others (e.g. $SO(2)$ acting on $\mathbb R^2$).  Indeed, there is an intrinsic group-theoretic property that governs whether or not the BT paradox can hold, namely amenability.
The study of group actions and their interaction with measure theory is an entire branch of mathematics; see
e.g. Topics in orbit equivalence, by Kechris and Miller.   There is much more to this topic than just the use of choice.
Comment: Yes, the results on amenability proper are independent of any choice-related issues (actually, I just checked, and the Wikipedia article does a more than decent role highlighting this). An interesting side comment: The *continuum hypothesis* is another useful tool when studying amenability, due to results of Mokobodzki (and another one of those abstract transfering tools, that allows us to eliminate the assumption of $\mathsf{CH}$ when the statements being proved are projective).
Answer:
I am wondering whether the more experienced Mathematicians here find the implication of Banach-Tarski a perfectly acceptable Theorem

The Banach-Tarski paradox helps to illustrate the fact that a proof of existence within ZFC doesn't necessarily imply concrete existence in an intuitive sense. Stating the theorem in terms of real material objects like oranges or gold balls exaggerates this discrepancy between intuitive actual existence and existence within ZFC even further.
In a certain sense, already the existence of a Hammel basis of $\mathbb R$ as vector space over $\mathbb Q$ raises the question what existence within ZFC actually signifies. Banach-Tarski adds an intuition boost derived from the explicit constructive paradoxical decomposition of the free group on two generators to arrive at a theorem where even the layman can appreciate that this sort of existence is paradoxical.
However, the purpose of this answer is to state my opinion that it is a red herring to blame the axiom of choice for all undesirable features of ZFC. (Blaming the axiom of power set axiom instead wouldn't help either.) The paradox is derived from ZFC as a whole, not from the axiom of choice alone. I say this because the axiom of choice can be added (in an appropriate form) to most foundational systems without disturbing things. It is quite useful, and it basically expresses a property that we expect in a set universe allowing "arbitrary" sets. (It's a bit similar to adding a unit element to a semigroup. It can have some undesired side effects, but overall it just simplifies things.)

A feature of ZFC that I like much less than the axiom of choice is the impredicativity of the axiom schemes of comprehension and replacement. Hence I added to my initial answer that it might be a better idea to blame them instead of the axiom of choice. However, after reading a bit on Banach-Tarski now, I have to admit that these are probably completely unrelated to Banach-Tarski.
Comment: Equiconsistency (or even consistency strength) is not the issue here. The axiom of choice, on the other hand, is the reason why the theorem holds. This is not a red herring: If you remove choice from the axioms of set theory, even if you add dependent choice, you can no longer prove the Banach-Tarski theorem. You may want to explain better what you mean, since as stated this is misleading.
Comment: @AndresCaicedo After reading the 70+ page proof of the consistency of Peano arithmetic by Gerhard Gentzen, I realized that he really had proved the consistency by finitary means. What he actually needed where not the axioms of ZFC or any other foundational theory of this sort, but the principle that predicative definitions and constructions are OK. John Horton Conway made a remark pointing in this very direction when he explained how his surreal numbers can be constructed inside ZFC, and why this construction just obscures the real principles why the surreal numbers are a valid construction.
Comment: @AndresCaicedo I may extend the answer when I have time, but not with the content of the previous comment. The reason why Choice is a red herring is that there is nothing wrong with Choice, but people talk about Banach-Tarski when they want to express their uneasiness with ZFC. There may be reasons to be uneasy with ZFC, but Choice should not be one of these reasons. It expresses an important property that we want the universe of sets to have. Perhaps it is slightly too strong, but people should discuss the real contentious points of ZFC before focusing on such minor details.
Comment: I don't understand how this is even an answer to the question. Sure, it's a point for a discussion on this topic, but not an answer to the question. The fact that choice holding or failing is equiconsistent has nothing to do with this. The question is **about implications** rather than equiconsistency. I agree that if this was a discussion over lunch, coffee or drinks, this would be a good point to raise. But unfortunately, MSE is not a place for discussions of this sort.
Comment: @AsafKaragila The funny thing is that "being equiconsistent" is a red herring too. The important point of my answer is that there is nothing wrong with the Axiom of Choice. This is different from being equiconsistent, i.e. the axiom "every subset of the reals is measurable" would also be equiconsistent, but there would nevertheless be something wrong with it if used in the foundations of set theory. But I think I understand now why my answer is easy to misinterpret, and I will try to improve it later.
Comment: First of all, the models that we know of "every subset of the reals is measurable" either requires that there will be an inaccessible cardinal (stronger consistency) or tha t $\aleph_1$ is singular (strange universes). Secondly, this is not an issue of wrong or not wrong. The question is what sort of foundation you want, and what sort of things you intend to do with it.
Comment: @AsafKaragila I clarified my answer now. Let me comment on the "every subset of the reals is measurable" issues here (let's abbreviate it as "Solovay property"). In my opinion, directly using the Solovay property as an axiom, or using it as motivation for another axiom which implies the Solovay property would be misguided. It is simply not a property of a set universe on which we should have any prejudices. If the Solovay property should fall out by coincidence from an axiom that we adopted for good independent reasons, then there would be nothing wrong with the Solovay property.
Comment: Calling it "Solovay property" feels wrong. Besides that your comment feels like a lot of words without much meaning. *"It is simply not a property of a set universe on which we should have any prejudices."* What? (The rest of the comment too.)
Comment: @AsafKaragila I just used "Solovay property" because it's short. I don't intent to convince you of the correctness of my answer or my comments, I just try to clarify what I mean, and also what I don't mean. I just wanted to bring this to an end. If you prefer that I delete the answer instead, then please let me know. I wouldn't have any problem with it either.


How can I get matplotlib's imshow to refresh once every second?

Question: Have a sensor that gives me an 8x8 grid of temps that I am to display on a live heatmap. I have made an 8x8 rand to simulate that data. This heatmap should be able to run until I tell it not to run anymore. I'm using python3 and matplotlib to attempt this visualization.
I've tried may ways to make this work, including clearing the screen, turning the plt into a figure, telling show() to not block, etc. You can see many of my attempts in the comments. It either displays once only, or never displays at all (e.g. ion() and plt.show(block=False) never display any data). I've hit my head against a wall for 2 whole work days and I can't figure out why it won't display properly.
import time
import socket
import matplotlib.pyplot as plt
import numpy as np
import random

first = True
randArray = []

#plt.ion()
plt.show(block=False)
#fig = plt.figure()
#str1 = ''.join(str(e) for e in amg.pixels)
#print (type(str1))
while True:
    #create a bunch of random numbers
    randArray = np.random.randint(0,50, size=(8,8))
    #print the array, just so I know you're not broken
    for x in randArray:
        print(x)
    #This is my attempt to clear.
    if (first == False):
        plt.clf()
    first = False
    #basical visualization
    plt.imshow(randArray, cmap='hot', interpolation='nearest')
    plt.draw()
    plt.show()
    #fig.canvas.draw()
    #plt.canvas.draw()
    #plt.display.update
    print("Pausing...")
    time.sleep(5)

I expect the code to generate a new set of numbers every 5 seconds, and then refresh the screen with the colors of those new numbers. This should be able to run for hours if I don't interrupt, but the screen never refreshes.
More: I have tried everything listed in the post "How to update a plot in matplotlib?" and everything they do just makes it so that no graph ever populates. The launcher acts like it's going to do something by showing up in the task bar, but then does nothing. I've tried it on a Mac and a Pi, both have the same issue. Maybe it's because that post is 8 years old, and this is python 3 not python 2? Maybe it's because I use imshow() instead of plot()? I haven't figured out how to make their code work on my machine either.
Edit: I've gotten it to work on the raspberry pi thanks to the first commenters recommendations. But now I'm left wondering.... what's wrong with my Mac??
Comment: Possible duplicate of [How to update a plot in matplotlib?](https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib)
Comment: Nope. I've tried everything in that post, and still can't get anything to work. I've even tried the code that was posted that people said worked, and I can't get it to work. That recommendation is 8 years old, so I'm guessing something in Python 3 changes how this works.
Answer: This is a similar question to this one.
You could try to modify your code to something like this:
import time
import socket
import matplotlib.pyplot as plt
import numpy as np
import random

first = True
randArray = []

#plt.ion()
plt.show(block=False)
#fig = plt.figure()
#str1 = ''.join(str(e) for e in amg.pixels)
#print (type(str1))
fig = plt.figure()
for i in range(0,5):
    #create a bunch of random numbers
    randArray = np.random.randint(0,50, size=(8,8))
    #print the array, just so I know you're not broken
    for x in randArray:
        print(x)
    #This is my attempt to clear.
    if (first == False):
        plt.clf()
    first = False
    #basical visualization
    ax = fig.add_subplot(111)
    ax.imshow(randArray, cmap='hot', interpolation='nearest')
    fig.canvas.draw()
    fig.canvas.flush_events()
    #fig.canvas.draw()
    #plt.canvas.draw()
    #plt.display.update
    print("Pausing...")
    time.sleep(2)

Have a nice day and get some rest :).
Comment: VtotheT, This has the same issue as my other attempts at fig.canvas. Python pops up in my menu bar (mac) and bounces, like it's going to do something, but never displays anything. It just keeps making new data, with no visualization. I would think that this is a problem with my computer, except that I tried it on a pi as well.
Answer: Try this one:
import matplotlib.pyplot as plt
import numpy as np

while True:
    #create a bunch of random numbers
    random_array = np.random.randint(0,50, size=(8,8))
    #print the array, just so I know you're not broken
    print(random_array)

    #clear the image because we didn't close it
    plt.clf()

    #show the image
#    plt.figure(figsize=(5, 5))
    plt.imshow(random_array, cmap='hot', interpolation='nearest')
    plt.colorbar()
    print("Pausing...")
    plt.pause(5)

   #uncomment this line and comment the line with plt.clf()
#    plt.close()

The magic is with the line plt.pause(5), it shows the image for five seconds. It's up to you if you want to close it (plt.close()) or clear it (plt.clf()). When you want to update constantly your plot, you don't use plt.show() or plt.draw(), you use plt.pause().
Uncomment some lines to try some variations... of course, some of them won't work.


Internet connection drops out

Question: I have this random network failure. No error pops up, the system says it's still connected to the internet(wifi and wired).
The problem is, I can't connect to anything, even a ping google.com gives no feedback. This only affects eth0, wifi is still working correctly, the cable and the port are fine.
I know this because when I boot my device, it is connected to the internet, skype logs in, but when I want to open a connection to anything else(browser, vm, ping or whatever) it drops out, saying it is still connected and no errors.
I noticed that the /etc/resolv.conf contains this line:

nameserver 127.0.0.1

I had a random 3 sec connection, after which it dropped out again, and this line was added in the resolv.conf

search lan

When I change the nameserver to 188.8.131.52, I am still unable to connect to anywhere.
Does anyone got a clue what is happening here?
I will provide any information asked.
Thanks in advance
p.s. I run Ubuntu 13.04, and started after upgrading from 12.10 to 13.04
Comment: You write "When I change the nameserver to 220.127.116.11, I am still able to connect to anywhere." Did you mean to say "I am still UNable to connect"?
Comment: @jdthood woops, yes I meant that
Answer: One known bug that could be affecting you is this: https://bugs.launchpad.net/ubuntu/+source/dnsmasq/+bug/1003842
Try disabling the local forwarding nameserver. In NetworkManager.conf
gksudo gedit /etc/NetworkManager/NetworkManager.conf

or
sudo gedit /etc/NetworkManager/NetworkManager.conf

comment out the line dns=dnsmasq
#dns=dnsmasq

and save the file and restart NetworkManager.
sudo restart network-manager

Comment: Aren't we supposed to use gksudo for graphical things that use sudo? Not that it works differently
Comment: The gksu package isn't installed by default. But I will edit the answer to mention it because gksudo seems to be preferred for launching graphical applications with root privs.

Internet connection drops out


Json data not writing to SQLite DB - Python

Question: My Json data contains the following (but larger)
{
    "realms": [
        {

            "status": true,
            "battlegroup": "Shadowburn",
            "name": "Zuluhed",
            "locale": "en_US",
            "queue": false,
            "connected_realms": [
                "ursin",
                "andorhal",
                "scilla",
                "zuluhed"
            ],
            "timezone": "America/New_York",
            "type": "pvp",
            "slug": "zuluhed",
            "population": "medium"
        }
    ]
}

and this is my code snipet should put the data into the db file
( json data was loaded into data variable(data = json.loads(response)) )
db=sqlite3.connect("temp.db")
c=db.cursor()
for record in data['realms']:
    c.execute('INSERT INTO realms (status, name, queue, timezone, type, population) VALUES (?,?,?,?,?,?)', (record['status'], record['name'],record['queue'], record['timezone'],record['type'], record['population']))

Running the script runs without error but checkin the contents of the table there is nothing
# sqlite3 temp.db
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> SELECT * FROM "realms";
sqlite>
sqlite> .tables
realms
sqlite>

I'm new to json and sqlite so I assume im doing something wrong.
Thanks
Comment: Did you do `db.commit()` afterwards? The cursor won't update the table until you commit the changes.
Comment: Please reduce your original program to the shortest possible program and data set that demonstrates the problem. Please [edit] your post and copy-paste that entire short program and dataset, along with the expected and actual output. See [mcve] for more info.
Comment: You don't describe where/how you invoked `create table realms`, and that table doesn't appear in the `temp.db` that you examine. It is possible that the `temp.db` that your Python writes to is in a different directory than the `temp.db` that you examine by hand. Can you `print(os.getcwd())` in your Python program?
Comment: @roganjosh That is exactly what I was forgetting thank you, if you make a full comment ill mark that as the answer.
Comment: @Robᵩ  please read the question again before requesting the info you are requesting, 1) its not possible to reduce the question further as all data pertains to a]what im writing to the db b] how im writing it the db 2) how I invoked the tables in temp.db does not matter as the tables exist - seen in the sqlite3 command and subcommand output, im not sure if you read the question or not but the table exists as seen by
sqlite> .tables
realms
Answer: Any updates you do to your database via the cursor object will not take effect until you commit them. In your case, your connection to the database is called db (db=sqlite3.connect("temp.db")) so you need db.commit() somewhere after your INSERT commands.
Answer: You could dump entire json to sqlite, and later pull from db and do whatever you want.
db=sqlite3.connect("temp.db")
cur = db.cursor()
sql_create_data_table= """CREATE TABLE IF NOT EXISTS myrealms (
                                id integer PRIMARY KEY AUTOINCREMENT,
                                data json NOT NULL
                            ); """
cur.execute(sql_create_data_table)

Inserting:
sql = '''INSERT INTO myrealms(data) VALUES(json('%s'))'''%json.dumps(response)
cur.execute(sql)
db.commit()

Getting dat from db:
cur.execute("SELECT * FROM myrealms")
rows = cur.fetchall()
print(rows)


Spherical decomposition for a radial Dirac delta?

Question: Is this a spherical coordinate decomposition for a radial Dirac delta?
$\delta(\overrightarrow r-\overrightarrow r_0)=\frac{\delta(r-r_0)\delta(\theta -\theta_0)\delta(\phi-\phi_0)}{r^2sin(\theta)}$
Answer: Correct. Notation such as $\delta(u,\,v):=\delta(u-v)$, whether the variables be $1$- or $3$-dimensional, facilitates our equating two expressions for $f(\vec{r}_0)=\int_{\Bbb R^3}\delta(\vec{r},\,\vec{r}_0)f(\vec{r})d^3\vec{r}$:$$\begin{align}&\color{white}{=}\underbrace{\int_0^{2\pi}\int_0^\pi\int_0^\infty}_{\int_{-\infty}^\infty\int_{-\infty}^\infty\int_{-\infty}^\infty}\delta(\vec{r},\,\vec{r}_0)f(\vec{r})\underbrace{r^2\sin\theta drd\theta d\phi}_{d^3\vec{r}}\\&=\int_0^{2\pi}\int_0^\pi\int_0^\infty\delta(r,\,r_0)\delta(\theta,\,\theta_0)\delta(\phi,\,\phi_0)f(\vec{r})drd\theta d\phi.\end{align}$$Hence$$\delta(\vec{r},\,\vec{r}_0)r^2\sin\theta=\delta(r,\,r_0)\delta(\theta,\,\theta_0)\delta(\phi,\,\phi_0),$$as you suggested.


Ubuntu Does not BOOT after Started GNOME

Question: Ubuntu stuck after

[OK] Started GNOME

then nothing happens it doesn't even says what its doing next
I remember I deleted some ppa dependencies from Ubuntu Software Center

I don't know if this is causing the problem
I need a fix for this I have some important files on PC else I would have Reinstalled
Please reply soon :'(
Update:
I can boot into old version 5.0.0-31 not the default  5.0.0-32
can anyone fix it now for me?
Comment: Boot up with a live CD. This will allow you to copy your files to a safe backup drive. Then you can reinstall. Alternatively, you can boot into an emergency prompt then rescue your files using the terminal.
Answer:
I have some important files on PC else I would have Reinstalled.

You can access the files on the drive using the Ubuntu installation media ISO. Simply boot from your installation media and Try Ubuntu without installing. From there, open the regular file manager, and in the devices pane on the sidebar, find your drive which had Ubuntu installed. Assuming it is not LVM and/or encrypted, you will be able to access all the files from here, and back them up to another drive before reinstalling. After backing up the necessary files, then you can safely reinstall from the same medium. Hopefully this helps :)
Comment: I just discovered i can boot into 5.0.0-31 in advanced options... Does this help?
Comment: @MuditKumarSingh - can you boot the full desktop GUI? If not, you can drop to a root shell prompt and manually mount/copy from here.
Comment: I can boot in full gui... I guess it's an older version... I would be happy if this can be made to default
Comment: Keuboard does not work with The older version
Comment: @MuditKumarSingh - yep, this "older version" is an older version of the Kernel which is still installed, even after Kernel update. Running `sudo apt autoremove` will get rid of this Kernel version and the boot option, so it is not advised :). And you may need to use external USB keyboard if this is the case.
Comment: @MuditKumarSingh - I believe it is also possible to edit the grub menu options to be able to make it the default, although I'm not too sure on how to do this, but it is possible.
Answer: Reboot into recovery mode.
 İfcannot , press e when boot menu change "quiet splash" to "text" hit ctrl+x
as told here :http://ask.xmodulo.com/boot-into-command-line-ubuntu-debian.html
then
<code>sudo apt-get update
sudo apt-get purge gnome
sudo apt-get install gnome
sudo reboot
</code>


Square ImageView in the center of the screen

Question: I would like to position ImageView in the center of the screen and set the width and height of the ImageView to the width of the screen.
I tried this, but the width of the ImageView  is not equal to the width of the screen and ImageView is positioned in the top left corner:
<code>        DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)dpWidth, (int)dpWidth);
        imageView.setLayoutParams(layoutParams);
</code>
In xml ImageView is in the center of the screen:
<code>    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</code>
Comment: I guess , this. some time this code has run after load the screen . so , It cannot change the layout style.please check it.
Answer: In Java code, setLayoutParams is overriding layout rules (params starting with layout_) you defined in xml.
You need to add the rules to keep centering the image.
Also LayoutParams will take integer in "pixels" not "dp".
So try this -
<code>DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels;

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)dpWidth, (int)dpWidth);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
imageView.setLayoutParams(layoutParams);
</code>
Also, you might want to play with scaleType to let image fill the space.
Please check here for the available scaleType.
http://developer.android.com/reference/android/widget/ImageView.ScaleType.html


Reliable way to work out if a given year and quarter are before or after another?

Question: E.g. given:
<code>$quarter1 = 4;
$year1 = 2011;

$quarter2 = 3;
$year2 = 2012;
</code>
I need to know that the second set are in the future compared to the first set.
I did think this could be done by literally appending the quarter onto the year. e.g.
<code>$qy1 = 20114;
$qy2 = 20123;
// $qy1 < $qy2
</code>
But I'm sure this is not a reliable way to compare the two. Is there a better, more reliable way?
Many thanks
Comment: I don't know, but I thought I would ask just incase! Don't want to get a couple of years into my program knowing its doing it wrong! Plus I thought there might be a robust method using php's date() function. Something less raw. It just looks too simple to be reliable.
Comment: I would say that is a pretty reliable way, as it is just comparing 2 integers that will not get very much bigger for a long time.
Answer: Nothing wrong with your method, other than having to do a few string concatenations and typecasting back to int. It could fail, however, if you fail to force the values back to integers, and you're comparing years with different string lengths, e.g.:
<code>$date1 = '9994';  // year 999, q4
$date2 = '10011'; // year 1001, q1
</code>
String 9994 will compare as larger than string 10011.
Purely as an alternative, this would work as well, keeping things purely numeric:
<code>$date1 = $year1 + (($quarter1 - 1) / 4);
$date2 = $year2 + (($quarter2 - 1) / 4);
if ($date1 < $date2) { ... }
</code>
Comment: Ah, that makes more sense than mine... because then you get 2011.25 or similar which makes more sense (e.g. literally year 2011 and a quarter). :) I like this idea.
Answer: Yes, I do think this is the best, simplest, and quickest way to do this.
Answer: <code>if($year1<$year2 || $year1==$year2 && $quarter1<$quarter2)
    echo "Date1 is before Date2!";
else
    echo "Date1 is NOT before Date2!";
</code>
Comment: I wasn't the one that downvoted, but out of interest why do you add a dash? Surely that'll impede a numerical comparison?
Comment: It is a string comparison, not a numerical comparison.
Comment: This would fail if you were comparing years with different string lengths, e.g. `year 999 v.s. year 1001`. Not too likely to happen, but should be considered.
Comment: I changed it completely, using strings was not necessary.
Comment: @MarcB: I had not considered going so far back in the past. The same problem would have occurred past year 9999. But with numeric types it works with all dates.
Comment: Your new comparison will now fail if you're working with 2012/4 and 2013/1. 4<1 = false.
Comment: I guess date calculations and I aren't good friends today :-( I updated again my answer.


How can I secure these inadequate/leaning deck supports?

Question: I am in the process of buying a house. The home inspector noted problems with the deck, most significantly "leaning posts."

What would be required to get those 4x4 supports adequately secured to the deck surface?
Does the fact that some of the precast foundations are tilted (that one in the back is just horrifying) mean that I'll need to have those reseated?
Is any of this work feasible without disassembling the entire thing -- is it a better idea to look into a complete rebuild?

This isn't a tall deck (~3-4 feet off the ground at highest point), and the surface is approximately 15x15 feet.
Comment: That is...hilarious...if it weren't a safety issue. It looks like they were just plopped randomly on the ground with no care given to level or solid base. I think you need to consider a rebuild. You could maybe get by with temporary jacks and then reset each pier one-by-one but that could be tough crawling under a 3' deck.
Comment: It isn't quite funny enough to be worth leaving, but it is definitely hilarious ;)
Comment: See if you can get some compensation for deck repairs on the purchase price.  It might be worth $1000
Comment: @ChrisCudmore It's going to be part of the negotiation going forward for sure -- what I've been unsure about was whether to adjust the price (to pay for a whole new deck) or request repairs (which seller would pay for before sale), and knowing whether repair was even _possible_ was my biggest question :)
Comment: may be due to frost heaving,
Comment: I wouldnt go for repairs, they would br just as shoddy. Go for a discount.
Answer: There are lots of different types of post to beam connectors.
Like this:

However, the real weird thing is that you don't really have beams. They are just supporting the joists with a bunch of random posts on concrete deck blocks...
If it were me I'd lose all of those and put in a couple (or more) beams under those joists and put some posts under those.
Not in that order, though. Leave the posts in, put in some proper beams and posts, and then lose the crappy ones you have there.
Below is an example of a similar height deck I did. There are two beams under the joists of this deck, and four piers (two for each beam). The beams are the ones with the white flashing tape on top. You can clearly see one in this image, and how I attached it to the joists.
Comment: Build a proper beam then use proper pads and cribbing blocks like a manufactured home.
Answer: Please if you ever see something like this DO NOT get under it; don't get on it, and don't stand too close to it.  The photo shows, literally, a "house of cards" with no lateral bracing in any direction - that could collapse at any time.
There's a lot of weight in that assembly, inadequately supported, with questionable stability. I've built and remodeled homes and done many framing projects meeting building safety code.  Another poster observed it would be so difficult to reconstruct from underneath it would be best to start over.
Comment: We ended up disassembling it. It was, indeed, a total disaster (and we found other hilariously bad construction techniques while taking it apart).
Answer: I know this is years too late, but I would have installed temporary jacks, removed all the decking boards and driven in 2ft galvanised ground spikes (2 ft underground) adjacent to the existing bad foundations and built a subframe of beams under it.  Could have been done without removing the existing joists.
Comment: Hello, and welcome to Home Improvement. Late answers aren't a problem; we're looking to accumulate knowledge, and this is a great contribution.
Comment: This would have been worthwhile for a larger deck, and so it's a great answer. Thanks!
Answer: I used a rock bar a tire and a tie down strap to pull the board somewhat straight then wedged in 2×4 cut and beat them in to straighten them
Comment: Is this what was done to fix the OP's actual deck from 6 years ago, or is this what you did to fix a similar situation on your deck? Your wording is a bit confusing.


Is it possible to optimize solution of this linear system?

Question: I have a matrix of the form:
<code>A1 A2 A3 A4 A5 A6  ... An P |
1   0 0  0  0   0  ... 0 -1 | c * f1
f1  1 0  0  0   0  ... 0 -1 | c * f2
f2 f2 1  0  0   0  ... 0 -1 | c * f3
f3 f3 f3 1  0   0  ... 0 -1 | c * f4
f4 f4 f4 f4 1   0  ... 0 -1 | c * f5
f5 f5 f5 f5 f5  1  ... 0 -1 | c * f6
........................ -1 | ......
fn fn fn fn fn fn  ... 1 -1 | c * fn
 1  1  1  1  1  1  ... 1  0 | c
</code>
I need to solve this linear system, but i just need to calculate the value of 1 variable (preferably P), the values of f1 to fn are known.
I'm supposed to write an algorithm to solve this one, but the matrix will have big ranks (n = 400 more or less) so solving by getting the inverse or by crammer rule is a little expensive for me. Is there a quicker solution? given that this matrix looks a lot like a triangular one, but i cant get it to take the correct form :(
Also, for the input im expecting, is inverting with gaussian elimination or crammers rule good enough?
I'm very bad at math, let alone linear algebra, but iI can see there is a pattern there, but I can't figure it out
Answer: The system can be written in the block form
$$\tag{1}
Ax:=\begin{bmatrix}L & -e \\ e^T & 0\end{bmatrix}\begin{bmatrix}a\\ p\end{bmatrix}=\begin{bmatrix}f \\ g \end{bmatrix}=:b,
$$
where $a:=[a_1,\ldots,a_n]^T$, $e:=[1,\ldots,1]^T$, etc.
Note that $L$ is lower triangular. To solve this is simple (no need to factorize anything or, worse, to actually attempt to use the Cramer's rule (please don't mention this rule in the numerical linear algebra section)). The first equation in (1) reads: $La-ep=f$; hence we have $a=L^{-1}(f+ep)$. The second equation in (1), $e^Ta=g$, gives hence $e^TL^{-1}(f+ep)=g$ and thus
$$\tag{2}
e^TL^{-1}e=g-e^TL^{-1}f.
$$
To solve this efficiently, first solve
$$
L^Th=e,
$$
which can be done simply by the back substitution ($L^T$ is upper triangular). This transforms (2) to
$$
(h^Te)p=g-h^Tf,
$$
which is a scalar equation,
and therefore
$$
p=\frac{g-h^Tf}{h^Te}.
$$


Is there a CSS way, or non-reflowing way to minimize the width of an element (without increasing height)?

Question: Below is a photo of iMessage, sorry it's a bit oversized.  In the image, you will see that different multi-line messages are different widths.  In fact, each one seems to be optimized for minimal width without creating a newline.

The following is some code which achieves this effect very slowly.

// finds the minimum width an element can be without becoming taller
function minimizeWidth(domNode) {
  if (domNode.offsetWidth < 160) { return; }
  const squinchFurther = () => {
    const startHeight = domNode.offsetHeight;
    const startWidth = domNode.offsetWidth;
    if (startWidth === 0) {
      return;
    }

    domNode.style.width = (startWidth - 1) + "px";
    // wait for reflow before checking new size
    requestAnimationFrame(() => requestAnimationFrame(() => {
      // if the height has been increased, go back
      if (domNode.offsetHeight !== startHeight) {
        domNode.style.width = startWidth + "px";
      } else {
        squinchFurther();
      }
    }));
  }
  requestAnimationFrame(() => requestAnimationFrame(squinchFurther));
}

const divs = document.querySelectorAll("div");
for (let i = 0; i < divs.length; i++) {
  minimizeWidth(divs[i]);
}
div {
  box-sizing: border-box;
  display: inline-block;
  max-width: 160px;
  padding: 5px;
  border-radius: 5px;
  margin: 10px;
  background: #08F;
  color: white;
}

Here's some multi line text

Word

Crux case a a a a a a a a

Is there any CSS which will do this automatically?  If not, is there a way to calculate it in JS without waiting for reflows?
I remember seeing at one point something about a "Reflow Worker" that could be coded with WASM, but I can't find a thing on it right now.  If anyone knows what I'm talking about, please share a link.
Answer: As far as I can tell this is not possible with CSS alone. The solution below holds each text block in a simple
 +  structure, then uses getBoundingClientRect() to measure the 's width and updates it to be display:block with the correct width.
It looks like there is definitely a max-width which accounts for the line wrapping, that is if "McCormick" or "interesting" were on the previous line the width would be too long. I don't believe I've ever seen messages that extend over ~75% of the screen width. I've set a max-width of 160px for this demo.
Note that there are two for loops so that the widths can be cached so we don't continually read then write to the DOM (and cause multiple reflows).

function updateWidths() {
  const elems = document.querySelectorAll('.inner');
  const len = elems.length;
  const widths = [];

  // Read from the DOM
  for (let i = 0; i < len; i++) {
    widths.push(elems[i].getBoundingClientRect().width);
  }

  // Write to the DOM
  for (let i = 0; i < len; i++) {
    elems[i].style.display = 'block';
    elems[i].style.width = widths[i] + 'px';
  }
}

updateWidths();
.outer {
  margin-top: 10px;
  max-width: 160px;
}

.inner {
  background-color: blue;
  border-radius: 5px;
  color: white;
  padding: 5px;
}

  Yeah, this week at McCormick place apparently

  Negative, seems interesting tho

  Some other random message which is a little bit longer than the other messages

Comment: This is a really neat way to cut off some of the slack, but it still doesn't achieve the desired effect.  I've modified my post to include a snippet which has a "crux case" that should do a better job of illustrating what I mean.  Sorry I wasn't clear the first time.
Comment: @SephReed I see what you mean, but just so you know, you specifically cited iMessage which does not wrap its messages that way, it will wrap it the way I demonstrated (try sending a message like that to see). Are you sure that's the behavior you need?
Comment: I don't have iMessage, but believe that's true.  My mistake.  For my cases, the solution I have is fine (pdf renders).  But, a back story for how this happens: It's deadly simple to resize a textbox within tools like sketch/illustrator, and the result is much nicer looking with less wasted space.  Should I want (or need) to do this real time in the future, it'd be nice to have a better approach.  That's my impetus.
Answer: I've found a trick that can be used to cause only one reflow, but it would be a bit of a doozy.  The basic gist of it is:
// helper fns from npm el-tool
const div = (children: HTMLElement[]) => {
  const out = document.createElement("div");
  children.forEach((child) => out.appendChild(child));
  return out;
}
const span = (text: string) => {
  const out = document.createElement("span");
  out.innerText = text;
  return out;
}

export default function minimalWidthDiv(innerText: string) {
  // split string into words with following spaces included
  const wordEls = innerText.trim().match(/\S+\s+/g).map(span);
  const thinDiv = div(wordEls);
  // set to hidden while computing width to avoid thrashy renders
  thinDiv.style.visibility = "hidden";

  // wait for first render
  requestAnimationFrame(() => requestAnimationFrame(() =>
    const numberOfLines = magicFnThatFindsNumberOfLines();
    const currentWidth = thinDiv.offsetWidth;
    const minimalWidth = currentWidth/numberOfLines;
    let bestWidth = 0;
    // figure out the best width based of the widths of the words
    // if more than two lines, the loop below won't work is most cases
    for (let i = 0; i < wordEls.length && bestWidth < minimalWidth; i++) {
      bestWidth += wordEls[i].offsetWidth;
    }
    // update the width of the thinDiv and make it visible.
    thinEl.style.width = bestWidth + "px";
    thinEl.style.visibility = "";
  ));
  return thinDiv;
}

The trick here is to put all of the words into separate spans so their width can be computed.  From there, it's possible to figure out the minimum width without needing a new line.