text:
Q: What do you use to create flowcharts? I'm curious what tools people have found useful for building flowcharts. Obviously MS Visio and OmniGraffle come to mind but they both feel so bloated and also tend to emphasize the document formatting/printing side and less on helping to organize the actual logic. Is there anything else out there that fellow developers would recommend?
I'm hoping to find something fairly simple that would let me throw together flowcharts on the fly when I'm working through complex logic. I don't care about formatting or fonts or the like, just something that would help me keep my logic organized as I work through it. Even something that would arrange the chart itself and simply allow me to specify where to branch and what to check, etc.
Any OS would be fine, though I personally lean towards OS X apps as this has recently been my primary work environment.

A: take a look at graphviz.
Example:
digraph finite_state_machine {
    rankdir=LR;
    size="8,5"
    node [shape = doublecircle]; LR_0 LR_3 LR_4 LR_8;
    node [shape = circle];
    LR_0 -> LR_2 [ label = "SS(B)" ];
    LR_0 -> LR_1 [ label = "SS(S)" ];
    LR_1 -> LR_3 [ label = "S($end)" ];
    LR_2 -> LR_6 [ label = "SS(b)" ];
    LR_2 -> LR_5 [ label = "SS(a)" ];
    LR_2 -> LR_4 [ label = "S(A)" ];
    LR_5 -> LR_7 [ label = "S(b)" ];
    LR_5 -> LR_5 [ label = "S(a)" ];
    LR_6 -> LR_6 [ label = "S(b)" ];
    LR_6 -> LR_5 [ label = "S(a)" ];
    LR_7 -> LR_8 [ label = "S(b)" ];
    LR_7 -> LR_5 [ label = "S(a)" ];
    LR_8 -> LR_6 [ label = "S(b)" ];
    LR_8 -> LR_5 [ label = "S(a)" ];
}

produces:

(source: graphviz.org)
it is particularly well suited to be generated from programs.

A: How about paper and pencil?  Or a whiteboard?
Sometimes the ease and tactile feedback of physical objects is the most appropriate.

A: Though you list it as bloated I nonetheless use OmniGraffle.
For quick flowcharting a series of boxes with lines to magnets in the boxes is sufficient, but the rest of the formatting options are good to have later. I find that any flowchart I take the time to draw generally ends up in a document somewhere. Even when I'm just trying to understand some difficult code, I end up with a one page document which attempts to explain that code for the next poor schmuck who has to dig in.

A: I use Dia on Linux. It's quite lightweight and is simple to use, but it doesn't automatically position elements, and I've found the interface to be a bit inhibitive at times.
There's an OS X port at dia.darwinports.com, although I've not used it.

A: Open Office's Draw is pretty good too. I've used it to create everything from simple flow charts to complex genealogical trees.

A: For the OmniGraffle, is it good enough for its FREE version? i.e. after its 14 days trial, is it still a good choice?
I am attempting to use the yEd.

A: I don't do a lot of complex flowcharts but I when I am flowcharting or putting together a data flow I tend to use Powerpoint. It is simple enough and I know it well enough.

A: I use Microsoft Visio 2003, a tad bit of overkill with all its extra junk I don't need, but I like it's simple UI.

A: I generally don't do flow charts, but do do state diagrams.
I do a high level flow on a white board,
then lower levels, on A3 paper.
Once it is all working correctly, I create it in Visio,
which becomes part of the release documentation.

A: I do not use it for programming related tasks but I don't see why it wouldn't work. Mindjet Mindmanager is a great tool for creative thought mapping. (It can be pretty expensive however)


text:
Q: How do I get the for loop to only loop every time the player presses Z I am trying to cycle through a list of dialogue to update a text component.
The var i is only supposed to increases when the player presses z but every time I try the var i increases to the max value instead of once every time I press Z.
IEnumerator gameDialog ( )
{
    while ( i < prologueDialog.Count )
    {
        PlayerPrefs.SetInt ( "StoryProgress(Prologue)", i );
        currentListIndex = PlayerPrefs.GetInt ( "StoryProgress(Prologue)" );

        if ( i == 0 )
        {
            dialogText.text = prologueDialog [ 0 ];
        }

        if ( Input.GetKey ( KeyCode.Z ) )
        {
            pressedZ = true;
            dialogText.text = "";
            dialogText.text = prologueDialog [ i ];
        }

        yield return new WaitUntil ( ( ) => pressedZ );
        pressedZ = false;
        oldi = i;
        i++;
        if ( oldi + 1 != i )
        {
            i = oldi + 1;
        }
        Debug.Log ( i );
    }
}

I've tried everything I could think of using yield, WaitUntil, WaitForSeconds, bool values to stop the if statement from running more than once.

A: The WaitUntil IEnumerator causes the code execution to pause at that spot, until the function predicate returns true. What that means in layman's terms is that the code is going to stop on that line, and move no further, until pressedZ somehow becomes true. But, given that the code won't progress, you can start to see that the keys aren't ever read again, and therefore, pressedZ will never become true.
One thing to note is that saving any game state to the PlayerPrefs is almost universally frowned upon. But that's another issue that can be resolved after getting your dialogue running.
Instead of trying to poll your keyboard input in a "coroutine", might I suggest you use the already available Update method to use as your frame based polling mechanism? It also still includes the PlayerPrefs persistence, which I would suggest replacing at your earliest convenience. This has been written, but not tested.
public class Test : MonoBehaviour
{
    [SerializeField] private TextMeshPro dialogText;

    private List<string> _dialoguePhrases = null;
    private string _storyName;
    private int _dialogueIndex = 0;

    private void Awake ( )
    {
        HideDialogue ( );
    }

    public void ShowDialogue ( List<string> dialoguePhrases, string storyName = "StoryProgress(Prologue)" )
    {
        _dialogueIndex = PlayerPrefs.GetInt ( storyName, 0 );

        // check the saved progress index with the newly passed in dialoguePhrases (or -1 if null).
        if ( _dialogueIndex >= ( dialoguePhrases?.Count ?? -1 ) )
        {
            HideDialogue ( );
            return;
        }

        _dialoguePhrases = dialoguePhrases;
        _storyName = storyName;
        dialogText.text = dialoguePhrases [ _dialogueIndex ];
        enabled = true; // Lets the Update method run.
    }

    public void HideDialogue ( )
    {
        _dialoguePhrases = null;
        _dialogueIndex = 0;
        dialogText.text = string.Empty;
        enabled = false; // Stops the Update method from being called.
    }

    private void Update ( )
    {
        if ( Input.GetKeyDown ( KeyCode.Z ) && _dialoguePhrases != null )
        {
            if ( ++_dialogueIndex < _dialoguePhrases.Count )
            {
                dialogText.text = _dialoguePhrases [ _dialogueIndex ];
                PlayerPrefs.SetInt ( "StoryProgress(Prologue)", _dialogueIndex );
            }
            else
            {
                // You've clicked on the last one, and now you need to do something after the dialogue has finished.
                HideDialogue ( );
            }
        }
    }
}

The idea here is that you send through a list of dialogue phrases, and a name (id) of where the dialogue state would be persisted (preferably not in the PlayerPrefs).
The Update method is then enabled, when the component itself has it's enable flag set to true. The normal checks are made in Update, and when the end of the dialogue is reached, the component turns itself off waiting for the next show dialogue command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: checking the existence of the user in the data store for authentication how to check that the user is authenticated. Asp.net tells me that the user is authorized If set cookies, but I need to check whether a user with the name in my data store. Where can I add additional checks?

A: You should Use: Request.IsAuthenticated
Check the MSDN here.
Also, Below is a great explanation taken from question: How does Request.IsAuthenticated work?
Request.IsAuthenticated is not just for forms authentciation - it is valid no matter what type of authentication is being used (Windows, Passport, Forms or our own custom scheme)
HttpRequest.IsAuthenticated will be true when the user making the request has been authenticated. Essentially, this property provides the same information as Context.User.Identity.IsAuthenticated.
At the start of a request, Context.User.Idenity contains a GenericIdentity with a null username. The IsAuthenticated property for this object will return false so Request.IsAuthenticated will be false. When an authentication module handles the Application_AuthenticateRequest event and successfuly authenticates the user it replaces the GenericIdentity in Context.User.Identity with a new IIdentity object that will return true from its IsAuthenticated property. Request.IsAuthenticated will then return true.
In the case of Forms authentication, the forms authentication module uses the encrypted authentication ticket contained in the authentication cookie to authenticate the user. Once it has done this, it replaces the GenericIdentity in Context.User.Identity with a FormsIdentity object that returns True from its IsAuthenticated property.


text:
Q: Automating a PL/SQL Procedure I have created below pl/sql procedure. I want to schedule it to execute it every day. I am using dbms.job to schedule it to run in a particular time daily. The procedure compiles successfully. But it does not execute automatically though I scheduled.
CREATE OR REPLACE PROCEDURE Schema.Payment_Updation_Process
AS
BEGIN
dbms_output.put_line ('The payments updation process started at '|| rpad(' ',0,' ')||SYSDATE);

EXECUTE IMMEDIATE 'drop table account_new_arr_1'
;
update tab_dld
set dr_date = sysdate
where table_name = 'account_new_arr_1'
and dr_date is null
;
commit
;
insert into tab_dld
values ('account_new_arr_1',sysdate,null,null,null,tab_dld_seq.nextval)
;
commit
;
EXECUTE IMMEDIATE 'create table account_new_arr_1
tablespace TOOLS
storage (initial 1M next 1M)
as (
select t1.customer_segment,t2.account_num,t2.last_bill_seq,
round((t2.total_billed_tot - t2.total_paid_tot);1000,2) new_arr
from accountattributes t1, account t2
where t1.customer_segment in (''01'',''05'',''31'',''32'',''36'',''37'')
and t2.account_num = t1.account_num
and t2.invoicing_co_id = 1
and to_char(t2.last_bill_dtm,''YYYYMM'') > ''201204''
and t2.currency_code = ''LKR''
)'
;

update tab_dld
set en_date = sysdate,
cc = (select count(*)
from account_new_arr_1)
where table_name = 'account_new_arr_1'
and en_date is null
and dr_date is null
;
commit
;
EXECUTE IMMEDIATE 'create index i_account_new_arr_1
on account_new_arr_1(account_num)
tablespace TOOLS
storage (initial 1M next 1M)'
;
END;
/

This is the way that I am trying to schedule.
declare
jid number;
begin
dbms_job.submit(
    JOB => jid,
    WHAT => 'Payment_Updation_Process;',
    NEXT_DATE =>  to_timestamp_tz('09-JULY-21 08.28.00 Asia/Calcutta',
  'DD-MON-RR HH24:MI:SS TZR'),
    INTERVAL  => 'sysdate +1');
end;
/
commit;

When check the status using 'select * from user_jobs;' it shows failures. Does anyone know the reason?


text:
Q: What is '-1[p]' when p points to an array (of int) index? Today I stumbled over a C riddle that got a new surprise for me.
I didn't think that -1[p] in the example below would compile, but it did. In fact, x ends up to be -3.
    int x;
    int array[] = {1, 2, 3};
    int *p = &array[1];
    x = -1[p];

