text:
Q: How to add list within bootstrap  with JavaScript I have tried to add list within Bootstrap   but it adds the list outside of my bootstrap code..
This is the output image I get:

Code:

var title = document.getElementById('title');
var list = document.getElementById('list');
var li = list.getElementsByTagName('li');

var addBtn = document.getElementById('add-Btn');

for (var i = 0; i < li.length; i++) {
  list.addEventListener('click', activeItem);
}

function activeItem() {
  title.innerHTML = this.innerText;

  for (var i = 0; i < li.length; i++) {
    li[i].removeAttribute('class');
  }
  this.setAttribute('class', 'active');

}

addBtn.addEventListener('click', function() {
  var txt = prompt('Task to do is.....');
  list.innerHTML += '
' + txt + '
';

});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

I appreciate any tips!

A: You should add li with list-group-item class:

var list = document.getElementById('list');
var addBtn = document.getElementById('add-Btn');

addBtn.addEventListener('click', function(){
  var txt = prompt('Task to do is.....');
  list.innerHTML += '
' + txt + '
';
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

<button id="add-Btn" class="mb-2">Add item</button>

Cras justo odio

Dapibus ac facilisis in

A: Try This:

var title = document.getElementById('title');
var list = document.getElementById('list');
var li = list.getElementsByTagName('li');
var addBtn = document.getElementById('add-Btn');
for (var i = 0; i < li.length; i++) {
  list.addEventListener('click', activeItem);
}
function activeItem() {
  title.innerHTML = this.innerText;
  for (var i = 0; i < li.length; i++) {
    li[i].removeAttribute('class');
  }
  this.setAttribute('class', 'active');
}
addBtn.addEventListener('click', function() {
  var txt = prompt('Task to do is.....');
  list.innerHTML += '
' + txt + '
';
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" type="text/css" />

      TO DO LIST

    <button type="button" class="btn btn-warning" id="add-Btn">Add To Task</button>

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros


text:
Q: XmlSerializer replaces non-ASCII characters with question mark '?' I have an XML serializer that works great for ASCII but when non-ASCII characters are encountered they are replaced with a question mark '?'.  I believe I have it configured correctly for UTF8 and am unsure why it is doing this.
XmlSerializer xmls = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
    XmlWriterSettings settings = new XmlWriterSettings();
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");

    settings.Encoding = Encoding.UTF8;
    settings.Indent = true;
    settings.NewLineChars = "\n";
    settings.NewLineHandling = NewLineHandling.None;
    settings.NewLineOnAttributes = false;
    settings.ConformanceLevel = ConformanceLevel.Document;
    settings.OmitXmlDeclaration = true;

    using (XmlWriter writer = XmlTextWriter.Create(ms, settings))
    {
        xmls.Serialize(writer, obj, ns);
    }

    string xml = Encoding.UTF8.GetString(ms.ToArray());

    // remove the BOM character at the beginning which screws up decoding
    if (xml.Length > 0 && xml[0] != '<')
    {
        xml = xml.Substring(1, xml.Length - 1);
    }

    return xml;
}

A: All looks fine here; tested with
public class Foo
{
    public string Bar { get; set; }
}
...
string xml = Test(new Foo { Bar = "Jalapeño" });

output:
<Foo>
  <Bar>Jalapeño</Bar>
</Foo>

As a minor change, I removed the "remove the BOM character" code completely, and did that in the encoding explicitly:
settings.Encoding = new UTF8Encoding(false);

Additionally, if I include the xml declaration to check what encoding it thinks it is using:
<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <Bar>Jalapeño</Bar>
</Foo>

So basically... cannot reproduce.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the name of the calling alias method? I am having method called link_to_admin then I have aliased another method called simple_link_to
def link_to_admin(name,url,options={})

  # My stuff here
  link_to(name,url,options)
end

alias_method :simple_link_to, :link_to_admin

Here I am facing one problem if I call link_to_admin, I want print the value into
 tag
Ex.
def link_to_admin(name,url,options={})

  # My stuff here
   menu = ""
   menu << "
 #{link_to(name,url,options)}
"
   menu.html_safe
end

And if I call simple_link_to no need of
 tag. So currently I am passing one options like li_required then am checking condition in my method. This is working perfectly, I know this is correct way to do it.
def link_to_admin(name,url,options={})
   menu = ""
   menu << options[:li_required] ? "
 #{link_to(name,url,options)}
" : link_to(name,url,options)
   menu.html_safe
end

But,Before I was trying to find the calling method like simple_method or link_to_admin, so I tried with:
1.__method__
2.caller[0]=~/`(.*?)'/

This is not working as expected.
I am calling simple_method or link_to_admin methods in layout so __method__ is always returning link_to_admin only.
But caller[0]=~/(.*?)'/if am calling fromlayoutmeans, it's returning layout path and if I am calling from any otherhelperorclass` means it's returning current method.
Any other way is there to check method name.
I know this is not good question, could any one please tell me any other way.
Note:- I have created alias_method for naming conversion only. Other than adding
 tag I am not doing any thing.
Not only here am having this doubt from long back. I know I can define one more method and I can do it.
Leave my scenario, generally I wants to know this answer.

A: I would recommend that, instead of relying on method names and branching (which will become brittle with any method name refactoring, is obviously more complex, etc.) that you simply break apart the methods more to abstract common logic into a shared method.
Here's how I would write it:
def simple_link_to(name, url, options = {})
  # shared_link_to(name) ... or whatever
  link_to(name, url, options)
end

def link_to_admin(name, url, options = {})
  # shared_link_to(name) ... or whatever
  content_tag(:li) do
    simple_link_to(name, url, options)
  end
end

private
def shared_link_to(name)
  # do whatever is common
end

Note: I've made a bit of a guess that you have common code that you'd want to abstract out into some method (which I've called shared_link_to)... but do what you need with that part.

A: Using __callee__ instead of __method__ will get the name of the alias being run.


text:
Q: Compiling application for mac with PyQt5 I have finished application that was written in pyqt5 and compilled for windows(.exe file) with pyinstaller.
Can i do the same for mac? I wanna get the same application but for mac.
How can i do this? Thanks.


text:
Q: Почему получился бесконечный цикл? while (answer != 'y' || 'n' != answer) {
  system("cls");
  printf("\nLose.. try again?(y/n)");
  scanf("%c",&answer);
}

Это фрагмент кода. Его цель - запрашивать ввод в переменную, до тех пор , пока пользователь не введет любое удовлетворяющие значение, то есть n или y. Но я не понимаю почему цикл идет бесконечным путем, так же продолжая спрашивать, после ввода y или n.
Цель кода - при вводе y или n цикл должен прерваться, иначе - продолжить

A: Если answer='y', то, значит answer!='n', или наоборот. Возможен также вариант, когда ответ не равняется ни y, ни n. Соответственно, цикл будет запускаться при любых условиях(он будет бесконечен). Так что в ответ на ваш вопрос(который, кстати, не был задан), если вы имели ввиду y и n как переменные(в чем я сильно сомневаюсь) - пишите без кавычек.
P.S.: НЕ путайте && и ||. Это разные вещи!

A: Хотя бы одному из них answer не равен.
Если он n, то не y; а если y, то не n. А в остальных случаях он ни один из них.
В общем, не надо путать && и ||.

Ну и ещё, весьма вероятно, что правильнее написать
scanf(" ");
scanf("%c", &answer);

но это к (незаданному) вопросу не относится.


text:
Q: VBA calling same function gives 2 different answers I have a function that gives me the last open row, that I call form 2 worksheets. When I call the function I get a different answers from each sheet. The one gives me the correct value, and the other worksheet gives me a value that is one less. I have tried breaking the function down, but in the end the difference comes in at the second half of the main row (the long row), where I use Abs.
I probably did not explain it very well, but the code runs with a button from two different sheets, and looks at the same data on one of the two sheets. Meaning, the code runs on the exact same data with different results, depending on the button I press. (Both buttons call the exact same macro to run the code)
I got the code from a website that showed all the ways that a person can get the last open row from a worksheet.
My code:
Public Function lastOpenRow(sheetName) As Long
    lastOpenRow = 1
    With sheetName
        For a = 1 To 50
            Count = Worksheets(sheetName).Cells(Rows.Count, a).End(xlUp).Offset(Abs(Cells(Rows.Count, 1).End(xlUp).value <> ""), 0).Row
            If lastOpenRow < Count Then
                lastOpenRow = Count
            End If
        Next a
        MsgBox "The lastOpenRow and Count = " & lastOpenRow & " " & Count

    End With
End Function

Any idea why I get two different answers?

A: Always qualify references to Cells, Rows, Columns, Range, etc unless you are absolutely certain that you want to refer to whichever sheet is currently active:
Public Function lastOpenRow(sheetName) As Long
    lastOpenRow = 1
    With Worksheets(sheetName) 'I'll make use of this by just typing ".something"
                               ' rather than saying "Worksheets(sheetName).something"
        For a = 1 To 50
            Count = .Cells(.Rows.Count, a).End(xlUp).Offset(Abs(.Cells(.Rows.Count, 1).End(xlUp).value <> ""), 0).Row
            If lastOpenRow < Count Then
                lastOpenRow = Count
            End If
        Next a
        MsgBox "The lastOpenRow and Count = " & lastOpenRow & " " & Count

    End With
End Function

A: Oh well, might as well post anyways. At least I've declared all variables ;-)
Public Function LastOpenRow(ByVal psSheetName As String) As Long
    Dim result As Long
    Dim colIndex As Long
    Dim colLastRow As Long

    With ThisWorkbook.Worksheets(psSheetName)
        For colIndex = 1 To 50
            colLastRow = .Cells(.Rows.Count, colIndex).End(xlUp).Offset(Abs(.Cells(.Rows.Count, 1).End(xlUp).Value <> ""), 0).Row
            If result < colLastRow Then
                result = colLastRow
            End If
        Next
    End With

    LastOpenRow = result
End Function

Not sure about the offset part, though.


text:
Q: How to accurately extract the email and unit number string text from OCR content? I've used google cloud vision OCR to extract business card email string text from here and used the below regular expression to try to extract but without much good results. Any better suggestions to increase the performance?
function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);

    return isset($m[0]) ? $m[0] : array();
}

$Email = extract_emails($gcv_response);

if (!empty($Email))
{
    $Email = reset($Email);
}
else
{
    $Email = 'NULL';
}

OCR text 1:  "ALGEN MARINE PTE LTD Specialist in Fire Protection and Safety Engineering Philip Cheng Assistant Sales Manager 172 Tuas South Avenue 2, West Point Bizhub, Singapore 637191 Email: philip @algen.comsg Website: www.algen.comsg Tel: (65) 6898 2292 Fax: (65) 6898 2202 (65) 6898 2813 HP : (65) 9168 9799"
Result from the running the above code = NULL; Desired output: philip@algen.comsg
OCR text 2: "Allan Lim Yee Chian Chief Executive Officer Alpha Biofuels (S) Pte Ltd LHCCBNFLN FR2 a mobile 9790 3063 tel 6264 6696 fax 6260 2082 C#01-05, 2 Tuas South Ave 2 Singapore 637601 tang. Steve. Eric@alphabiofuels.sg www.alphabiofuels.sg"
Result from the running the above code = NULL; Desired output: tang.Steve.Eric@alphabiofuels.sg;

A: The two problems you were facing were that you were not converting your code to lowercase and second thing is that you have not covered the scenario of spaces occurring in your code. I tried to cover those but you have to modify according to your requirements.
function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/(([a-z0-9_\-])+\.\\s?)?/([a-z0-9_\.\-])+\\s?\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    //$regexp = '/(([a-zA-Z0-9_\-])+\.\\s?)?/([a-zA-Z0-9_\.\-])+\\s?\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';//for using uppercase letters.

preg_match_all($regexp, strtolower($str), $m);

    return isset($m[0]) ? $m[0] : array();
}

$Email = extract_emails($gcv_response);

if (!empty($Email))
{
    $Email = reset($Email);
}
else
{
    $Email = 'NULL';
}


text:
Q: Фоновый рисунок на JPanel + компоненты Всем привет!
Перебрал ворох информации, но не могу понять:

Как  на панель задать фоновый рисунок так, что бы можно было добавлять
  другие компоненты (кнопки, текстовые поля и т.д.).

Все варианты какие находил - фон перекрывает все элементы.
На фрейм добавить - без проблем, менеджер компоновки даже удобней, но хочу понять, как сделать для панели?

A: Для этого вы должны использовать метод paintComponent класса JPanel, пример:
class Example extends JPanel{

    private BufferedImage image;

    public void paintComponent(Graphics g){
        try {
            image = ImageIO.read(new File("background.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

Рекомендую в будущем не связываться с библиотекой swing, т.к она устарела.
Используйте JavaFX в сочетании с Scene Builder.
----------Дополнено----------
    private JPanel panel = new JPanel();

private BufferedImage image;

public void paintComponent(Graphics g){
    try {
        image = ImageIO.read(new File("background.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    panel.paint(g);
    g.drawImage(image, 0, 0, panel);
}


text:
Q: How do i fix this positioning? i'm trying to create personal portfolio website, but having problem with position or images itself. I've tried everything, nothing fixes it. For example: tried adding float left, display block. Not working. I gave up at the end. Please help guys.

/* About - Portfolio */

.about-portfolio {
    float: left;
    width: 100%;
    color: rgb(199, 199, 199);
    -webkit-transition: all .5s ease-in-out;
    transition: all .5s ease-in-out;}

.portfolio-header {
    margin-top: 20px;}

.about-style .portfolio-text {
    font-size: 40px;}

.about-portfolio:hover {
    color: rgb(0, 0, 0);}

.works-gallery {
    position: relative;}

.about-portfolio .grid-item {
    padding: 0px;}

.works-gallery img {
    width: 100%;}

.clearfix {
 clear: both;
}

Our Works

That whitespace
after adding clearfix

A: What you are asking for is already provided by Bootstrap library out of the box. All you need to do is take care not to break the necessary markup. Here's a working example:

.img-responsive {
  min-width: 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Our Works

You might notice the only CSS rule I added is making small images fit their parent width. Also please notice there is only one row that contains all the col-*s. There is no need of any .clearfix.

If you want the images to be glued together, the simplest way would be to use this CSS:
.img-responsive {
  min-width: calc(100% + 30px);
  position: relative;
  left: -15px;
}

.img-responsive {
  min-width: calc(100% + 30px);
  position: relative;
  left: -15px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Our Works

A: The problem you're running into is quite common in grid layouts. If each column isn't exactly the same height they won't clear correctly.
You need to clear the first element of each new row. The clearfix div you've added will break the 2 column version of the layout. It's also worth noting that Bootstrap includes a clearfix class so the styling you've added is overriding defaults.
Start by wrapping all your grid items in a div.

        . . . ALL THE WAY TO THE LAST ITEM . . .

Then apply some CSS.
@media only screen and (min-width: 768px) and (max-width: 991px) {
    .work-gallery-container .grid-item:nth-child(2n+1) {
        clear: both;
    }
}

@media only screen and (min-width: 992px) {
    .work-gallery-container .grid-item:nth-child(3n+1) {
        clear: both;
    }
}

This assumes that you're using standard Bootstrap 3 breakpoints.


text:
Q: Who delivered Amidala's body back to Naboo? In Revenge of the Sith, after first being Force-choked by Anakin and then given births to Luke and Leia, Padme Amidala eventually lost her life on Polis Massa. We later, however, see her in the funeral procession on Naboo. The question is, how did she get there?

I mean, whoever delivered her there must have faced a lot of difficult questions, not just from her family but also from both the people and the authorities, since she was the former queen of the planet. Whoever it was, he could not have been just somebody, because it most certainly must not have been an easy task. It most likely was not any of the Jedi, since the world was probably half full of Palpatine's collaborators who would have immediately given them away.
So, who was it? And how was it carried out, in practice?

A: After her death, Bail Organa (in the Sundered Heart) took the Jedi to their destinations on Tatooine and Dagobah. Presumably this included dropping Padmé's body off at Naboo en route.

"To Naboo, send her body …" Yoda stretched his head high, as though
  tasting a current in the Force. "Pregnant, she must still appear.
  Hidden, safe, the children must be kept. Foundation of the new Jedi
  Order, they will be."
...
Obi-Wan and Yoda watched the funeral from Bail Organa's starcruiser.
  It was as close as they dared come. The Emperor's attention would
  surely be fixed on the funeral, and they would not take the risk of
  being found.
Revenge of the Sith: Junior Novelisation

As far as the circumstances of her death were concerned, it was apparently not Naboobian tradition to ask too many questions. Her family were simply informed that the Jedi murdered her on Coruscant during their attempted coup.

Further down the canon, the EU novel Dark Lord: The Rise of Darth Vader contains the following info

Holocams at the Temple or in the former Republic Plaza might easily
  have captured his speeder, and those images could have found their way
  to Palpatine or his security advisers. Word might have leaked that
  Bail was the person who had arranged for Padme to be delivered to
  Naboo for the funeral. If Palpatine had been apprised of that fact, he
  might begin to wonder if Obi-Wan, having carried Padme from distant
  Mustafar, had informed Bail about Palpatine's secret identity, or
  about the horrors committed on Coruscant by Anakin, renamed Darth
  Vader by the Sith Lord, whom Obi-Wan had left for dead on the volcanic
  world.
And then Palpatine might begin to wonder if Padme's child, or
  children, had in fact died with her…

This seems to lend weight to the idea that Bail didn't visit her family personally, but perhaps waited in orbit while one of his men went down.


text:
Q: Unit test on redux that involves a firebase call I have a actionCreator method that I would like to do unit test on. It will make a firebase call and on success or fail it will dispatch 2 methods relatively.
It looks sth like this:
export function removeItem(itemId) {
   return dispatch => {
       return firebase.database().ref('items').child(itemId).remove()
           .then(
                 success => dispatch(updateList()),
                 error => dispatch(failRemovingItem(error))
           );
       };
}

I am following the example from redux. http://redux.js.org/docs/recipes/WritingTests.html
But I am not able to mock the firebase call via nock.
Does anyone have experience with unit-testing something similar?

A: One of the scenarios is to extract line:
firebase.database().ref('items').child(itemId).remove()

to the helper, for example, FireBasehelper.removeEntity(id) and then you can easily mock this helper inside action creator by following common practices. Your code then would look like this:
export function removeItem(itemId) {
   return dispatch => {
       return Databasehelper.removeEntity(itemId)
           .then(
                 success => dispatch(updateList()),
                 error => dispatch(failRemovingItem(error))
           );
       };
}

In the helper, you only returning what we've just extracted so
 function removeEntity(itemId) {
     return firebase.database().ref('items').child(itemId).remove()
 }


text:
Q: Meteor: subscribe is not working I'm trying to build a very simple Meteor app. I have implemented all CRUD. But my problem is when I have use publish and then subscribe, no data is returned. My code is given below:
imports\api\tasks\tasks.js
import { Mongo } from 'meteor/mongo';
import { Meteor } from 'meteor/meteor';

TasksSchema = new SimpleSchema({
   title: {
    type: String
   },
   owner: {
     type: String
   }
 });

export const Tasks = new Mongo.Collection('tasks', { schema: TasksSchema });

if (Meteor.isServer) {
   Meteor.publish('task.list', function() {
       return Tasks.find({ owner: this.userId });
   });
}

imports\ui\components\home\home.js
import { Tasks } from '/imports/api/tasks/tasks.js';
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating'
import { ReactiveDict } from 'meteor/reactive-dict';

import './home.html';

if (Meteor.isClient) {
    Template.home.onCreated(function bodyOnCreated() {
       Meteor.subscribe('task.list');
    });

    Template.home.helpers({
        tasks() {
            let userId = Meteor.userId();
            return Tasks.find({ owner: userId }, { sort: { updatedAt: -1 } });
        }
   });
}

imports\ui\components\home\home.html

 {{#each task in tasks  }}

      {{task.title}}

  {{/each}}

Any suggestion? Thanks in advance.

A: Instead of {{task.title}} try {{title}} and also check in browser console Task.find({}).fetch() and see whether you can see records or not.

A: Its probably because your subscription isn't ready to be used on client.
What you have to do is wrap your each code in subscriptionsReady function like below:
{{#if Template.subscriptionsReady}}
  {{#each task in tasks  }}
    {{task.title}}
  {{/each}}
{{else}}

Loading...

{{/if}}

Above should work.
You can check this link for more information of how to use subscriptionsReady


text:
Q: VB 2013, modify word document property/custom property I wish to make an add-in to update word document properties. I'm all ready to go with the addin / ribbon / etc. as I have other ribbon functions that are working. I used the MSVS wizard to create the word ribbon project.
I'm stuck on how to; access the active word document, and access the properties/custom properties. I can't figure out the; declarations, calls, library, etc. I have not been able to make any of the MSDN samples work…. I'm totally missing something.
For example: 'ActiveDocument.CustomDocumentProperties' does not work.
Disclaimer - I'm not a coder. I had this all working with vba, I'm trying to port it over to vb. I'm also still reading through the posted help, and trying samples.
Any suggestions would be appreciated. Kind regards,

A: I got it figured.
Outside the module declare:
Imports moDoc = Microsoft.Office.Interop.Word

Within the sub - This associates the open app with an object:
Dim oActiveApp As moDoc.Application
oActiveApp = GetObject(, "Word.Application")

Now to associate the open app as a document:
Dim mocCustProperties As Microsoft.Office.Core.DocumentProperties
Dim odpProp As Office.DocumentProperty

Now odpProp is an available to read/add properties:
For Each odpProp In mocCustProperties
  If odpProp.Name = "something" Then
   'do dtuff
  End If
Next

There must be a way to do this by referencing the active document as a document rather than an application, but I was unable to make this work.
Cheers,

A: Drat - missed a couple lines above - please ignore.
I got it figured.
Outside the module declare:
Imports moDoc = Microsoft.Office.Interop.Word

Within the sub, This associated the open app with the object
Dim oActiveApp As moDoc.Application
oActiveApp = GetObject(, "Word.Application")
oDocCustomProperty = oActiveApp.ActiveDocument.CustomDocumentProperties

Now to associate the open app as a document
Dim mocCustProperties As Microsoft.Office.Core.DocumentProperties
Dim odpProp As Office.DocumentProperty
mocCustProperties = CType(oDocCustomProperty, Office.DocumentProperties)

Now odpProp is an available to read/add propoeties
For Each odpProp In mocCustProperties
  If odpProp.Name = "something" Then
    'do dtuff
  End If
Next

A: Learned some more.
I no longer need the:
Imports moDoc = Microsoft.Office.Interop.Word

Using the Office.Core. rather than the Office.Core.Interop
Dim Prop As Microsoft.Office.Core.DocumentProperty
Dim oBuiltInProperties As Microsoft.Office.Core.DocumentProperties
Dim oCustomProperties As Microsoft.Office.Core.DocumentProperties

oBuiltInProperties = DirectCast(Globals.DocSelect.Application.ActiveDocument.BuiltInDocumentProperties, Microsoft.Office.Core.DocumentProperties)
oCustomProperties = DirectCast(Globals.DocSelect.Application.ActiveDocument.CustomDocumentProperties, Microsoft.Office.Core.DocumentProperties)

For Each Prop In oBuiltInProperties
    'do stuff
    Prop.Name = sx
    sy=Prop.Value.ToString
next

'create properties
sx="New Property"
sy="New Property Value"
oCustomProperties.Add(sx, False, Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString, sy)

All works now.


text:
Q: Como agrupar os microdados de pessoas do censo por residência? Estou tentando responder a seguinte pergunta: Em quantos casais com filhos menores de 18 anos ambos pais trabalham fora?
Dado uma tabela censo de pessoas do censo 2010  (como essa do Acre), primeira coisa que fiz foi filtrar a tabela por casais com filhos.
  censo <- read.csv("AC.csv", sep = "\t")

  # V5090 -- TIPO DE COMPOSIÇÃO FAMILIAR DAS FAMÍLIAS ÚNICAS E CONVIVENTES PRINCIPAIS
  #  1 - Casal sem filho(s)
  #  2 - Casal sem filho(s) e com parente(s)
  #  3 - Casal com filho(s)   <----------------------
  #  4 - Casal com filho(s) e com parente(s)
  #  5 - Mulher sem cônjuge com filho(s)
  #  6 - Mulher sem cônjuge com filho(s) e com parente(s)
  #  7 - Homem sem cônjuge com filho(s)
  #  8 - Homem sem cônjuge com filho(s) e com parente(s)
  #  9 - Outro
  #  Branco

 censo_cf <- censo[which(censo$"V5090"  == 3),]

Depois filtrei para que pelo menos um dos filho tivesse menos de 18 anos:
# V6660 IDADE DO ÚLTIMO FILHO TIDO NASCIDO VIVO ATÉ 31 DE JULHO DE 2010:
censo_cf18 <- censo_cf[which(censo_cf$V6660  < 18),]

meu passo seguinte seria agrupar os entrevistados por domicílio (para depois verificar em quais domicílios ambos trabalhavam). Apesar de eu não ver isso documentado em nenhum lugar para o censo de 2010, segundo a documentação do censo de 2000 (página 83) a variável controle seria:

Identificação do domicílio

Assim, eu esperaria que dentro desse meu subconjuntos (casais com filhos) todos os domicílios tivessem pelo menos três entrevistados (marido, mulher e filho). Porém, somente três domicílios apresentavam isso:
# V0300 CONTROLE
table_V0300 <- table(censo_cf18$V0300)
pessoas_por_domicilio  <- table(table_V0300)
pessoas_por_domicilio

   1    2    3
9340   57    3

Qual é o meu erro?

A: O teu erro está nesse parte:
censo_cf18 <- censo_cf[which(censo_cf$V6660  < 18),]

No momento que tu faz isso, tu está cortando fora 1) os homens (essa variável só existe para as mulheres) e os filhos. Portanto, a contagem de quantas vezes a variável V0300 (que também é o controle no censo de 2010) está sendo feita de maneira errada, e por isso o resultado inesperado.
O que tu deve fazer é armazenar essa variável (V0300) dos casos que tu quer (domicílios com pelo menos 1 filho menor de 18 anos, formado por casal e filho(s) e onde o casal trabalha) e depois selecionar esses domicílios.
Segue um código (usando o pacote data.table e o banco que eu tenho da amostra já possui os labels, mas fica fácil adaptar para data.frame e sem os labels):
# Primeiro filtro - Pegar o código das residências dos casais com filhos

Filtro1 <- dados[V5090 == 'Casal com filho(s)', V0300]

# Segundo filtro - Pegar, dos casais com filhos, as mães que tem filhos com menos de 18 anos

Filtro2 <- dados[V0300 %in% Filtro1 & V6660 < 18, V0300]

# Agora, pegar somente o responsável ou seu conjuge:

temp <- dados[V0300 %in% Filtro2 & V0502 %in% c('Pessoa responsável pelo domicílio', 'Cônjuge ou companheiro(a) de sexo diferente', 'Cônjuge ou companheiro(a) do mesmo sexo'), .(V0300, PessoaTrabalhando = V0641 == 'Sim')] # Aqui já pego só as variáveis de interesse.

# Terceiro filtro - Pegar, dos casais com filhos e com pelo menos 1 filho com menos de 18 anos, os que ambos trabalham.

Filtro3 <- temp[, .(PessoasTrabalhando = sum(PessoaTrabalhando)), by = V0300][PessoasTrabalhando == 2, V0300]

# Agora sim da para fazer as análises

novosdados <- dados[V0300 %in% Filtro3, ]
novosdados[, .(N = .N), by = V0300][, table(N)]

# Resultado em Porto Alegre:
# N
#    3    4    5    6    7    8    9   10   11   12   13
# 1570 1139  397  141   52   17   13    6    1    1    1

Só lembrando que os dados da amostra devem ser ponderados pela variável V0010. Se não me engano, o peso do domicílio/família é o mesmo que o do responsável. Aproveitando, podes baixar a documentação do Censo 2010 nesse link (FTP do próprio IBGE).

A: Boa tarde rcoster e celacanto. Obrigado para sua conversa, resolveu uma das minhas dúvidas.
Gostaria contribuir que suas soluções ignoram famílias secundárias, ex. a família da filha convivendo com a família das pais. Neste caso, a família primária tem V5040=1 e a família secundária V5040=2. V5090=2, "casal com filhos" somente se aplica para a familia primária; para as outras precisa V5100=2. Em outras palavras, suas soluções deveriam ainda incluir as famílias secundárias (com a maior probabilidade de ter filhos<18 anos).
Os membros de uma família no mesmo domicílio (V0300) estão agrupados pelo V5020. Agrupando somente pelo V0300 ignora as limites entre famílias. "N" na solução do Rcoster é o número de pessoas por domicílio? Os números altos deixam me pensar em domicílios de duas famílias.
Para a família do responsável do domicílio, V0502 IN (1,2,3) é suficiente para identificar ambos os pais. Para a família secundária, deve agrupar pelo V0300 e e V5020 e testar se a mãe e mais uma pessoa tem V5090=2. Em domicílios de quatro gerações poderia dar errado, mas aqui acaba minha paixão para genealogia :-)


text:
Q: change timestamp in bind logfile i need to change the timestamps in a bind logfile because half of them are incorrect now that i have updated the system time...
every line in the file follows this format:
04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (10.0.0.1)

all the time stamps are out by 8 hours. this is what i have so far:
#!/usr/bin/python
from time import strftime, strptime

f = open("query.log","r")
d = f.readlines()

i = 0
while not d[i].startswith("20-Aug"):
  print strftime('%d-%b-%Y %H:%M:%S', strptime(d[i].split(".")[0], '%d-%b-%Y %H:%M:%S'))
  i+=1

any ideas would be appreciated!!

A: from datetime import datetime, timedelta

tfmt = "%d-%b-%Y %H"
tfmtlen = 14

def changestamp(line, **kwargs):
    linetime = datetime.strptime(line[:tfmtlen],tfmt)
    linetime += timedelta(**kwargs)

    return linetime.strftime(tfmt) + line[tfmtlen:]

Output:
>>> line = "04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.c...
>>> changestamp(line, hours=8)
'04-Aug-2010 15:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (...
>>> changestamp(line, hours=-8)
'03-Aug-2010 23:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (...
>>> changestamp(line, weeks=52, days=-365+1/3, hours=24)
'04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (...


text:
Q: Python Pandas: Vlookup across multiple dataframes I have a pandas dataframe that has a specific list of email addresses like:
Email
123@abc.com
234@abc.com

My master list of email contact info is split up across 5 pandas dataframes (imported from excel). I need to vlookup across these 5 dataframes to pull the first_name & last_names of the contacts in my initial dataframe. Is there a quick way of doing this?
EDIT: The other dataframes would have email addresses as the primary identifier, with separate columns for first_name & last_name like:
Email|first_name|last_name
123@abc.com|James|Bond
234@abc.com|Jason|Bourne

Thanks for your help!

A: Once you've imported the Excel file(s) using df = pd.read_excel(path_to_file), you can use pd.merge:
df1 = pd.DataFrame({'Email': ['123@abc.com', '234@abc.com']})
df2 = pd.DataFrame({'Email': ['123@abc.com', '234@abc.com'],
                    'first_name': ['James', 'Jason'],
                    'last_name': ['Bond', 'Bourne']})

pd.merge(df1, df2, on='Email')
         Email first_name last_name
0  123@abc.com      James      Bond
1  234@abc.com      Jason    Bourne


text:
Q: Installed Ubuntu 22.04 and I experience frequent freezes and crashes (when using NVIDIA graphics card) I have been using an old Windows desktop (Asus motherboard, i5 CPU, 120 GB SSD, about 8 years old) to run my Home Assistant server without issues for a few months. I decided I wanted to switch to Ubuntu so that I could run an Ad Guard DHCP server.
I first installed Ubuntu 22.04 along side Windows. I would continuously run into freezing after using Ubuntu for a maximum of 5 minutes. It would often happen when I open a folder or sometimes it would happen without me even touching the mouse. The screen would stay on and sometimes it would display a distorted error message or no error message at all. If there was an error message, it would say "Sorry, Ubuntu has experienced an internal error. If you notice further problem, try restarting the computer." The screen would stop changing completely and all inputs were unresponsive.
I concluded that this must be an issue with my dual boot set up with Windows, especially since I had only allocated 25GB to Ubuntu. So I re-installed Ubuntu (same version) but this time I got rid of the windows partition. I am still experiencing the same freezing issue.
I have tried running sudo apt update and sudo apt upgrade. /var/crash is completely empty. I have tried running memtest86 (no errors found after several passes). I have used Gnome disk utility SMART self test to check the health of my SSD. The result was that the SSD is fine. I'm now wondering could it be an issue with my motherboard?
The weird part for me is that Windows was working just fine but Ubuntu can't run 5 minutes without crashing. Any advice would be greatly appreciated. Thanks.

A: Turns out that the open source GPU driver for my NVIDIA graphics card was the issue. Switching to the proprietary one fixed it.

A: Solution that worked for me on Ubuntu 22.04:
At login screen in bottom right corner press the little gear icon, and select Ubuntu on Xorg instead of just Ubuntu ( i think Wayland window manager is used there by default ).
Useful link:
https://itsfoss.com/switch-xorg-wayland/
I came to this solution because i did use secondary SSD to store the games, but even after i unmounted it, freezing happen again, so i excluded SSD as source of problem. And later on by reading online since many users complain about the Wayland issues i decided to give xorg a try and so far so good :)
Also i would like to mention that my Ubuntu system is now much more responsive.
It bugged me quite a while and i decided to post this here in hope that it might help someone else as well.

A: *

*Update 25 Jan. 2023: Ubuntu kept undoing my manual driver installation when it would run automatic updates (see my notes at the end of Option 2 below), so my final configuration is this: choose the latest-possible-version non-open-kernel NVIDIA driver version provided by Ubuntu which works properly, makes external monitors work, and still allows you to adjust laptop screen brightness with your function keys. For me, that is version nvidia-driver-515 (proprietary). You can see it in the image below in my "Software & Updates" GUI as "Using NVIDIA driver metapackage from nvidia-driver-515 (proprietary":

*Update 22 Dec. 2022: I found Option 2 below to be the best (I think...so far).

*Note to self: future thing to try next time first instead of doing everything below:
See also:

*

*Can you reverse 'ubuntu-drivers autoinstall'?

*https://www.linuxcapable.com/install-nvidia-drivers-on-ubuntu-linux/ - this looks really useful!

*HDMI Port not recognised (NVidia Geforce RTX 3060, Xubuntu 22.04, Dell laptop)
# Do NOT run this now if you've already got your drivers working!
# This is just a note to myself to try this *first* next time is all,
# and then only try the manual steps below if this doesn't work.
# - Supposedly this will fix the NVIDIA issue I first experienced on
# Ubuntu 22.04 where my external monitor would not work when I
# plugged it in.
sudo ubuntu-drivers autoinstall
reboot

How to install the proper NVIDIA graphics driver to hopefully prevent freezes
I'm trying to follow the OP's accepted answer, but don't know which "proprietary one" to use to fix it. I have 8 proprietary driver options to choose from. From the "Software & Updates" --> "Additional Drivers" tab, here is what I am using now (the bottom "X.Org X server" one in the list below--with lots of freezes):

I plan on choosing the top option in that list to see if that works, then moving my way down the list.
I may also go to NVIDIA's website directly to see if they have any driver downloads I can get straight from them.
My computer literature says my graphics card is the "NVIDIA RTX A2000 4GB GDDR6". This seems to coincide with what lspci shows, which is good. Notice lspci says I have the NVIDIA Corporation GA107GLM [RTX A2000 Mobile] (rev a1):
$ lspci | grep -i nvidia
01:00.0 VGA compatible controller: NVIDIA Corporation GA107GLM [RTX A2000 Mobile] (rev a1)
01:00.1 Audio device: NVIDIA Corporation Device 2291 (rev a1)

First (required for compatibility with NVIDIA-provided proprietary graphics drivers, probably regardless of which option you do below): enable "Discrete Graphics" in your BIOS/UEFI
Follow the instructions in my answer here: Enable "Discrete Graphics" in your BIOS/UEFI. NVIDIA's documentation which I cite there and below as well states that disabling "Hybrid"/"Integrated" graphics is required, meaning that you have to choose the "Discrete Graphics" option instead.
Changing the setting from "Hybrid" to "Discrete" graphics is likely required since your computer's manufacturer probably shipped it with the "Hybrid Graphics" option set instead, since hybrid is a little more energy-efficient.
Option 1: use the first driver in the list in the image above
Before beginning this option, first enable "Discrete Graphics" in your BIOS/UEFI, as explained above, in order to follow NVIDIA's guidance and be compatible with their drivers.
So, after choosing the first driver in the "Software & Updates" --> "Additional Drivers" list, the little blurb at the top now says:

This device is using the recommended driver.

...which is good, instead of:

This device is using an alternative driver.

Here is the new selection and that text:

So, "the recommended driver" seems like a good option. :) We'll see how well this one works now.
Update 4 hrs. later: Nope! Bad option! 2 important tips:

*

*Plug in an external monitor and test it any time you change your update your graphics driver! Some drivers don't support or work with exteranal drivers at all! But, you won't notice at first if you don't test it.

*Reboot right after changing your graphics driver, even if not prompted to! Rebooting ensures you're actually testing your newly-installed driver and not the one you had running before.

So, after I changed to the driver above, it seemed to work fine for 15 minutes or so (because it was actually still running the previous driver), then it randomly spit this image onto my main monitor only, and froze (note: sorry for the horrible quality of the image; I'm uploading a high-quality image and this site keeps horribly compressing it days later):

When I rebooted, prior to the boot screen even coming up, it also printed these error messages. The "ACPI BIOS Error" was already there, but the last few lines, starting with the line which says "[nvidia_drm]", are all new!:

And, this new driver didn't work with an external monitor at all! The external monitor was blank.
So, I reverted back to the "X.Org X server" driver I had previously in-use above (which freezes sometimes), and after rebooting, it was back and my external monitor worked again. Let's go on to Option 2 now.
(Recommended) Option 2: download and install the driver straight from NVIDIA
Before beginning this option, first enable "Discrete Graphics" in your BIOS/UEFI, as explained above, in order to follow NVIDIA's guidance and be compatible with their drivers.
(Here's a quick link to the NVIDIA "Advanced Driver Search" page, in case you need to rapidly try installing multiple drivers to see which one doesn't break your screen brightness function keys.)
If the above option still has lots of freezes or otherwise doesn't work (ex: with external monitors as I saw here), then you should download the driver straight from the manufacturer, here: https://www.nvidia.com/Download/index.aspx?lang=en-us#
Remember, you can find your NVIDIA graphics card version from the output of lspci via lspci | grep -i nvidia, as I show above.
To find the driver for this card, I went to the link above and chose these options. I highlighted the "Product" line which shows "NVIDIA RTX A000 Laptop GPU", which seems to be my card:

Once I clicked the "Search" button it brought me to this page: https://www.nvidia.com/Download/driverResults.aspx/196723/en-us/:

Here is the info. for this driver. Notice how new it is (from 28 Nov. 2022 when today is 20 Dec. 2022):

Linux X64 (AMD64/EM64T) Display Driver
Version:  525.60.11
Release Date: 2022.11.28
Operating System: Linux 64-bit
Language: English (US)
File Size:  394.72 MB

First, I check to make sure my card is supported. Under the "Supported Products" tabs I search with Ctrl + F in my browser and see that NVIDIA RTX A2000 Laptop GPU is in the list.
The "Additional Information" has this valuable information and installation help from NVIDIA:

Note that many Linux distributions provide their own packages of the NVIDIA Linux Graphics Driver in the distribution's native package management format. This may interact better with the rest of your distribution's framework, and you may want to use this rather than NVIDIA's official package.
Also note that SuSE users should read the SuSE NVIDIA Installer HOWTO before downloading the driver.
Installation instructions: Once you have downloaded the driver, change to the directory containing the driver package and install the driver by running, as root, sh ./NVIDIA-Linux-x86_64-525.60.11.run
One of the last installation steps will offer to update your X configuration file. Either accept that offer, edit your X configuration file manually so that the NVIDIA X driver will be used, or run nvidia-xconfig
Note that the list of supported GPU products is provided to indicate which GPUs are supported by a particular driver version. Some designs incorporating supported GPUs may not be compatible with the NVIDIA Linux driver: in particular, notebook and all-in-one desktop designs with switchable (hybrid) or Optimus graphics will not work if means to disable the integrated graphics in hardware are not available. Hardware designs will vary from manufacturer to manufacturer, so please consult with a system's manufacturer to determine whether that particular system is compatible.
See the README for more detailed instructions.
For further information please visit our forum, https://forums.developer.nvidia.com/c/gpu-unix-graphics/linux/148.

See their README or forum above, if needed.
Then, I search the "Release Highlights" tab for the word "bug" to see if this new driver has any relevant bug fixes. Sure enough, they do! Here are some of them that look particularly important:

*

*Fixed a bug which caused Dynamic Boost to not engage on certain AmpereGPU based notebooks.

*Fixed a bug that resulted in stutter when moving windows in GNOME.

*Fixed a bug which caused suspend to fail on systems running GNOME 3as a Wayland compositor with NVreg_PreserveVideoMemoryAllocations enabled.

*Fixed a bug in the Vulkan driver which could lead to corruption ingeometry and tessellation control shaders.

etc.
Anyway, this manufacturer-provided driver looks corrrect and useful, so let's try it!
Click "Download" --> "Agree & Download". It's a pretty large file, at 414 MB.
Install the driver:
For any NVIDIA installation help, reference their readme here: http://us.download.nvidia.com/XFree86/Linux-x86_64/525.60.11/README/installdriver.html.

*

*First, we must disable the Nouveau open-source reverse-engineered GPU driver in order to continue. Read more about that here if you need background info. or to do additional debugging later: http://us.download.nvidia.com/XFree86/Linux-x86_64/525.60.11/README/commonproblems.html#nouveau.
To disable the Nouveau NVIDIA driver, follow these instructions here: https://linuxconfig.org/how-to-disable-blacklist-nouveau-nvidia-driver-on-ubuntu-22-04-jammy-jellyfish-linux:
# create the file to disable Nouveau
sudo bash -c "echo blacklist nouveau > /etc/modprobe.d/blacklist-nvidia-nouveau.conf"
sudo bash -c "echo options nouveau modeset=0 >> /etc/modprobe.d/blacklist-nvidia-nouveau.conf"

# Verify its contents
cat /etc/modprobe.d/blacklist-nvidia-nouveau.conf
# It should now contain this:
#       blacklist nouveau
#       options nouveau modeset=0

# Update the kernel initramfs file system.
# Don't quote me on this, but I *think* this is a RAM-loaded file system
# which helps the system boot.
sudo update-initramfs -u

# reboot
reboot

*Enable the grub boot menu, if needed, as a tool to let you boot into the command-line without loading graphics drivers first.
See: How to get to the GRUB menu at boot-time?. In short:
# edit the grub file
sudo gedit /etc/default/grub

Comment out GRUB_TIMEOUT_STYLE=hidden by adding a # at the beginning of that line. Then change GRUB_TIMEOUT=0 to GRUB_TIMEOUT=5 to give it a 5 second delay before automatically loading the OS. Then:
# apply the grub changes
sudo update-grub

# reboot to the grub menu
reboot

*Now, you can not be graphically logged in, since we are about to update the graphics drivers. So, at the Grub screen, shown here, choose "Advanced options for Ubuntu":

Next, choose the "recovery mode" option, as shown here:

It will begin printing a bunch of boot-up text to the screen, and if your partition is LUKS-encrypted, it will ask you to type in your password:

Begin: Mounting root file system ... Begin: Running /scripts/local-top ... Please unlock disk nvme0n1p5_crypt: _

Type in your encryption password, if applicable.
On the "Recovery Menu" screen, choose the "root" option to "Drop to root shell prompt":

It will say:

Press Enter for maintenance
(or press Control-D to continue): _

Press Enter to enter the command prompt as root. You'll now see a prompt like this:

root@my_computer_name:~#

You're ready to go! Just keep in mind that when cding into a directory, ~ will not get you to your user's home directory, since you're logged in as root, not as your user. Getting to your user's home directory will look like this:
cd /home/username

*(Optional, I think, but I did this anyway) Install some 32-bit compatibility libraries:
sudo apt update
sudo apt install pkg-config
# Install cmd source: https://zoomadmin.com/HowToInstall/UbuntuPackage/libglvnd-dev
sudo apt install libglvnd-dev

*Start the installer.
# cd to where you saved it; ex:
cd /home/my_username/Downloads/Install_Files/NVIDIA
# start the installer
sudo sh ./NVIDIA-Linux-x86_64-525.60.11.run

It will extract the file and run the installer.
Choose "Continue installation" when prompted, by selecting with the arrow keys and hitting Enter.
It will then say "Building kernel modules" and have a green bar which progresses to 100%.
If you chose to install the 32-bit compatibility libraries above (I did), then when it says this:

Install NVIDIA's 32-bit compatibility libraries?

Choose "Yes".
When it says:

Would you like to run the nvidia-xconfig utility to automatically update your X configuration file so that the NVIDIA X driver will be used when you restart X?"

Use the arrow keys to move the white selector box, and choose "Yes".
When it says the installation is complete, choose "Ok".

*Cool. That was a pain. I'm glad that's over :). Now reboot.
reboot

*Log in and test an external monitor with your setup. Test your screen brightness function keys. Do they work? If yes, great! You're done! If not, follow my instructions here: Brightness not working after installing NVIDIA driver. You'll have to repeatedly download and install the next-oldest NVIDIA driver until you find one which has functioning brightness buttons. In my case, the latest driver at the time of this writing, 525.60.11, did not work, but 5.15.86.01 did.

*

*Reinstalling the graphics driver is actually really fast and can be done in < 5 minutes now that you know how to do it. Just reboot into the root terminal via the Grub boot menu and install the next NVIDIA driver, as you just did above.

*DON'T LET UBUNTU ACCIDENTALLY AUTO-UPDATE YOUR NVIDIA GRAPHICS DRIVER IN THE FUTURE: in the future, when running Ubuntu's automatic updates, read carefully and uncheck any options to install or update NVIDIA graphics drivers. Apparently I wasn't paying attention, and I accidentally allowed it to auto-install some Ubuntu-provided NVIDIA graphics driver, ruining my ability to have an external monitor and control my screen brightness again, so I just had to re-install version 5.15.86.01 manually again, minutes ago (on 8 Jan. 2023). I didn't notice the change until I rebooted and my external monitor didn't work, my screen brightness was at 100% (too bright), and I was unable to decrease it using my Fn + BrightnessDown button. That was annoying. So, watch out for that. If anyone knows how to block Ubuntu's automatic updates from trying to upgrade the graphics driver automatically after doing a manual NVIDIA install, let me know please.
Update 18 Jan. 2023: it did it again. :( I just rebooted and my driver was mysteriously changed. Since I had manually installed the 5.15.86.01 driver which worked perfectly, this time I chose the 5.15 option provided by Ubuntu, and rebooted, and it seems to work just fine as well, including allowing me to adjust my screen brightness using my laptop's function keys. Here's the option I just chose:

It's flipping annoying that my manually-installed driver keeps getting changed by Ubuntu, so I'll try to investigate that further to make it stop. Meanwhile, the 5.15 version provided by Ubuntu (same version as what I manually installed) works just fine.
Here is my follow-up question about this: Ubuntu keeps undoing my manually-installed NVIDIA graphics driver after reboots every couple weeks
Last tip for a smoother-running experience, in particular when typing in Chrome, use the X11 window server instead of Wayland!
X11 is a surprisingly much faster and much better experience, especially in Chrome.
Wayland seems to be more buggy and glitchy and slow. I especially notice it when typing in Chrome, such as when editing this answer right now in Ask Ubuntu. X11 works much smoother, whereas Wayland is jerky and feels a bit unresponsive, again, even while typing this.
To use X11, when you reboot and get to the login screen (assuming your computer doesn't automatically log in for you), after you type in or select your username only, there will be a little gear icon in the bottom-right of the login screen. Click it and select the "Ubuntu" option rather than Ubuntu 22.04's default "Ubuntu with Wayalnd" option. The "Ubuntu" option runs the traditional X11 window manager server, whereas the "Ubuntu with Wayland" option runs the newer (and glitchier, in my experience) Wayland window manager server.
Note to self: other things to look into in the future

*

*See also my new notes about sudo ubuntu-drivers autoinstall at the very top of this answer.

*Which display manager (dm) to use?

*

*Google search for "lightdm vs gdm3"

*https://www.linuxfordevices.com/tutorials/linux/gdm3-vs-lightd

*Is gdm3 preferred to lightdm?

A: This is what helped solve my problems.
ubuntu 20.04 worked fine, update it to ubuntu 22.04 and got 2 or 3 freezes a day
with no errors in the logs. There can be many causes for this...this is just my issue solution.
What was happening is my nvme drive was turning off.
You can test to see if you have the same issue as I did very easily
When it freezes hit alt + print screen and while holding those keys
type reiusb when you hit b it will reboot and you should see your pc logo if it just sticks on the pc logo and eventually takes you to bios and your storage drive is gone and you have to hit power off to get it to boot back up then you have my issue.
Add this to /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="nvme_core.default_ps_max_latency_us=0"
sudo update-grub
reboot
Solved my issues


text:
Q: How to use datagrid in HTML5 I've a flex application for one of my client and he is planning to upgrade it into HTML5. This application contains a few pages which contains simple UI controls like data grid, combo box etc. I'm not familiar which HTML5. Is there any control in HTML5 close to Data grid combo box.
Also, if there is any similar controls, how can I populate these controls with my existing .Net code (Data layer to load/store date into the database). Any help on this will be appreciated.
Regards,
Amit

A: The datagrid element was removed from HTML5 a long time ago.  Typically you implement these sort of controls via some sort of JavaScript toolkit.  All of these have a grid widget:

*

*Kendo UI

*ExtJS (see also Ext.Net)

*Dojo Toolkit


text:
Q: POST a File Using vb.net based on CURL command I will start this off by setting the stage. I am new to vb.net and programming in general. We are in the process of converting our front end Access program to vb.net. During this process someone started using FormStack, WebMerge and CudaSign while our program is being converted. Our program handles the FormStack and WebMerge stuff, what we want now is to be able to send these documents to CudaSign for clients to be able to sign.
Through days of research I have been able to successfully create a user and retrieve a token needed for uploading the file.
The instruction I have are of little help to me because I know nothing about any of this.
The cURL statement is:
curl -H 'Authorization: Bearer ACCESS_TOKEN' -F 'file=@FILE_NAME' https://capi-eval.signnow.com/api/document
What I have so far:
 Public Shared Function postFile(ByVal url As String, toSerialize As String, strHeader As String) As DataTable
    Dim strmFile As New FileStream(toSerialize, FileMode.Open, FileAccess.ReadWrite)
    Dim wHeader As WebHeaderCollection = New WebHeaderCollection
    wHeader.Clear()
    wHeader.Add(strHeader)
    Dim wReq As WebRequest = WebRequest.Create(url)
    'Dim postData As String = toSerialize
    wReq.Headers = wHeader
    wReq.Method = "POST"
    wReq.ContentType = "multipart/form-data"
    wReq.ContentLength = strmFile.Length

    Dim dataStream As Stream = wReq.GetRequestStream()
    Dim inData As Byte() = New Byte(strmFile.Length - 1) {}
    Dim bytesRead As Integer = strmFile.Read(inData, 0, strmFile.Length)
    dataStream.Write(inData, 0, strmFile.Length)

    strmFile.Close()
    Dim wResp As WebResponse = wReq.GetResponse()
    MsgBox(CType(wResp, HttpWebResponse).StatusDescription)
    dataStream = wResp.GetResponseStream()
    Using reader As New StreamReader(dataStream)
        Dim respFromServer As String = reader.ReadToEnd()
        Dim dtCudaFile As DataTable = JsonConvert.DeserializeObject(Of DataTable)("[" & respFromServer & "]")
        MsgBox(dtCudaFile.Rows(0).ToString)
        iqSTAMP.gvCudaClients.DataSource = dtCudaFile
        reader.Close()
        dataStream.Close()
        wResp.Close()
        Return dtCudaFile
    End Using
    Return Nothing
End Function

My Question is what is the -F='file=@FILE_NAME' expecting? A string doesn't seem to work. Maybe more specifically what is the @? Also, is there a better way to do this?
Further more here is the cURL statement for creating a client:
curl -H 'Authorization: Basic ENCODED_CLIENT_CREDENTIALS' --data '{"first_name":"Test", "last_name":"User","email":"user@test.com", "password":"test"}' https://capi-eval.signnow.com/api/user
and my code that successfully runs this:
    Public Shared Function postRequest(ByVal url As String, ByVal toSerialize As Object, strHeader As String) As DataTable
    Dim wHeader As WebHeaderCollection = New WebHeaderCollection
    wHeader.Clear()
    wHeader.Add(strHeader)
    Dim wReq As WebRequest = WebRequest.Create(url)
    Dim postData As String = JsonConvert.SerializeObject(toSerialize)
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
    wReq.Headers = wHeader
    wReq.Method = "POST"
    wReq.ContentType = "application/json"
    wReq.ContentLength = byteArray.Length

    Dim dataStream As Stream = wReq.GetRequestStream()
    dataStream.Write(byteArray, 0, byteArray.Length)
    dataStream.Close()

    Dim wResp As WebResponse = wReq.GetResponse()

    MsgBox(CType(wResp, HttpWebResponse).StatusDescription)
    dataStream = wResp.GetResponseStream()
    Using reader As New StreamReader(dataStream)
        Dim respFromServer As String = reader.ReadToEnd()
        Dim dtCudaClient As DataTable = JsonConvert.DeserializeObject(Of DataTable)("[" & respFromServer & "]")
        MsgBox(dtCudaClient.Rows(0).ToString)
        iqSTAMP.gvCudaClients.DataSource = dtCudaClient
        reader.Close()
        dataStream.Close()
        wResp.Close()
        Return dtCudaClient
    End Using
    Return Nothing
End Function

UPDATE: I figured out Fiddler and went through CudaSigns website to upload a file. This is how it is formatted:
POST https://signnow.com/proxy/index.php/document HTTP/1.1
Host: signnow.com
Connection: keep-alive
Content-Length: 130269
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: https://signnow.com
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryKL4kOmxYJU4yAmfq
Referer: https://signnow.com/app/account?upload=1429548553882
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: SNTooltipPresentation-Session-DockFirstTime=true; __distillery=v20150227_62e2ac9d-afa9-4bf4-bcb9-f274dd69dde1; email=pcasey%40infoqwest.net; SNTooltipPresentation-Session-SignatureWindow=true; signnowpurchasecookie=twelve_dollars_per_user; _ga=GA1.2.1823410227.1427173595; AWSELB=71BF89DD1C8E4B50D0322FBC8BE6CADD106081F9D15080EB8ED1032966C88138EDD4A5CB885B172D889C54E0A93AE079C744AE6A31914D5F430F7EF5D17B7728585B6641D1; visitor_id10742=354511558; __utma=187131127.1823410227.1427173595.1429500610.1429548417.4; __utmb=187131127.11.9.1429548510020; __utmc=187131127; __utmz=187131127.1429500610.3.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); session=m05vam1n9uh1pcaptnk7c9lfl3; isActiveMember=true; SNTooltipPresentation-Session-addFields=true

------WebKitFormBoundaryKL4kOmxYJU4yAmfq
Content-Disposition: form-data; name="file"; filename="CudaSignTest.pdf"
Content-Type: application/pdf
(then there is the encoded file stream)

This looks closer to some of the posts I've seen pertaining to uploading a file via vb.net webrequest, but I still am lost as to what is going on and how their example translates to this. Thanks in advance for any help.

A: WebMerge actually has an integration (called a delivery) with CudaSign that you can use to automatically send the documents for signature without having to do any programming.  Have you tried using that integration?


text:
Q: Extract ISP From hostname C# I am using ipstack to get information about the user's IP. It gives me the hostname, but I would like to use the hostname to get the ISP. The hostname I am getting is:

d9687b05.cm-24.dynamic.ziggo.nl

Where I would like to extract the ziggo.nl <-- thats the ISP.
Of course it wont allways be ziggo, and it wont allways be .nl, so how would I go about getting that part of the hostname on different ones?

A: You can use this regex to capture the last two words,
.*\.(\w+\.\w+)

Demo
Explanation:

*

*.*\. --> Matches zero or more any character followed by a literal dot

*(\w+\.\w+) --> Matches one or more word char followed by literal dot followed by one or more word char

Here is a sample C# code,
    public static void Main(string[] args)
    {
        var pattern = ".*\\.(\\w+\\.\\w+)";
        var match = Regex.Match("d9687b05.cm-24.dynamic.ziggo.nl", pattern);
        Console.WriteLine("DomainName: " + match.Groups[1].Value);
    }

This gives following output,
DomainName: ziggo.nl

A: Instead of using Regex I would do something like this:
string isp = "";
string[] split = hostname.Split('.');
int len = split.Length;
if(len >= 2)
   isp = $"{split[len-2]}.{split[len-1]}";

Or this:
    string isp = "";
    string hostname = "d9687b05.cm-24.dynamic.ziggo.nl";
    int a = hostname.LastIndexOf(".");
    if(a>0)a=hostname.LastIndexOf(".", a-1);
    if(a!=-1) isp = hostname.Substring(a+1);

Live Demo

A: Without Regex and extra explanations it can be done in readable and comprehensible way ;)
var names = hostname.split(".");
var notRequired = Math.Max(0, names.Count() - 2);

var isp = string.Join(".", names.skip(notRequired));


text:
Q: Java: Set timeout for threads in a ThreadPool I want to set timeouts for threads which are executed within a thread pool. At the moment I have following code:
ExecutorService executor = Executors.newFixedThreadPool(8);
for(List<String> l: partition) {
    Runnable worker = new WorkerThread(l);
    executor.execute(worker);
}

executor.shutdown();
while (!executor.isTerminated()) {

}

The code just splits a big list of objects into sublists and process these sublist within single threads. But this is not the point.
I want to give each single thread in the thread pool a timeout. For only one thread in the pool I found following solution:
Future<?> future = null;

for (List<String> l : partition) {
    Runnable worker = new WorkerThread(l);
    future = executor.submit(worker);
}

try {
    System.out.println("Started..");
    System.out.println(future.get(3, TimeUnit.SECONDS));
    System.out.println("Finished!");
} catch (TimeoutException e) {
    System.out.println("Terminated!");
}

But this would not work for more than one thread. Maybe I have to put each thread in a List<Future> list and iterate over this list and set a timeout for each future object?
Any suggestions?
EDIT AFTER USING CountDownLatch:
CountDownLatch doneSignal = new CountDownLatch(partition.size());
List<Future<?>> tasks = new ArrayList<Future<?>>();
ExecutorService executor = Executors.newFixedThreadPool(8);
for (List<String> l : partition) {
    Runnable worker = new WorkerThread(l);
    tasks.add(executor.submit(doneSignal, worker));
}

doneSignal.await(1, TimeUnit.SECONDS);
if (doneSignal.getCount() > 0) {
    for (Future<?> fut : tasks) {
    if (!fut.isDone()) {
        System.out.println("Task " + fut + " has not finshed!");
        //fut.cancel(true) Maybe we can interrupt a thread this way?!
    }
    }
}

Works good so far.
So next question is how to interrupt a thread which is timed out? I try fut.cancel(true) and add following construct in some critical loops in the worker thread:
if(Thread.interrupted()) {
    System.out.println("!!Thread -> " + Thread.currentThread().getName() + " INTERRUPTED!!");
        return;
}

So the worker thread is "killed" after the timeout. Is this a good solution?
Furthermore: Is it possible to get the name of the thread which timed out over the Future interface? At the moment I have to print out the name in the if condition of the Thread.interrupted() construct.
Thanks for help!
Regards

A: Have you seen this? ExecutorService.invokeAll
It should be exactly what you want: Invoke a bundle of workers and have them timeout if taking too long.
EDIT after comment - (new idea):
You can use a CountDownLatch to wait for the tasks to finish AND timeout via await(long timeout, TimeUnit unit)!
You can then even do a shutdownNow and see which tasks have taken too long ...
EDIT 2:
To make it clearer:

*

*Have a CountDownLatch be count down by each Worker, when finished.

*In the main execution thread await with timeout on said latch.

*When that call returns, you can check the Latches's count to see if there has been the timeout hit (if it is >0).

*a) count = 0, all tasks finished in time.
b) if not, loop the Futures and check their isDone. You don't have to call shutdown on the ExecutorService.

*Call shutdown if you do not need the Executor any longer.

Note: Workers can finish in the meantime between the timeout and calling their Future's isDone().

A: Future future = executorService.submit(callable)
future.get(timeout, unit)

For more information see this link.


text:
Q: How to get images one size I have a quiz app created however the images are different sizes. Would it make sense to use a gridview for one image or is there a way to make sure imageview is set to the same size for different images?

A: You can limit the ImageView size instead of use wrap_content just write a static number for example
300dp
the image will fill the ImageView no matter how big the picture is.


text:
Q: Left join on last record (simple discussion board with topics, last posts and users) I'm trying to make a simple discussion board and as a result I need topics titles with their authors and authors of topics last posts.
So far I have this
SELECT
    `t`.`id`,
    `t`.`title`,
    `t`.`date` as theme_date,
    `u`.`id` as user_id,
    `u`.`username` as user_username,
    COUNT(p.id) as count_posts,
    SUBSTRING_INDEX(GROUP_CONCAT(`p`.`id` ORDER BY `p`.`id` DESC SEPARATOR "| " ), "| ", 1) as last_post_id,
    SUBSTRING_INDEX(GROUP_CONCAT(`p`.`date` ORDER BY `p`.`id` DESC SEPARATOR "| " ), "| ", 1) as last_post_date,
    IFNULL(MAX(p.date), t.date) AS pts
FROM
    `topics` t
LEFT JOIN
    `posts` p ON `p`.`topics_id` = `t`.`id`
LEFT JOIN
    `users` u ON `u`.`id` = `t`.`user_id`
GROUP BY
    `t`.`id`
ORDER BY
    `pts` DESC
LIMIT 10

I got here 10 latest topics titles, their authors usernames and IDs, number of messages in each topic, last ID and date of post in each topic, and everything sorted by activity... basically everything. All I need is authors username of those last posts. I guess I have to make one left join with subquery but I'm kinda stuck.
Can someone help me?

A: Rather than form strings containing the concatenation of the entire thread's posts from which you then obtain the first substring (ordered by id), which is not only a performance drag (because it's not sargable and requires expensive string operations) but is also subject to bugs (should the separator happen to appear within the strings being concatenated or the concatenated result exceed MySQL's limits)…
What you are really looking to do instead is obtain the groupwise maximum, which can be obtained by joining the posts table with a subquery upon it.  You then merely need join the users table a second time (this time against the last post) to obtain the desired username:
SELECT   topic.id
 ,       topic.title
 ,       topic.date
 ,       topic.user_id
 ,       topic_user.username
 ,       t.count_posts
 ,       lastpost.id
 ,       lastpost.date
 ,       lastpost_user.username
 ,       IFNULL(lastpost.date, topic.date) AS pts

FROM     topics topic
         LEFT JOIN users topic_user ON topic_user.id = topic.user_id
         LEFT JOIN (
           (
             SELECT   topics_id
               ,      COUNT(*)  AS count_posts
               ,      MAX(date) AS date
             FROM     posts
             GROUP BY topics_id
           ) t  JOIN posts lastpost USING (topics_id, date)
           LEFT JOIN users lastpost_user ON lastpost_user.id = lastpost.user_id
         ) ON lastpost.topics_id = topic.id

ORDER BY pts DESC

LIMIT    10

Note that I'm also identifying the lastpost by date rather than id as synthetic keys shouldn't really be used to ascertain natural properties; however, this assumes that date is actually a timestamp.


text:
Q: Call Webservice on iBeacon found event in backround My customer asked if it is possible that when a customer walks by his store he receives an email with todays special prices, even if the app is not running.
My question is: Is it allowed by iOS to call a restservice if the app is wakened by the iBeacon event?
I tried to play a system sound to simulate the restservice call and this is not working. Only when the app is in foreground.
To give you an idea how I designed my Beaconhandler so far, here is my code. Perhaps someone has an idea to improve it:
#import "BeaconHandler.h"

@interface BeaconHandler ()

@property (strong, nonatomic) CLLocationManager *locationManager;
@property CLProximity lastProximity;

@end

@implementation BeaconHandler

-(void) startMonitoring{

    if(![self monitoringIsAllowed]){
        return;
    }

    [self initLocationManager];
    [self startMonitoringBeacons:[self beaconIDsToMonitor]];
}

-(BOOL) monitoringIsAllowed{

    //TODO configuration

    return YES;
}

-(NSDictionary*) beaconIDsToMonitor{

    //TODO: load beacons from server

    return @{@"region1":[[NSUUID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D"],
             @"region2":[[NSUUID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6A"]
             };
}

-(void) initLocationManager{

    self.locationManager = [[CLLocationManager alloc] init];

    if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestAlwaysAuthorization];
    }
    self.locationManager.delegate = self;
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
}

-(void) startMonitoringBeacons:(NSDictionary*)beacons{

    for (NSString* beaconIdentifier in beacons.allKeys) {
        NSUUID *beaconUUID = beacons[beaconIdentifier];

        CLBeaconRegion *beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID identifier:beaconIdentifier];
        beaconRegion.notifyEntryStateOnDisplay = YES;

        [self.locationManager startMonitoringForRegion:beaconRegion];
        [self.locationManager startRangingBeaconsInRegion:beaconRegion];
    }

    [self.locationManager startUpdatingLocation];
}

//TODO replace by backend call
-(void)sendLocalNotificationWithMessage:(NSString*)message{

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody =message;

    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

}

#pragma CLLocationDelegate

-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {

    for (CLBeacon *beacon in beacons) {

        if(beacon.proximity == self.lastProximity ||
           beacon.proximity == CLProximityUnknown) {
            return;
        }
        self.lastProximity = beacon.proximity;

        [self sendLocalNotificationWithMessage:[NSString stringWithFormat:@"You are inside region %@", region.identifier]];
    }
}

A: Yes, this is possible.  I can confirm I have done this successfully on iOS.  A couple of tips to get it running in the background:

*

*Get this working in the foreground first.

*You only have 5 seconds of background running time after entering/exiting a region, so make sure your web service returns quickly.

*Add NSLog statements to your callbacks to figure out what is and is not completing in the background.
If the above does not help, post your code in the callback.


text:
Q: How to set up gruntfile so compiled files go on same directory as their source I'm working on a really old project that used Grunt 0.3 and Coffee, and I need to update it to newer versions of both, but I'm not particularly familiar to Grunt. Previously, Grunt would compile the .js files to the exact same folder and name of source .coffee files, and I need to keep it that way. However, I'm having trouble configuring the task. This is what I have right now:
coffee: {
  options: {
  bare: true,
  sourceMap: true,
  expand: true,
  flatten: false,
  cwd: '.',
  src: ['**/*.coffee'],
  dest: '.',
  ext: ".js"
  }
}

This is the message I get:
C:\projetos\sesc-bertioga\bertioga-server\src\main\webapp (newGrunt -> origin) (sesc-bertioga@1.0.0)
λ grunt watch
Running "watch" task
Waiting...
>> File "public\javascript\app\views\solicitacao_grupo\tripulacao_view.coffee" changed.
>> No "coffee" targets found.
Warning: Task "coffee" failed. Use --force to continue.

I absolutely can not change the output place, the new files must be on the same directory as the original ones. Do you have any ideas?

A: So after a bit of tinkering, a friend of mine came up with this, in case anyone is having a similar problem!
coffee: {
      files: {
        expand: true,
        cwd: 'public/javascript/app',
        src: ['**/*.coffee'],
        dest: 'public/javascript/app/',
        ext: '.js',
        rename: (dest, src) => {
          return (dest + src.replace('coffee', 'js'))
        }
      },
      options: {
        bare: false,
        sourceMap: false,
        flatten: false,
        app: {
          src: ['public/javascript/app/**/*.coffee'],
        }
      }
    }

Thanks anyway =)


text:
Q: Linkedin "Scope" Variable not set I'm having trouble setting up a connection to Linkedin Api using Spring Social.
I am passing the "scope" variable "r_emailaddress" as a hidden field with the form to retrieve the email address but it's not working - I don't see the email_address permission like you do here. https://developer.linkedin.com/sites/default/files/gp-dialog.png
I am following the Spring Social Showcase Application Example.  I should add, the Social Application there is no hidden scope field.
It works fine with Facebook.
Form
<form name="linkedinin_signin" id="linkedin_signin" action="${linkedin_uri}" method="POST">
    <input type="hidden" name="scope" value="r_basicprofile, r_emailaddress" />
    <input type="image" src="${linkedin_img_uri}" />
</form>

A: It is correct that LinkedIn is an OAuth 1.0a provider and that the "scope" parameter is non-standard with regard to OAuth 1.0(a). Therefore, Spring Social did not recognize the scope parameter for OAuth 1.0(a) providers.
However, you may be interested to know that yesterday I pushed a change to Spring Social that will allow any arbitrary parameter to be passed along to the request token URL and the authorization URL...including the "scope" parameter. This change, being relatively new, is only available in the latest 1.1.0.BUILD-SNAPSHOT builds, but will soon make an appearance in 1.1.0.M2. This should address your need.
You may also want to look at the Spring Social Showcase example, as it now uses the "scope" parameter to request "r_emailaddress" scope when a user connects to LinkedIn.
I'd appreciate any feedback you have on this change, preferably as comments to https://jira.springsource.org/browse/SOCIAL-349 or in the Spring Social forum at http://forum.springsource.org/forumdisplay.php?82-Social. (I do not monitor questions on StackOverflow nearly as often as I do on the Spring Social forum.)

A: I've had the same issue with LinkedIn. Here is what I did to resolve it:
instead of
    final OAuth1Parameters params = new OAuth1Parameters();
    params.set("scope", "r_emailaddress r_basicprofile");

I had to send a map with the fetchRequestToken
    final MultiValueMap<String, String> mvm = new LinkedMultiValueMap<String, String>();
    mvm.add("scope", "r_emailaddress");
    mvm.add("scope", "r_basicprofile");
    inRequestToken = oauth1Operations.fetchRequestToken(redirectUri, mvm);

A: LinkedIn is recognized by SpringSecurity as OAuth1 provider. OAuth1 does not support "Access Token Scope" feature. So your scope parameter is silently ignored. Actually LinkedIn uses non official OAuth 1.0a protocol version that has support for scopes. As a workaround you can try to override some SpringSocial classes and send scope parameter to LinkedIn. See this thread.

A: The oAuth1 API of linked in doesn't support the scope parameters at all, you must use oAuth2 - http://developer.linkedin.com/documents/authentication - to be able to get the email address


text:
Q: Noisy linear relationship: Can the functional form be known? Let's say I know the relation between x and y is linear yet noisy. Given a noisy (x,y) dataset is there a way to deduce if it was most likely generated  out of an underlying function
(a) $y = a + b \times x + noise$
or via
(b) $x=c + d \times y + noise$
I'm not sure if I know the nature of the noise but let's assume it is gaussian and non correlated.
Normally I would use regression to determine the coeficents and I do know that the estimated parameters differ depending on whether x is taken to be the independent variable or y.
But I don't know if there is a statistical way to differentiate the two cases (a) and (b) that I described.

A: Not as far as I know.  Which variable is dependent and which is independent depends on what the variables are. It can be determined (if at all) by arguments outside of statistics.
Sometimes, it's just that one "makes sense" and the other doesn't. If we have data on height and weight of human adults, it "makes sense" for weight to depend on height, but not the other way around.
Sometimes the temporal order of the variables determines which is which: Something that happens earlier cannot depend on something that happens later. For example, if the variables are "who you voted for in 2012" and sex, only one relationship makes any sense at all (I voted for Obama and therefore I'm female????)
Sometimes there is mutual causation. Does depression cause anxiety? Does anxiety cause depression? Probably both.
And sometimes there is no way to tell at all. Indeed, sometimes, there is no dependency in the relationship because, e.g. both variables depend on something else.


text:
Q: PWA Building Best Practices: Determinsitic Updates Android I just built my first PWA from an existing website, using PWABUILDER and not able to figure out how to handle updates after installs. Currently only deterministic way of updating the PWA, is by uninstall & reinstalling.
As per web.dev, it's very ambiguous:

*

*Chrome Android checks every 24 hour to seek a copy of manifest

*if there is a change in manifest, it queues the manifest and then several conditions a) all PWA windows are closed,                                   b) Device is plugged in, c) connected to WIFI, chrome requests for the updated manifest.

*if the above fails, it may increase the time between checks to 30 days!

What is the right way to keep a PWA updated?
Ref:

Updates on Chrome for Android #
When the PWA is launched, Chrome determines the last time the local
manifest was checked for changes. If the manifest hasn't been checked
in the last 24 hours, Chrome will schedule a network request for the
manifest, then compare it against the local copy.
If select properties in the manifest have changed (see list below),
Chrome queues the new manifest, and after all windows of the PWA have
been closed, the device is plugged in, and connected to WiFi, Chrome
requests an updated WebAPK from the server. Once updated, all fields
from the new manifest are used.
If Chrome is unable to get an updated manifest from the server, it may
increase the time between checks to 30 days.

A: PWA updates on macos chrome happens moment the Web app or browser is opened.
On android, it still works, but requires at least two opens.
IOS is just about uninstall and install, as what is been observed.


text:
Q: 60s comic character who resembled Gru In a UK comic back in the sixties, there was some villain who looked like Gru (from Despicable Me), but he did a big grin sometimes, and then bats flew out his mouth.

A: Grimly Feendish

Grimly Feendish was a supervillain who sought to conquer the world,
using both his monsters and bizarre plot devices, such as exploding
treacle, to do so. He was usually thwarted by Eagle-Eye, Junior Spy.
At one point Grimly started Doomsday School for young monsters across
the road from Eagle-Eye's school, Conker Crescent High. One of the
students at Doomsday School was Grimly's nephew, Fred Feendish, who
became friends with Eagle-Eye and would sometimes try to warn him of
his uncle's schemes.
Source

A Google search for "Gru british comic 1960's" turned up the info fairly easily.


text:
Q: Cannot access SMTP server I'm running on my iMac 10.11.6, using the default email.
The last 2 months or so, I cannot send mail.  All my settings are correct.  I've had them checked by Apple, those who provide my mail service have logged into my computer to check the settings, and I've taken my computer in for support where I purchased it from a certified Apple Dealer.  I've run Malware as well. I receive email with no problem.  No one can seem to figure out why I cannot send.  The connection doctor indicates I cannot access the SMTP server.  Any ideas please.  Thanks


text:
Q: Extended Activity's Title Not Appearing With Custom Style I am overriding the Activity class in following way;
public class MyCustomActivity extends Activity {
 ...
 ...

}

public class MyActivity extends MyCustomActivity {
 ...
 ...

}

And the activity declaration in manifest is like this;
<activity
    android:name=".MyCustomActivity"
    android:label="@string/app_name" >
</activity>

<activity
    android:name=".MyActivity"
    android:label = "ChildActivity">

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

My problem is, the activity title defined in manifest at android:label="ChildActivity" is not appearing with custom style. How could I make it appear without calling setTitle(charSeq); in every activity?
Edit:
One thing (terrible thing) I forgot mentioning is that I am using custom style in following way;
<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/CustomTheme" >
 ...
 ...
</application>

Edit (After @Mudassir's answer):
The custom title bar layout I am using is as given below;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50dip"
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:gravity="left"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/imageViewIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/vector_arts"
            android:layout_marginLeft="-15dp" />

        <TextView
            android:id="@+id/textTitleBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>

A: You get the same title as you set in the manifest file in activity title.
if you do like this :
<activity android:name=".MyActivity"
     android:label="ChildActivity"
             >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".TestingMyAcivity"></activity>

public class TestingMyAcivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

}
public class MyActivity extends TestingMyAcivity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.main_);
}

}
you get the title "ChildActivity" and layout in main_.xml file.

A: You are launching MyActivity where you have set ChildActivity as title. MyActivity is the child class of MyCustomActivity. While you set title of child class it came to the front. The activity what you are seeing is actually Child Activity not Parent. So title of ChildActivity is shown to you
Thanks
Sunil Kumar Sahoo

A: As I understood your question, you are using a text view (custom style) to show the title text. So to show the default title text (one defined in manifest at android:label) in you custom title bar (text view), you have to override the method setTitle in your parent (MyCustomActivity) as given below;
@Override
public void setTitle(CharSequence titleText) {

    // Assuming you text view's name is titleTextView in the style XML file
    TextView customTitle = (TextView) findViewById(R.id.titleTextView);
    customTitle.setText(titleText);
}

then call this method from onCreate() of same class as follows;
setTitle(getTitle());
This will get the activity label defined in manifest file and pass it to the method setTitle() which will show it on your custom title bar that is text view (customTitle here). Note here that this approach will work only if you are using a text view to show the title text.


text:
Q: Adding color to JLabel next to my JSliders Wanting to change the text color of Red,Green,Blue to their appropriate colors in my JLabel with keeping my background and JSliders still the default color of the program. I am not concerned with the Height and Width colors, but just the Text next to the JSliders that say Red,Blue, and Green. Any help is appreciated! Thank you!
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import javax.swing.event.*;
public class ControlApp extends JFrame
{
    private JPanel mainPanel;
    private PrintWriter out;
    private JSlider height,width,red,green,blue;
    private String aspect;
    private String value;

public static void main(String []args)
{
    new ControlApp();
}

public ControlApp()
{
    super("ControlApp");
    mainPanel = new JPanel();
    add(mainPanel,BorderLayout.CENTER);

    //SliderListener sl = new SliderListener();

    height = new JSlider(JSlider.VERTICAL, 0,500,0);
    //height.addChangeListener(sl);
    width = new JSlider(JSlider.VERTICAL, 0,500,0);
    //width.addChangeListener(sl);
    red = new JSlider(JSlider.VERTICAL, 0,255,0);
    //red.addChangeListener(sl);
    green = new JSlider(JSlider.VERTICAL, 0,255,0);
    //green.addChangeListener(sl);
    blue = new JSlider(JSlider.VERTICAL, 0,255,0);
    //blue.addChangeListener(sl);

    mainPanel.add(new JLabel("Height"));
    mainPanel.add(height,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Width"));
    mainPanel.add(width,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Red"));
    mainPanel.add(red,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Green"));
    mainPanel.add(green,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Blue"));
    mainPanel.add(blue,BorderLayout.CENTER);

    setLocationRelativeTo(null);
    this.setSize(500,250);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
}
}

A: You shouldn't be using BorderLayout constants when adding to a JPanel which by default uses FlowLayout. In fact, I suggest that you use a completely different layout altogether, a GridLayout so that all the columns are lined up nice and neatly together. Another option is to use a TitledBorder around your JSlider, something like:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.EnumMap;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.*;

public class ControlPanel extends JPanel {
    private static final int GAP = 3;
    private Map<Control, JSlider> sliderMap = new EnumMap<>(Control.class);

    public ControlPanel() {
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new GridLayout(1, 0, GAP, GAP));
        for (Control control : Control.values()) {
            JSlider slider = new JSlider(JSlider.VERTICAL, 0, control.getMaxValue(), 0);
            slider.setPaintLabels(true);
            slider.setPaintTicks(true);
            slider.setPaintTrack(true);
            slider.setMajorTickSpacing(100);
            slider.setMinorTickSpacing(20);
            slider.addChangeListener(new SliderListener(control));
            sliderMap.put(control, slider);
            JPanel panel = new JPanel(new BorderLayout());
            TitledBorder titleBorder = BorderFactory.createTitledBorder(control.getText());
            titleBorder.setTitleColor(control.getColor());
            panel.setBorder(titleBorder);
            panel.add(slider);
            add(panel);
        }
    }

    private class SliderListener implements ChangeListener {
        private Control control;

        public SliderListener(Control control) {
            this.control = control;
        }

        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider slider = (JSlider) e.getSource();
            int value = slider.getValue();
            System.out.printf("Control: %s, Value: %d%n", control, value);
        }

    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Control Panel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new ControlPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

public enum Control {
    HEIGHT("Height", 500, Color.BLACK), WIDTH("Width", 500, Color.black), RED("Red", 255, Color.RED),
    GREEN("Green", 255, Color.GREEN), BLUE("Blue", 255, Color.BLUE);

    private String text;
    private int maxValue;
    private Color color;

    private Control(String text, int maxValue, Color color) {
        this.text = text;
        this.maxValue = maxValue;
        this.color = color;
    }

    public String getText() {
        return text;
    }

    public int getMaxValue() {
        return maxValue;
    }

    public Color getColor() {
        return color;
    }

}

Which displays as:

A: ttrigger10 -
You want to set the foreground color on those JLabels to get them to be a specific color with the setForgroundColor method. See the modified code below to change the colors:
    JLabel redLabel, blueLabel, greenLabel;
    redLabel = new JLabel("Red");
    redLabel.setForeground(Color.RED);
    greenLabel = new JLabel("Green");
    greenLabel.setForeground(Color.GREEN);
    blueLabel = new JLabel("Blue");
    blueLabel.setForeground(Color.BLUE);

    mainPanel.add(new JLabel("Height"));
    mainPanel.add(height, BorderLayout.CENTER);
    mainPanel.add(new JLabel("Width"));
    mainPanel.add(width, BorderLayout.CENTER);
    mainPanel.add(redLabel);
    mainPanel.add(red, BorderLayout.CENTER);
    mainPanel.add(greenLabel);
    mainPanel.add(green, BorderLayout.CENTER);
    mainPanel.add(blueLabel);
    mainPanel.add(blue, BorderLayout.CENTER);


text:
Q: How to print null in JSON response without quotes using the "json-c" library? I'd like to keep a field as null (without quotes) in a JSON response object that I'm working on.
I'm using the "json-c" library and am programming in C.
When I define the null object as a string I get "null"; if I define it as an integer I get 0 as the response.
Is there any way to print just something like "req_id": null using this library?
This is what I want the JSON object to look like:
{
   "status" : "PROCESSING",
   "request_id" : 85521,
   "result" : null,
   "error" : null
}

But this is what it looks like now:
{
   "status" : "PROCESSING",
   "request_id" : 85521,
   "result" : "null",
   "error" : "null"
}

This is part of my code
json_data[2] = {
    {"result", OBJECT, NULL},//add result object to root object
    {"error", STRING, "null"}//add error to root object
}
resp_obj = ipbt_json_wrapper_api_create_obj(json_data, 2);


text:
Q: How do I make the Linux and Windows versions of a game share save files? I recently obtained a new computer. I also got a 1 TB hard drive. I want to partition it so I can use both Linux and Windows. This is mainly used for gaming. More games are available for Windows, so I want to set it up to give Windows more space. I'm thinking 256 GB to Linux and the rest to Windows. I want to be able to use Ubuntu for general Linux use, and SteamOS for gaming. However, I also want to be able to run games in Ubuntu, for when I'm already in Ubuntu and want to get going fast.
Since Linux and Windows can't share the same game executables, I'll have to install each game twice. Further, if I want to have Ubuntu and SteamOS both installed, they need separate partitions. I'll have to split the 256 GB Linux partition. I don't want to have identical game files in there twice though; that's a waste of space. So I figured out that the Linux partition can be split into 3 sub-partitions: Ubuntu, SteamOS, and a separate one called "Games". Then both Linux distros can pull from that one partition. I figure I'll allocate 32 GB for each of those 2 OS's, then put the rest of the 256 into the Games partition.
So my games will be installed twice: Once in the Windows partition, once in the Games partition. The problem is that I want my game saves and progress to be shared. I don't want to play a few levels in Linux and have that erased in Windows. Is it possible to make another partition that game saves will go into? In the same way that the Linux partitions share a Games section, can I make Linux and Windows share a Saves partition?

A: Linux supports NTFS, so you can create an NTFS volume on Windows, and mount it on Ubuntu.
From a linux cli, you can do the steps below.
Print block device attributes:
sudo blkid

Example output:
/dev/sda1: LABEL="Recovery" UUID="B23613F43613B875" TYPE="ntfs"
/dev/sda2: LABEL="Windows" UUID="38CE9483CE943AD8" TYPE="ntfs"
/dev/sda3: LABEL="Saves" UUID="519CB82E5888AD0F" TYPE="ntfs"
/dev/sda5: UUID="00d7d951-2a35-40fd-8e5d-411bb824ff3b" TYPE="swap"
/dev/sda6: LABEL="Ubuntu" UUID="02f778eb-a386-47a4-94c0-15509e95d526" TYPE="ext4"
/dev/sda7: LABEL="Games" UUID="40cd5b43-7330-4a48-bcf0-656473fec0fb" TYPE="ext4"

Create a mount point:
sudo mkdir /media/saves

Edit fstab, so it will mount on boot:
sudo nano -w /etc/fstab

Using the information from your blkid output, add a line to the /etc/fstab file:
/dev/sda3 /media/saves  ntfs-3g  defaults,windows_names,locale=en_US.utf8  0 0

Finally, mount the directory:
sudo mount /media/saves


text:
Q: Cutting donuts in QGIS I'm trying to cut donut polygons ready to go into a system that can't display them. Basically the exact opposite of this post: How to convert fake donut holes in polygons to real ones?
I want to cut at any point so that the polygon no longer contains an inner ring(s). (Ideally the shortest path but I don't really care.)
Is this possible in QGIS?


text:
Q: After adding two conditions in a "for" loop in C I am getting errors I am getting this error message while trying to run the following program "relational comparison result unused".
#include <stdio.h>

int main(void)
{
    int i, j;
    for(i = 0, j = 0; i < 10, j < 3; i++, j++)
    {
        printf("%i %i\n",i, j);
    }
}

I am expecting a result
0 0
1 1
2 2

A:
After adding two conditions

It's not two conditions, you probably need i < 10 && j < 3.

relational comparison result unused

As user3386109 mentioned, it's because the compiler discards the result of i < 10 caused by the comma, so you need to change it to i < 10 && j < 3.

I am expecting a result 0 0, 1 1, 2 2

Actually, I'm getting this result.
0 0
1 1
2 2


text:
Q: How to install codec g729 on asterisk server I tried more but i am unable to install codec g729 on asterisk server.
the uname -i return x86_64
the model name  : Intel(R) Xeon(R) CPU E3-1271 v3 @ 3.60GHz
Asterisk version 13.1

A: Use following steps to install g729 codec:
[root@localhost ~]#cd /usr/src
[root@localhost src]#wget http://asterisk.hosting.lv/bin/codec_g729-ast18-gcc4-glibc-pentium4.so
[root@localhost src]#cp codec_g729-ast18-gcc4-glibc-pentium4.so /usr/lib/asterisk/modules/codec_g729.so
[root@localhost src]#chmod  +x /usr/lib/asterisk/modules/codec_g729.so
[root@localhost src]#asterisk -rx "module load codec_g729.so"
[root@localhost src]#service asterisk restart