text:
Q: Dynamic scoping questions in R I'm reading the AdvancedR by Hadley and am testing the following code on this URL
subset2 = function(df, condition){
  condition_call = eval(substitute(condition),df )

  df[condition_call,]
}

df = data.frame(a = 1:10, b = 2:11)

condition = 3

subset2(df, a < condition)

Then I got the following error message:

Error in eval(substitute(condition), df) : object 'a' not found

I read the explanation as follows but don't quite understand:

If eval() can't find the variable inside the data frame (its second argument), it looks in the environment of subset2(). That's obviously not what we want, so we need some way to tell eval() where to look if it can't find the variables in the data frame.

In my opinion, while "eval(substitute(condition),df )", the variable they cannot find is condition, then why object "a" cannot be found?
On the other hand, why the following code won't make any error?
subset2 = function(df, condition){
  condition_call = eval(substitute(condition),df )

  df[condition_call,]
}

df = data.frame(a = 1:10, b = 2:11)

y = 3

subset2(df, a < y)

A: This more stripped down example may make it easier for you to  see what's going on in Hadley's example. The first thing to note is that the symbol condition appears here in four different roles, each of which I've marked with a numbered comment.
                              ## Role of symbol `condition`

f <- function(condition) {    #1 -- formal argument
    a <- 100
    condition + a             #2 -- symbol bound to formal argument
}

condition <- 3                #3 -- symbol in global environment

f(condition = condition + a)  #4 -- supplied argument (on RHS)
## Error in f(condition = condition + a) (from #1) : object 'a' not found