I searched the internet for something like -1[pointer] but couldn't find anything. Okay, it is difficult to enter the correct search query, I admit. Who knows why -1[p] compiles and X becomes -3?

A: This
int array[] = {1, 2, 3};

looks like
array[0]   array[1]  array[2]
 --------------------------
|     1   |    2    |   3  |
 --------------------------
 0x100     0x104     0x108   <-- lets assume 0x100 is base address of array
array

Next when you do like
int *p = &array[1];

the integer pointer p points to address  of array[1] i.e 0x104. It looks like
array[0]   array[1]  array[2]
 --------------------------
|     1   |    2    |   3  |
 --------------------------
 0x100     0x104     0x108   <-- lets assume 0x100 is base address of array
             |
            p holds 0x104

And when you do like
x = -1[p]

-1[p] is equivalent to -(1[p]) i.e -(p[1]). it looks like
-(p[1]) ==> -(*(p + 1*4)) /* p holds points to array[1] i.e 0x104 */
        ==> -(*(0x104 + 4))
        ==> -(*(0x108)) ==> value at 0x108 is 3
        ==> prints -3

A: I'm the person that made this "riddle" (see my Twitter post)
So! What's up with -1[p]?
ISO C actually defines [] to be symmetrical, meaning x[y] is the same as y[x], where x and y are both expressions.
Naively, we could jump to the conclusion that -1[p] is therefore p[-1] and so x = 1,
However, -1 is actually the unary minus operator applied to the constant 1, and unary minus has a lower precedence than []
So, -1[p] is -(p[1]), which yields -3.
This can lead to funky looking snippets like this one, too:
sizeof(char)["abc"] /* yields 'b' */

A: What happens here is really interesting.
p[n] means *(p+n). Thats why you see 3, because "p" points to array[1] which is 2, and -p[1] is interpreted as -(*(p+1)) which is -3.

A: First thing to figure out is the precedence. Namely [] has higher precedence than unary operators, so -1[p] is equal to -(1[p]), not (-1)[p]. So we're taking the result of 1[p] and negating it.
x[y] is equal to *(x+y), so 1[p] is equal to *(1+p), which is equal to *(p+1), which is equal to p[1].
So we're taking the element one after where p points, so the third element of array, i.e. 3, and then negating it, which gives us -3.

A: According to the C Standard (6.5.2 Postfix operators) the subscript operator is defined the following way
postfix-expression [ expression ]

So before the square brackets there shall be a postfix expression.
In this expression statement
x = -1[p];

there is used the postfix expression 1 (that is at the same time a primary expression), the postfix expression 1[p] (that is the subscript operator) and the unary operator - Take into account that when the compiler splits a program into tokens then integer constants are considered as tokens themselves without the minus. minus is a separate token.
So the statement can be rewritten like
x = -( 1[p] );

because a postfix expression has a higher priority than an unary expression.
Let's consider at first the postfix sub-expression 1[p]
According to the C Standard (6.5.2.1 Array subscripting)

2 A postfix expression followed by an expression in square brackets []
  is a subscripted designation of an element of an array object. The
  definition of the subscript operator [] is that E1[E2] is identical to
  (*((E1)+(E2))). Because of the conversion rules that apply to the
  binary + operator, if E1 is an array object (equivalently, a pointer
  to the initial element of an array object) and E2 is an integer,
  E1[E2] designates the E2-th element of E1 (counting from zero).

So this sub-expression evaluates like *( ( 1 ) + ( p ) ) and is the same as *( ( p ) + ( 1 ) ).
Thus the above statement
x = -1[p];

is equivalent to
x = -p[1];

and will yield -3, because the pointer p points to the second element of the array due to the statement
int *p = &array[1];

and then the expression p[1] yields the value of the element after the second element of the array. Then the unary operator - is applied.


text:
Q: Is there a way to get a tailMap or a headMap from an immutable Guava sorted multimap? There are a couple of ways in Guava to create a sorted immutable multiMap. One way is to first create a ListMultiMap with the keys as a tree and then turn it into an immutable multiMap.
Using a ListMultiMap we can have duplicate values for the same key:
ListMultimap<Integer, String> mutableMap = MultimapBuilder.treeKeys().arrayListValues().build();
return ImmutableListMultimap.copyOf(mutableMap);

Using a TreeMap we won't have duplicate values for the same key:
TreeMultimap<Integer, String> mutableMap = TreeMultimap.create(Ordering.natural(), Ordering.arbitrary());
return ImmutableListMultimap.copyOf(mutableMap);

The problem is that in both cases the immutable interface is generic and doesn't give a way to access the keys in a sorted manner so that we could have e.g. tailMap and headMap which are found in Java's NavigationalMap.
Is there a way to have an immutable sorted multi map in Guava that gives access to tailMap and headMap? Or do I need to just manually build an ImmutableSortedMap<Integer, ImmutableList<String>> to get this functionality?

A: You can use your custom ListMultimap with treeKeys() and cast the resulting map — it's safe as guaranteed by Guava's contract:

Uses a naturally-ordered TreeMap to map keys to value collections.
The collections returned by Multimap.keySet(), Multimap.keys(), and Multimap.asMap() will iterate through the keys in sorted order.
For all multimaps generated by the resulting builder, the Multimap.keySet() can be safely cast to a SortedSet, and the Multimap.asMap() can safely be cast to a SortedMap.

Example:
ListMultimap<Integer, String> multimap = MultimapBuilder.treeKeys().arrayListValues().build();
multimap.putAll(ImmutableMultimap.of(1, "one", 1, "uno", 2, "two", 42, "forty-two"));
// {1=[one, uno], 2=[two], 42=[forty-two]}

SortedMap<Integer, List<String>> sortedMap = (SortedMap<Integer, List<String>>) Multimaps.asMap(multimap); // safe, see javadoc
// `.asMap()` directly on `multimap` would give you SortedMap<Integer, Collection<String>>
// SortedMap<Integer, Collection<String>> sortedMap = (SortedMap<Integer, Collection<String>>) multimap.asMap();
SortedMap<Integer, List<String>> tailMap = sortedMap.tailMap(2);
// {2=[two], 42=[forty-two]}


text:
Q: Winsorizing on column with NaN does not change the max value Please note that a similar question was asked a while back but never answered (see Winsorizing does not change the max value).
I am trying to winsorize a column in a dataframe using winsorize from scipy.stats.mstats. If there are no NaN values in the column then the process works correctly.
However, NaN values seem to prevent the process from working on the top (but not the bottom) of the distribution. Regardless of what value I set for nan_policy, the NaN values are set to the maximum value in the distribution. I feel like a must be setting the option incorrectly some how.
Below is an example that can be used to reproduce both correct winsorizing when there are no NaN values and the problem behavior I am experiencing when there NaN values are present. Any help on sorting this out would be appreciated.
#Import
import pandas as pd
import numpy as np
from scipy.stats.mstats import winsorize

# initialise data of lists.
data = {'Name':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'], 'Age':[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0]}

# Create 2 DataFrames
df = pd.DataFrame(data)
df2 = pd.DataFrame(data)

# Replace two values in 2nd DataFrame with np.nan
df2.loc[5,'Age'] = np.nan
df2.loc[8,'Age'] = np.nan

# Winsorize Age in both DataFrames
winsorize(df['Age'], limits=[0.1, 0.1], inplace = True, nan_policy='omit')
winsorize(df2['Age'], limits=[0.1, 0.1], inplace = True, nan_policy='omit')

# Check min and max values of Age in both DataFrames
print('Max/min value of Age from dataframe without NaN values')
print(df['Age'].max())
print(df['Age'].min())

print()

print('Max/min value of Age from dataframe with NaN values')
print(df2['Age'].max())
print(df2['Age'].min())

A: It looks like the nan_policy is being ignored. But winsorization is just clipping, so you can handle this with pandas.
def winsorize_with_pandas(s, limits):
    """
    s : pd.Series
        Series to winsorize
    limits : tuple of float
        Tuple of the percentages to cut on each side of the array,
        with respect to the number of unmasked data, as floats between 0. and 1
    """
    return s.clip(lower=s.quantile(limits[0], interpolation='lower'),
                  upper=s.quantile(1-limits[1], interpolation='higher'))

winsorize_with_pandas(df['Age'], limits=(0.1, 0.1))
0      3.0
1      3.0
2      3.0
3      4.0
4      5.0
5      6.0
6      7.0
7      8.0
8      9.0
9     10.0
10    11.0
11    12.0
12    13.0
13    14.0
14    15.0
15    16.0
16    17.0
17    18.0
18    18.0
19    18.0
Name: Age, dtype: float64

winsorize_with_pandas(df2['Age'], limits=(0.1, 0.1))
0      2.0
1      2.0
2      3.0
3      4.0
4      5.0
5      NaN
6      7.0
7      8.0
8      NaN
9     10.0
10    11.0
11    12.0
12    13.0
13    14.0
14    15.0
15    16.0
16    17.0
17    18.0
18    19.0
19    19.0
Name: Age, dtype: float64

A: You can consider filling the missing values with the mean in the column, then winsorize and select only the original non nan
df2 = pd.DataFrame(data)

# Replace two values in 2nd DataFrame with np.nan
df2.loc[5,'Age'] = np.nan
df2.loc[8,'Age'] = np.nan

# mask of non nan
_m = df2['Age'].notna()
df2.loc[_m, 'Age'] = winsorize(df2['Age'].fillna(df2['Age'].mean()), limits=[0.1, 0.1])[_m]
print(df2['Age'].max())
print(df2['Age'].min())
# 18.0
# 3.0

or the other option by removing the nan before the winsorize.
df2.loc[_m, 'Age'] = winsorize(df2['Age'].loc[_m], limits=[0.1, 0.1])
print(df2['Age'].max())
print(df2['Age'].min())
# 19.0
# 2.0

A: I used the following code snipped as the basis for my problem (Whereas I needed to winsorize on a yearly basis, so i introduced two categories (A,B) in my toy data)
I got the same issue with not replacing the max p99 values because of the NaNs.
import pandas as pd
import numpy as np

# Getting the toy data

# To see all columns and 100 rows
pd.options.display.max_columns = None
pd.set_option('display.max_rows', 100)

df = pd.DataFrame({"Zahl":np.arange(100),"Group":[i for i in "A"*50+"B"*50]})

# Getting NaN Values for first 4 rows

df.loc[0:3,"Zahl"] = np.NaN

# Defining a grouped list of 99/1% percentile values

p99 = df.groupby("Group")["Zahl"].quantile(.9).rename("99%-Quantile")
p1 =  df.groupby("Group")["Zahl"].quantile(.1).rename("1%-Quantile")

# Defining the winsorize function

def winsor(value,p99,p1):

    if (value < p99) & (value > p1):
        return value
    elif (value > p99) & (value > p1):
        return p99
    elif (value < p99) & (value < p1):
        return p1
    else:
        return value

df["New"] = df.apply(lambda row: winsor(row["Zahl"],p99[row["Group"]],p1[row["Group"]]),axis=1)

The good thing of the winsor-function is that it naturally ignores NaN Values!
Hope this Idea helps for your problem


text:
Q: Mongoose and Kue - Node.js - Object passed has no method save I'm using mongoose and Kue for the Flow control. I pass an object retrieved from the database to Kue. When the job get processed, the object hasn't anymore some functions, like .save() & others.
  jobs.process('process', 5, function(job, done) {
        var url = job.data.url;
        var objo = job.data.comp;

        request({uri:url, json:true}, function(err, res, body) {
            objo.meta = body;

            // Here it throw an error that save is note defined
            // TypeError: Object #<Object> has no method 'save'
            objo.save(function(err) {
                if (err)
                    throw err;
                console.log('Saved data for ' + objo.title);
                done();
            });
        });
    });

    var q = db.Entity.find({}).sort('_id', 1).limit(10);

    q.execFind(function(err, docs) {
        docs.forEach(function(objo) {

            jobs.create('process', {
                comp : objo,
                url : 'http://example.com/' + encodeURIComponent(objo.permalink) + '.js'
            }).save();
        })
    });

Thanks in advance

A: This is because the Kue doesn't save the object entirely, it just saves the value of calling JSON.stringify() on it. You'll need to pass the id of the object in, and grab the mongoose representation back out of the database in your worker.


text:
Q: Using Visual Studio Team Services on Microsoft Azure We have web application developed in visual studio 2015. We are using Microsoft SQL server 2008 R2.
So far only single developer was handling the development so source code was in one machine only. Now we are thinking of expanding the team. So If we go for online
Visual Studio Team Services
which is free for 5 users (I guess so), do we need to upload all source code to Azure?
How about the security about the source code?
Is there any possibility of leaking the code or any issues regarding security?
Any one has used this?

A: Yes, Visual Studio Team Services is free for up to five users, and includes unlimited private Git repositories.
Your repositories are private, and you can manage who can view and edit your repositories.  The VSTS team is aggressively committed to security.  Microsoft's own source code is managed in Visual Studio Team Services, and stored in Azure.
But if you are truly worried about bringing your source code outside of your firewall, then you can use Team Foundation Server instead.  This is the on-premises version of Visual Studio Team Services, with the same functionality.  It's also free for up to five users, but you will need to configure and manage it yourself.


text:
Q: FragmentActivity causing ClassNotFoundException I just used Android SDK Manager to update Android SDK Tools to revision 17, and Android Compatiblity to revision 7.  Now, the program I've been running for ages crashes on startup.
Narrowing down the issue, I have created a new blank project, added android-support-v4.jar to the build path, and changed Activity to FragmentActivity and that's all.  Now it crashes.
The error message is:
java.lang.ClassNotFoundException: com.example.test.TestActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.test-2.apk]

The code is:
package com.example.test;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

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

Everything else, including the manifest, is unchanged from the defaults.  Any help is much appreciated!
Edit: Manifest included below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="9" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

A: Turns out it's a problem with Android SDK Tools r17.  I had previously been using the method given in the tutorial at:
http://mobile.tutsplus.com/tutorials/android/android-compatibility-working-with-fragments/
However, this no longer works.  Instead, all I needed to do was right-click on my project in Eclipse and choose Android Tools-->Add Support Library...
Doing this means it is no longer necessary to go to Java Build Path and click "Add External JARs..."
Many thanks to eMich for this solution from: Jar-file issue with ADT r17

A: I had the same issue and none of the answers I found in stackoverflow solved my problem. After hours of several (many) trial-and-error, I solved my problem by configuring build path of my project. In Eclipse, right click the project > Build Path > Configure Build Path..., in Order and Export tab, check Android Private Libraries, click OK. After that, clean up the project and try running again.
I solved this problem by comparing my project with other (newly created) project that could run as expected. I compared each configurations and AndroidManifest.xml of them.
Hope this helps you too :)
UPDATE Other solution: using ANT
I found another way to solve this problem: using ANT. My friend faced the same issue, but fixing the build path didn't solve his problem. I don't know whether it was because we use the different IDE version, different ADT version, or different operating system (I use GNU/Linux). And then, I suggested him to use ANT rather than the IDE's one.
First, setup the project (create build.xml) by executing android update project -p <project-dir> -n <project-name> for each project (including library projects). And then, from the main project's directory, execute ant debug to build, ant installd to install, and run the application.
The strange thing was, once he succeeded with this way, he even can compile by using IDE again, without ANT at all.

A: I assume that fragment activity is listed in the manifest properly? Here's my main FragmentActivity class in the Manifest:
    <activity android:name=".Polling" android:label="@string/app_name"
        android:windowSoftInputMode="stateHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

A: select your project in Package Explorer > Right Click it > Android Tools > Fix PRoject Properties
and also
Try Project > Clean
Then rerun.

A: I got the
 java.lang.NoClassDefFoundError: com.android.example.SupportFragment
    at com.android.example.SupportFragmentActivity.onCreate()

on PopupMenu
SupportFragment extends SherlockFragment implements PopupMenu.OnMenuItemClickListener
...
    @Override
    public boolean onMenuItemClick(android.view.MenuItem item) {
        return onOptionsItemSelected(item);
    }

when trying to make a api 17 app compatible with api 8, the only indication was the logcat error above, so check that all your imported classes are supported if you get this error.

A: Same issue got solved by Doing Build path->Configure Build path->order and export->Check Add private libraries->ok.
Then clean up the project.
Done a big problem solved.

A: I also got the same issue, and resolved it by the below way.
If because of some reason you have UNCHECKED to the private libraries from build path, so just add Androidv-4 jar in build path and enable(check) it in "Order and Export" tab

A: *

*Remove anything lib about v7 or v4. Move your Android project,  Alt+Enter, click  android, look  is lib:  make sure there is nothing about v7 or v4 lib

*add v4 lib

*clean project

*run again

if you remove v7,  will be error with  styles... you may look this


text:
Q: SpriteKit game fails to load next day on iPhone I have a game that works great when my iPhone is connected to the SK simulator and for about a day after installing the app from the computer, but after about a day if I try to open it a white screen displays and the app closes immediately before my main menu scene ever displays. Once the app crashes once, it cannot be reopened again after that. I have an iPhone 6 using iOS 10.3.3. It always works the day of installation and then never works the next day, and sometimes will even display my game over scene only in the "task manager" view after double tapping the home button (when I click the app from that view it just takes me back to my home screen).
This is my UIViewController Class:
class GameViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    let scene = MainMenuScene(size: self.view.bounds.size)
    let skView = view as! SKView
    scene.scaleMode = .resizeFill
    skView.presentScene(scene)
}

}
I also get these error messages overtime I build my app on xCode:
2017-08-24 10:56:54.517973-0500 Laser Space Man 3000[581:110941] [DYMTLInitPlatform] platform initialization successful
2017-08-24 10:56:54.672835-0500 Laser Space Man 3000[581:110775] Metal GPU Frame Capture Enabled
2017-08-24 10:56:54.673802-0500 Laser Space Man 3000[581:110775] Metal API Validation Enabled
2017-08-24 10:56:54.737885-0500 Laser Space Man 3000[581:110775] libMobileGestalt MobileGestaltSupport.m:153: pid 581 (Laser Space Man 3000) does not have sandbox access for frZQaeyWLUvLjeuEK43hmg and IS NOT appropriately entitled
2017-08-24 10:56:54.737987-0500 Laser Space Man 3000[581:110775] libMobileGestalt MobileGestalt.c:550: no access to InverseDeviceID (see )
I use a TextureAtlas in my main menu scene, too. (IDK if that could be problematic)
Any ideas on what's going on? Thank you!

A: This appears to be a bug with certain frameworks, or even just UIKit itself. The main error here is the one that says libMobileGestalt no access etc and the does not have sandbox
It may also be an issue with your provisioning profile, are you using developer, local team, ??

*

*What frameworks are you using? (they may need to be reconfigured, like cordova, ionic, or admob)

*Do you have a developer account? Are you using that as your provisioning profile?

*Are you asking to display a content that requires permission, before getting the user's permission?

*In app purchases?

There is no clear solution here without more information. My best guess is to start a new project, copy everything over, restart your iphone / relog iCloud, and get a new provisioning profile / try changing your signing.
Here are some other threads that may be useful to supplement this answer:
MobileGestalt no access to InverseDeviceID
https://forums.developer.apple.com/thread/72286

A: add following key in info.plist
<key>aps-environment</key>
<string>development</string>

and try again.


text:
Q: Dynamic HTML Menu? I want my website to consist purely of HTML, CSS and JS, no Php.
I'm used to doing this in php, is there any way to do this in html?:
<?php include 'menu.php' ?>

A: Nope.  Can't do it purely in HTML.
If you wanted to go old-school, you could setup some server-side includes:
<!--#include file="menu.html" -->

Because you have shared external JS files, that's one avenue to avoid repeating yourself.

A: I've done something similar with jQuery using the following syntax:
$(function(){
    $('#header-region').load('menu.html');
});


text:
Q: How to unwrap, extract, constraint violations exceptions in a list of constraint violations? I'm not exactly sure on how to ask this question but I have a customer class on which i created a custom validator with an annotation and implementing the ConstraintValidator in the validator class. It works perfectly, but obviously when thrown, it is wrapped pretty deep into other exceptions. But getting the rootcause I get this:
javax.validation.ConstraintViolationException: Validation failed for classes [vidleytake4.data.entity.Customer] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='Customer must be 18 years old to become a member', propertyPath=, rootBeanClass=class se.soccan.vidleytake4.data.entity.Customer, messageTemplate='Customer must be 18 years old to become a member'}
]

Of course I want to display that interpolated message to the user through the interface, but that kind of starts with med being able to get it out of that list a few different approaches have not gotten me any closer, 20-or-so google sessions haven't helped either so I'm open for suggestions... I looked into Exceptionhandlers, not understanding them really, and trying to check if my cought TransactionSystemException's root cause is an instance of ConstraintViolationExceotion by using NestedExceptionUtils.getRootcause(e)no luck...

A: TransactionSystemException should contain the root cause: TransactionSystemException.getRootCause()
If it's not the root cause, you may need to iterate over the causes.
List<String> violationMessages;
for (Exception exception : exceptionList) {
    if (exception instanceof ConstraintViolationException) {
        ConstraintViolationException constraintEx = ((ConstraintViolationException) exception);
        Set<ConstraintViolation<?>> violations = constraintEx.getConstraintViolations();
        // do something with violations, for example:
        violationMessages = violations.stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        break;
    }
}

Helpers: ExceptionUtils.getThrowableList(ex)