The other important thing to understand is that symbols in supplied arguments (here the right hand side part  of condition = condition + a at #4) are searched for in the evaluation frame of the calling function. From Section 4.3.3 Argument Evaluation of the R Language Definition:

One of the most important things to know about the evaluation of arguments to a function is that supplied arguments and default arguments are treated differently. The supplied arguments to a function are evaluated in the evaluation frame of the calling function. The default arguments to a function are evaluated in the evaluation frame of the function.

In the example above, the evaluation frame of the call to f() is the global environment, .GlobalEnv.
Taking this step by step, here is what happens when you call (condition = condition + a). During function evaluation, R comes across the expression condition + a in the function body (at #2). It searches for values of a and condition, and finds a locally assigned symbol a. It finds that the symbol condition is bound to the formal argument named condition (at #1). The value of that formal argument, supplied during the function call, is condition + a (at #4).
As noted in the R Language Definition, the values of the symbols in the expression condition + a are searched for in the environment of the calling function, here the global environment. Since the global environment contains a variable named condition (assigned at #3) but no variable named a, it is unable to evaluate the expression condition + a (at #4), and fails with the error that you see.

A: I want to add some details in case someone stumbles on this question. The problematic line is
condition_call = eval(substitute(condition),df )

*

*The condition object in substitute() function is a promise object, its expression slot is "a < condition" and substitute(condition) takes expression and returns a call object with expression as "a < condition".

*Then eval() function start to evaluate the "a < condition" in the df environment. Its target is finding both a and condition.

*

*a is found in df successfully, and this is not where the bug generated.

*Then R starts searching condition in df and cannot find it.

*So R goes up to the execution environment of subset2, and finds condition in the execution environment.

*The variable it finds is actually the promise object mentioned before with expression slot as "a < condition".

*To evaluate this expression, R has to find a again, and now it cannot find a any more because it has passed the df environment. This is the part that really generates the error.
To summarize the problem here:

*

*R does find a in the df for once.

*The bug arises when R tries to look for condition and then R takes the promise object condition instead of the 4 assigned outside as the argument and tries to evaluate it.

*Then R runs into the problem:

*

*it tries to evaluate "a < condition" and it cannot find a either in the execution environment of subset2() or global environment.

For my second example, R cannot find y in the execution environment and then finds y in the calling environment of subset2() as 4, generating no errors. In this case, the name of y is different from the promise object condition and R won't try to evaluate "a < y" and no bugs generated.


text:
Q: Adjoint of $T_A = Ax$ Is it true that if $T_A(x) = Ax$ then $T^*_A(x) = A^*x$?  I tried to prove this for the standard inner product
$$
\newcommand{\innp}[2]{\left\langle #1,#2 \right\rangle}
\innp{Ax}{x} = x^tA^t\overline{x} = x^t\overline{A^*}\overline{x} = \innp{x}{A^*x}
$$
but I can't seem to prove for a general inner product.
Is it true? How do I generalize this for any inner product?

A: Note that any inner product on $\def\C{\mathbf C}\C^n$ has the form
$$ \def\<#1>{\left<#1\right>}\<x,y>_B = x^t B\bar y $$
for some hermitian positive $B$. ($B$ has the entries $b_{ij} = \<e_i, e_j>_B$). To compute the matrix of the adjoint of multiplication by $B$, we can argue as follows:
\begin{align*}
  \<Ax, y>_B &= x^tA^t B\bar y\\
             &= x^t \overline{\bar A^t B^t} \bar y \\
             &= x^t B\overline{\bar B^{-1}\bar A^t B^t y}\\
             &= \<x, B^{-t}\bar A^t B^t y>
\end{align*}
So the matrix of $T_A^*$ (adjoint with respect to $\<,>_B$) for the standard basis is $B^{-t}\bar A^t B^t$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Servir arquivo .js customizado em rota Express Tenho uma página especifica "home" para usuário autenticado que é servida por um router contudo esta autenticação é feita via cookie se houver este cookie de "sessão" (criado após o login do usuário e definido seu path para o root) todo pedido diferente de "home" é redirecionado para ela (home).
Más preciso servir um arquivo javascript customizado que irá receber um tokem para ser usado por socket.io e também irá mostrar (incorporar) informações básicas do usuário e não posso faze-lo inline por questões de um "CSP" restritivo.
Como poderia conciliar isto?
index.js
// get routes
var GetRoutes = require('./routes/GetRoutes');
app.use('/', GetRoutes);

/**
 * Store sockets auth [in memory]
 */
var memory_auth = {};

io.on('connection', function(socket){
    // pre-store
    memory_auth[socket.id] = false;
    //
    socket.on('disconnect', function(){
        // flush socket from "memory_auth"
        try{
            delete memory_auth[socket.id];
        }catch(ex){}
    });
    //
    socket.on('authenticate', function(payload){
        //
        try{
            jwt.verify(payload, process.env.TOKEN_LOGGED, function(error, data){
                if ( !error ) {
                    /**
                     * check "socket.auth" ever "socket requests in home page"
                     */
                    memory_auth[socket.id] = true;
                    // add socket to user id room [to connect all user connections]
                    socket.join(data.id);
                }
            });
        }catch(ex){
            console.log('Authentication token failed!');
        }
        //
        setTimeout(function(){
            if ( !memory_auth[socket.id] ) {
                socket.disconnect('unauthorized');
            }
        }, 1000);
    });
});

GetRoutes.js
// middleware that is specific to this router
router.use((req, res, next)=> {
    var auth_cookie = req.signedCookies['_SCD_'];
    if ( auth_cookie && req.path !== '/home' ) {
        let user = users.getSession(auth_cookie); // function to getSession
        if ( user ) {
            res.redirect('/home');
            res.end();
        } else {
            next();
        }
    } else {
        next();
    }
});

router.get('/home', (req, res, next)=> {
    var auth_cookie = req.signedCookies['_SCD_'];
    if ( auth_cookie ) {
        let user = users.getSession(auth_cookie); // function to getSession
        if ( user ) {
            let file = getFile('home'); // function to get "home.html" file
            res.send(file);
        } else {
            res.redirect('/');
        }
    } else {
        res.redirect('/');
    }
});

router.get('/home/customJavaScript.js', (req, res, next) => {
    //
    var auth_cookie = req.signedCookies['_SCD_'];
    if ( auth_cookie ) {
        let user = users.getSession(auth_cookie); // function to getSession
        if ( user ) {
            // generate auth_token
            let auth_token = jwt.sign({
                data: {
                   id: user.id
                }
            }, process.env.TOKEN_LOGGED, { issuer: 'localhost:3000', noTimestamp: true, expiresIn: 5 });
            //
            var model = getFile('homeCustomJavaScript'); // function to get "custom.js" file
            model = model.replace(/{{+[a-zA-Z0-9_]+=+[a-zA-Z0-9=:.\/@#&-]+}}/gi, function(wholeMatch){
                if ( wholeMatch ) {
                    wholeMatch = wholeMatch.replace(/{{/g, '').replace(/}}/g, '');
                    var index = wholeMatch.split('=');
                    //
                    switch(index[0]){
                        case 'basic_nf':
                            let alias = (user.alias !== '') ? user.alias : 'Anonymous';
                            let user_nf = {
                                id: user.id,
                                alias: alias,
                                avatar: user.avatar,
                                mail: user.mail
                            };
                            return JSON.stringify(user_nf, null, 4);
                        break;
                        case 'auth_token':
                            return auth_token;
                        break;
                    }
                } else {
                    return '';
                }
            });
            res.type('application/javascript')
            .send(model)
            .end();
        } else {
            res.redirect('/');
        }
    } else {
        res.redirect('/');
    }
});

home.html
<body>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="./home/customJavaScript.js"></script>
</body>

customJavaScript.js
 'use strict';
 var socket = io();
/**
 * send authentication to socket connections [ever]
 * this auto add authenticated socket to user id room [to all user connections]
 */
socket.emit('authenticate', '{{auth_token=auth}}');

var basic_user_nf = {{basic_nf=basic}};


text:
Q: Reflection optimizations with attributes .  Is there a way in C# to:

*

*Get all the properties of a class that have attributes on them (versus having to loop through all properties and then check if attribute exists.

*If i want all Public, Internal, and Protected properties but NOT private properties, i can't find a way of doing that.  I can only do this:
PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
Is there a way to avoid getting private properties but do get everything else.

A: Regarding caching: if you access properties via TypeDescriptor.GetProperties then you get caching for free. The TypeDescriptor class has some other nice utility methods for reflection situations like this. It only operates on public properties though (no protected or internal members, and no fields).

A: There isn't really a way to do it any quicker - but what you can do is do it less often by caching the data. A generic utility class can be a handy way of doing this, for example:
static class PropertyCache<T>
{
    private static SomeCacheType cache;
    public static SomeCacheType Cache
    {
        get
        {
            if (cache == null) Build();
            return cache;
        }
    }
    static void Build()
    {
        /// populate "cache"
    }
}

Then your PropertyCache.Cache has the data just for Foo, etc - with lazy population. You could also use a static constructor if you prefer.

A: I don't believe there's a way to do either of these.
Just how many types do you have to reflect over, though? Is it really a bottleneck? Are you able to cache the results to avoid having to do it more than once per type?

A: In response to (2): If you're outside of the class/assembly in question, internal and protected are the same as private.
If you want to access these, you'll need to ask for all properties, as you've already done, and filter the list yourself.


text:
Q: Flutter firebase streams I am trying to use
StreamBuilder<QuerySnapshot>(
            stream: _firestore.collection('messages').snapshots(),
            builder: (context,snapshot){
              if(snapshot.hasData) {
                final messages = snapshot.data.docs;
                List<Text> messageWidgets=[];
                for(var message in messages){
                 final messageText=message.data['text'];
                 final messageSender=message.data['sender'];
                 final messageWidget=
                     Text('$messageText from $messageSender');
                 messageWidgets.add(messageWidget);
                }
              }
            },
            ),

I am getting error in
final messageText=message.data['text'];
final messageSender=message.data['sender'];

I know it may be because of the new update but I want to access it and in documentation could not find anything like this.
In database in document I have two fields sender and text that is what I want to get individually out of data in messageText and messageSender. also please suggest some source where I could read so that next time I would not need to ask such question.

A: Change these lines:
final messageText=message.data['text'];
final messageSender=message.data['sender'];

to:
final messageText=(message.data() as Map<String, dynamic>)['text'];
final messageSender=(message.data() as Map<String, dynamic>)['sender'];

The data contained in a QueryDocumentSnapshot can be retrieved by calling the .data() method.


text:
Q: How permissions bitmask should look like with view/edit/add/remove permissions. How to use it? User can view/edit/add/remove objects (categories, users, items etc.). What is the best practice to store (in MySQL), manage and check if user have such permissions.
Acl class will control if user allowed to execute controller's method or not.

A: I'm using binary-string stored as hex value in database.
When I've read hex value (permissions) from database for appropriate client I convert it to binary string where every digit (0 or 1) represents state of some permission flag. Permission flags has been defined by position in binary-string. e.g
0 -> can read
1 -> can write
2 -> can access gallery
3 -> can access pools
4 -> can ban users
5 -> can drink beer
...

When needed, just validate every binary digit with appropriate permission and store it in permission array as boolean value.
Also, I have stored some permissions as groups like administrators, moderators, gallery editors, etc...
Look here: Which data type is suitable for storing this situation? for better explanation and examples.

A: Are you sure you want to go with bitmasks?
If you have many roles your bitmask number can get very high, and a query to search who has permission X would be bad performance wise.
Personally, I like to store such data in a two column table (UserId, PermissionId), this way it's both scalable and easy to maintain. To check who has a permission or which permissions has a user, you only need a SELECT or a JOIN.


text:
Q: Set default option in md-select in angular material 2 I am trying to set the default option in md-select of angular-material2 but to no avail.
form2.component.ts:
export class Form2Component implements OnInit {
    frequency = [
                {"title" : "One Time",         "description" : "", "discount" : {"value" : 0,  "type" : "value"} },
                {"title" : "Weekly",           "description" : "", "discount" : {"value" : 20, "type" : "percent"} },
                {"title" : "Every other Week", "description" : "", "discount" : {"value" : 15, "type" : "percent"} },
                {"title" : "Monthly",          "description" : "", "discount" : {"value" : 10, "type" : "percent"} }
            ]
    constructor(){}
    ngOnInit(){}
}

form2.component.html:
<md-select placeholder="Frequency" [formControl]="userForm.controls['frequency']">
    <md-option *ngFor="let frequ of frequency" [value]="frequ" [selected]="frequ.title == 'Weekly'">{{frequ?.title}}</md-option>
</md-select>

A: Since you are using a reactive form, you can set the default value to the formcontrol. So you can do find the frequency you want from the array and set it as the default value, like:
this.userForm = this.fb.group({
  frequency: this.frequency.find(x => x.title == 'Weekly')
})

And remove selected from your template:
<form [formGroup]="userForm">
  <md-select placeholder = "Frequency" formControlName="frequency" >
    <md-option  *ngFor="let frequ of frequency" [value]="frequ" > {{frequ?.title}} </md-option>
  </md-select>
<form>

Demo

A: Component HTML
 <md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food">
    <md-option *ngFor="let food of foods" [value]="food.value" >
      {{food.viewValue}}
    </md-option>
  </md-select>

  <p> Selected value: {{selectedValue}} </p>

Component.ts
@Component({
  selector: 'select-form-example',
  templateUrl: './select-form-example.html',
})
export class SelectFormExample {
  foods = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];

   // setting this is the key to initial select.
   selectedValue: string = this.foods[0].value;

set the selected value to the value from the array you want it to be default, you are not using two way binding

A: When you use Objects in md-option value, the object reference of the default value and the correponding option in the options list are not equal.
To fix this, you need to override the default value using the correponding option in the options list before setting the FormGroup.
Here is an example :
my.component.ts
export class MyComponent implements OnInit {

    myobject: Object = {id:'1323', label:'myform', service: {id:'S01', label:'Service 01': desc:''}}
    services: Array<Service> = [
        {id:'S01', label:'Service 01' , desc:'Service desc'},
        {id:'S02', label:'Service 02' , desc:'Service desc'},
        {id:'S03', label:'Service 03' , desc:'Service desc'}];

    myForm : FormGroup;

    constructor(private fb: FormBuilder) {

        // Override the service in  myobject before setting the FormGroup myForm
        this.services.forEach(srv => {
            // Compare service By id
            if (srv.id === myobject.service.id) {
                myobject.service = srv;
            }
        });

        // Set the formGroup with the myobject containing the good reference to the services array.
        this.myForm = this.fb.group(myobject);
    }
}

my.component.html
<md-select class="carrier-select form-control" formControlName="service">
    <md-option class="carrier-option" *ngFor="let service of services" [value]="service">{{service.label}}</md-option>
</md-select>


text:
Q: Rich Text Box Image Drop not showing image I have a simple page. One Rich Text Box bound to a test table in my database.
I have turned the EnableAutoDragDrop to true.
Everything works great, the contents of the box are saved and able to pull back up when asked for.
My issue is dropping image into the RTB.  If I drag them directly from the file manager (any type of image file) then I get an Icon with the file name that shows up, not the actual image.
If I open up Word and drop the image into Word, then drag it into the RTB then the image shows just fine.
I guess I dont understand the mechanics of the process between the file manager and word and my RTB.  Can anyone elighten me?

A: Answer provided by @climbage has good explaination. here is how to achieve drag and drop in RichTextBox

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace rich_RichtextboxDragDrop
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            AllowDrop = true;
            this.richTextBox1.DragEnter += new DragEventHandler(richTextBox1_DragEnter);
            this.richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
        }
        void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {

            if ((e.Data.GetDataPresent(DataFormats.FileDrop)))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }
        void richTextBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            Image img = default(Image);
            img = Image.FromFile(((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString());
            Clipboard.SetImage(img);

            this.richTextBox1.SelectionStart = 0;
            this.richTextBox1.Paste();
        }
    }

}

Edited for more information
This is why you don't see it in the PropertiesTab.  The Attribute [Browsable(false)] tells the PropertyGrid not to display the property.  Here's source the code from MSDN.
    /// <include file='doc\RichTextBox.uex' path='docs/doc[@for="RichTextBox.DragEnter"]/*' />
    /// <devdoc>
    ///     RichTextBox controls have built-in drag and drop support, but AllowDrop, DragEnter, DragDrop
    ///     may still be used: this should be hidden in the property grid, but not in code
    /// </devdoc>
    [Browsable(false)]
    public new event DragEventHandler DragEnter {
        add {
            base.DragEnter += value;
        }
        remove {
            base.DragEnter -= value;
        }
    }

A: The drag event can contain multiple format types that are determined by the source of the drag event.  When I drag an image (.png) from a the file system to a C# control, I get this set of available formats (note you can get these from DragEventArgs.Data.GetFormats())
Shell IDList Array
Shell Object Offsets
DragImageBits
DragContext
InShellDragLoop
FileDrop
FileNameW
FileName

Now when I drag that same image on to word, and then to my C# control, I get this list of formats :
Woozle
Object Descriptor
Rich Text Format
HTML Format
System.String
UnicodeText
Text
EnhancedMetafile
MetaFilePict
Embed Source

It is entirely up to the target control to determine how to handle the drag data, and which format(s) to use.  MS Word may take the format FileNameW, which is  just the path to the file dropped, and read the image.  While the RichTextBox probably takes the FileNameW and gets its icon.


text:
Q: Eureka Swift: Dismiss Controller for MultipleSelectorRow I have the following code:
form.last! <<< MultipleSelectorRow<String>() {
                $0.title = field.question
                $0.options = []
                for option in field.answers {
                    $0.options.append(option.answer)
                }
            }.onPresent {
                    from, to in
                // TODO FIX
                to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: from, action: #selector(InputVC.multipleSelectorDone(_:)))
            }

Which should add a MultipleSelectorRow that - if clicked - pops another VC and shows some options. Once at least one option is clicked, it should show the "done" button and be able to go back. The button is not appearing, even tho i took the code from the official example.
What did i miss here or do i need to do in order to be able to dismiss the popped Field?
Thanks :)
The multipleSelectorDone function is as follows:
func multipleSelectorDone(_ item: UIBarButtonItem) {
        _ = navigationController?.popViewController(animated: true)
    }

A: Had the same feature for a project and found this question. If someone needs here is the solution with Swift 4.2
<<< MultipleSelectorRow<String>() {
    $0.title = "Subjects"
    $0.selectorTitle = "Choose"
    $0.options = ["Option 1", "Option 2", "Option 3", "Option 4"]
    $0.tag = "subjectTypes"
}.onPresent { from, to in
    to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: from, action: #selector(self.multipleSelectorDone(_:)))
}

And multipleSelectorDone method is:
@objc func multipleSelectorDone(_ sender:Any?) {
    _ = navigationController?.popViewController(animated: true)
}


text:
Q: How to call CheckedChanged(sender,e) from another private method I have two different functions :
Public Sub CB_CheckChanged(sender As Object, e As EventArgs)
    line of code;
End Sub

Protected Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound
    line of code;
End Sub

I am trying to call CB_CheckChanged() inside GV_RowDataBound() function.
Can you please tell me, how to call one event into another event.
Note : Checkbox is inside gridview

A: Protected Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound
    CB_CheckChanged(Nothing, Nothing)
End Sub

A: You can try this
Public Sub CB_CheckChanged(sender As Object, e As EventArgs)
   line of code;
End Sub

Protected Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound
  CB_CheckChanged(Nothing, Nothing)
End Sub

If the event is not handling any task,You can use
 Public Sub CB_CheckChanged()
   line of code;
End Sub

Protected Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound
  CB_CheckChanged()
End Sub


text:
Q: cURL doesn't seem to work in a while loop I'll just post the whole thing since it would be a bit confusing otherwise:
<?php
echo "

  <title>ARMORY.</title>
  <meta http-equiv='Content-Type' content='text/html' charset=iso-8859-1>

";

$server = "Sunstrider";
$guild = "Mist";
$url='http://eu.wowarmory.com/guild-info.xml?r='.$server.'&gn='.$guild.'&p=1';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_USERAGENT,  "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
$xml = curl_exec($ch);
$rosterxml = new SimpleXMLElement($xml);
curl_close($ch);
$array = array();

foreach($rosterxml->guildInfo->guild->members->character as $char)
  if(strtolower($char['level']) === '80')
  {
        $array[] = $char['name']."
";

  }

  echo "

    Name
    TEST

";
$i = 0;
while($array[$i] != null)
{

 $name = $array[$i];
 $raidurl='http://eu.wowarmory.com/character-achievements.xml?r='.$server.'&cn='.$name.'&c=168';
 $ch = curl_init();
 curl_setopt ($ch, CURLOPT_URL, $raidurl);
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt ($ch, CURLOPT_USERAGENT,  "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
 $xml2 = curl_exec($ch);
 $achievementxml = new SimpleXMLElement($xml2);
 curl_close($ch);
 var_dump($achievement);

 echo "

  $array[$i]

";
 $i++;

}

?>

That var_dump of $achievement just produces NULL over and over again (obviously due to the loop) instead of any information about the array. Doing a var_dump of $rosterxml produces the expected effect though, so cURL seems to work fine outside of the while loop.

A: That is because your variable is called $achievementxml and not $achievement.
I would advise you to code with error_reporting=E_ALL so you can catch errors like this. Undefined variables will result in an E_NOTICE level error message.


text:
Q: Excel VBA: Insert a column in an Array from an ADODB Result Set I've queried an MS-Access database from within VBA, and returned the result set to an array, as follows:
Sub ChartData()

    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")

    ' Hard code database location and name
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\server1\myDB.mdb"

    ' Construct SQL query
    strSql = "TRANSFORM Count(Names) AS CountOfNames SELECT Ticker FROM Pricing GROUP BY Ticker PIVOT Source; "

    ' execute the query, and return the results to the rs object
    cn.Open strConnection
    Set rs = cn.Execute(strSql)

    ' Copy the result set to an array
    Dim myArr() As Variant
    myArr = rs.GetRows

    ' Close the connection
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

    ...

End Sub

Next, I'd like to insert one column into myArr, which has dynamic dimensions. I've attempted to use ReDim Preserve for this purpose, but learned that ReDim Preserve will only allow changing the first dimension. For example, the following code results in the Run-time error, Subscript out of range:
Sub ChartData()

    ...

    Dim newRowCount As Integer
    Dim newColCount As Integer
    newRowCount = UBound(myArr, 2) + 1
    newColCount = UBound(myArr, 1) + 2

    ReDim Preserve myArr(newColCount, newRowCount) ' Run-time error here

End Sub

Is there an elegant way to work-around this ReDim Preserve limitation to insert a column without wiping the data?
Thanks!

A: Consider adjusting SQL query at the source as suggested by @TimWilliams in the comments which avoids memory overhead and use of manipulating data objects.
Crosstab queries use an aggregate groupby within its structure which you can easily add scalar values including empty, numeric, or string values (which will be the same across all rows):
TRANSFORM Count(Names) AS CountOfNames
SELECT Ticker, NULL As EmptyColumn, 1 As AllOnesColumn, 'SQL in Excel' As AllStringColumn
FROM Pricing
GROUP BY Ticker
PIVOT Source;

Alternatively, save the crosstab query as a stored query object in Access database and run a typical select statement in Excel ADO connection referencing the stored query. Again, you can add scalar columns as needed:
SELECT storedquery.*, NULL As EmptyColumn, 1 As AllOnesColumn,
       'SQL in Excel' As AllStringColumn
FROM storedquery


text:
Q: To create sub folders and adding files into it during Wix Installtion I am doing a Wix Installation for my C# application, EVERYTHING SEEMS TO BE WORKING. However the following code is unable to create sub folders and not putting files into it. I will appreciate if you guys can review it and let me know what wrong I have done.
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
  <Product Id="*" Name="MyApp" Language="1033" Version="1.0.0.0" Manufacturer="MyApp" UpgradeCode="a84565c2-d23a-456e-a69b-507890e7d08b">
      <Package Id="*" InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

      <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
      <MediaTemplate EmbedCab="yes" />

      <Feature Id="ProductFeature" Title="MyApp" Level="1">
          <ComponentGroupRef Id="ProductComponents" />
      </Feature>

  <!--User Interface-->
  <UIRef Id="WixUI_Mondo" />

  </Product>

  <Fragment>
      <Directory Id="TARGETDIR" Name="SourceDir">
          <Directory Id="ProgramFilesFolder">
      <Directory Id="INSTALLFOLDER" Name="MyApp" />
          </Directory>
  </Directory>

  <DirectoryRef Id="INSTALLFOLDER">
    <Directory Id="LangPL" Name="pl-PL" />
    <Directory Id="LangDE" Name="de-DE" />
    <Directory Id="LangNL" Name="nl-NL" />
    <Directory Id="LangIT" Name="it-IT" />
    <Directory Id="LangZH" Name="zh-Hans" />
    <Directory Id="LangES" Name="es-ES" />
    <Directory Id="LangRU" Name="ru-RU" />
    <Directory Id="LangFR" Name="fr-FR" />
    <Directory Id="LangUS" Name="en-US" />
  </DirectoryRef>
</Fragment>

<!-- Fragment to Add files to install folder-->
  <Fragment>
      <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
    <Component Guid="{0F129003-1A21-4F8F-93E6-E1B5D32EA2E7}">
      <File Source="$(var.App.TargetPath)" KeyPath="yes" />
    </Component>
    <Component Guid="{8E58912F-C519-4163-9DD8-1AB9D355A046}">
      <File Source="..\App\bin\Debug\APP.exe.config" KeyPath="yes" />
    </Component>

    <!-- Database Files -->
    <Component Guid="{37ABA3DA-86D9-4523-BDB7-0AD5C3708762}">
      <File Source="..\App\bin\Debug\DB.mdf" KeyPath="yes" />
    </Component>
    <Component Guid="{1194A878-D4B8-4B22-8F14-9D9EF93747D3}">
      <File Source="..\App\bin\Debug\DB_log.ldf" KeyPath="yes" />
    </Component>

    <!-- DLL Files -->
    <Component Guid="{87FCEE21-E1C4-4A2C-AA62-B6C668AB0E52}">
      <File Source="..\App\bin\Debug\AxInterop.AcroPDFLib.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{BFF2CCF9-3503-47AB-AB77-E78F273B2FC6}">
      <File Source="..\App\bin\Debug\AxInterop.ShockwaveFlashObjects.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{6C0D941F-A005-4E10-BAA6-391E70295EB2}">
      <File Source="..\App\bin\Debug\Interop.AcroPDFLib.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{9B0BB779-74F3-456B-B616-BBF4BAE139E3}">
      <File Source="..\App\bin\Debug\Interop.ShockwaveFlashObjects.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{09071A2C-1DB6-4AE5-9D9E-17DB57616D4B}">
      <File Source="..\App\bin\Debug\Microsoft.SqlServer.BatchParser.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{75321BD4-C241-499F-90A6-B6363357F20C}">
      <File Source="..\App\bin\Debug\Microsoft.SqlServer.ConnectionInfo.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{46A6DBEC-D969-40F4-AAF3-AF212FE5281E}">
      <File Source="..\App\bin\Debug\Microsoft.SqlServer.Replication.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{815B4D31-A7B8-4CD7-8470-99DFADF7AEE3}">
      <File Source="..\App\bin\Debug\Microsoft.SqlServer.Smo.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{33354D4A-5CB6-49CB-8C05-18D0F3191538}">
      <File Source="..\App\bin\Debug\Microsoft.SqlServer.SqlEnum.dll" KeyPath="yes" />
    </Component>
    <Component Guid="{9D8D4126-A718-48D9-BA34-EAD91F30CE88}">
      <File Source="..\App\bin\Debug\Utilities.dll" KeyPath="yes" />
    </Component>
      </ComponentGroup>
  </Fragment>

<!-- Fragment for Language -->
<Fragment>

  <!-- Language Files -->
  <DirectoryRef Id="LangDE">
    <Component Id="cmp86C295D7F66EC9578F96F4623F089C67" Guid="{1C8790A6-41C2-4E16-8E31-10EDECE86247}">
      <File Id="fil3C1CE3C61A61928116642D76E1CB2FD1" KeyPath="yes" Source="..\App\bin\Debug\de-DE\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangPL">
    <Component Id="cmp8F8D4A93706A9F8808F5E2985188A413" Guid="{17C8306C-5974-405B-952F-DC45B0818E39}">
      <File Id="fil55B857264E5ABC88F6EA12CEA4B93C2A" KeyPath="yes" Source="..\App\bin\Debug\pl-PL\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangIT">
    <Component Id="cmpA89C227C566FDB4BCDF630318E40C7E5" Guid="{C09B8F97-ADD5-4FB8-8670-8BA1E34F6709}">
      <File Id="filA0C4161E00B664DB9961F7F1D1FC40AD" KeyPath="yes" Source="..\App\bin\Debug\it-IT\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangFR">
    <Component Id="cmpC6BCCBC4286751A9F3AA247597AD0861" Guid="{F74428CD-F7ED-4C36-8AE4-1BC72F43FCBA}">
      <File Id="fil1784EB69DBD3581198FFE97FB812B1E0" KeyPath="yes" Source="..\App\bin\Debug\fr-FR\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangUS">
    <Component Id="cmpCC8D717E06A1A3AC08A128C5A16928A2" Guid="{EC66B5A5-42F4-45AB-A782-9C4420855A25}">
      <File Id="filBF78840BD50DBF938D4331D2BE1EC95C" KeyPath="yes" Source="..\App\bin\Debug\en-US\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangES">
    <Component Id="cmpDDA77EFB7EFD0EAC732A90C4F40031CF" Guid="{2AFDCEEE-5F75-47CC-BE81-4473C523C583}">
      <File Id="fil702C9D4400C38C1E053F89C06FB02125" KeyPath="yes" Source="..\App\bin\Debug\es-ES\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangNL">
    <Component Id="cmpE263B74764498E93EE67602DF6EC34A3" Guid="{EBE1DC48-709A-4B27-ABFD-C2EAF1F8F045}">
      <File Id="fil25E319C7D7844EE691033BE7B5076021" KeyPath="yes" Source="..\App\bin\Debug\nl-NL\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangRU">
    <Component Id="cmpEA3A3E0AC21B81AC658C77C2DD655AB6" Guid="{E10BA360-E9ED-48D2-9A32-17E436764BA1}">
      <File Id="fil6C4DA2534BE3D68B4E4FB677FAC1660C" KeyPath="yes" Source="..\App\bin\Debug\ru-RU\App.resources.dll" />
    </Component>
  </DirectoryRef>
  <DirectoryRef Id="LangZH">
    <Component Id="cmpF2AD194BB8C30284155E9D01AE39BF26" Guid="{7C236F8F-B790-4C8F-8573-3A86D083BC7B}">
      <File Id="fil0A5479D9006A1049B58101823121F91A" KeyPath="yes" Source="..\App\bin\Debug\zh-Hans\App.resources.dll" />
    </Component>
  </DirectoryRef>
</Fragment>
</Wix>

A: The problem is that you are not adding the components containing your Directories to any feature.
You need to create a ComponentGroup containing every one of the Component ID's of your Directories and then a ComponentGroupRef to that in your Feature.
However I suggest to create a new sub feature "Language packs" and another sub feature of it for each language and then your users will have the option to install or not specific language packages.
Something like this:
<Feature Id="ProductFeature" Title="MyApp" Level="1">
      <ComponentGroupRef Id="ProductComponents" />
      <Feature Id="LanguagePacks" Title="Language Packs" Level="1">
          <Feature Id="FrenchPack" Title="French" Level="1">
              <ComponentRef Id="FrenchComponentId" />
          </Feature>
          <Feature Id="ItalianPack" Title="Italian" Level="1">
              <ComponentRef Id="ItalianComponentId" />
          </Feature>

      </Feature>
  </Feature>


text:
Q: jQuery Setting Element Styles Based On Modal Visibility Behaves Differently in Firefox and Chrome I'm new to jquery and javascript. I have a website with multiple unique modal/popups that are triggered via a CSS :target selector, which sets them to display: block. I'm trying to use jquery to hide a separate element among other things.
The logic is:
If a modal is visible, then hide element. Else show element. I'm currently using popstate in my jquery. This is because the modals can close if the user presses their browser back button. So I don't want to use any click functions. Everything seems to be working fine, except the if/else statements that detect the visibility of the modals seem to behave differently between Firefox and Chrome? When it hides the element in Firefox, it shows it Chrome. When it hides it in Chrome, it shows it in Firefox. Why the opposite behavior? What am I doing wrong?

$(window).on('popstate', function(event) {
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});
.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}

This element should hide when modal is open

  Click Me To Open Modal

I'm a Modal. Press browser back button to close

Alternate jQuery:
Setting the length to 1 works in Firefox and works oppositely in Chrome.
Setting the length to 0 works in Chrome and works oppositely in Firefox.
$(window).on('popstate', function(event) {
    if ( $('.modal-overlay:visible').length === 1 ) {
        console.log("Modal ON");
        $('#wrapper').css('overflow-y', 'hidden');
        $('#extra_element').css('display', 'none');
    }
    else {
        console.log("Modal OFF");
        $('#wrapper').css('overflow-y', 'scroll');
        $('#extra_element').css('display', 'block');
    }
});

Is there another way to do this correctly?

A: This would be a Chrome bug, according to the specs, at the step 10 of the History traversal algorithm the UA should call the "scroll to fragment" algorithm which is responsible for updating the document's target element (:target) and only at the step 18.1 it should fire the popstate event.
Chrome does fire the event before it updates the document's target element, and thus your CSS :target selector doesn't match yet.
I did open an issue so they get this in-line with the standards, but for the time being you can workaround that by waiting just a task after the event fired:

$(window).on('popstate', async function(event) {
  await new Promise(res => setTimeout(() => res()));
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});
.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}

This element should hide when modal is open

  Click Me To Open Modal

Press browser back button to close


text:
Q: Lighting an LED when a capacitor is fully charged I've been messing around with electronics lately and I wanted to make a simple circuit that lights up an LED when a capacitor is fully charged. I know that something could be done with a diode or something like this! Who could help me?
P.S. Does anyone know the minimum Farads that are needed to have a spark with a capacitor? and it is better to link them in series or in parallel.

A: Yes, it can be done with a diode or something.

But you will need a few other components. R1 limits the charging current to C1 AND also limits the current taken from the battery when you short out the capacitor. Z1 (a 6V zener diode) will not conduct until there is a 6V across it. The LED also needs about 2.5V to turn on leaving about 0.5V across R2 which acts as a current limiter to the zener/LED circuit. With the values given the LED current will be about 10mA when turned ON.
It will give a spark when the output terminals of the capacitor are shorted. Beware of vaporised metal/burn hazard.


text:
Q: Изменение шрифта у всех элементов в Delphi Как изменить шрифт у всех элементов элементов, у которых есть свойство Font?
A: У всех наследников от TWinControl свойство Font может наследоваться от родительского контейнера. За это отвечает свойство ParentFont. Поэтому, если изменить Font у формы, он также изменится у всех вложенных в эту форму элементов с ParentFont = True (и дальше по каскаду от контейнера к содержимому).
UPD: Перебор всех компонентов формы с фильтром тех классов, в которых нужно менять шрифт:
for i := 0 to Form1.Components - 1 do
begin
  if Form1.Components[i] is TButton then
    TButton(Form1.Components[i]).Font := MyFont
  else
  if Form1.Components[i] is TLabel then
    TLabel(Form1.Components[i]).Font := MyFont
  else
  // ... и так далее ...
end;

A: for i := 0 to Form1.ControlCount - 1 do
    case Form1.Controls[i].ClassName of
        "TLabel", "TButton" { ... типы имеющие свойство font }:
            (TLabel)(Form1.Controls[i]).Font = NewFont;
        { может быть некоторые элементы также нужно рекурсивно перебирать }
    end;

примерно так, с перебором всех элементов управления. Могу допускать синтаксические ошибки.
A: для Delphi это будет выглядеть так:

type
  TMyControl = class(TControl)
  public
    property Font;
  end;

procedure SetFontByComponent(comp: TComponent; font: string);
var
     i: Integer;
  ctrl: TControl;
begin
  for i := 0 to comp.ComponentCount-1 do
    if comp.Components[i] is TControl then
      (TMyControl(comp.Components[i])).Font.Name := font;
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  SetFontByComponent(self, 'Verdana');
end;

A: Я вот так решаю эту проблему в C++ Builder, работает в том числе для TLabel и пр., включая все дочерние объекты:

*

*Создаем свой класс для получения публичного доступа к свойству Font

    class TMyControl: public TControl
    {
      public:
        __property Font;
    };

*Далее перебором ставим шрифт всем компонентам, кроме верхнего меню

      AnsiString Name("Verdana");
      for (int i=0; iComponentCount; ++i)
      {
        TControl* ctrl = dynamic_cast<TControl*>(this->Components[i]);
        if (NULL == ctrl) continue;
        ((TMyControl*)ctrl)->Font->Name = Name;
      };


text:
Q: Delete a user Completely in SharePoint 2010 Is there a way that when an administrator deletes a user from a SharePoint group the user can be totally deleted?  Presently when an admin deletes a user from the group he can still see the user in the User Information List (UIL) and that's causing lot of confusion to the non-technical community administrators.  They are seeing this list because whenever they edit the current view (Detail View) they are ending up in UIL and that's confusing them.  Is there a power shell script which will delete the users in the user information list once they are deleted from the community.

A: Delete the user from the Site Collection.  This will mark them as tp_Deleted != 0 in the UIL.  Do not remove users from the UIL manually as this will break functionality on items the user was stamped on (e.g. Workflows will fail to start if that user saved them).
http://msdn.microsoft.com/en-us/library/dd303914(v=prot.13).aspx


text:
Q: 64 bit function returns 32 bit pointer This function is buried in a complex nest so actually finding the cause is probably beyond anything I can ask, but I'm wondering if anyone might be able to give some tips on how I might go about debugging this.
Here is the gist of the code I'm having trouble with
//func1.c
somestruct* func1(somestruct* mystruct)
{
    printf("func1: %p, %i\n", mystruct, mystruct->foo);
    return mystruct;
}
//func2.c
somestruct* func1(somestruct* mystruct);
void func2()
{
    somestruct *mystruct = malloc(sizeof(somestruct));
    mystruct->foo = 10;
    printf("func2: %p, %i\n", mystruct, mystruct->foo);
    mystruct = func1(mystruct);
    printf("back in func2: %p\n", mystruct);
    free(mystruct);
}

And I call func2.  The output is like so
func2: 0x7f38a00008c0, 10
func1: 0x7f38a00008c0, 10
back in func2: 0xffffffffa00008c0
(SEGFAULT trying to free 0xffffffffa00008c0)

The actual code is more complex, "mystruct" gets passed around in many other places as well without issue, the fact that the functions are in different files seems like it might be part of the problem, yes it needs to return the pointer (the returned pointer is not guaranteed to be the same as the input pointer).
It seems really weird to me that it's kind of (but not actually) getting truncated to 32 bits, and then filled with ffffffff at the top.
When compiled on a 32 bit machine it works exactly as it should.
I'd considered memory corruption somewhere, so I ran it through valgrind.  Valgrind reports no errors, and in fact causes it to complete successfully.  Textbook heisenbug.  At least I can use GDB.
Does anyone have any idea what might be causing this, or at least how I might start tracking down the problem?

A: Check your code if you missed out function prototype (somestruct* func1(somestruct* mystruct);).in func2.c.
By default all return values are int. So if a prototype is missing for function then compiler treats the return value as 32-bit and generates code for 32-bit return value. Thats when your upper 4 bytes gets truncated.


text:
Q: trying to parse a Localizable.string file for a small project in swift on MacOS I'm trying to parse a Localizable.string file for a small project in swift on MacOS.
I just want to retrieve all the keys and values inside a file to sort them into a dictionary.
To do so I used regex with the NSRegularExpression cocoa class.
Here is what those file look like :
"key 1" = "Value 1";
"key 2" = "Value 2";
"key 3" = "Value 3";

Here is my code that is supposed to get the keys and values from the file loaded into a String :
static func getDictionaryFormText(text: String) -> [String: String] {
    var dict: [String : String] = [:]
    let exp = "\"(.*)\"[ ]*=[ ]*\"(.*)\";"

    for line in text.components(separatedBy: "\n") {
        let match = self.matches(for: exp, in: line)
        // Following line can be uncommented when working
        //dict[match[0]] = match[1]
        print("(\(match.count)) matches = \(match)")
    }
    return dict
}

static func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range) }
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

When running this code with the provided Localizable example here is the output :
(1) matches = ["\"key 1\" = \"Value 1\";"]
(1) matches = ["\"key 2\" = \"Value 2\";"]
(1) matches = ["\"key 3\" = \"Value 3\";"]

It sounds like the match doesn't stop after the first " occurence. When i try the same expression \"(.*)\"[ ]*=[ ]*\"(.*)\"; on regex101.com the output is correct though. What am i doing wrong ?

A: Your function (from Swift extract regex matches ?) matches the entire pattern
only. If you are interested in the particular capture groups then
you have to access them with rangeAt() as for example in
Convert a JavaScript Regex to a Swift Regex (not yet updated for Swift 3).
However there is a much simpler solution, because .strings files actually use one possible format of property lists, and
can be directly read into a dictionary. Example:
if let url = Bundle.main.url(forResource: "Localizable", withExtension: "strings"),
    let stringsDict = NSDictionary(contentsOf: url) as? [String: String] {
    print(stringsDict)
}

Output:
["key 1": "Value 1", "key 2": "Value 2", "key 3": "Value 3"]

A: For anyone interested I got the original function working. I needed it for a small command-line script where the NSDictionary(contentsOf: URL) wasn't working.
func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        guard let result = regex.firstMatch(in: text, options: [], range: NSRange(location: 0, length: nsString.length)) else {
            return [] // pattern does not match the string
        }
        return (1 ..< result.numberOfRanges).map {
            nsString.substring(with: result.range(at: $0))
        }
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

func getParsedText(text: String) -> [(key: String, text: String)] {
    var dict: [(key: String, text: String)] = []
    let exp = "\"(.*)\"[ ]*=[ ]*\"(.*)\";"

    for line in text.components(separatedBy: "\n") {
        let match = matches(for: exp, in: line)
        if match.count == 2 {
            dict.append((key: match[0], text: match[1]))
        }
    }
    return dict
}

Call it using something like this.
let text = try! String(contentsOf: url, encoding: .utf8)

let stringDict = getParsedText(text: text)

A: Really nice solution parsing directly to dictionary, but if someone wants to also parse the comments you can use a small library I made for this csv2strings.
import libcsv2strings

let contents: StringsFile = StringsFileParser(stringsFilePath: "path/to/Localizable.strings")?.parse()

It parses the file to a StringsFile model
/// Top level model of a Apple's strings file
public struct StringsFile {
    let entries: [Translation]

    /// Model of a strings file translation item
    public struct Translation {
        let translationKey: String
        let translation: String
        let comment: String?
    }
}


text:
Q: Can spacy recognize bigrams as a single token? I am parsing the Game of Thrones script so that I can use word2vec.  The problem is the parsing of the proper nouns. Take for example:
s = "The Night's Watch is a joke to you, is it? Is that what we are, Lannister? An army of jesters in black?"

Here is sample code:
import spacy
nlp = spacy.load('en_core_web_lg')
[token.lemma_ for token in nlp(s) if not token.is_stop]

This gives:
['Night',
 'Watch',
 'joke',
 ',',
 '?',
 ',',
 'Lannister',
 '?',
 'army',
 'jester',
 'black',
 '?']

I would really like Night's Watch to be recognised as a single token, e.g. Night's_Watch.
Can spacy do this?

A: You can try spacy's noun chunks feature. Noun chunks are a noun plus the words describing the noun e.g. "night watch", "a joke":
import spacy
nlp = spacy.load('en_core_web_lg')

doc = nlp("The Night's Watch is a joke to you, is it? Is that what we are, Lannister? An army of jesters in black?")
list(doc.noun_chunks)

Output:
[The Night's Watch, a joke, you, it, what, we, An army, jesters]

If you instead want to get all the true bigrams in a given text then you can use nltk.util.ngrams instead.

A: Here is how you can use a for loop with if, elif and else:
lst = ['Night','Watch','joke',',','?',',','Lannister','?','army','jester','black','?']
bigrams = ['Night Watch'] # You can put as many bigrams as you like
new = []

for i,v in enumerate(lst):
    if i+1 < len(lst):
        b = f'{v} {lst[i+1]}'
        if b in bigrams:
            new.append(b)
        elif f'{lst[i-1]} {v}' in bigrams:
            pass
        else:
            new.append(v)

print(new)

Output:
['Night Watch',
 'joke',
 ',',
 '?',
 ',',
 'Lannister',
 '?',
 'army',
 'jester',
 'black',
 '?']

UPDATE: The bigrams are unknown:
lst = ['Night','Watch','joke',',','?',',','Lannister','?','army','jester','black','?']
new = []

for i,v in enumerate(lst):
    if i+1 < len(lst):
        if v.istitle() and lst[i+1].istitle():
            new.append(f'{v} {lst[i+1]}')
        elif lst[i-1].istitle() and v.istitle():
            pass
        else:
            new.append(v)

print(new)

Output:
['Night Watch',
 'joke',
 ',',
 '?',
 ',',
 'Lannister',
 '?',
 'army',
 'jester',
 'black',
 '?']


text:
Q: Why cepheus don't send int without quotes to orion? In this question I have a problem that the orion conditions were not satisfied but it was solved by removing the quotes on the especial value Why this orion subscription don't works as I want?
The new problem is that when I process an event with cep that calculates the mFlag int attribute it send it to orion but apparently it is send with the quotes (same problem as described in the related question posted before) because the orion entity is changed but the notification is not triggered.
The cepheus cep config out is like this one:
"out":[
    {
      "id":"algo",
      "type":"Event",
      "brokers":[
        {
          "url":"http://localhost:1026" //orion
        }
      ],
      "attributes":[
         { "name":"IdEvent", "type":"int" },
         { "name":"mFlag", "type":"int" }
      ]
    }
  ],

Is this problem of the cepheus cep or it is a orion bug not interpreting the type of the attribute in the conditions?

A: You seem to have hit an incompatibility in the NGSIv1 protocol implementation between Cepheus and Orion.
NGSIv1 has been well defined for its XML format (as a OMA standard), but not for its JSON version. The Cepheus team has based the JSON implementation one of the only existing document defining the JSON format of NGSIv1: the API  Walkthough of the Orion documentation.
In this document, all values are exchanged (like in the XML format of the stantard) as strings. Therefore, Cepheus uses strings regardless of the type of the value.
If we were to decide to use some other representation than JSON strings for values, we would need a document (a proper specification for the NGSIv1 JSON !) defining which types can be represented as a JSON number.


text:
Q: ASP.NET MVC - ref is null when user goes from youtube.com I develop an ASP.NET MVC application and I need to get url of youtube page, from user goes to my page. For example, on youtube.com under my video I put a link to my web-site. When user goes to my website I should receive link to youtube page. I try to receive this link using the next code:
Request.UrlReferrer

but when I go to my page from youtube.com the Request.UrlReferrer is null.
Also, note, that I click on my link on youtube.com page I go to my page thru page like:
https://www.youtube.com/redirect?q=http%3A%2F%2mysite.azurewebsites.net%2FHome%2FFillForm%3FFormID%3DbdHN7K9oFkQ&redir_token=tl-svjka0c6n2TVko3CXXXoDak18MTM5NzMyODMwMUAxMzk3MjQxOTAx
How can I get UrlReferrer value?

A: This is most likely caused by the fact that it's redirecting from an https URL to an http URL and the browser gets paranoid about security.
That said, the referer header is not guaranteed to be sent in any case and your logic can't depend on it being available.


text:
Q: Happy number program using array, help me how to calculate Time Complexity? I have written a Happy number program using an array, help me how to calculate Time Complexity? Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to number '1'. All other (not-happy) numbers will never reach '1'. Instead, they will be stuck in a cycle of numbers which does not include '1'.
def happy(num):
    ls = []
    result = 0
    while True:
        result = sqr_digits(num)
        if result == 1:
            return True
        elif result in ls:
            return False  # not happy
        else:
            ls.append(result)
            num = result

def sqr_digits(num):
    result = 0
    while(num > 0):
        digit = num % 10
        result += digit ** 2
        num //= 10
    return result

    num = 145
    print(happy(num))

A: [Note: While answering the question, I forgot that your code is using digit^2, but I've just provided the solution based on digit. The complexity calculation mechanism is same. If you read the answer, you can easily find out the complexity for digit^2 by yourself. I'll update the answer, when I get sometime. Hope you wouldn't mind]
Well, if there is a number n(base 10), then it can have at most log10(n) + 1 digits. I hope, i would not have explain it...just google it how many digits in a 10 based number and how to find it using log.
Now, let's explain the complexity of the provided algo:
The algo will only be stopped when the sum turns into a single digit.
So, we can calculate the number of digits, we've to add and that'll be the complexity ultimately.
Exactly calculate the complexity of this algo is not possible, but we can calcuate the complexity of worst case...what would could be max number with 3 digits, of course 999, so we'll always consider d nines in a d digits number.
1st iteration:: no of digits, d1 = log10(n) + 1, and n1 = d1*10, (originally d1*9 in worst
case, but we're taking much worse and the reason is to calculate complexity properly)

2nd iteration:: no of digits, d2 = log10(n1) + 1 and n2 = d2*10
                                 = log10(d1*10) + 1
                                 = log10(d1) + 1 + 1 (cause, log(a*b) = log(a)+log(b))
                                 = log10(log10(n) + 1) + 1 + 1

3rd iteration:: no of digits, d3 = log10(log10(log10(n)+1)+1) + 1 + 1 + 1

...
...

I guess, you can see where this is going. The total digits number can be written as:
total digits = d1 + d2 + d3 + ....

By removing the 1 inside log's(for simplification) we can write simply:
total digits = log10(n) + 1 + log10(log10(n)) + 2 + log10(log10(log10(n))) + 3 + ...

but, log10(n) + 1 >>> log10(log10(n)) + 2

So, we can see that the ultimate complexity is determined by log10(n). The ultimate complexity would be:
complexity = c * log10(n) // here is "c" a constant such that c * log10(n) > total digits
which
we can say O(log10(n))

I hope you've understood the concept properly...


text:
Q: How to access to widget class from another dialog class Firstly, I have two classes.
The First class called Widget, and the second class called addItem.
The Widget class is the main class(main window) of application ui, but the addItem class is just window, appears when click on add person to add new contact.
Also the Widget class has a child element called tableWidget  .

Now I'm in addItem class,  How to access to tableWidget element that is a child followed to Widget class?
Widget Class (.h)
namespace Ui {
    class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

protected:
    void resizeEvent(QResizeEvent *event);

private slots:
    void on_delete_btn_clicked();
    void on_add_btn_clicked();

private:
    Ui::Widget *ui;
};

addItem Class (.h)
namespace Ui {
    class addItem;
}

class addItem : public QDialog
{
    Q_OBJECT

public:
    explicit addItem(QWidget *parent = 0);
    ~addItem();

private slots:
    void on_addBtn_clicked();

private:
    Ui::addItem *ui;
};

Edit
The following method belong to addItem class.

addItem.cpp:
void addItem::on_addBtn_clicked(){
    emit mySignal(ui->name_txt->text(), ui->address_txt->text(), ui->phoneNum_txt->text(), ui->mobileNum_txt->text());
    Widget *widget = new Widget;
    connect(this, SIGNAL(mySignal(QString,QString,QString,QString)), widget, SLOT(addMyItem(QString,QString,QString,QString)));
    this->close();
}

See also the rest of the code that I wrote :
addItem.h:
signals:
    void mySignal(QString, QString, QString, QString);

Widget.h (mainwindow):
private slots:
    void addMyItem(QString, QString, QString, QString);

Widget.cpp (mainwindow):
void Widget::addMyItem(QString name, QString address, QString phone_number, QString mobile_number){
    qDebug() << name << "\n" << address << "\n" << phone_number << "\n" << mobile_number;
}

A: Setting
public:
    Ui::Widget *ui;

isn't good practice, so you can use getters and setters.
For example, if you want take text from QTableWidget, provide method for example
QString Widget::getCellData(int row, int col)
{
    return ui->tableWidget->item(row,col)->text();
}

To set data:
void Widget::setCellData(int row, int col, QString txt)
{
    //create item if you need
    ui->tableWidget->item(row,col)->setText(txt);
}

and so on. I hope you will understand main idea and how to do it.
But you can use also signals and slots:
For example user clicks on add button and you want add new data in table, then emit from addItem button signal:
 emit mySignal(name, address, phone , mobile);

where name is ui->nameLineEdit->text() and so on. Just take text from lineEdit and send it.
Catch it with special slot in Widget class. In this slot you can create new row and set data.
void Widget::mySlot(QString name,QString address,QString phone ,QString mobile)
{
    //create cells and set data in it
}

And of course you should connect mySignal from addItem class to mySlot in Widget class.
addItem *mDialog = new addItem;
connect(mDialog,SIGNAL(mySignal(QString,QString,QString,QString)),this,SLOT(mySlot(QString,QString,QString,QString)));

Conclusion: I think, you should use signals and slots.

Edit
Explanation in detail:
You have Dialog class and mainwindow:
dialog.h:
signals:
    void mySignal(QString,QString,QString,QString);

dialog.cpp When user clicks we get data, emit signal and close dialog.
void Dialog::on_addItemButton_clicked()
{
    emit mySignal(ui->lineEdit_2->text(),ui->lineEdit_3->text(),ui->lineEdit_4->text(),ui->lineEdit_5->text());
    this->close();
}

mainwindow.h
private slots:
      void addMyItems(QString,QString,QString,QString);

mainwindow.cpp
void MainWindow::addMyItems(QString name,QString address,QString phone ,QString mobile)
{
    ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);//increase row count by 1

    int row = ui->tableWidget->rowCount() - 1;

    //set all data in cells
    ui->tableWidget->setItem(row,0,new QTableWidgetItem(name));
    ui->tableWidget->setItem(row,1,new QTableWidgetItem(address));
    ui->tableWidget->setItem(row,2,new QTableWidgetItem(phone));
    ui->tableWidget->setItem(row,3,new QTableWidgetItem(mobile));
}

Slot for button in mainwindow which opens dialog:
void MainWindow::on_Add_clicked()
{
    Dialog *dia = new Dialog;//our dialog
    dia->setAttribute(Qt::WA_DeleteOnClose);//we don't want memory leak
    //connection
    connect(dia,SIGNAL(mySignal(QString,QString,QString,QString)),this,SLOT(addMyItems(QString,QString,QString,QString)));
    dia->setModal(true);//you can use modal window instead of exe()
    dia->show();
}

Result:
I clicked on Add button and get dialog:

Now I set some data and clicked Additem button:

As you can see, our connection works, data properly placed in the tableWidget.

A: The way I normally handle these things is quite non Qt-ish, but it makes unit testing easier. I have something like MVC (model-view-controller), but in Qt the V and C are one.
For example the model could be:
class Record
{
public:
  std::string mName;
  std::string mAddress;
  std::string mPhoneNumber;
  std::string mMobileNumber;
};

class Model
{
public:
  void AddRecord(std::unique_ptr<Record> rec)
  {
      mRecords.emplace_back(std::move(rec));
  }

  const Record* ItemAt(size_t index) const
  {
     if (index > mRecords.size()) { return nullptr; }
     return mRecords(index);
  }

  size_t NumRecords() const
  {
    return mRecords.size();
  }
private:
  std::vector<std::unique_ptr<Record> mRecords;
};

Then in your main function you can construct a model and pass it to your main/view window:
int main( int argc, char **argv )
{
    // Create app instance
    QApplication a( argc, argv );

    Model model;
    MainWindow mainWindow(model); // MainWindow stores a reference to the model
    mainWindow.exec();

And the when you create the sub dialog simply pass that the model too. Or have it return a std::unique_ptr<Record>
void MainWindow::on_Add_clicked()
{
    Dialog *dia = new Dialog(this, mModel);//Where mModel is the Model instance reference we passed to Widget in main()
    dia->exec();
}

Its worth noting that Qt comes with its own model classes for the views. You could take your own Model class and have Qts view model auto update the UI when your view model changes. This is much more advanced though. For now you could just manually keep your model in sync with your UI, i.e if you add a record or remove a record from model, then update your table widget.
Disclaimer: I didn't actually try to compile any of this code, treat it as pesudo code ;)


text:
Q: Why is my CSS working in Chrome, but not IE8? There's a <div> on the right side of my site that displays properly. It says "Look at the new Hunt Group Hunter". If you open the same site in IE8, that <div> is missing. I am not sure how to account for IE8.
Here's the CSS I have for this object.
#hg {
    text-align:center;
    font-size:180%;
    width: 210px;
    height: 150px;
    position:absolute;
    margin: 240px 0px 0px 920px;
    }

#hg_hunter {
    width: 168px;
    height: 148px;
    position:absolute;
    margin: 80px 100px 0 62px;

    }

I'm lost here because this is basic <div> placement.
Any ideas?
PS - IE8 is our corporate browser. I can't do anything about that.

A: change
margin: 80px 100px 0 62px;

to
margin: -80px 100px 0 62px;

works on Chrome and IE for me then

A: I can't test it in IE8 here (mac only), but have you tried using top, bottom, left and right in stead of margin? In my experience IE8 is not very good with margins, definitly when positioning absolute. I suspect your div is just somewhere of screen...


text:
Q: "Inline parts" in exam class like inlineitem Producing exams with exam class, I want to know if there is a command like \inlineitem, for parts, where I can write parts of a question in the same line, something like \part, \inlinepart. Let me kindly remark that I want to "inline" the environment part, because I use it in my exercises with the option addpoints, where the parts are given as in the MWE, \part[2] and \part[3], and the option uses the points given into brackets to produce gradetable and so...  I give the MWE:
\documentclass[12pt,addpoints]{exam}

\usepackage[inline]{enumitem}   % The option inline enables "inline" itemizing
\makeatletter
\newcommand{\inlineitem}[1][]{%
\ifnum\enit@type=\tw@
    {\descriptionlabel{#1}}
  \hspace{\labelsep}%
\else
  \ifnum\enit@type=\z@
       \refstepcounter{\@listctr}\fi
    \quad\@itemlabel\nobreakspace\hspace{\labelsep}%
\fi}
\makeatother

\begin{document}
\begin{questions}
\question
\begin{parts}
\part[2] First part
\part[3] Second part
\end{parts}
\begin{enumerate}
\item First item
\inlineitem Second item
\end{enumerate}
\end{questions}
\end{document}

and the file produced,


text:
Q: How to transform a range of records to the values of the record after that range in SQL? I am trying to replace some bad input records within a specific date range with correct records. However, I'm not sure if there is an efficient way to do so. Therefore my question is how to transform a (static) range of records to the values of the record after that range in SQL? Below you will find an example to clarify what I try to achieve.

In this example you can see that customer number 1 belongs to group number 0 (None) in the period from 25-06-2020 to 29-06-2020. From 30-06-2020 to 05-07-2020 this group number changes from 0 to 11 for customer number 1. This static period contains the wrong records, and should be changed to the values that are valid on 06-07-2020 (group number == 10). Is there a way to do this?

A: I think that window function first_value() does what you want:
select
    date,
    customer_number,
    first_value(group_number) over(partition by customer_number order by date) group_number,
    first_value(role)         over(partition by customer_number order by date) role
from mytable

A: If I understand correctly, you can use window functions to get the data on that particular date and case logic to assign it to the specific date range:
select t.*,
       (case when date >= '2020-07-01' and date <= '2020-07-05'
             then max(case when date = '2020-07-06' then group_number end) over (partition by customer_number)
             else group_number
        end) as imputed_group_number,
       (case when date >= '2020-07-01' and date <= '2020-07-05'
             then max(case when date = '2020-07-06' then role end) over (partition by customer_number)
             else role
        end) as imputed_role
from t;

If you want to update the values, you can use JOIN:
update t
    set group_number = tt.group_number,
        role = tt.role
    from tt
    where tt.customer_number = t.customer_number and tt.date = '2020-07-06'

A: You can do the following as an example. Here i have choosen the criteria that if role='Leader' its a bad record and therefore you would be applying the next available group_number --> in column group_number1, and role1.
I have used a smaller subset of the rows you have in your excel example.
  select date1
        ,customer_number
        ,group_number
        ,case when role='Leader' then
                  (select t1.group_number
                     from t t1
                    where t1.date1>t.date1
                      and t1.role<>'Leader'
                   order by t1.date1 asc
                   limit 1
                  )
             else group_number
         end as group_number1
        ,role
       ,case when role='Leader' then
                  (select t1.role
                     from t t1
                    where t1.date1>t.date1
                      and t1.role<>'Leader'
                   order by t1.date1 asc
                   limit 1
                  )
             else role
         end as role1
   from t
order by 1

+------------+-----------------+--------------+---------------+--------+--------+
|   DATE1    | CUSTOMER_NUMBER | GROUP_NUMBER | GROUP_NUMBER1 |  ROLE  | ROLE1  |
+------------+-----------------+--------------+---------------+--------+--------+
| 2020-06-25 |               1 |            0 |             0 | None   | None   |
| 2020-06-26 |               1 |            0 |             0 | None   | None   |
| 2020-06-27 |               1 |            0 |             0 | None   | None   |
| 2020-06-28 |               1 |            0 |             0 | None   | None   |
| 2020-06-29 |               1 |            0 |             0 | None   | None   |
| 2020-06-30 |               1 |           11 |            10 | Leader | Member |
| 2020-07-01 |               1 |           11 |            10 | Leader | Member |
| 2020-07-06 |               1 |           10 |            10 | Member | Member |
+------------+-----------------+--------------+---------------+--------+--------+

db fiddle link
https://dbfiddle.uk/?rdbms=db2_11.1&fiddle=c95d12ced067c1df94947848b5a94c14


text:
Q: How to sort terms of custom taxonomies created programmatic via Wordpress back-end? I have a problem with sorting terms of custom taxonomy. I need some way to sort them manually (not alphabetical or by date) via WP back-end. In future I need to show them in that order.
Would be gratefull for some pointers.

A: The plugin Custom Taxonomy Sort (http://wordpress.org/extend/plugins/custom-taxonomy-sort/) will be of great assistance to you. Install the plugin, visit your custom taxonomy page, and start inputting order values to control the order of your terms.


text:
Q: In ggplot2/stat_summary, how to add the `median` value as label to plot (as geom_text()) In ggplot2/stat_summary, how to add the median value as label to plot ? Thanks!
library(ggplot2)
d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point()
d + stat_summary(fun = "median", colour = "red", size = 2, geom = "point")

A: One potential option is to use after_stat() to get the labels, i.e.
library(ggplot2)
d <- ggplot(mtcars, aes(cyl, mpg)) +
  geom_point()
d + stat_summary(fun = "median", colour = "red", size = 4,
                 geom = "text", aes(label = after_stat(y)),
                 position = position_nudge(x = 0.25))

Created on 2022-05-16 by the reprex package (v2.0.1)


text:
Q: Как добавить возможность загрузки аватарки при регистрации пользователя на сайте wordpress? Есть сайт на wordpress с установленным плагином Theme My Login Хочу сделать так, чтобы при регистрации пользователя была возможность добавления и сохранения аватарки пользователя. С добавлением вопрос решил так:

Загрузка аватарки

        <?php echo get_simple_local_avatar( $profileuser->ID ); ?>
        <?php
          if ( ! $upload_rights = current_user_can('upload_files') )
            $upload_rights = empty( $this->options['caps'] );

          if ( $upload_rights ) {
            do_action( 'simple_local_avatar_notices' );
            wp_nonce_field( 'simple_local_avatar_nonce', '_simple_local_avatar_nonce', false );
        ?>

          <input type="file" name="simple-local-avatar" id="upload_hidden" onchange="document.getElementById('upload_visible').value = this.value;" />
          <button type="button" id="review" onclick="document.getElementById('upload_hidden').click();">Выбрать</button>

              <?php if ( current_user_can( 'upload_files' ) && did_action( 'wp_enqueue_media' ) ) : ?><?php _e( 'Choose from Media Library', 'simple-local-avatars' ); ?>  <?php endif; ?>

        <?php
          } else {
            if ( empty( $profileuser->simple_local_avatar ) )
              echo '' . __('No local avatar is set. Set up your avatar at Gravatar.com.','simple-local-avatars') . '';
            else
              echo '' . __('You do not have media management permissions. To change your local avatar, contact the blog administrator.','simple-local-avatars') . '';
          }
        ?>

А как теперь ее сохранить? здесь указано как добавлять и регистрировать дополнительные поля, но для аватарки подход другой


text:
Q: Fit a Vertical UISlider into an Existing Container View? I want to create a vertical UISlider and exactly fit it into an existing container view that is sized and placed from a .xib file using autoLayout.  But I simply cannot get it to work and I have Googled my fingers bloody.
The closest I have gotten creates a slider that is too long and extends off the screen.
Am I putting the code in the wrong place?
I am putting my code in "layOutSubviews"
Some Points of interest:
1.Per Apple's docs, the view's "frame" is not valid after the transformation and should not be set.
2.The frame of the slider is set to the future parent's dimensions before the transformation (with x and y swapped).
3.The transformed view appears to maintain its bounds in the pre-transformation coordinate frame. i.e. After the 90 degree transformation, the width and height of the transformed view's bounds appear to be swapped.
This code doesn't work. The slider looks right except that it extends off the bottom of the screen. The slider bounds and even the frame (which Apple says is not valid) seem to match the bounds and frame of the container view. The slider doesn't even stay within its own bounds.
[super layoutSubviews];

CGRect trigLevelSliderFrame=self.trigLevelSliderContainer.bounds;
trigLevelSliderFrame.size.height=self.trigLevelSliderContainer.bounds.size.width;
trigLevelSliderFrame.size.width=self.trigLevelSliderContainer.bounds.size.height;

UISlider *mySlider=[[UISlider alloc] initWithFrame:trigLevelSliderFrame];
self.trigSlider=mySlider;
[mySlider release];

self.trigSlider.transform=CGAffineTransformMakeRotation(-M_PI_2);
CGPoint center=CGPointMake(self.trigLevelSliderContainer.bounds.size.width/2,self.trigLevelSliderContainer.bounds.size.height/2);
self.trigSlider.center=center;
[self.trigLevelSliderContainer addSubview:self.trigSlider];

A: There is no problem with this code to add and rotate the slider.  The problem is that the the code must be put into the "layoutSubviews" method of the slider's parent view; instead I had it in the "layoutSubviews" of the parent view of the parent view of the slider.  When my original code executed the slider's parent view had not yet been laid out and did not yet have the correct dimensions.
During "layoutSubviews" of a view, the subviews have not yet been laid out and so their bounds are not yet valid.  I needed to wait until later in the layout process to get the bounds of the parent view and transform the slider to fit.
In the end, I put the code to add the slider and transform the slider in the "viewDidAppear" of the top level view controller.  This was the same code as in the original question - just in a different place.


text:
Q: Java parser rename variable I need to write a parser for Java programming language. I've seen some implementations (JavaCC, SableCC) and i think i can handle it.
The thing is I need to rename the variables. Could I do this using the parser?
If yes, how?

A: You don't need a parser if all you want to do is rename variables globally.  All you need is an (island) lexer that can pick out identifiers, so that you can replace them.  You can get such a lexer from any parser generator that has a Java grammar by simply ignore the parser part.  That should save you a lot of trouble.
If you try to use a parser for this, that builds an AST, it will be easy to determine the identifiers (there will IDENTIFIER tree nodes) and probably even replacing them by smashing the tree nodes. Your problem will be regenerating legal source text.   Most parser generators don't provide text-to-tree-to-text capabilities.
If you want to rename variables according to scopes, you need a parser, and full name and type resolution.  That's way harder than a mere parser; the rules about name lookup in Java 7 are pretty complicated.   Again, there are parser generators out there with Java grammars; but in this case, they won't help you unless you want to implement that name and type resolution.  You'll find that a lot more work than you expect.


text:
Q: How to encrypt (and decrypt) data with pycrypto and RSA? I've been trying to encrypt data in Python with RSA in pycrypto.  I've tried to follow the instructions here: http://www.laurentluce.com/posts/python-and-cryptography-with-pycrypto/ but here's what comes out when I call enc_data = public_key.encrypt('abcdefgh', 32):
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
  enc_data = public_key.encrypt('abcdefgh', 32)
  File "C:\Python35\lib\site-packages\Crypto\PublicKey\RSA.py", line 150, in encrypt
    return pubkey.pubkey.encrypt(self, plaintext, K)
  File "C:\Python35\lib\site-packages\Crypto\PublicKey\pubkey.py", line 75, in encrypt
    ciphertext=self._encrypt(plaintext, K)
  File "C:\Python35\lib\site-packages\Crypto\PublicKey\RSA.py", line 224, in _encrypt
    return (self.key._encrypt(c),)
  File "C:\Python35\lib\site-packages\Crypto\PublicKey\_slowmath.py", line 65, in _encrypt
    return pow(m, self.e, self.n)
TypeError: unsupported operand type(s) for pow(): 'str', 'int', 'int'

Thanks in advance for any advice regarding this issue.

A: If you look at the encrypt method:

plaintext (byte string or long) - The piece of data to encrypt with RSA. It may not be numerically larger than the RSA module (n).

Your data is not a byte string or long. If you want to input text then you first need to use a character encoding such as UTF-8 for input.
Note that "plaintext" is just the input for the cryptographic primitives. All modern ciphers operate on bytes. Historically the input may have been actual text, but not anymore.

Also note that:

Attention: this function performs the plain, primitive RSA encryption (textbook). In real applications, you always need to use proper cryptographic padding, and you should not directly encrypt data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules Crypto.Cipher.PKCS1_OAEP or Crypto.Cipher.PKCS1_v1_5 instead.

For these functions it is also required to convert your text to byte arrays.


text:
Q: convert COleDateTime to ticks or integer representation how to convert COleDateTime to some sort of integer representation which can be easily converted back.

A: I think the simplest way is through COleDateTimeSpan as follow:
// Create an epoch
static COleDateTime epoch( 2000, 1, 1, 0, 0, 0 );

// Convert to integer
COleDateTime someTime;    // initialize it from somewhere
__int64 nOleDateTimeAsInt = static_cast<__int64>( (someTime - epoch).totalSeconds() );

// Create from integer
COleDateTimeSpan span( nOleDateTimeAsInt / SecondsInDay,
    (nOleDateTime % SecondsInDay) / SecondsInHour,
    (nOleDateTime % SecondsInHour) / SecondsInMinute,
    (nOleDateTime % SecondsInMinute) );
COleDateTime someTime( epoch + span );


text:
Q: assign the ip address by the using the batch file i have a batch file for assigning the static ip by only to click the batch file . but its showing error (the filename, directory name, or volume label syntax is incorrect." ) on some systems. what would be the solutoin.
my batch file is
 netsh interface ip set address "Wireless Network Connection" static 192.168.1.26 255.255.255.0 192.168.1.1
netsh interface ip set dns "Wireless Network Connection" static 8.8.8.8
netsh interface ip add dns "Wireless Network Connection" 4.2.2.2

A: The problem seems to be with the connection name.
If you run
netsh interface ip set address "Wireless Network Connection" static 192.168.1.26 255.255.255.0 192.168.1.1

"Wireless Network Connection" should exist exactly like that given name as an interface. It is like an Alias name you are referencing.
If you look at your interfaces by netsh interface ip show config does "Wireless Network Connection" actually exist? Might be something else like "Wireless Network Connection 2" and then you will then get the exact error as you have posted.
EDIT
As per your comment.
Remember to add the correct interface name for each of the lines, but your latest problem is really with adding the DNS server in the last line
netsh interface ip set address "Connection name goes here" static 192.168.1.26 255.255.255.0 192.168.1.1
netsh interface ip set dns "Connection name goes here" static 8.8.8.8
netsh interface ip add dnsserver "Connection name goes here" address=4.2.2.2 index=1

note you can also use
 netsh interface ipv4 add dnsserver "Connection name goes here" address=4.2.2.2 index=1

As far as index=1 is concerned, remember to set it according to which DNS server you want to index first.

A: Looks like you try to change a nonexistent connection.
I'd enumerate the current connections first:
for /f tokens^=2delims^=^" %%A in (
  'netsh interface ip show config'
) Do Echo %%A

Sample output:
> List-Conn.cmd
LAN-Verbindung
Ethernet 2
Loopback Pseudo-Interface 1


text:
Q: android screen i scrolling down on every input to editText insert I have the following layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue_bg" >

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal"
                android:orientation="vertical" >

....
                <View
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.3" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:src="@drawable/signup_illu_verificationcode" />

            <View
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_weight="0.0" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:background="@android:color/white"
                android:padding="5dp"
                android:paddingLeft="25dp"
                android:paddingRight="25dp" >

                <LinearLayout
                    android:id="@+id/inputBox"
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="15dp"
                    android:background="@drawable/input_box_idle"
                    android:gravity="center"
                    android:orientation="horizontal" >

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" >

                        <EditText
                            android:id="@+id/verificationCodeEditText"
                            style="@style/textOnBg"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:background="@android:color/transparent"
                            android:hint="-  -  -  -  -"
                            android:inputType="number"
                            android:textColor="#516063"
                            android:textColorHint="#b4c8cf"
                            android:textSize="25dp" >
                        </EditText>
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.7" />

          ...

        </LinearLayout>
    </ScrollView>

</RelativeLayout>

and the following code
which suppose to detect softkeboard opening and scroll the view a bit down (once)
    public class PhoneVerifyYourNumbersActivity extends Activity {

        private String mDisplayOptions[] = new String[3];
        private LinearLayout mInputBox;
        private LinearLayout mContinueButton;
        private TextView mVerifyByPhoneCallText;

        private ScrollView mScrollView;

        private EditText mVerificationCodeEditText;
        private String mHash = null;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.phone_verify_your_numbers);

            mHash = getIntent().getStringExtra("Hash");

            initMembers();
            setOnClickListeners();
            initFieldsTexts();
            setKeyboardVisibilityListener();

        }

..

        private void setKeyboardVisibilityListener() {
            final View root = findViewById(R.id.rootLayout);

            root.getViewTreeObserver().addOnGlobalLayoutListener(
                    new OnGlobalLayoutListener() {

                        @Override
                        public void onGlobalLayout() {
                            // TODO Auto-generated method stub

                            int heightDiff = root.getRootView().getHeight()
                                    - root.getHeight();
                            if (heightDiff > 100) { // more than 100 pixels is
                                                    // probably a keyboard
                                // keyboard is shown
                                mInputBox
                                        .setBackgroundResource(R.drawable.input_box_active);
                                //mScrollView.scrollTo(0, mScrollView.getBottom());
                                mScrollView.scrollBy(0, +20);
                            } else {
                                // keyboard is not shown
                                mInputBox
                                        .setBackgroundResource(R.drawable.input_box_idle);
                            }
                        }
                    });
        }
}

}

my manifest:
<activity
    android:name=".phone.PhoneVerifyYourNumbersActivity"
    android:theme="@android:style/Theme.NoTitleBar"
    android:windowSoftInputMode="stateHidden|adjustResize" />

a strange behavior is that whenever the user insert input to the editText,
the scroll moves 1-2 dps down wise. What can cause this?
I guess this mScrollView.scrollBy(0, +20); happens multiple times
but then how can I make it happen once?
(any clever idea other than adding a boolean flag isMovedAlready) ?

A: mScrollView.scrollBy() is scrolling by px(Pixels) not dp. you may want to calculate dp to px first.
but i think you want something different. something like this:
View v = findViewById(R.id.verificationCodeEditText);
mScrollView.scrollTo(0, v.getBottom()+10);//or similar

A: // try to add one properties on AndroidManifest.xml Activity declaration like below.
**AndroidManifest.xml**
<activity
  android:name="PhoneVerifyYourNumbersActivity"
  android:windowSoftInputMode="stateHidden|adjustPan">
</activity>