text:
Q: React + Redux: Separating the presentation from the data I am building a weather app with React & Redux. I've decided to venture into uncharted waters as a noob to React & Redux. I'm splitting things up into presentational components and their respective container that will handle the data. I'm having some problems wrapping my head around this though. It might come down to how I'm trying to do it I'm just really unsure.
Right now I have SearchBar, CurrentWeather, & Forecast components and an AppContainer that I'm trying to integrate those components into. I have the SearchBar component integrated into the AppContainer so far and it is working with no problems. Here is where I am getting confused. So I have provided the needed actions and components to the container and the container has been connected so when the user does a search the api call will be made and the state will update through the reducers.
That data should be available through mapStateToProps now correct?
How can I go about using that data after the user has performed the action but have it not be used upon the initial render? If AppContainer is rendering these three components I will obviously be passing props to them so they render and function as they are expected to. I'm thinking this is where a lifecycle could be used I'm just unsure of which or how to use them. My code for the AppContainer, SearcBar, & CurrentWeather are below. CurrentWeather & Forecast are nearly identical (only providing different data from different endpoints for the api) so I did not provide it. I also didn't provide the actions or reducers because I know they work fine before I decided to attempt this refactor. Maybe I need more than one container to pull this off? Any advice or direction would be greatly appreciated, thanks all and have a good night.
** Do have a side question: on _weatherSearch I have event.preventDefault(); because the SearchBar is a form element. Do I even need to provide this? If event is not what is being passed but the term I think no. The event is being used as seen below in the form element of SearchBar:
onSubmit={event => getWeather(event.target.value)}
App Container:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchCurrentWeather, fetchForecast } from '../actions/actions';

import SearchBar from '../components/SearchBar';
import CurrentWeather from '../components/CurrentWeather';

class AppContainer extends Component {

  _weatherSearch(term) {
    event.preventDefault();
    // Here is where we go to fetch weather data.
    this.props.fetchCurrentWeather(term);
    this.props.fetchForecast(term);
    }

  render() {
    const getWeather = term => {this._weatherSearch(term);};
    return (

        <SearchBar getWeather={getWeather}/>
        <CurrentWeather />

    );
  }
}

const mapStateToProps = ({ current, forecast }) => {
  return {
    current,
    forecast
  }
}

export default connect(mapStateToProps,
  { fetchCurrentWeather, fetchForecast })(AppContainer);

SearchBar:
import React from 'react';

const SearchBar = ({ getWeather }) => {
  return(
    <form className='input-group' onSubmit={event => getWeather(event.target.value)}>
      <input
      className='form-control'
      placeholder='Search a US City' />

        <button className='btn btn-secondary' type='submit'>Submit</button>

    </form>
  );
}

export default SearchBar;

CurrentWeather: *NOTE: I have not removed any of the logic or data processing from CurrentWeather yet so it has not been refactored to a presentational only component yet.
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {unitConverter} from '../conversions/conversions_2.0';

export class CurrentWeather extends Component {
    _renderCurrentWeather(cityData) {
        const name = cityData.name;
        const {temp, pressure, humidity} = cityData.main;
        const {speed, deg} = cityData.wind;
        const {sunrise, sunset} = cityData.sys;
        return (

                {unitConverter.toFarenheit(temp)} F
                {unitConverter.toInchesHG(pressure)}"
                {humidity}%
                {unitConverter.toMPH(speed)}mph {unitConverter.toCardinal(deg)}

        );
    }

    render() {
        let currentWeatherData = [];
        if (this.props.current) {
            currentWeatherData = this.props.current.map(this._renderCurrentWeather);
        }
        return (

                        Temperature
                        Pressure
                        Humidity
                        Wind

                    {currentWeatherData}

        );
    }
}

function mapStateToProps({current}) {
    return {current};
}

export default connect(mapStateToProps)(CurrentWeather);

A: Your render function is very dynamic. You can omit anything you like:
class AppContainer extends Component {

  _weatherSearch(term) {
    // event.preventDefault(); We can't do this because we don't have an event here...

    this.props.fetchCurrentWeather(term);
    this.props.fetchForecast(term);
    }

  render() {
    const getWeather = term => { this._weatherSearch(term); };
    return (

        <SearchBar getWeather={getWeather}/>
        { Boolean(this.props.current) && <CurrentWeather /> }

    );
  }
}

const mapStateToProps = ({ current }) => ({ current });

export default connect(mapStateToProps,
  { fetchCurrentWeather, fetchForecast })(AppContainer);

This is how you deal with missing data. You just either show nothing, or a message to search first, or if it's loading,you can show a spinner or throbber.
The technique used above to hide CurrentWeather is to pass a Boolean to React if we're wanting to hide the component. React ignores true, false, null and undefined.
Note that it's a good idea to only ever pass data in mapStateToProps that you'll actually be using inside the component itself. In your code you're passing current and forecast but you don't use them.
Redux will rerender when any of the mapStateToProps, mapDispatchToProps or props data changes. By returning data you'll never use you instruct Redux to rerender when it's not necessary.

A: I'm a react-redux noob myself :-) and I've come across similar issues.
As far as I can tell, the container/presentational separation you've made looks good, but you can go even a step further and separate the container's fetching and mounting.
The solution I'm referring to is what people variously call "higher-order components" and "wrapper components": (the code below isn't tested - it's just for illustration purposes)
import {connect} from blah;

const AppWrap = (Wrapped) => {
  class AppWrapper extends Component {
    constructor(props) {
      super(props);
      this.state = {foo: false};
    }
    componentWillMount() {
      this.props.actions.fooAction()
      .then(() => this.setState({foo: false}));
    }
    render() {
      return (<Wrapped {...this.props} foo={this.state.foo}/>);
    }
  }

  function mapState(state) { blah }
  function mapDispatch(dispatch) { blah }

  return connect(mapState, mapDispatch)(AppWrapper);
}

export default AppWrap;

Notice the = (Wrapped) => { part at the top. That is what's doing the actual "wrapping", and the argument can be named anything so long as you refer to it in the render hook.
Now inside your AppContainer, you get a this.props.foo which acts as a flag telling you that fooAction() has completed, and you can use it to render your presentational components accordingly. Until fooAction completes, you can be sure that the foo passed into AppContainer will be false.
To put what I just said into code, your AppContainer might look something like this:
import AppWrapper from './AppWrapper';

class AppContainer extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (!this.props.foo) ?
bar
 : (

        <SearchBar blah/>
        <CurrentWeather blah/>

    );
  }
}

export default AppWrapper(AppContainer);

The benefit of using a wrapper component like this is that

*

*you can take more control over how and when exactly the data gets rendered

*account for "loading" mechanisms and logic

*avoid quirky problems like having to make dispatches within componentWillMount hooks and having to deal with the consequences.

Take a look at this blog post for more information about HoCs: https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750


text:
Q: C# UpdateResource function fails I'm coding a simple application in C# that allows to add a resource to a .EXE file chosen by me.
The problem is that the call to UpdateResource function fails with the error 6, that according to MSDN is InvalidHandle(despite it seems that the call to BeginUpdateResource is successful) (The code is copied and pasted from a bigger file, so if some { lacks, don't care, the code compiles, but doesn't work as expected)
public partial class Form1 : Form
{
    [DllImport("kernel32.dll", SetLastError=true)]
    static extern bool UpdateResource(IntPtr hUpdate, string lpType, string lpName, ushort wLanguage, IntPtr lpData, uint cbData);

    [DllImport("kernel32.dll",SetLastError=true)]
    static extern IntPtr BeginUpdateResource(string pFileName, [MarshalAs(UnmanagedType.Bool)]bool bDeleteExistingResources);

    [DllImport("kernel32.dll",SetLastError=true)]
    static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);

    static unsafe void  SetRes(string path)
    {
        IntPtr beginPointer = BeginUpdateResource(path, false);

        if (beginPointer != null)
        {
            MessageBox.Show("Begin works");//This is shown

            ushort id = (ushort)Language.MakeLanguageID();
            string newMessage = "hello world!";
            Byte[] bytes = new ASCIIEncoding().GetBytes(newMessage);
            GCHandle bHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            IntPtr ptr = bHandle.AddrOfPinnedObject();

            bool update = UpdateResource(beginPointer,"FILE", "Test", id,ptr, (uint)bytes.Length);

            if (update == true)
            {
                MessageBox.Show("Update");
                EndUpdateResource(beginPointer, false);

            }
            else
            {
                MessageBox.Show(Marshal.GetLastWin32Error().ToString()); //It gives error 6
            }
        }
    }


text:
Q: Xamarin.Essentials WebAuthenticator server side implementation redirects to login page instead of 401? I'm trying to make sense of the WebAuthenticator documentation and sample. The goal for me is to have a server based social login in the app (oauth 2).

*

*ASP.NET core server back end

*Sample.Server.WebAuthenticator
When using this implementation, it must be assumed that I in another Controller can use the [Authorize] attribute to require authentication. But when I do that what happens is that it tries to redirect to /Account/Login which in turn doesn't exist, giving a 404.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Sample.Server.WebAuthenticator.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class SampleController : ControllerBase
    {
        // GET: api/Sample
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

So trying the concept from the Android emulator results in the api controller url "not being found" aka 404, instead of some kind of authentication required like 401.

To test this, download the Xamarin essentials sample from above. Add a SampleController using the API read/write template. Build the Sample.Server.WebAuthenticator, set it as the only startup project and debug it.
Make sure you can access /api/sample and receive a json result.
Next add [Authorize] to the SampleController, and debug it.
It will redirect to a missing login page.
I'm a little confused that the server sample doesn't work a little more like the Jwt article from wildermuth
What is the correct way to notify the app that it should authenticate?

A: The sample is not intended to authenticate against the server, even thou it looks like it. The intention is to authenticate against for example google. Then the token can be used in api calls to google. Nothing else. Even if a Jwt authentication is added, the token can't be used to an own web API.
So in order to have social authentication for an own web API, a solution able to federate, such as IdentityServer4, has to be used. ID4 would take the place of the sample server, and it would after auth against the social provider issue a token of it's own, that can be used by the app to authenticate to the own web API.

A: Authenticating Microsoft accounts in Sample server is returning the following error when routed to /signin-microsoft:
Exception: OAuth token endpoint failure: Status: BadRequest;Headers: Cache-Control: no-store, no-cache

A: You need to take out the [Authorize] attribute from the SampleController controller class, or add the [AllowAnonymous] attribute to allow it to be accessible from the app without the need to authenticate through the login page first.


text:
Q: Height div and image i have a problem with a div height. I have an image in a left div "image_view" and the height of this div is dinamically based on image.
On the right side I have a div with some informations. This div must have the same height of the image_view div. how can I do it?
This is my code now.

    <img src="<?php echo base_url().'upload/images/'.$nome_immagine; ?>" />

<div id="info_image" style="height:<?php echo $altezza.'px'; ?>">
   content of this div

Thanks

A: You can do like this:
$('#info_image').css("height", $("#image_view").height());

A: Alternatively you can get the image height with getimagesize() and assign it to the info_image element.
<?php
$imagePath = base_url().'upload/images/'.$nome_immagine;
$size = getimagesize($imagePath);
?>

    <img src="<?php echo $imagePath; ?>" />

<div id="info_image" style="height:<?php echo $size[1].'px'; ?>">
   content of this div

A: Solution without JavaScript
You can restructure your HTML, to force the
's the same height as the image:
HTML

           info here

CSS
#image-info {
    width: 600px;
    background:#eeeeee;
}

#info {
    float: left;
    width: 200px;
    background: #eee;
}

#image {
   float: left;
   background: #f0e;
   width: 400px;
}

#image img {
   height: 500px;
}

This will force the #image-info-area to become same height as the image, and you will be able style the
's anyway you want.
Here's a fiddle

A: You can use jQuery's height() function:
$('#info_image').height($('#image_view').height());

jsFiddle here


text:
Q: Can Wix3 check if a service exists? Does Wix 3 have a built in way to just check whether a service exists? The closest guess I can come up with is using ServiceConfig and trying to detect a failure.

A: The AppSecInc. Community MSI Extensions has a Service_Exists custom action.
http://msiext.codeplex.com
Online Documentation:
http://code.dblock.org/Source/msiext/1.2/Docs/_custom_actions_2_system_tools_2_service_impl_8h.html#a6fdcddc7b04a310a368c08726d3be6b3
<Binary Id="SystemTools" SourceFile="$(var.BinDir)\SystemTools.dll" />

<CustomAction Id="SetServiceName" Property="SERVICE_NAME" Value="Service1" />
<CustomAction Id="ServiceExists" BinaryKey="SystemTools" DllEntry="Service_Exists" Execute="immediate" Return="check" />

<InstallExecuteSequence>
     <Custom Action="SetServiceName" After="InstallFiles">NOT Installed</Custom>
     <Custom Action="ServiceExists" After="SetServiceName">NOT Installed</Custom>
</InstallExecuteSequence>

SERVICE_EXISTS is set to "1" if service exists, "0" otherwise.


text:
Q: Python: Printing Tasks for the logged in user Please, assist as I am a newbie with this.
I need to have the tasks printed for the user that is logged in.

*

*Add the following functionality when the user selects 'vm' to view all the
tasks assigned to them:

*Display all tasks in a manner that is easy to read. Make sure that
each task is displayed with a corresponding number which can be
used to identify the task.

*Allow the user to select either a specific task by entering a number
or input '-1' to return to the main menu.

*If the user selects a specific task, they should be able to choose to
either mark the task as complete or edit the task. If the user
chooses to mark a task as complete, the 'Yes'/'No' value that
describes whether the task has been completed or not should be
changed to 'Yes'. When the user chooses to edit a task, the
username of the person to whom the task is assigned or the due
date of the task can be edited. The task can only be edited if it has
not yet been completed.

user.txt
admin, adm1n
Peter, Peter
Amy, A3y

task.txt
Peter, Peter has a new task, Testing the task manager, 20/09/2022,Yes
Amy, First new task, Checking the first new task, 21/09/2022,Yes
admin, Admin to assign tasks, Admin is the main user that has to assign all tasks, 29/09/2022, No
Peter, Find Wally, Find Wally somewhere behind the grave yard, 31/09/2022, No

My code thus far:
elif menu == 'vm':
        pass
        def view_more():
            username = new_task_username
            num_task = 0
            with open('tasks.txt', 'r') as f:
                view_more = f.read()
            for row in view_more:
                field = row.strip().split(",")
                num_task += 1
                if username == field[0]:
                    print("Task Number: " + str(num_task) + "\nUsername: " + field[0] + "\nTitle: " + field[1] + "\nDescription: " + field[2] + "\nDue Date: " + field[3] + "\nCompleted: " + field[4] + "\n")

            editTask = input("\nWould you like to edit a task? (Edit) or return to the menu? (-1)\n")

            def _edit_file(taskComplete):
                userTask = taskFile[taskNum].strip().split(",")
                new_state = taskFile[taskNum].strip().replace(userTask[4], taskComplete)
                print(new_state)
                updated_string = view_more.replace(taskFile[taskNum].strip(), new_state)
                with open('tasks.txt', 'w') as f:
                    f.write(updated_string)

            if editTask == "Edit":
                taskNum = int(input("Please enter the Task number?\n"))
                taskNum = taskNum - 1
                with open('tasks.txt', 'r') as file:
                    taskFile = file.readlines()
                for line in taskFile:
                    print(taskFile[taskNum] + "\n")
                    break

                taskComplete = input("Has this task been completed?\n")
                if taskComplete == "Yes":
                    _edit_file(taskComplete)

                elif taskComplete == "No":
                    _edit_file(taskComplete)

                elif editTask == "-1":
                    menu()

        view_more()

It does not print:
if username == field[0]:
                    print("Task Number: " + str(num_task) + "\nUsername: " + field[0] + "\nTitle: " + field[1] + "\nDescription: " + field[2] + "\nDue Date: " + field[3] + "\nCompleted: " + field[4] + "\n")
    ```


text:
Q: Prove that $\mathbb E[\sup_{s\in [0,t]}M_s^2]\leq 4\mathbb E M_t^2$. Let $(M_t)$ a continuous martingale. Prove that $$\mathbb E\left[\sup_{s\in [0,t]}M_s^2\right]\leq 4\mathbb E[ M_t^2].$$
I already proved that $$\mathbb P\left\{\sup_{s\in [0,t]}|M_s|\geq y\right\}\leq \frac{\mathbb E|M_t|}{y},$$
and I know that $$\mathbb E Y^2=\int_0^\infty 2y\mathbb P\{Y>y\}d y,$$
when $Y\geq 0$ a.s. I tried to use this last formula for $Y=|M_t|$ but it's not conclusif. How can I conclude ?

A: You should use a finer version of $$\mathbb P\left\{\sup_{s\in [0,t]}|M_s|\geq y\right\}\leq \frac{\mathbb E|M_t|}{y}$$
which is
 $$\mathbb P\left\{\sup_{s\in [0,t]}|M_s|\geq y\right\}\leq \frac{\mathbb E(|M_t|1_{\{\sup_{s\in [0,t]}|M_s|\geq y\}})}{y}$$
By integrating both sides with respect to $y$ , we have
$$\int_{0}^{\infty}{y\mathbb P\left\{\sup_{s\in [0,t]}|M_s|\geq y\right\}dy}\leq\int_{0}^{\infty}{\mathbb E(|M_t|1_{\{\sup_{s\in [0,t]}|M_s|\geq y\}})}dy$$
Using Fubini theorem on both sides, we have
 $$\mathbb E\left(\frac{\left(\sup_{s\in [0,t]}|M_s|\right)^2}{2}\right) \leq E\left(|M_t|\sup_{s\in [0,t]}|M_s|\right) $$
or
$$\mathbb E\left({\left(\sup_{s\in [0,t]}|M_s|\right)^2}\right)^2 \leq 4 E\left(|M_t|\sup_{s\in [0,t]}|M_s|\right)^2 $$
Using Cauchy-Schwarz inequality, and the fact that $\left(\sup_{s\in [0,t]}|M_s|\right)^2=\sup_{s\in [0,t]}|M_s|^2$ a.s., we conclude that
$$E\left(|M_t|\sup_{s\in [0,t]}|M_s|\right) \leq \sqrt{E\left(M_t^2\right)E\left(\left(\sup_{s\in [0,t]}|M_s|\right)^2\right)} $$
and finally,
$$\mathbb E\left[\sup_{s\in [0,t]}M_s^2\right]\leq 4\mathbb E[ M_t^2]$$


text:
Q: does Silverlight 4 support wshttpbinding? Now that the stable release is out, could someone please confirm if SL4 supports wsHttpBinding?
and also any feedback on netTcpBinding?

A: No it does not - right now, it supports basicHttpBinding (as before) and netTcpBinding (new in SL4).


text:
Q: How to draw a triangle with own texture on each corner? Basically, i want to give 3 textures for each corner of a triangle, and interpolate from one texture to another, just like the colors would be interpolated with glColor() on the corners.
Edit: Since this doesnt seem to be possible via texture combiners, i am willing to do it with shaders.
This is the fragment shader code that i have now:
vec4 c = gl_Color;
gl_FragColor = texture2D(Texture0, TexCoord0)*c.r+texture2D(Texture1, TexCoord1)*c.g+texture2D(Texture2, TexCoord2)*c.b;

Im using the glColor(); to push colors (1,0,0), (0,1,0), (0,0,1) to the corners of each triangle, and then i read the color to see how much which texture i need to blend accordingly.
Now the problem is that i cant use colors on my vertices anymore, so im asking, what is the best approach for telling my fragment shader how to blend the textures + being able to use glColor() on each corner of the triangle to apply some coloring?
Edit2: i managed to get it work by sending a 3d texcoord that tells the blending ratios, but is this the best approach? i would like to hear more ideas on this.

A: I don't think this is possible without using shaders. In your OpenGl code, I don't see anyway OpenGl could know which texture to affect to each corner. That would require a vertex property (other than color or texture coordinates), which is not possible without shaders.
However, maybe it can be possible with two textures, by using alpha blending (picking alpha value from the vertex color) on the second texture. but I'm not sure.


text:
Q: How to format an array with random numbers that has more than 1 indexes of 0 Java I am trying to make displayArray look like an array, but I can't figure it out.
It prints out this:
[7, 8, 9 , 0, 9, 0, ]

Instead of this:
[7, 8, 9, 0, 9, 0]

I know that the problem is because of
System.out.print(b + ", ");

but I don't know what else to do.
import java.util.*;
public class changeUp
{
    public static void main(String[] args)
    {
        int[] arr = new int[6];
        populateArray(arr);
        displayArray(arr);
    }
    private static void populateArray(int[] arr)
    {
        Random r = new Random();
        Scanner console = new Scanner(System.in);
        for(int i = 0; i < 6; i++){
            int ranInd = r.nextInt(6);
            System.out.print("Enter a value: ");
            arr[ranInd] = console.nextInt();
        }
    }
    private static void displayArray(int[] arr)
    {
        System.out.print("[");
        for(int b : arr)
        {
            System.out.print(b + ",  ");
        }
        System.out.println("]");
    }
}

A: You print ", " on the last iteration of displayArray() for loop.
To avoid this add index check:
private static void displayArray(int[] arr)
{
    System.out.print("[");
    for(int i = 0; i < arr.length; i++)
    {
        int b = arr[i];
        System.out.print(b);

        if(i < arr.length - 1) {
            System.out.print(", ");
        }
    }
    System.out.println("]");
}

Output:
Enter a value: 4
Enter a value: 4
Enter a value: 4
Enter a value: 4
Enter a value: 4
Enter a value: 4
[4, 4, 0, 4, 0, 4]


text:
Q: Getting the first occurence of an element, independent of parents I want to write a CSS selector which matches the first occurrence of an element with class "icon". The elements haven't got a common parent (as seen below), so the :first-child or :first-of-type pseudos didn't work for me.
The HTML markup isn't very good, but its specification, so it's not possible to change it.
Is there any CSS only solution, to match the first occurence of an element?

Category 1

..

Category 1

..

Category 1

..

OR

Category 1

..

Category 1

..

OR

Category 1

..

A: No, there isn't. You'd have to find out which of the parent div elements have .icon children in the first place, which you can't do with CSS selectors. The jQuery selector .icon:first does exactly what you want, but :first is not part of CSS.

A: I'd say you'll have to use some sort of javascript to do this. I've actually just done this on a project of my own.
jQuery:
$('.Icon:first').addClass('myclass'); // or .css('attribute', 'value') depending on what you want.

The above script will at all times ONLY affect the first match of .Icon it finds.
I know it's not CSS, but you can't really do what you want to achieve by only using CSS.


text:
Q: How to pass a variable into a function and return it modified? I've been learning c# for about three weeks now so please bear with me. I got through some online courses with no problem but I've come upon what I think is a very basic, but very real barrier to my understanding of how to use the code to actually write programs.
int inputOutput = 1;
Console.WriteLine(inputOutput); //Prints 1
static void IncrementTest(int inputInput, out int intputOutput)
{
    intputOutput = inputInput++;
}
IncrementTest(inputOutput, out inputOutput);
Console.WriteLine(inputOutput); //Also prints 1?

If using out parameters is not the way forward, what is?

A: The out keyword is for parameters that are used for output only. If you want to use a parameter for input and output then you use ref. When a parameter is unadorned, it is considered input-only, e.g.
public static void Main()
{
    var number = 1;
    Console.WriteLine("Outside Method before: " + number);
    Method(number);
    Console.WriteLine("Outside Method after: " + number);
}

public static void Method(int inputOnly)
{
    Console.WriteLine("Inside Method before: " + inputOnly);
    inputOnly++;
    Console.WriteLine("Inside Method after: " + inputOnly);
}

Output:

Outside Method before: 1
Inside Method before: 1
Inside Method after: 2
Outside Method after: 1

When a parameter is declared out, it is considered output-only. This code:
public static void Main()
{
    var number = 1;
    Console.WriteLine("Outside Method before: " + number);
    Method(out number);
    Console.WriteLine("Outside Method after: " + number);
}

public static void Method(out int outputOnly)
{
    Console.WriteLine("Inside Method before: " + outputOnly);
    outputOnly++;
    Console.WriteLine("Inside Method after: " + outputOnly);
}

will not compile because any existing value for an out parameter is ignored and it is considered uninitialised at the beginning of the method. You MUST assign a value to an out parameter before using it and, if you don't use it, before the end of the method.
public static void Main()
{
    var number = 1;
    Console.WriteLine("Outside Method before: " + number);
    Method(out number);
    Console.WriteLine("Outside Method after: " + number);
}

public static void Method(out int outputOnly)
{
    outputOnly = 10;
    Console.WriteLine("Inside Method before: " + outputOnly);
    outputOnly++;
    Console.WriteLine("Inside Method after: " + outputOnly);
}

Output:

Outside Method before: 1
Inside Method before: 10
Inside Method after: 11
Outside Method after: 11

When a parameter is declared ref, it is considered input-output, e.g.
public static void Main()
{
    var number = 1;
    Console.WriteLine("Outside Method before: " + number);
    Method(ref number);
    Console.WriteLine("Outside Method after: " + number);
}

public static void Method(ref int inputOutput)
{
    Console.WriteLine("Inside Method before: " + inputOutput);
    inputOutput++;
    Console.WriteLine("Inside Method after: " + inputOutput);
}

Output:

Outside Method before: 1
Inside Method before: 1
Inside Method after: 2
Outside Method after: 2

A: int  is a Value types
You can use the ref keywords
But I recommend that you deepen the difference between Value types to Reference types.


text:
Q: vehicle finance calculation php I am trying to build a vehicle finance calculator, i would like to improve the code by displaying each month principle payment and each months interest, i have the following code
$interest = 10 /100/12;//10 is the interest rate
$months = 60; //60 months term
$loan = 12000;// total loan amount

$monthly_payment = $loan * $interest / (1-(pow((1+$interest),-$months)));
$total_payable = $monthly_payment * $months;
$total_interest = ($total_payable - $loan);

echo "Monthly Payment = " . $monthly_payment. '
';
echo "Total Payable = " . $total_payable . '
';
echo "Total Interest = " . $total_interest . '
';
echo "Monthly Interest = " . ($total_interest / $months) . '
';

to do what i want i need to use the formula on this page
http://www.ifsautoloans.com/car-loan-interest/
this is the formula
$100 [$100 = 10%/12 months * $12,000). Consequently, with the first payment, you will pay down your principal by $154.96 [$154.96 = $254.96 – $100].
i just don't understand it, thank you for any help
what i want to do is the same as this link
http://www.thecalculatorsite.com/finance/calculators/carloancalculator.php

A: I'm giving you quick PHP with a form and output table for monthly view without any styling. The variables are self-explanatory.
<!DOCTYPE html>

    <title>Loan Calculator</title>

Enter your car loan Details...

        <form id="calculate-loan" method="post" action="">

                        Currency:

                            <select id="currency" name="currency">
                                <option>$</option>
                                <option>₹</option>
                            </select>

                        Vehicle Value:
                        <input type="number" id="vehicle_value" name="vehicle_value">

                        Interest Rate:
                        <input type="number" min="1" max="100" id="interest_rate" name="interest_rate">

                        Months:
                        <input type="number" step="1" id="months" name="months">

                        <input type="submit" name="submit" value="Submit">

        </form>

    <?php
    if(isset($_POST['submit'])) {
    ?>

Vehicle Loan Repayments By Month

        <?php
            $balance = (float) $_POST['vehicle_value'];
            $monthly_payment = (($_POST['interest_rate'] /(100 * 12)) * $_POST['vehicle_value']) / (1 - pow(1 + $_POST['interest_rate'] / 1200,  (-$_POST['months'])));
        ?>

            Loan Payments: <?php echo $_POST['currency'].number_format($monthly_payment * $_POST['months'], 2); ?>

            Monthly Payment: <?php echo $_POST['currency'].number_format($monthly_payment, 2); ?>

            Total Interest: <?php echo $_POST['currency'].number_format($monthly_payment * $_POST['months'] - $balance, 2); ?>

                    Month
                    Balance
                    Principal
                    Interest
                    Payment

                <?php
                for($month = 0; $month < (int)$_POST['months']; $month++) {
                    $interest = $balance * $_POST['interest_rate'] / 1200;
                    $principal = $monthly_payment - $interest;
                ?>

                    <?php echo $month + 1 ?>
                    <?php echo $_POST['currency']. number_format($balance, 2) ?>
                    <?php echo $_POST['currency']. number_format($principal, 2) ?>
                    <?php echo $_POST['currency']. number_format($interest, 2) ?>
                    <?php echo $_POST['currency']. number_format($monthly_payment, 2) ?>

                <?php
                    $balance -= $principal;
                }
                ?>

    <?php } ?>


text:
Q: vba/vb6 prevent PowerPoint screenupdating I'm using the code here for preventing PPT screen updating
It works well under Win7 and office2013 but seems not to apply to Win10 and Office2016. I have of course added the case "16"
Any idea?


text:
Q: Java get property value by property name Is it possible in Java to get class property value by its name?
for example, i have class like
public class Test {
    private String field;
    public String getField() {...}
    public void setField() {...}
}

and another class with Map
public class Main {
    private static final Map<String, Long> map = new HashMap<String, Long>();
    static {
        map.put("field", new Long(1));
    }
    public void doSth() {
    Set<String> keys = map.keySet();
    Test t = new Test();
    for (String key : keys) {
    //t.getPropertyValueByName(key); ?
    }
    }

A: Yes. You can replace the commented out line with t.getClass().getField(map.get(key)).get(t). which will retrieve the value of the field on t.

A: You can use some of the Libraries that offer property-based access. I think the most known and used is beanutils. You can find one good example of the beanutils "in action" here.
Some sample code:
A someBean = new A();

// access properties as Map
Map<String, Object> properties = BeanUtils.describe(someBean);
properties.set("name","Fred");
BeanUtils.populate(someBean, properties);

// access individual properties
String oldname = BeanUtils.getProperty(someBean,"name");
BeanUtils.setProperty(someBean,"name","Barny");

A: bjc2406's answer works fine as long as the field(s) in question are accessible:

t.getClass().getField(map.get(key)).get(t)

If you can't reasonably make it public, reflection and other field access APIs should get the job done: How do I read a private field in Java?

A: Apart from
String org.apache.commons.beanutils.BeanUtils.getProperty(object, propertyName)
there is Object org.apache.commons.beanutils.PropertyUtils#getProperty(object, propertyName)  which does not turn value into String.
This might be helpful to preserve integer, decimal and boolean types.

A: The question is how often do the properties change? Are the constants, or will it depend on the situation?
If it is the latter case, which it often is, you want the properties in an external file. The standard java properties api is great for that: http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html.
If you use a framework like spring, it will also come with standard ways to deal with properties. Look in their documentation.

A: This solution work :
// access individual properties
String oldname = BeanUtils.getProperty(someBean,"name");
BeanUtils.setProperty(someBean,"name","Barny");

This solution variante preserve object's type
Object a = BeanUtilsBean.getInstance().getPropertyUtils().getNestedProperty(someBean, "name");
if(a instanceof Boolean) {
...
}

A: You can also go for Properties.java class : http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
It does same job.


text:
Q: ffmpeg with libfdk_aac: AAC-HE-V2 profile doesn't work for mono sound? Whenever I use ffmpeg with libfdk_aac to convert a piece of audio to AAC, I noticed the aac_he_v2 profile does not work if the source audio is mono. For example:
ffmpeg -i mono.wav -c:a libfdk_aac -profile:a aac_he_v2 output.m4a

Gives an error:

Unable to initialize the encoder: SBR library initialization error
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height

I can overcome this by adding the -ac 2 option to force stereo. However it seems strange to me that this profile demands the audio to be stereo, whereas it works fine without specifying the AAC-HE-V2 profile. Maybe that's my lack of understanding how this encoder or profile works, but is it supposed to be like that?
Furthermore I assume that by specifying -ac 2 ffmpeg will just 'fake' stereo by copying the single audio stream to an identical left and right channel?

A: HE-AAC v2 is HE-AAC with Parametric Stereo - it's not meant for monaural signals.


text:
Q: Unexpected behavior with eq operator in a perl while loop. while loop does not stop While loop below does not stop after scalar $quit clearly does not equal 'j'.
Why won't it stop?
#!/usr/bin/perl -w

use strict;
my $quit = 'j';

while ($quit eq 'j') {

    print "Enter whatever value you want and I bet I still continue.\n";
    chomp (my $quit = <STDIN>);
    print "quit equals: $quit\n";

}

A: Inside the loop you are creating a new $quit variable with the my keyword:
chomp (my $quit = <STDIN>);

You actually want to assign to the existing variable:
chomp($quit = <STDIN>);

Note that a Perl linting program such as Perl::Critic would have alerted you to this problem:

Reused variable name in lexical scope: $quit at line 9, column 12.  Invent unique variable names.  (Severity: 3)

A: You redefine $quit in the Loop : chomp (my $quit = <STDIN>); remove my in this line
#!/usr/bin/perl -w
use strict;
my $quit = 'j';

while ($quit eq 'j') {

    print "Enter whatever value you want and I bet I still continue.\n";
    chomp ($quit = <STDIN>);
    print "quit equals: $quit\n";

}

A: Because you define a new variable $quit inside your while loop.
This is what you want:
chomp ($quit = <STDIN>);

So, without 'my'.


text:
Q: Trying to bind DateTime.Now in gridview I am using Visual Web Developer Express 2013 and have created a gridview.  When I update other values in the grid, I want txtDate to show the time the values were updated.
I set it up as an item template.
<asp:TemplateField HeaderText="txtDate" SortExpression="txtDate">
<itemtemplate><asp:label id="txtDate" runat="server"
 text="<%# Bind DateTime.Now.ToString()%>"></asp:label>
</itemtemplate>
</asp:TemplateField>

When I use the above code without Bind - I get the current time displaying.  I added Bind so that the current date would insert into the database and I  get the following error;
Compiler Error Message: CS1026: ) expected
I'm trying to figure out the best way to insert the date when the values are updated.  I also tried adding txtDate as a hidden field but that didn't work either.

A: Uses GetDate() function directly in the insert query, you don't need to show this to the user, because its just for logging purpose as far as I have understood what you want to do.


text:
Q: Extract field from xml file xml file:
<head>
  <head2>
    <dict type="abc" file="/path/to/file1"></dict>
    <dict type="xyz" file="/path/to/file2"></dict>
  </head2>
</head>

I need to extract the list of files from this. So the output would be
/path/to/file1
/path/to/file2

So far, I've managed to the following.
grep "<dict*file=" /path/to/xml.file | awk '{print $3}' | awk -F= '{print $NF}'

A: quick and dirty based on your sample, not xml possibilties
# sed a bit secure
sed -e '/<head>/,/<\/head>/!d' -e '/.*[[:blank:]]file="\([^"]*\)".*/!d' -e 's//\1/' YourFile

# sed in brute force
sed -n 's/.*[[:blank:]]file="\([^"]*\)".*/\1/p' -e 's//\1/' YourFile

# awk quick unsecure using your sample
awk -F 'file="|">' '/<head>/{h=1} /\/head>{h=0} h && /[[:blank:]]file/ { print $2 }' YourFile

now, i don't promote this kind of extraction on XML unless your really know how is your source in format and content (extra field, escaped quote, content of string like tag format, ...) are a big cause of failure and unexpected result and no more appropriate tools are available
now to use your own script
#grep "<dict*file=" /path/to/xml.file | awk '{print $3}' | awk -F= '{print $NF}'
awk '! /<dict.*file=/ {next} {$0=$3;FS="\"";$0=$0;print $2;FS=OFS}' YourFile

*

*no need of a grep with awk, use starting pattern filter /<dict.*file/

*second awk for using a different separator (FS) could be done inside the same script changing FS but because it only occur at next evaluation (next line by default), you could force a reevaluation of current content with $0=$0 in this case

A: Use an xmllint solution with -xpath as //head/head2/dict/@file
xmllint --xpath "//head/head2/dict/@file" input-xml | awk 'BEGIN{FS="file="}{printf "%s\n%s\n", gensub(/"/,"","g",$2), gensub(/"/,"","g",$3)}'
/path/to/file1
/path/to/file2

Unfortunately couldn't provide a pure xmllint logic, because thought applying,
xmllint --xpath "string(//head/head2/dict/@file)" input-xml

will return the file attributes from both the nodes, but it was returning only the first instance.
So added coupled my logic with GNU Awk, to extract the required values, doing
xmllint --xpath "//head/head2/dict/@file" input-xml

returns values as
file="/path/to/file1" file="/path/to/file2"

On the above output, setting a string de-limiter as file= and removing the double-quotes using gensub() function solved the requirement.

A: Also PE [perl everywhere :) ] solution:
perl -MXML::LibXML -E 'say $_->to_literal for XML::LibXML->load_xml(location=>q{file.xml})->findnodes(q{/head/head2/dict/@file})'

it prints
/path/to/file1
/path/to/file2

For the above you need to have installed the XML::LibXML module.

A: With xmlstarlet it would be:
xmlstarlet sel -t -v "//head/head2/dict/@file" -nl input.xml

A: This command:
awk -F'[=" ">]' '{print $12}' file

Will produces:
/path/to/file1
/path/to/file2


text:
Q: When connenting to Wifi with Netgear WNA3001m USB dongle whole Ubuntu 16.04 crashes Whenever I try to connect to wifi (with my USB dongle Netgear WNA3100M) Ubuntu freezes. There is no problem with plugging in the USB dongle. I can even see what networks are available. If I try to connect with a wrong password it still works (but offcourse tells me that the password is wrong) but as soon as I try to connect with the proper password Ubuntu freezes immediately.
This is happening since I updated to a newer kernel version.
When I boot into an older kernel (4.4.0-62) everything works fine.
Output of lsb_release -a:
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial

Ouput of uname -a
Linux MyPCName 4.4.0-66-generic #87-Ubuntu SMP Fri Mar 3 15:29:05 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Output of sudo lshw -class network
*-network
   description: Ethernet interface
   product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
   vendor: Realtek Semiconductor Co., Ltd.
   physical id: 0
   bus info: pci@0000:03:00.0
   logical name: enp3s0
   version: 06
   serial: 00:25:22:d9:35:b0
   size: 10Mbit/s
   capacity: 1Gbit/s
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
   configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=rtl8168e-3_0.0.4 03/27/12 latency=0 link=no multicast=yes port=MII speed=10Mbit/s
   resources: irq:36 ioport:e000(size=256) memory:d0004000-d0004fff memory:d0000000-d0003fff
*-network
   description: Wireless interface
   physical id: 1
   bus info: usb@2:5
   logical name: wlxa42b8c5e383e
   serial: a4:2b:8c:5e:38:3e
   capabilities: ethernet physical wireless
   configuration: broadcast=yes driver=rtl8192cu driverversion=4.4.0-66-generic firmware=N/A link=no multicast=yes wireless=IEEE 802.11bgn

output of lsusb
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 002: ID 0846:9021 NetGear, Inc. WNA3100M(v1) Wireless-N 300 [Realtek RTL8192CU]
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 046d:0841 Logitech, Inc.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 009 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 008 Device 003: ID 145f:0176 Trust Isla Keyboard
Bus 008 Device 002: ID 046d:c03e Logitech, Inc. Premium Optical Wheel Mouse (M-BT58)
Bus 008 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 007 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 006 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Output of lspci
00:00.0 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h Processor Root Complex
00:01.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] BeaverCreek [Radeon HD 6550D]
00:01.1 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] BeaverCreek HDMI Audio [Radeon HD 6500D and 6400G-6600G series]
00:10.0 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB XHCI Controller (rev 03)
00:10.1 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB XHCI Controller (rev 03)
00:11.0 SATA controller: Advanced Micro Devices, Inc. [AMD] FCH SATA Controller [IDE mode] (rev 40)
00:12.0 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB OHCI Controller (rev 11)
00:12.2 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB EHCI Controller (rev 11)
00:13.0 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB OHCI Controller (rev 11)
00:13.2 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB EHCI Controller (rev 11)
00:14.0 SMBus: Advanced Micro Devices, Inc. [AMD] FCH SMBus Controller (rev 13)
00:14.1 IDE interface: Advanced Micro Devices, Inc. [AMD] FCH IDE Controller
00:14.2 Audio device: Advanced Micro Devices, Inc. [AMD] FCH Azalia Controller (rev 01)
00:14.3 ISA bridge: Advanced Micro Devices, Inc. [AMD] FCH LPC Bridge (rev 11)
00:14.4 PCI bridge: Advanced Micro Devices, Inc. [AMD] FCH PCI Bridge (rev 40)
00:14.5 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB OHCI Controller (rev 11)
00:15.0 PCI bridge: Advanced Micro Devices, Inc. [AMD] Hudson PCI to PCI bridge (PCIE port 0)
00:15.3 PCI bridge: Advanced Micro Devices, Inc. [AMD] Hudson PCI to PCI bridge (PCIE port 3)
00:18.0 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 0 (rev 43)
00:18.1 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 1
00:18.2 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 2
00:18.3 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 3
00:18.4 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 4
00:18.5 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 6
00:18.6 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 5
00:18.7 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 12h/14h Processor Function 7
03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)

Output of rfkill list all
0: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no

Output of lsmod | grep rtl
rtl8192cu              69632  0
rtl_usb                20480  1 rtl8192cu
rtl8192c_common        53248  1 rtl8192cu
rtlwifi                77824  3 rtl_usb,rtl8192c_common,rtl8192cu
mac80211              737280  3 rtl_usb,rtlwifi,rtl8192cu
cfg80211              565248  2 mac80211,rtlwifi

Output of dpkg -l network-manager
||/ Naam                                          Versie                      Architectuur                Omschrijving
+++-=============================================-===========================-===========================-===============================================================================================
ii  network-manager                               1.2.6-0ubuntu0.16.04.1      amd64                       network management framework (daemon and userspace tools)

By the way, all output was generated with my usb-dongle inserted, but not connected to the Wifi-network.

A: For a while the solution was booting into the older kernel. But since kernel update 4.4.0-75-generic everything is working again.
So the current solution is updating the kernel to the latest version.


text:
Q: Show $1+1/p+1/p^2+...=\exp(1/p+O(1/p^2))$ In this note, T.Tao proved Thm 2 while invoking $$1+\frac{1}{p}+\frac{1}{p^2}+\dots=\exp(\frac{1}{p}+O(\frac{1}{p^2})).$$
Why does this hold?

A: You have $e^h=1+h+O(h^2)$ or similarly $1+x=e^{x+O(x^2)}$. Or if you want it more strictly
$$
1+h+h^2+h^3+...=\frac1{1-h}=e^{h+h^2/2+h^3/3+...}=e^{h+O(h^2)}.
$$


text:
Q: detected circular import in python3 I have read various threads on the subject but have not found an answer( or I do not understand the problem)
The case looks like this:
main.py:
from a import aa

aa()

a.py
from b import bb
from c import cc

class aError(Exeption):
...

def aa():
  try:
    bb()
    cc()
  except aError:
    ...
...

b.py
from a import aError

class bError(aError):
...

def bb():
  raise bError
...

c.py
from a import aError

class cError(aError):
...

def cc():
  raise cError
...

as you can see, I have circular import a -> b/c -> a. Is there any nice way to solve this problem without throwing aError from a.py ?


text:
Q: How to determine the Page Frame Number for device memory? How does one determine the page frame number for device memory? From LDD3/ Ch. 15/ sections "Using remap_pfn_range" and "A Simple Implementation", pfn has been equated to the vm_pgoff field. I am confused by this. How can that be so?
Note that vm_pgoff is described as:

The offset of the area in the file, in pages. When a file or device is
  mapped, this is the file position of the first page mapped in this
  area.

Thus if the first page mapped corresponds to the first page of the file as well (which, I think would be quite common), vm_pgoff would be 0. correct? If so, this doesn't seem to be the correct value for the pfn parameter of remap_pfn_range( ).  What am I missing here? What is the correct value? For ease of reference, I am reproducing the relevant code from LDD3 below (Page no. 426)
static int simple_remap_mmap(struct file *filp, struct vm_area_struct *vma)
{
if (remap_pfn_range(vma, vma->vm_start, vm->vm_pgoff,
                    vma->vm_end - vma->vm_start,
                    vma->vm_page_prot))
    return -EAGAIN;
...
}

A: venk, I am just a newbie.
I am very curious about your question, and also I have read the part that you pointed in Linux device driver.
There is another book I should recommend, Professional Linux kernel architecture.
some details on mmap are described there.
from within the book above, it seems there are some transformations to vm->vm_pgoff before calling the function simple_remap_mmap() as a example here, which does not exist in Linux kernel source code.
so, even if vm_pgoff is 0, after some transformation to it, there may be a correct value in that member variable vm_pgoff.
the codes below are present in Linux kernel source code 3.3.5
#ifdef CONFIG_DEVKMEM

static int mmap_kmem(struct file *file, struct vm_area_struct *vma)
{

    unsigned long pfn;

    /* Turn a kernel-virtual address into a physical page frame */

    pfn = __pa((u64)vma->vm_pgoff << PAGE_SHIFT) >> PAGE_SHIFT;   <----- Here

    /*
     * RED-PEN: on some architectures there is more mapped memory than
     * available in mem_map which pfn_valid checks for. Perhaps should add a
     * new macro here.
     *
     * RED-PEN: vmalloc is not supported right now.
     */
    if (!pfn_valid(pfn))
        return -EIO;

    vma->vm_pgoff = pfn;
    return mmap_mem(file, vma);
}
#endif


text:
Q: Loop variable error in for loop When I'm using for like
 for i in 1 2 3 4 5

then my file contains #!/bin/sh at the top.
But when I'm using
for(( i = 0; i<=5; i++))

then it is showing error
Syntax error: Bad for loop variable

and running properly when I remove shebang. Please tell me the reason behind this.

A: I have solved this problem by using ./ instead of sh command.
For an example if you put sh test.sh instead just make your command as ./test.sh And most probably problem will be solved.

A: for(( i = 0; i<=5; i++))

for this type of loop only runs on Bash shell. so, if you want to run this, then try this command :
$bash filename.sh

I think It will work fine. and see this one also.

A: for(( i = 0; i<=5; i++)) is Bash specific and doesn't work with plain Bourne shell (/bin/sh).
If you remove the shebang the script is run by your current shell (which likely is Bash) so it works.
Replace #!/bin/sh with #!/bin/bash to make the shebang work.

A: Try this out may be this could solve your problem
#!/bin/bash
j=0
for (( i=1; i <= 5; i++ ))
do
 echo "the loop is runing $i time: and value of j is $j"
 j=`expr $j + 1`
done


text:
Q: Selecting values from a column based on value from another column determined dynamically I have a data frame.
df <- data.frame(A = 1:10, B = 101:110, C = 201:210)

And I want to find values in column A using the following criteria,
df$A[df$B > 101 & df$B < 105]
[1] 2 3 4

However, I want to be able to specify the criteria programmatically using the following approach,
var <- noquote(paste0("df$", names(df[2])))
df$A[var > 101 & var < 105]

But all I am getting is integer(0).
Obviously something is not right. Could anyone help? Thank you.

A: If we need it, then use eval(parse
df$A[eval(parse(text=var))> 101 & eval(parse(text=var)) < 105]
#[1] 2 3 4


text:
Q: P-values from aov in R I'm conducting a simulation study in R.  Basically, I generate fake data sets and then run an ANOVA on the data using the aov function.  But I'm having difficulty extracting p-values.  Previous questionss do not help (Extract p-value from aov) -- I am running a mixed ANOVA.
First I have an ANOVA:
results <- summary(aov(dv~(A*B*C*D*E)+Error(subj/(A*B*C*D)), data = mdata))  #  conduct repeated measures ANOVA

which generate this output:
Error: subj
      Df   Sum Sq Mean Sq F value Pr(>F)
E          1  1039157 1039157    0.95  0.334
Residuals 58 63428016 1093586

Error: subj:A
      Df Sum Sq Mean Sq F value Pr(>F)
A          1   1996    1996   0.220  0.641
A:E        1   2294    2294   0.253  0.617
Residuals 58 526389    9076

...

I'm truncating the output for space. What I want list of p-values with the effect name (A or A:E).  I have halfway succeeded, but it's messy.  I can extract the p-values using this get_p function that I made.
#Function
get_p = function(results,head){
  results[[1]]$'Pr(>F)'
}

#Get p-values
p <- sapply(results, get_p)

I end up with a this:
$`Error: subj`
[1] 0.3337094        NA

$`Error: subj:A`
[1] 0.6408826 0.6170181        NA

...

Any ideas on how to get a list of p-values (.6408, .6178) and effect names ('A', 'A:E')?

A: I found the answer, which seems to be:
 get_p1 = function(results){
    results[[1]]$'Pr(>F)'[[1]]
 }
 get_p2 = function(results){
    results[[1]]$'Pr(>F)'[[2]]
 }
 pvals <- c(sapply(results, get_p1), sapply(results, get_p2))


text:
Q: Cocos2d Scroll for iOS It took several days trying to do this (image). And I don't find how do it.
In summary I need a scroll with snapping (like CCScrollLayer) on left, and change content panel (right) when scrolling.
I tried with CCScrollLayer, but the scroll is horizontal, and I can't resize.
I find other solutions with vertical scroll, but it is continuous scroll, and I need the same effect like CCScrollLayer (snapping).
I would be grateful if someone could help me.
I'm using the Cocos2D-iPhone framework.


text:
Q: PHP. Cannot append to the file Well, I have a problem. On my local LAMP (14.04 LTS 32 bit) all works as magic. Remote server also is Ubuntu 14.04 (64 bit).
On the production my program successfully rewrites file:
$myfileresult = fopen('taranko.csv','w+');
echo fwrite($myfileresult,"");
fclose($myfileresult);

but after it my script failed to append any information.
$myfileresult = fopen('download.csv','a');
                fwrite($myfileresult, $ids.";".$imageLinkAlt.";".$itemNameAlt.";".$features.";".$mods[$x].";".$prices[$x].";".$stockQty[$x].PHP_EOL);
                fclose($myfileresult);

I have
ini_set('display_errors', 1);
error_reporting(E_ALL);

in my script, but there are no errors or warnings in PHP echo, indeed.
I tried to append this string:
"1701-1;http://taranko-shop.ru/.."
So, I used strace, this is what I found:
open("/home/ci65797/web/mydomain.com/public_html/download.csv", O_WRONLY|O_CREAT|O_APPEND, 0666) = 24
2056  fstat(24, {st_mode=S_IFREG|0644, st_size=160740, ...}) = 0
2056  lseek(24, 0, SEEK_CUR)            = 0
2056  lseek(24, 0, SEEK_CUR)            = 0
2056  write(24, "1701-1;http://taranko-shop.ru/wa"..., 377) = 377
2056  close(24)

So, next to the latest string contains my string, which I tried to append.
My all directories are 755, the file is 644.
What should I do to fix this?

A: as @Chris suggests, my script just wrote to another file. It happened because I renamed file in the first part of my script and don't renamed in the second.


text:
Q: arduino and esp8266 problem I can't seem to connect my esp8266 d1 mini; can any one help me?
This is the error msg I get:
Arduino: 1.8.13 (Linux), Board: "LOLIN(WEMOS) D1 mini (clone), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, DOUT (compatible), 40MHz, 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 921600"

Executable segment sizes:
ICACHE : 32768           - flash instruction cache
IROM   : 231788          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 26777   / 32768 - code in IRAM          (IRAM_ATTR, ISRs...)
DATA   : 1496  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 876   ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 25616 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 260937 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27988 bytes (34%) of dynamic memory, leaving 53932 bytes for local variables. Maximum is 81920 bytes.
esptool.py v3.0
Serial port /dev/ttyUSB0
Traceback (most recent call last):
  File "/home/oem/.arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/pyserial/serial/serialposix.py", line 322, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
PermissionError: [Errno 13] Permission denied: '/dev/ttyUSB0'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/oem/.arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/upload.py", line 66, in <module>
    esptool.main(cmdline)
  File "/home/oem/.arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/esptool/esptool.py", line 3551, in main
    esp = chip_class(each_port, initial_baud, args.trace)
  File "/home/oem/.arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/esptool/esptool.py", line 271, in __init__
    self._port = serial.serial_for_url(port)
  File "/home/oem/.arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/pyserial/serial/__init__.py", line 90, in serial_for_url
    instance.open()
  File "/home/oem/.arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/pyserial/serial/serialposix.py", line 325, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyUSB0: [Errno 13] Permission denied: '/dev/ttyUSB0'
the selected serial port serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyUSB0: [Errno 13] Permission denied: '/dev/ttyUSB0'
 does not exist or your board is not connected

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.


text:
Q: Flask query not working with table I have this script that I import into the route:
import sqlite3

conn = sqlite3.connect("c:/DB/tvldb.db")

cursor = conn.cursor()

cursor.execute('''SELECT code, type, issue, item_type, list_code FROM Issues''')

datarows = cursor.fetchall()

conn.close()

That works fine when I print it.
Here is the route:
from flask import Flask, render_template
import db_issues

app = Flask(__name__)

datarows = db_issues.datarows

@app.route('/issues')
def issues():
   return render_template('leftside.html', datarows=datarows)

if __name__ == '__main__':
   app.run(debug=True)

And here is the template:

 Missing Items

        Code
        Type
        Issue
        Entry Type
        List Code

    {% for row in datarows %}

            {{ code }}
            {{ type }}
            {{ Issue }}
            {{ item_type }}
            {{ list_code }}

    {% endfor %}

{% endblock %}

The table shows ok but no data is filled in. I been trying all day to do this simple thing and having no luck. According to all the tutorials and stackoverflow answers I checked, this should be correct. Any help would be greatly appreciated.

A: I think you should write your table like this (not tested yet):
{% for row in datarows %}

        {{ row['code'] }}
        {{ row['type'] }}
        {{ row['issue'] }}
        {{ row['item_type'] }}
        {{ row['list_code'] }}

{% endfor %}

A: Look more closely at datarows. It'll be a list of tuples, not a dictionary. That is, there no names to associate with each 'column', so attempts to reference in the template, say, row.code are going to fail, because row is a tuple.
You could, with a bit of work, turn the rows into dictionaries, by matching up the slots in each tuple with names found in cursor.description. There's an example of how to do that using row_factory in the sqlite3 docs.

A: Always debug the variable that you are passing to the rendered page this will let you know that whether the data are inside the index or not
print(variable)

Using this you will be confirmed that what data you have to parse to the template page