text:
Q: Find $1 \le a < b \le n$ such that $a\cdot b + a + b = n\cdot (n+1)/2$
Find $1 \le a < b \le  n$ such that $$a\cdot b + a + b = \frac{n\cdot (n+1)}2$$

Is there a more efficient way than picking $a$ or $b$ and trying all values between $1$ and $n$ ?

A: $(a+1)(b+1)=\dfrac{n^2+n+2}{2}$.
If $a$ and $b$ are restricted to integers, consider the factors of $\dfrac{n^2+n+2}{2}$.


text:
Q: oracle SQL developer debug output I am using SQL Developer to debug code like below, the output result will be shown on debug dialog ONLY after I finish all stored procedure. Do I need to turn on some configurations ?
Thanks
 FOR j IN REVERSE 1..i LOOP
     DBMS_OUTPUT.PUT_LINE(emp_tab(j).first_name);
  END LOOP;

log
Connecting to the database hr.
Executing PL/SQL: ALTER SESSION SET PLSQL_DEBUG=TRUE
Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( '192.168.1.4', '53475' )
Debugger accepted connection from database on port 53475.
Source breakpoint occurred at line 24 of EMP_LIST.pls.
Source breakpoint occurred at line 24 of EMP_LIST.pls.
Source breakpoint occurred at line 24 of EMP_LIST.pls.
Source breakpoint occurred at line 24 of EMP_LIST.pls.
Source breakpoint occurred at line 24 of EMP_LIST.pls.
Source breakpoint occurred at line 24 of EMP_LIST.pls.
Executing PL/SQL: CALL DBMS_DEBUG_JDWP.DISCONNECT()
Shelli
Hermann
David
Mozhe
Sundar
Ellen
Process exited.
Disconnecting from the database hr.
Debugger disconnected from database.

A: If you are using DBMS_OUTPUT to debug, you won't see any output until the process completes.  That's the way DBMS_OUTPUT works.
It appears you are successfully using the SQL Developer debugger, however, which is a much more effective way of debugging a stored procedure.  You are apparently setting breakpoints so you can examine the values of variables at those breakpoints.  There is no need to print the values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap dropdown stoppropagation Issue I have an angular project running, but that's relevant since this issue is primarily related to bootstrap 4.
So I heavily depend on bootstraps dropdown in my project, and what bootstrap does is, it prevents event propagation on the dropdown buttons. And this seems to be intentional.
I have a click event listening on the document, to check whether other elements in the page should be hidden or not, but due to event not propagating I'm unable to achieve this.
Any help on the issue will be appreciated, and I will definitely mark an accepted answer.
$(document).on('click', function(e){
  console.log('Click triggered');
});
http://jsbin.com/galaqeguke/edit?html,js,output
JSBin for reference.

A: Swap out the 'document' with '.dropdown' in the function:
$('.dropdown').on('click', function (e){
      $('#message').text('Clicked '+e.target.tagName);
});


text:
Q: Can not parse retrofit rxjava errorBody this is login error response :
 override fun onError(e: Throwable) {
...
...

e:response  : error :
 [size=86 text={"message":"Object reference not set to an instance of an object…]

it should be something like this  :  "Wrong username or password ... "
but it can't cast to desire object .
I Also tried to cast it to custom object but no success.
Any solution?


text:
Q: How to calculate query time to decide which one is faster or more efficient? I want to compare my algorithm, here is some simplification from my case,
Assume that the table is indexed using the log_timestamp column.
First query:
SELECT
    name
FROM
    user_table
WHERE
    DATE(DATETIME_ADD(log_timestamp , INTERVAL 7 HOUR)) >= DATE('2018-01-01')
    AND
    DATE(DATETIME_ADD(log_timestamp , INTERVAL 7 HOUR)) < DATE('2019-01-01');

Second query:
SELECT
    name
FROM
    user_table
WHERE
    log_timestamp >= DATETIME_SUB('2018-01-01', INTERVAL 7 HOUR)
    AND
    log_timestamp < DATETIME_SUB('2019-01-01', INTERVAL 7 HOUR);

Which of the two queries above would be faster and why?

A: To find out how a query works fast or slow, we must know how many records are in the table.
if the number of records is still between 100 - 1000 (depending on the number of fields in the table), when both queries are executed, both will display results in almost the same time.
if the number of records has exceeded 100,000, it will start to see the time difference in displaying the results.
Remember, don't forget to use the EXPLAIN function to see how the query goes.
let's analyze the two queries
First Query
SELECT
    name
FROM
    user_table
WHERE
    DATE(DATETIME_ADD(log_timestamp , INTERVAL 7 HOUR)) >= DATE('2018-01-01')
    AND
    DATE(DATETIME_ADD(log_timestamp , INTERVAL 7 HOUR)) < DATE('2019-01-01');

MySQL will :

*

*do this DATE(DATETIME_ADD(log_timestamp , INTERVAL 7 HOUR)) through all records in table without using index,

*after that MySQL will compare with >= DATE('2018-01-01')

*do this DATE(DATETIME_ADD(log_timestamp , INTERVAL 7 HOUR)) through all records in table without using index,

*after that MySQL will compare with < DATE('2019-01-01');

*and display the results
Notes :
imagine you have 100,000 records in the table, it will takes time to display the results

Second Query
SELECT
    name
FROM
    user_table
WHERE
    log_timestamp >= DATETIME_SUB('2018-01-01', INTERVAL 7 HOUR)
    AND
    log_timestamp < DATETIME_SUB('2019-01-01', INTERVAL 7 HOUR);

MySQL will :

*

*compare log_timestamp >= DATETIME_SUB('2018-01-01', INTERVAL 7 HOUR) through indexes, not full scan table

*and compare log_timestamp < DATETIME_SUB('2019-01-01', INTERVAL 7 HOUR); through indexes, not full scan table

*and display the results

Notes :

*

*Remember!!!... Index in tables, it's just like index in a book. when you wanna read a book that have more than 1000 page, you will see the index first to find the page you looking for. You will not read all the pages, to find the topic you wanna read.

A: The question you asked should really be two separate questions.  The first, along the lines of what you asked above, is which of the two queries is faster right now.  The second question, which is really the one to consider, is how can you tune both queries to make them faster, and which one would be the fastest.
As it turns out, only the second query can use an index:
SELECT name
FROM user_table
WHERE log_timestamp >= DATETIME_SUB('2018-01-01', INTERVAL 7 HOUR) AND
      log_timestamp < DATETIME_SUB('2019-01-01', INTERVAL 7 HOUR);

This query should benefit from an index on (log_timestamp, name).  Note that your first query cannot really benefit from any index, so I expect your second query to be much faster, after the right index has been created.


text:
Q: In a bootstrap responsive page how to center a div
I need to create a responsive page using bootstrap by position a div at the centre of a page as like in the below mentioned layout.

A: For centering a div assign three class names of bootstrap inside into a div:  ml-0 mr-0 mx-auto
Just look at the simple example below how it is being centered

      Center

A: CSS:
html,
body {
    height: 100%;
}

.container {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

HTML:

    example

Example fiddle

A: You don't need to change anything in CSS you can directly write this in class and you will get the result.

    TEXT

A: In bootstrap 4
to center the children horizontally, use bootstrap-4 class
justify-content-center

to center the children vertically, use bootstrap-4 class
 align-items-center

but remember don't forget to use d-flex class with these
it's a bootstrap-4 utility class, like so

MIDDLE

Note: make sure to add bootstrap-4 utilities if this code does not work

A: without display table and without bootstrap , i would rather do that

TEXT

 html, body, .container-table {
    height: 100%;
}
.container-table {
    width:100vw;
  height:150px;
  border:1px solid black;
}
.vertical-center-row {
   margin:auto;
  width:30%;
  padding:63px;
  text-align:center;

}

http://codepen.io/matoeil/pen/PbbWgQ

A: In Bootstrap 4, use:

...

You can also change the position depending on what you want:

...

...

...

...

Reference here

A:

body{
    height: 100vh;
}
.container{
    height: 100%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Counter

                0

                <button class="btn btn-outline-primary">Decrease</button>
                <button class="btn btn-danger">Reset</button>
                <button class="btn btn-outline-success">Increase</button>

you can do also that way.

A: Update for Bootstrap 5
Simpler vertical grid alignement with flex-box

@import url('https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.1/css/bootstrap.min.css');
html,
body {
  height: 100%
}

    TEXT

Solution for Bootstrap 4
Simpler vertical grid alignement with flex-box

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');
html,
body {
  height: 100%
}

    TEXT

Solution for Bootstrap 3

@import url('http://getbootstrap.com/dist/css/bootstrap.css');
 html, body, .container-table {
    height: 100%;
}
.container-table {
    display: table;
}
.vertical-center-row {
    display: table-cell;
    vertical-align: middle;
}

TEXT

It's a simple example of a horizontally and vertically div centered in all screen sizes.

A: Update for Bootstrap 4
Now that Bootstrap 4 is flexbox, vertical alignment is easier. Given a full height flexbox div, just us my-auto for even top and bottom margins...

Hello, world!

http://codeply.com/go/ayraB3tjSd/bootstrap-4-vertical-center

Vertical center in Bootstrap 4

A: Good answer ppollono. I was just playing around and I got a slightly better solution.
The CSS would remain the same, i.e. :
html, body, .container {
    height: 100%;
}
.container {
    display: table;
    vertical-align: middle;
}
.vertical-center-row {
    display: table-cell;
    vertical-align: middle;
}

But for HTML:

TEXT

This would be enough.

A: Here is simple CSS rules that put any div in the center
.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

A: I think the simplest way to accomplish the layout with bootstrap is like this:

Content goes here

all I did was to add layers of divs that allowed me to center the div, but since I am not using percentages, you need to specify the max-width of the div to be center.
You can use this same method to center more than one column, you just need to add more div layers:

Some content

More content

Note: that I added a div with column 12 for md, sm and xs, if you don't do this the first div with background color (in this case "blueviolet") will collapse, you will be able to see the child divs, but not the background color.

A: For actual version of Bootstrap 4.3.1 use
Style
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Code

Title

Desc

</div

A: Not the best way ,but will still work

    This div is in middle

A: Try this, For the example, I used a fixed height. I think it is doesn't affect the responsive scenario.

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

A: Here is the snippet used and worked,

A: jsFiddle
HTML:

text

TEXT

CSS:
#parent {
    text-align: center;
}
#child {
    margin: 0 auto;
    display: inline-block;
    background: red;
    color: white;
}

A: Simplest solution will be adding one blank column in both sides like below:

Yuvraj Patil


text:
Q: Vlookup in VBA runs very slow, any ideas? I have created the following macro to be able to have a sheet called "Macron" which looks inside different cells and sheets in my workbook, from there i want to create a macro that finds the value based on a name instead of a specific cell (since VBA code does not get updated if i add another cell etc, then i need to rewrite all the macro references which is extremely timeconsuming).
So i decided to work with the application.Vlookup function in my code, but now i see that this goes extremely slow compared to only looking inside the cells.
Is this the case all the time, or is it something wrong with my code that could be updated or cleaner to make it work faster.
Here is my code for the macro:
Sub Motesbokning_saljare()
Dim OutApp As Object
Dim OutMail As Object
Dim a As String
Dim o As String
Dim a1 As String
Dim o1 As String
Dim strbody As String
Dim ws As Worksheet
Dim ws1 As Worksheet

' ä
a = Chr(228)
'å
a1 = Chr(229)
'ö
o = Chr(246)
'Ö
o1 = Chr(214)

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(1)
Set ws = Sheets("Macron")
Set ws1 = Sheets("Offert")

On Error Resume Next
With OutMail
    .To = Application.VLookup("kundEpost", ws.Range("A:C").Value, 3, False)
    .Subject = Application.VLookup("partnerNamn", ws.Range("A:C").Value, 3, False) & ", " & Application.VLookup("kundFulltNamn", ws.Range("A:C").Value, 3, False)
    .location = "" & Application.VLookup("kundAdress", ws.Range("A:C").Value, 3, False) & ", " & Application.VLookup("kundPostnr", ws.Range("A:C").Value, 3, False) & ", " & Application.VLookup("kundPostort", ws.Range("A:C").Value, 3, False)
    .Body = "Projekttyp: " & Application.WorksheetFunction.VLookup("moteProjekttyp", ws.Range("A:C").Value, 3, False) & vbNewLine & "Fastighetstyp: " & Application.WorksheetFunction.VLookup("moteFastighetstyp", ws.Range("A:C").Value, 3, False) & vbNewLine & vbNewLine & "Portkod: " & _
    Application.VLookup("motePortkod", ws.Range("A:C").Value, 3, False) & vbNewLine & "Telefon: " & Application.VLookup("kundTelefon", ws.Range("A:C").Value, 3, False) & vbNewLine & "V" & a1 & "ning: " & Application.VLookup("moteVaning", ws.Range("A:C").Value, 3, False) & vbNewLine & vbNewLine _
    & "Upphandlingsunderlag: " & Application.VLookup("moteUpphandlingsunderlag", ws.Range("A:C").Value, 3, False) & vbNewLine & Application.VLookup("moteUpphandlingsunderlagTyp", ws.Range("A:C").Value, 3, False) & vbNewLine & vbNewLine & "K" & o & "rtid: " & Application.VLookup("moteKortid", ws.Range("A:C").Value, 3, False) & " minuter" _
    & vbNewLine & "GPS URL: " & Application.VLookup("moteGPSurl", ws.Range("A:C").Value, 3, False) & vbNewLine & vbNewLine & "K" & a & "lla: " & Application.VLookup("moteKalla", ws.Range("A:C").Value, 3, False) & vbNewLine & o1 & "vrigt: " & Application.VLookup("moteOvriginfo", ws.Range("A:C").Value, 3, False) & vbNewLine & vbNewLine & "Referenskund i n" & a & _
    "romr" & a1 & "de: " & vbNewLine & ws1.Range("I35").Value & ", " & ws1.Range("K35").Value & ", " & ws1.Range("M35").Value & vbNewLine & ws1.Range("I36").Value & ", " & _
    ws1.Range("K36").Value & ", " & ws1.Range("M36").Value & vbNewLine & ws1.Range("I37").Value & ", " & ws1.Range("K37").Value & ", " & ws1.Range("M37").Value & vbNewLine & _
    ws1.Range("I38").Value & ", " & ws1.Range("K38").Value & ", " & ws1.Range("M38").Value & vbNewLine & ws1.Range("I39").Value & ", " & ws1.Range("K39").Value & ", " _
    & ws1.Range("M39").Value
    .Start = Application.VLookup("moteDatum", ws.Range("A:C").Value, 3, False) + Application.VLookup("moteKlockslag", ws.Range("A:C").Value, 3, False)
    .ReminderMinutesBeforeStart = Application.VLookup("moteReminder", ws.Range("A:C").Value, 3, False)
    .Duration = Application.VLookup("moteTidsatgang", ws.Range("A:C").Value, 3, False)
    .Recipients.Add Application.VLookup("moteLaggTillDeltagare", ws.Range("A:C").Value, 3, False)
    .Categories = Application.VLookup("moteKategori", ws.Range("A:C").Value, 3, False)
    .Display
End With

Set OutMail = Nothing
Set OutApp = Nothing

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

End Sub

Thanks for any help that can be offered.
Best regards
Agatonsaxx

A: To skip the tremendous amount of vlookups (combined with them being for whole columns and not smaller defined ranges), while using VBA I suggest using a single iteration over column A to determine the contents of your mail body. For that purpose you need 2 arrays. One for the words you are looking for in column A (searchWords) and one for the needed values in column C (mailContents). My approach would be as follows ("..." marking skips that need to be filled in with your existing code):
Sub Motesbokning_saljare()
    ...
    Set ws = Sheets("Macron")
    Set ws1 = Sheets("Offert")

    Dim searchWords(1 To 100) As String
    'Fill all the words that need to be searched:
    searchWords(1) = "kundEPost"
    searchWords(2) = "partnerNamn"
    searchWords(3) = "kundFulltNamn"
    ...
    Dim mailContents(1 To 100) As String
    Dim i As Integer
    Dim j As Integer
    Dim LastRow As Long
    With ws
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
    For i = 1 To LastRow
        'i is for the rows of the excel sheet
        For j = 1 To UBound(searchWords)
            'j is for the lookup in the array searchwords
            If ws.Cells(i, 1) = searchWords(j) Then
                mailContents(j) = ws.Cells(i, 3)
            End If
        Next j
    Next i
    'Now, fill the mail body:
    On Error Resume Next
    With OutMail
        .To = mailContents(1)
        .Subject = mailContents(2) & ", " & mailContents(3)
        ...
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

    ...
End Sub

As you can see, I only filled in the first 3 words of the mail body. You'd need to fill searchWords with the mail body lookups and further fill the mail body. I'd also recommend to change the size of the arrays to the exact number of lookups your formerly did (1 To 100 means that it can contain up to 100 entries).


text:
Q: What is wrong with my SQLite code? The error i get: SQLite error near"name":syntax error I have looked at many examples on the web and tried to adjust my program according to that, none of that helped me.. Please can you point out what should I do to fix this problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;
using Restaurant_app_1.Business_Layer;

namespace Restaurant_app_1.Data_Access_Layer
{
    class PersonSQLProvider : PersonProviderBase
    {
        private SQLiteConnection _sqlConnection;
        private string _connStr = "Data Source=c:\\DataStores\\PersonDatabase.s3db;Version=3";

Here it tries to insert data into the database, when it reaches the .ExecuteNonQuery() method it jumps to the catch and throw me the error.
        public override int Insert(Manager Manager)
        {
            int rc = 0;

            try
            {
                _sqlConnection = new SQLiteConnection(_connStr);
                _sqlConnection.Open();

                string insertQuery = "INSERT INTO PersonDatabase([_staffFirstName], [_staffLastName], [_staffAge], [_staffID], [_staffeMail], [_staffNumber], [_staffStreet], [_staffProvince], [_staffCity], [_staffPostalCode], [_staffAreaCode], [_staffPhoneNumber], [_staffType]) VALUES(" +
                                     "@First name, @Last name, @Age, @ID, @eMail, @Staff number, @Street, @Province, @City, @Postal Code, @Area code, @Number, @Type)";
                SQLiteCommand sqlCommand = new SQLiteCommand(insertQuery, _sqlConnection);
                SQLiteParameter[] sqlParams = new SQLiteParameter[]
                {
                new SQLiteParameter("@First name",DbType.String),
                new SQLiteParameter("@Last name",DbType.String),
                new SQLiteParameter("@Age",DbType.Int32),
                new SQLiteParameter("@ID",DbType.String),
                new SQLiteParameter("@eMail",DbType.String),
                new SQLiteParameter("@Staff number",DbType.String),
                new SQLiteParameter("@Street",DbType.String),
                new SQLiteParameter("@Province",DbType.String),
                new SQLiteParameter("@City",DbType.String),
                new SQLiteParameter("@Postal Code",DbType.String),
                new SQLiteParameter("@Area code",DbType.String),
                new SQLiteParameter("@Number",DbType.String),
                new SQLiteParameter("@Type",DbType.String)
                };

                sqlParams[0].Value = Manager.FirstName;
                sqlParams[1].Value = Manager.LastName;
                sqlParams[2].Value = Manager.Age;
                sqlParams[3].Value = Manager.ID;
                sqlParams[4].Value = Manager.Email;
                sqlParams[5].Value = Manager.StaffNr;
                sqlParams[6].Value = Manager.AddressStreet;
                sqlParams[7].Value = Manager.AddressProvince;
                sqlParams[8].Value = Manager.AddressCity;
                sqlParams[9].Value = Manager.AddressPostalCode;
                sqlParams[10].Value = Manager.AreaCode;
                sqlParams[11].Value = Manager.Number;
                sqlParams[12].Value = Manager.PhoneType;

                sqlCommand.Parameters.AddRange(sqlParams);
                rc = sqlCommand.ExecuteNonQuery();

                if (rc == 1)
                {
                    rc = 0;
                }
                _sqlConnection.Close();
            }
            catch (SQLiteException ex)
            {
                if (ex.ErrorCode == SQLiteErrorCode.Constraint)
                {
                    rc = -1;
                }
                else
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rc;
        }
    }
}

A: I do not think that you can have spaces in the Parameter names
@First name
@Last name
@Staff number
@Postal Code
@Area code
These will all have the same problem. Remove the space and it should work
@FirstName
@LastName
@StaffNumber
@PostalCode
@AreaCode

A: Variable names cannot contains spaces. Change
@First name, @Last name,

to
@Firstname, @Lastname,

for instance.


text:
Q: Error inflating class fragment Android Map v2
I know this is a duplicate question, but solutions from previous post doesn't worked for
  me. Thats why am asking this question.

I am trying to implement Google Map V2 in Android App, I got below error
06-26 19:24:51.035: E/AndroidRuntime(7679): FATAL EXCEPTION: main
06-26 19:24:51.035: E/AndroidRuntime(7679): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.titutorial.mapdemo/com.titutorial.mapdemo.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.os.Looper.loop(Looper.java:137)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.ActivityThread.main(ActivityThread.java:4898)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at java.lang.reflect.Method.invokeNative(Native Method)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at java.lang.reflect.Method.invoke(Method.java:511)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at dalvik.system.NativeStart.main(Native Method)
06-26 19:24:51.035: E/AndroidRuntime(7679): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:308)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.Activity.setContentView(Activity.java:1924)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at com.titutorial.mapdemo.MainActivity.onCreate(MainActivity.java:12)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.Activity.performCreate(Activity.java:5206)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
06-26 19:24:51.035: E/AndroidRuntime(7679):     ... 11 more
06-26 19:24:51.035: E/AndroidRuntime(7679): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.MapFragment: make sure class name exists, is public, and has an empty constructor that is public
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.Fragment.instantiate(Fragment.java:584)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.Fragment.instantiate(Fragment.java:552)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.Activity.onCreateView(Activity.java:4849)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
06-26 19:24:51.035: E/AndroidRuntime(7679):     ... 20 more
06-26 19:24:51.035: E/AndroidRuntime(7679): Caused by: java.lang.ClassNotFoundException: com.google.android.gms.maps.MapFragment
06-26 19:24:51.035: E/AndroidRuntime(7679):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
06-26 19:24:51.035: E/AndroidRuntime(7679):     at android.app.Fragment.instantiate(Fragment.java:574)
06-26 19:24:51.035: E/AndroidRuntime(7679):     ... 23 more

I followed below tutorial,
https://developers.google.com/maps/documentation/android/start#installing_the_google_maps_android_v2_api
I did below things

*

*Install Google Play services

*Created a new app in Google Console, and got Google Map API key

*Created new app in eclipse and added permission and Google Map API key in AndroidManifest.xml

*Added Google Play Services library to App

*Add a Map to the App (main.xml)

*Set targeted API level 17

in my main.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

here is my complete source code
https://github.com/railskarthi/MapDemo

A: After API 11+, I think you now have have to replace your MapFragment by SupportMapFragment. It would be something like:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/map"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:name="com.google.android.gms.maps.SupportMapFragment"/>

Take a look here for further information. Let me know how are you going with.

A: I have download your project from git and after checking i found that you have missed a line which is required to display map Fragment.
Replace your main activity code with the following code:-
public class MainActivity extends FragmentActivity {
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();
}

A: This could happen also if you did not define API_KEY for google maps in your manifest file.
It looks like this:
`....
<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="<your key>" />
....`

Create your key in Google Developer Console

A: Please add these line in your manifest file
     <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <!-- Goolge API Key -->
     <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="your Goolge API key" />


text:
Q: Splitting a string after max X characters and preserve whole words I would like to split a String using regex just like in this example,
but in my case I want that each words in a new line will not exceed X characters.
So the following code doesn't do the trick since it finds every instance of at least X non-newline characters (and not max X).
s = s.replaceAll("(.{" + x + ",}?)\\s+", "$1\n");

I can easily do this using other methods, but I would like to do it using a REGEX

A: Try this:
s = s.replaceAll("(.{0,"+ x+"})\\b", "$1\n");

or the trimmed version,
s = s.replaceAll("(?:\\s*)(.{1,"+ x +"})(?:\\s+|\\s*$)", "$1\n")


text:
Q: .NET WebService IPC - Should it be done to minimise some expensive operations? I'm looking at a few different approaches to a problem: Client requests work, some stuff gets done, and a result (ok/error) is returned.
A .NET web service definitely seems like the way to go, my only issue is that the "stuff" will involve building up and tearing down a session for each request. Does abstracting the "stuff" out to an app (which would keep a single session active, and process the request from the web service) seem like the right way to go? (and if so, what communication method)
The work time is negligible, my concern is the hammering the transaction servers in question will probably get if I create/drop a session for each job.
Is some form of IPC or socket based communication a feasible solution here?
Thoughts/comments/experiences much appreciated.
Edit:
After a bit more research, it seems like hosting a WCF service in a Windows Service is probably a better way to go...

A: well, here we go:

*

*Do not setup a new communication channel for every request. CLient side / Server side use WCF implementations and make sure the client does not get a new procxy for every call ;) Especially with HTTPS channel setup is expensive.

*Do not call the service ;) SImple as that - make as few calls as POSSIBLE. Have a coarse interface optimized into not making many calls. Allow batching of results. For example "GetInvoice" could be "GetDocuments" - returning not only an invoice, and taking multiple ID's, returning multiple documents. A list of 30 invoices turns from 30 calls into 1. Otherwise a messaging bus approach may work - I use one like that and transport up to 1024 messages per call.

*Try not to use a web service if you have a ton of load. Use WCF and NetTcp binding (which is binary and not using HTTP, so it is not a web service). THe HTTP overhead is tremendous - look up google, someone made a test and we talk net tcp sometimes being about 900 TIMES faster. Especially if you do little work and have lost of users this may increase scalability. Negative - you are only WCF compliant on the client side, no "Web Service" anymore.
This is pretty much all you can do. With different losses, but this is how to get performance up ;) If you talk of purely IPC consider using named pipes, not even net.tcp - named pipes are very efficient (using shared memory between the processes), but limited to the same machine in the .NET implementation.


text:
Q: Progress bar with PHP & Ajax I am working on progress bar which updates progress using ajax requests and session variables. When my program performs time consuming operation such as sending many emails etc. it just set proper session variable (which contains progress value). This operation is started by function post() in code below.
In the meantime, the second function ask() is performed in loop every 500ms. It should return current progress in real time. And here is the problem: every request sent by ask() are waiting for request sent by post() function is finished. The funny part is that if I set some URL like google.com instead of url/to/progress it works just fine except that it is not what I want :). Which means that problem is on the server side.
Not sure if it's important but I use Yii Framework.
All the code below is only scratch (but working) and its only purpose is to show what I meant.
Thanks in advance.
Sorry for my poor english :)
View part:
<script type="text/javascript">
function ask() {
  var d = new Date();
  var time = d.getTime();
  $.ajax({

    type: 'get',
    url: '/url/to/progress' + '?time=' + time,
    success: function(data) {
      $("#progress").html(data);
    }
  })
}

function post() {
  var d = new Date();
  var time = d.getTime();

  $.ajax({
      type: 'post',
      url: '/url/to/post' + '?time=' + time,
      data: {"some": "data"},
      success: function(data) {alert(data)}
    });
}

$("#test").click(
  function() {
    post();
    var progress = setInterval("ask();", 500);
  }
);
</script>

Controller part:
public function actionPost($time) {
  sleep(5); // time consuming operation
  echo $time . ' : ' . microtime();
  exit;
}

public function actionProgress($time) {
  echo $time . ' : ' . microtime();
  exit;
}

A: I think your problem here is session related.
When a script has an open session, it has a lock on the session file. This means that any subsequent requests which use the same session ID will be queued until the first script has released it's lock on the session file. You can force this with session_write_close() - but this won't really help you here, as you are trying to share the progress info with the session file so post script would need to keep the session data open and writable.
You will need to come up with another way of sharing data between the post and progress scripts - if post has the session data open throughout it's execution, progress will never be able to access the session data until after post has finished executing. Maybe you could use the session ID to create a temporary file which post has write access to, in which you put the progress indicator data. The progress can check the file and return that data. There are many options for IPC (inter-process communication) - this is not a particularly beautiful one but it does have the advantage of maximum portability.
As a side note - please don't pass strings to setInterval(), pass functions. So your line should actually read:
var progress = setInterval(ask, 500);

But - it would be better to use setTimeout() in the success/error handlers of the ask() ajax function. This is because by using setInterval(), a new request will be initiated regardless of the state of the previous one. It would be more efficient to wait until the previous request has finished before initiating the next one. So I would do something more like this:
<script type="text/javascript">

  // We'll set this to true when the initail POST request is complete, so we
  // can easily know when to stop polling the server for progress updates
  var postComplete = false;

  var ask = function() {

    var time = new Date().getTime();

    $.ajax({

      type: 'get',
      url: '/url/to/progress' + '?time=' + time,

      success: function(data) {
        $("#progress").html(data);
        if (!postComplete)
          setTimeout(ask, 500);
        }
      },
      error: function() {
        // We need an error handler as well, to ensure another attempt gets scheduled
        if (!postComplete)
          setTimeout(ask, 500);
        }
      }

    });

  }

  $("#test").click(function() {

    // Since you only ever call post() once, you don't need a seperate function.
    // You can just put all the post() code here.

    var time = new Date().getTime();

    $.ajax({

      type: 'post',
      url: '/url/to/post' + '?time=' + time,
      data: {
        "some": "data"
      },

      success: function(data) {
        postComplete = true;
        alert(data);
      }
      error: function() {
        postComplete = true;
      }

    });

    if (!postComplete)
      setTimeout(ask, 500);
    }

  });

</script>

...although this still doesn't fix the session problem.

A: @DaveRandom above correctly points out that you are a victim of a session storage lock.
The workaround is quite simple. You want to make the script that processes post() release the lock on the session data so that the script that handles ask() can access this session data. You can do that with session_write_close.
The fine print here is that after calling session_write_close you will not have access to session variables, so you need to structure the script for post accordingly:

*

*Read all data you will need from $_SESSION and save a copy of it.

*Call session_write_close to release the session lock.

*Continue your lengthy operation. If you need session data, get it out of your own copy and not $_SESSION directly.

Alternatively, you can toggle the lock on the session multiple times during the script's lifetime:
session_start();
$_SESSION['name'] = 'Jon';

// Quick operation that requires session data
echo 'Hello '.$_SESSION['name'];

//  Release session lock
session_write_close();

// Long operation that does not require session data.
sleep(10);

// Need access to session again
session_start();
echo 'Hello again '.$_SESSION['name'];

This arrangement makes it so that while the script it sleeping, other scripts can access the session data without problems.


text:
Q: How to pack/unpack a byte in q/kdb What I'm trying to do here is pack a byte like I could in c# like this:
string symbol = "T" + "\0";
byte orderTypeEnum = (byte)OrderType.Limit;
int size = -10;

byte[] packed = new byte[symbol.Length + sizeof(byte) + sizeof(int)]; // byte = 1, int = 4
Encoding.UTF8.GetBytes(symbol, 0, symbol.Length, packed, 0); // add the symbol
packed[symbol.Length] = orderTypeEnum; // add order type
Array.ConstrainedCopy(BitConverter.GetBytes(size), 0, packed, symbol.Length + 1, sizeof(int)); // add size

client.Send(packed);

Is there any way to accomplish this in q?
As for the Unpacking in C# I can easily do this:
    byte[] fillData = client.Receive();
    long ticks = BitConverter.ToInt64(fillData, 0);
    int fillSize = BitConverter.ToInt32(fillData, 8);
    double fillPrice = BitConverter.ToDouble(fillData, 12);

    new
    {
        Timestamp = ticks,
        Size = fillSize,
        Price = fillPrice
    }.Dump("Received response");

Thanks!

A: One way to do it is
symbol:"T\000"
orderTypeEnum: 123 / (byte)OrderType.Limit
size: -10i;
packed: "x"$symbol,("c"$orderTypeEnum),reverse 0x0 vs size / *

UPDATE:
To do the reverse you can use 1: function:
(8 4 8; "jif")1:0x0000000000000400000008003ff3be76c8b43958 / server data is big-endian
("jif"; 8 4 8)1:0x0000000000000400000008003ff3be76c8b43958 / server data is little-endian
/ ticks=1024j, fillSize=2048i, fillPrice=1.234

*) When using BitConverter.GetBytes() you should also check the value of BitConverter.IsLittleEndian to make sure you send bytes over the wire in a proper order. Contrary to popular belief .NET is not always little-endian. Hovewer, an internal representation in kdb+ (a value returned by 0x0 vs ...) is always big-endian. Depending on your needs you may or may not want to use reverse above.


text:
Q: FIFO SQL Query for stock and value I have a stock Ledger table like this:
    item  date           time      in_qty  out_qty  in_Price  out_Price
    ABC   01-April-2012  00:00:00  200              750.00
    ABC   05-April-2012  00:00:00          100                800.00
    ABC   10-April-2012  00:00:00  50               700.00
    ABC   16-April-2012  00:00:00  75               800.00
    ABC   25-April-2012  00:00:00          175                850.00
    XYZ   02-April-2012  00:00:00  150              350.00
    XYZ   08-April-2012  00:00:00          120               380.00
    XYZ   12-April-2012  00:00:00          80                370.00
    XYZ   24-April-2012  00:00:00  80               330.00
    XYZ   24-April-2012  00:00:00  90               340.00
    LPQ   26-April-2012  00:00:00  70               240.00
    LPQ   27-April-2012  00:00:00  30               230.00

I need the value of the inventory for each item in FIFO (First in first out) meaning the first purchased item should be consumed first. The output stock valuation of the above data is:
    Item    Qty   Value
    ABC     50    40000
    XYZ     110   40500
    LPQ     100   23700

Please help me to get the solution in FIFO

A: I got what I expected ,
declare @Stock table (item char(3) not null,[date] date not null,[time] time not null,in_qty decimal(18,5) null,out_qty decimal(18,5) null,in_Price decimal(10,2) null,out_Price decimal(10,2) null)
insert into @Stock(item , [date] ,[time] , in_qty, out_qty, in_Price,out_Price) values
('ABC','20120401','00:00:00',200 ,0 ,750 ,0),
('ABC','20120401','00:00:00',0 ,100 ,0 ,800),
('ABC','20120401','00:00:00',50 ,0 ,700 ,0),
('ABC','20120401','00:00:00',75 ,0 ,800 ,0),
('ABC','20120401','00:00:00',0 ,175 ,0 ,850),
('XYZ','20120401','00:00:00',150 ,0 ,350 ,0),
('XYZ','20120401','00:00:00',0 ,120 ,0 ,380),
('XYZ','20120401','00:00:00',0 ,80 ,0 ,370),
('XYZ','20120401','00:00:00',80 ,0 ,330 ,0),
('XYZ','20120401','00:00:00',90 ,0 ,340 ,0),
('PQR','20120401','00:00:00',70 ,0 ,240 ,0),
('PQR','20120401','00:00:00',30 ,0 ,230 ,0)

;WITH OrderedIn as
    (
        select *,ROW_NUMBER()OVER (PARTITION BY item ORDER BY date asc,time asc) as S_No
        from @Stock
        where in_qty <> 0
    ),  RunningTotals as
    (
        select item, in_qty, in_Price as price, cast(in_qty as varchar(100)) as Total
                ,cast(0 as varchar(100)) as PrevTotal,S_No from OrderedIn where S_No = 1
        union all
        select rt.item ,oi.in_qty ,oi.in_Price as price
                ,cast(rt.Total + oi.in_qty as varchar(100)),cast(rt.Total as varchar(100)),oi.S_No
        from
                RunningTotals rt
            inner join OrderedIn oi
                on rt.item = oi.item
                and rt.S_No = oi.S_No - 1
    ), TotalOut as
    (
        select item,SUM(out_qty) as Qty from @Stock where out_Price <> 0 group by item
    )
    select
         rt.item
        ,SUM(CASE WHEN PrevTotal > COALESCE(out.Qty,0) THEN rt.in_qty ELSE rt.Total - COALESCE(out.Qty,0) END) as Qty
        ,SUM(CASE WHEN PrevTotal > COALESCE(out.Qty,0) THEN rt.in_qty ELSE rt.Total - COALESCE(out.Qty,0) END * (price)) as Value
    from
        RunningTotals rt
            left join
        TotalOut out
            on
                rt.item = out.item
    where
        rt.Total > COALESCE(out.Qty,0)
    group by rt.item

The first observation is that we don't need to do anything special for OUT transactions - we just need to know the total quantity. That's what the TotalOut CTE calculates. The first two CTEs work with IN transactions, and compute what "interval" of stock each represents - change the final query to just select * from RunningTotals to get a feel for that.
If you have separate columns for date and time ,Then you should group by date first then time.

*

*In FIFO (First in first out) valuation Group by for date and time like ascending


text:
Q: Scrub filesystem to check all used sectors are readable I'd like to have a way to periodically check that I can indeed read all the data on my drives, so I can re-write any files and/or investigate further if there is an issue.
Both ZFS and Btrfs have a scrub command for this purpose.
How do I efficiently go about scrubbing ext* and NTFS?

A: One method is to simply read each file, expecting a message on STDERR if there is a problem:
(cd /mountpoint && find . -type d -o -type f -printf '%P\0' | xargs -0 b2sum -z) 2>errors | tee hashes

(cd /mountpoint && find . -xdev -print0 | xargs -0P4 xxhsum ) >hashes 2>errors
Using -z with b2sum (or sha256sum) allows for filenames with newlines.
This purposefully includes directories to allow for empty directories.

If empty directories aren't an issue, this is shorter:
(cd /mountpoint && sha256deep -0clrz -j0 -of . ) 2> errors | tee hashes

This will print the filesize, hash, and filename followed by a NUL.
Ideally, I'd add -t to sha256deep but there's currently this issue.


text:
Q: Why should you not restore a DC that was backed up 6 months ago? Why should you not restore a DC that was backed up 6 months ago?
As I am learning Active Directory Domain Services I came across this question in one of the blogs but I was unable to find a detailed answer. So please can anybody explain this concept to me.

A: There is a thing called tombstone lifetime in Active Directory. When you delete an object in Active Directory it is not immediately gone, it is converted to a tombstone and this information is replicated to the other DCs. When the tombstone lifetime is reached the object will be purged. If you restore prior to a state before the deletion and the tomsbtone is not replicated to the restored DC before it expires, the object will remain present in your restored DC but not in the other DCs. Now you have inconsistent data. Default tomsbtone lifetime for Server 2008 and onwards is 180 days (= 6 months).

A: Not only deleted objects.
Let us assume for a while that some servers have been configured IIS, Certificate server (PKI), policies have been applied on OU, delegation has been given to some users, Authentication has been done on some AD users like VPN access, etc.
All these changes will be replaced with old Active Directory.  This action is not acceptable at all.


text:
Q: Load Ubermenu Stylesheet in Header Rather Than Footer In Wordpress Recently took over managing a wordpress website, which I don't have much experience in. Wondering how I can move the Ubermenu minified css stylesheet and load that in the header rather than the footer. Since it loads in the footer, the sub menu flashes on page load and then hides. Any help on this would be great!
Thanks

A: First you will need to dequeue the stylesheet:
wp_dequeue_style( $handle )

Then you will need to requeue the stylesheet in the header:
wp_enqueue_style( $handle, $src, $deps, $ver, $media );

From what I can tell from the code, all stylesheets are enqueued to the header, which suggests that your stylesheet is being loaded in some 'non standard' way inorder to get it into the footer. So you'll really need to track that down as you'll likely have to manually remove it or use other hooks to remove it rather than dequeue it.


text:
Q: Sitecore MVC redirect to another page I had a requirement in my Sitecore MVC to display Carousel Items in the Homepage and when click the View More it will redirect to another page for user to view the full content
How could I achieve this? Currently all my items in Sitecore has Controller Rendering in Presentation Details. I'm just not sure how to get the GUID of the Carousel Item using  then in the controller action it will redirect on the page?

A: I assume that you have carousel items under one folder in your content tree in Sitecore with some specific fields for each carousel item like image, title ...etc, so you should have field in the carousel items with for link:
Name: Link  Type : GeneralLink
link each carousel item to the proper page ,And then in your view you can read the page URL:
and you can use this method to get link URL to the page from your carousel component :
public String LinkUrl(Sitecore.Data.Fields.LinkField lf)
{
    switch (lf.LinkType.ToLower())
    {
      case "internal":
        // Use LinkMananger for internal links, if link is not empty
        return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty;
      case "media":
        // Use MediaManager for media links, if link is not empty
        return lf.TargetItem != null ? Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem) : string.Empty;
      case "external":
        // Just return external links
        return lf.Url;
      case "anchor":
        // Prefix anchor link with # if link if not empty
        return !string.IsNullOrEmpty(lf.Anchor) ? "#" + lf.Anchor : string.Empty;
      case "mailto":
        // Just return mailto link
        return lf.Url;
      case "javascript":
        // Just return javascript
        return lf.Url;
      default:
        // Just please the compiler, this
        // condition will never be met
        return lf.Url;
    }
}

and in your carousel view :
Sitecore.Data.Fields.LinkField linkField = carouselItem.Fields["Link"];
var pageUrl = linkField.LinkUrl();

This code is taken from this answer

A: I think you need to prepare appropriate model object in the controller action and then pass it to the view.
Model class:
public class CarouselModel
{
    public List<Item> CarouselItems { get; set; }
}

Controller action:
public ActionResult Carousel()
{
    var model = new CarouselModel
    {
        CarouselItems = /* get appropriate items dependent on your logic */
    };

    return View("~/Views/renderings/Carousel.cshtml", model);
}

Razor view:
@model CarouselModel

    @foreach(var carouselItem in Model.CarouselItems)
    {
        Sitecore.Data.Fields.LinkField targetLinkField = carouselItem.Fields["Target"];
        Some link
    }

Example above assumes that template of 'Carousel Item' contains 'Target' link field.


text:
Q: swfobject 2.2 loader for swf Embedding swf with swfobject 2.2, I need loader for swf file and want callback on swf loads 100%. I am currently using swfobject's percentLoaded method as I found answer here on stackoverflow
But the problem is mozilla is giving me error of too much recursion and stops further execution.
Any help?

A: Why not using a swf lader as a shell to load the child swif? So you dont need to include any JS in the process?


text:
Q: Docker Redis TLS authentication failure with .netcore app I am trying to use redis with tls with a netcore application and I get an authentication error
The Setup:
Docker:
I created a redis docker container using redis:6.2.0
docker-compose.yaml:
.
.
redis:
    image: redis:6.2.0
    command: redis-server /usr/local/etc/redis/redis.conf --appendonly yes
    container_name: "cxm-redis"
    ports:
     - "6379:6379"
    volumes:
      - cxm-redis-data:/data
      - C:/SaaS/certs/redis.conf:/usr/local/etc/redis/redis.conf
      - C:/SaaS/certs/tests/tls/redis.crt:/usr/local/etc/redis/redis.crt
      - C:/SaaS/certs/tests/tls/redis.key:/usr/local/etc/redis/redis.key
      - C:/SaaS/certs/tests/tls/ca.crt:/usr/local/etc/redis/ca.crt

up to here all looks good, (as far as I can tell) I managed to authenticate using the following command
redis-cli --tls --cert ../usr/local/etc/redis/redis.crt --key /usr/local/etc/redis/redis.key --cacert /usr/local/etc/redis/ca.crt and I can succesfully ping and request keys.
I created the certificates with openssl and for the redis.conf i am using the redis.conf example from redis
The important bits:
### TLS
tls-port 6379
tls-cert-file /usr/local/etc/redis/redis.crt
tls-key-file /usr/local/etc/redis/redis.key
tls-ca-cert-file /usr/local/etc/redis/ca.crt

netcore:
For my .netcore application I am using the StackExchange library and for the TLS connection I followed the instructions here, like so
var options = new ConfigurationOptions
{
    EndPoints = { "redis-test:6379" },
    Password = "not-the-actual-password",
    Ssl = true
};
options.CertificateSelection += delegate {
    return new X509Certificate2("./redis_certificate.p12");
};
_db = ConnectionMultiplexer.Connect(options).GetDatabase();

the redis_certificate.p12 was generated using openssl with this command line
openssl pkcs12 -export -out sample_certificate.p12 -inkey redis.key -in redis.crt
The Issue:
When I make a request to redis from my app I get the following error:
It was not possible to connect to the redis server(s). There was an authentication failure; check that passwords (or client certificates) are configured correctly. AuthenticationFailure on redis-test:6379/Interactive, Initializing/NotStarted
in my apps logs, and I get the following in my redis logs:

*

*Error accepting a client connection: error:1408F10B:SSL routines:ssl3_get_record:wrong version number

*Error accepting a client connection: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca,

*Error accepting a client connection: (null)
Are there any apparent mistakes in my setup I am failing to see? This is my first time trying this and maybe I am assuming too much or heading down the wrong way..
Trying to resolve this I found several questions with a similar issue but implementing their fixes did not resolve my issue..
a few of the things I tried

*

*sending different ssl protocols from my .netcore app

*sending the pfx/p12 certificate in different ways

*several different redis configurations

Edit: I can provide as much code as needed!

A: For any one facing the same issue, it seems the server was using a non routed CA for the server certificates, the solution I found was to use the CertificateValidation callback of StackExchange.Redis library with the following code
private static bool CheckServerCertificate(object sender, X509Certificate certificate,
   X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors)
    {
        // check that the untrusted ca is in the chain
        var ca = new X509Certificate2(_redisSettings.CertificatePath);
        var caFound = chain.ChainElements
            .Cast<X509ChainElement>()
            .Any(x => x.Certificate.Thumbprint == ca.Thumbprint);

        return caFound;
    }
    return false;
}

also an important part of the code being the condition
if((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors)


text:
Q: ImageView Camera preview Can I set an ImageView to a camerapreview? Instead of using a surfaceview? I'm trying to make a camera preview semi transparent with setAlpha method, but It doesn't work on surfaceview. I mean it does work, but the camera preview is not semi transparent.

A: No you cannot do this, SurfaceView is the only way to create a Camera preview in Android.

A: Well actually you can but not using SurfaceView. You achieve this by using GLSurface view, where you render each of your frame using shaders. In the fragment shader you can specify the opacity of your video. If you don't know OpenGL ES 2.0 you can start from here http://developer.android.com/training/graphics/opengl/index.html, but there are also many tutorial including rendering frames using opengl.


text:
Q: How to run a django signal only once in order to affect more than one model instance Is it possible to run a django signal only once in order to affect more than one model instances?
And when this signal will run? I don't want to use crontab library.
Imagine that I have 10 instances of model A.
I want to run a signal that creates an instance of model B for every instance of model A.
Something like the below function but for all A instances:
@receiver(signals.post_save, sender=A)
def create_b(sender, instance, created, **kwargs):
    if created:
        B.objects.create()

A: What you need is a Data Migration.
First run:
python manage.py makemigrations --empty yourappname

This would generate an empty migration in your app (here yourappname), you can refer the documentation linked above to see how it would look. Now you would add your own code to the migration to do what you want. First you would add a function that would do your task for you and add it to the list operations by using RunPython. At the end your migration should look something like:
from django.db import migrations

def your_function(apps, schema_editor):
    # We can't import the models directly as it may be a newer
    # version than this migration expects. We use the historical version.
    A = apps.get_model('yourappname', 'A')
    B = apps.get_model('yourappname', 'B')
    for a in A.objects.all():
        b = B.objects.create()
        # Do something with b if needed

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(your_function),
    ]

Now anyone who runs python manage.py migrate would have run this command and be up to date on the changes you want them to have made.


text:
Q: reversing magnitude of real values I am not really a math guy, I had no clue what to title this question...
Anyways, the question:
I have a collection of values, let's say it's form is a matrix.  When I select a value from this matrix, I can no longer select a value from that row or column.
I want to select minimal values from the matrix.  This means that I want to avoid picking values, even if they are small, if they take away other small values I could potentially pick.
So my question is, is there a way to transform all of the values in my matrix, such that the values that are closer to zero (the smaller values) become larger, and in turn the values that are larger become smaller, while still maintaining some kind of proportionality to my original matrix?
Example:
[[2, 4, 7],
[3, 11, 1],
[5, 6,8]]
So I can pick say:
2,11,8
or 2,1,6
or 4,3,8
etc
And so, any pick I make can not only be measured in terms of it's own magnitude, but also in terms of the magnitude of the rest of the row and column.  Since it is required that for each pick, I will remove several other picks - then if that magnitude is greater it suggests the pick may be better.
But to take this one step further, what is specifically more important is that I do not pick entries that remove other good picks.
And, I feel that I could get a strong indicator for if I am going to remove other good picks, if I could make the small numbers stand out.  Simply taking the sum is not good enough.  It could be the case that all of my alternatives are "average" in magnitude, and there would be no way to tell the difference between this situation, and a situation where I was removing 2 optimal choices and some very poor choices.  So, I need a way to make my choices stand out more and more as their magnitude is lower, and less and less as their magnitude is higher.
Hopefully someone is following what I am asking for....


text:
Q: Implementing Profile Photo Upload for Student Database I am currently develop a student database system for my faculty. I am using the PHP together with MySQL. I am thinking to create an option for student to upload their profile photo but I could not find any proper instruction or tutorial of doing that.
Here's the code processing the file uploading:
<?php
 /* Script name: uploadFile.php
  * Description: Uploads a file via HTTP with a POST form.
  */
  if(!isset($_POST['Upload']))
  {
    include("form_upload.inc");
  }
  else
  {
    if($_FILES['pix']['tmp_name'] == "none")
    {
      echo "

        File did not successfully upload. Check the
            file size. File must be less than 500K.
";
      include("form_upload.inc");
      exit();
    }
    if(!ereg("image",$_FILES['pix']['type']))
    {
      echo "

        File is not a picture. Please try another
            file.
";
      include("form_upload.inc");
      exit();
    }
    else
    {
      $destination='c:\data'."\\".$_FILES['pix']['name'];
      $temp_file = $_FILES['pix']['tmp_name'];
      move_uploaded_file($temp_file,$destination);
      echo "

        The file has successfully uploaded:
            {$_FILES['pix']['name']}
            ({$_FILES['pix']['size']})
";
    }
  }
?>

Code for the file upload form:

<title>File Upload</title>

Enter the file name of the product picture you
        want to upload or use the browse button
        to navigate to the picture file.

When the path to the picture file shows in the
        text field, click the Upload Picture
        button.

<form enctype="multipart/form-data"
        action="uploadFile.php" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE"
         value="500000" />
  <input type="file" name="pix" size="60" />

<input type="submit" name="Upload"
        value="Upload Picture" />
</form>

I got the same outcome which I cant find the file that being uploaded and it is not being uploaded to the location as it should be.

A: You should change the destination:
$destination='c:\data'."\".$_FILES['pix']['name'];

Or, if this is not working, try to move the uploaded file somewhere near the script path, like:
$destination= dirname(__FILE__).DIRECTORY_SEPARATOR.$_FILES['pix']['name'];

If the second one works then is means, you have given a wrong directory for the upload.

A: I think you should first change your image path.
and than your datatype set to image in mysql manually,
it will be done.

A: Do you get any error messsage? Do the PHP user have write permissions to the upload directory?
Also, here's two advices possibly not related to your question:

*

*Don't use eregi in any new code. It is deprecated, which means it will be removed in a future version of PHP. Instead, use the preg_ functions, or just strpos in this case.

*Why would $_FILES['pix']['tmp_name'] ever be the string "none"?


text:
Q: Output a CHANGING OrderedDict to CSV I've poured over this post, but the answers don't seem to work for my needs. However, I'm very new to Python so that might be the problem as well.
Here's some lines from the output.csv:
Case Parties Address
25 THOMAS ST., PORTAGE, IN
67 CHESTNUT ST., MILLBROOK, NJ
1 EMPIRE DR., AUSTIN, TX, 11225
111 WASHINGTON AVE. #404, VALPARAISO, AK
89 E. JERICHO TPKE., Scarssdale, AZ
ORIGINAL POST CODE
import usaddress
import csv

with open('output.csv') as csvfile:
reader = csv.DictReader(csvfile)
    for row in reader:
        addr=row['Case Parties Address']
        data = usaddress.tag(addr)
        print(data)

(OrderedDict([('AddressNumber', u'4167'), ('StreetNamePreType', u'Highway'), ('StreetName', u'319'), ('StreetNamePostDirectional', u'E'), ('PlaceName', u'Conway'), ('StateName', u'SC'), ('ZipCode', u'29526-5446')]), 'Street Address'

Much like the previous post, I need to output the parsed data into csv. As best as I can tell, I need to do the following steps:

*

*Provide the headers as a list for reference. (They're listed here in 'Details'.)

*Using Usaadress.tag(), parse the source_csv as "data" BUT keep their corresponding "keys."

*Map the key:data to the header_reference

*Export into output_csv that has one header row.

I'm using the Python module, usaaddress, to parse a large csv (200k+). The module outputs the parsed data using OrderedDict. The aforementioned post only works if all the fields map to the same headers for all records. However, one of the MANY benefits of usaddress is that it parses out data even when there isn't fields to parse. So, for example, "123 Fake St, Maine, PA" maps to address,city,state headers perfectly. But "123 Jumping Block, Suite 600, Maine, PA" will put the "Suite 600" in the "city" column since it's matching statically based on position. If I parse the latter by itself, usaddress provides address, occupancy identifier (e.g. "suite #"), city, state headers.
The output format that I need is provided when I use the parserator's online parser, but it only can accommodate 500 rows at a time.
It seems like my code won't know what each data point is until it gets routed through the module; a chicken-or-the-egg situation. How do I write rows to a CSV file when each row might have a different subset of columns?
For reference, the error that I get when I try the closest solution (provided by isosceleswheel) is valueerror: I/O(...) and they reference lines 107 and 90 of the csv.py library, both of which pertain to fieldnames.
with open('output.csv') as csvfile:
reader = csv.DictReader(csvfile)

with open('myoutputfile', 'w') as o:  # this will be the new file you write to
    for row in reader:
        addr=row['Case Parties Address']
        data = usaddress.tag(addr)
        header = ','.join(data.keys()) + '\n'  # this will make a string of the header separated by comma with a newline at the end
        data_string = ','.join(data.values()) + '\n' # this will make a string of the values separated by comma with a newline at the end
        o.write(header + data_string)  # this will write the header and then the data on a new line with each field separated by commas

A: see this github issue for a solution
since we know all the possible labels in usaddress, we can use them to define the fields in the output.
I can't comment on an answer b/c I don't have enough reputation, but I'd recommend against using the usaddress parse method for this task. The tag method will parse an address and then concatenate consecutive address tokens when they have the same label, and will raise an error if there are non-consecutive tokens with the same label - it'd be good to capture tagging errors in the output.

A: You want to parse each address separately and store in a list. Then you can use a Pandas DataFrame to align the outputs. Something like this:
import pandas as pd

data = ['Robie House, 5757 South Woodlawn Avenue, Chicago, IL 60637',
        'State & Lake, Chicago']

tagged_addresses = [usaddress.parse(line) for line in data]

address_df = pd.DataFrame(tagged_addresses)

print(address_df)

  AddressNumber BuildingName IntersectionSeparator PlaceName SecondStreetName StateName StreetName StreetNamePostType StreetNamePreDirectional ZipCode
0          5757  Robie House                   NaN   Chicago              NaN        IL   Woodlawn             Avenue                    South   60637
1           NaN          NaN                     &   Chicago             Lake       NaN      State                NaN                      NaN     NaN


text:
Q: Suppose $A$ is Artinian and commutative with 1. If $J(A)M=M$, then $M=\{0\}$. $J(A)$ is the Jacobson radical of A. I just want to know if the following proof is valid for the above theorem. (Note: $M$ is a $A$-module)
Sketch: Since $A$ is Artinian we know that $J(A)$ is nilpotent i.e. there exists $k\geq 1, k\in \mathbb{Z}$ such that $J(A)^k=\{0\}$. Hence, ${0}=\{0\}M=J(A)^kM=J(A)^{k-1}M=...=J(A)M=M$. Is this valid? Does it also mean that Nakayama's Lemma holds for non-finitely generated modules of Artinian Rings?

A: It clearly shows that (this formulation of) Nakayama's lemma holds for all modules, not just finitely generated ones, over a ring with nilpotent Jacobson radical.
The formulation of Nakayama's lemma you gave is also still true for noncommutative rings.


text:
Q: ASP.NET Core Authorize Redirection to wrong URL I am trying to run a web application with the following route mapped:
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                "default",
                "WoL/{controller=Account}/{action=Login}/{id?}");
        });

If the user is not authenticated and tries to access a action having the AuthorizeAttribute, the user should be redirected to the default login URL (as seen above). But the user gets redirected to "/Account/Login" instead of "/WoL/Account/Login". How can I redirect the user to "/WoL/Account/Login", if the user is not authenticated? I have configured the following Cookie Authentication:
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            LoginPath = new PathString("/WoL/Account/Login"),
            AutomaticChallenge = true
        });

A: The answer of @Dmitry is not working anymore in ASP.NET Core 3.1. Based on the documentation that you can find here, you have to add the following code to the ConfigureServices:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest)
   .AddRazorPagesOptions(options =>
   {
       options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
       options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
    });

    services.ConfigureApplicationCookie(options =>
    {
       options.LoginPath = $"/Identity/Account/Login";
       options.LogoutPath = $"/Identity/Account/Logout";
       options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
     });

A: This works for me (in Startup.ConfigureServices):
services.AddIdentity<User, UserRole>(options =>
{
    options.Cookies.ApplicationCookie.LoginPath = new PathString("/Admin/Account/Login");
});

A: Try to add options.ForwardChallenge = "oidc"; to AddCookie options config


text:
Q: MS Excel - Combining two columns in two sheets by getting all rows of second column for each entry of first colmn I have 2 excel workbooks with a sheet each. Each sheet has a single column of unique codes. The first one has around 1000 rows like
COLUMN 1
1
2
3
4
.
.
.
1000

and the second one is like
COLUMN 2
a
b
c
d
.
.
.
r

I want to get them both in a single sheet like
COLUMN 1          COLUMN 2
1                 a
1                 b
1                 c
1                 d
1                 e
1                 f
1                 g
1                 h
1                 i
1                 j
1                 k
1                 l
1                 m
1                 n
1                 o
1                 p
1                 q
1                 r
2                 a
2                 b
2                 c
.                 .
.                 .
.                 .
.                 .
1000              p
1000              q
1000              r

Please suggest how do I do this ?

A: With formulas:
In A1 on Sheet3:
=INDEX(Sheet1!A:A,INT((ROW(1:1)-1)/COUNTA(Sheet2!A:A))+1)

In B2 on Sheet3:
=INDEX(Sheet2!A:A,MOD(ROW(1:1)-1,COUNTA(Sheet2!A:A))+1)

Then copy down.


text:
Q: After installing Chef Development Kit, i ran "chef verify" Does anyone know why i am getting this issue.
i dont know the reason i am doing it in ubuntu machine.
Please help me if any had faced the similar kind of issue.
machine config:
Ruby 2.2.1
chef 12 server
OS Ubuntu
Running verification for component 'berkshelf'
Running verification for component 'test-kitchen'
Running verification for component 'tk-policyfile-provisioner'
Running verification for component 'chef-client'
Running verification for component 'chef-dk'
Running verification for component 'chef-provisioning'
Running verification for component 'knife-spork'
Running verification for component 'delivery-cli'
Running verification for component 'git'
Running verification for component 'opscode-pushy-client'
Running verification for component 'chef-sugar'
..............
Generating cookbook example
- Ensuring correct cookbook file content

================================================================================
Error executing action `create_if_missing` on resource 'template[/tmp/d20160922-20221-1do1qzg/example/spec/unit/recipes/default_spec.rb]'
================================================================================

Chef::Mixin::Template::TemplateError
------------------------------------
undefined method `gsub' for nil:NilClass

Resource Declaration:
---------------------
# In /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/skeletons/code_generator/recipes/cookbook.rb

 84: template "#{cookbook_dir}/spec/unit/recipes/default_spec.rb" do
 85:   source "recipe_spec.rb.erb"
 86:   helpers(ChefDK::Generator::TemplateHelper)
 87:   action :create_if_missing
 88: end
 89:

Compiled Resource:
------------------
# Declared in /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/skeletons/code_generator/recipes/cookbook.rb:84:in `from_file'

template("/tmp/d20160922-20221-1do1qzg/example/spec/unit/recipes/default_spec.rb") do
  action [:create_if_missing]
  retries 0
  retry_delay 2
  default_guard_interpreter :default
  source "recipe_spec.rb.erb"
  helper_modules [ChefDK::Generator::TemplateHelper]
  declared_type :template
  cookbook_name :code_generator
  recipe_name "cookbook"
  atomic_update true
  path "/tmp/d20160922-20221-1do1qzg/example/spec/unit/recipes/default_spec.rb"
end

Template Context:
-----------------
on line #5
  3: # Spec:: default
  4: #
  5: <%= license_description('#') %>
  6:
  7: require 'spec_helper'

Platform:
---------
x86_64-linux

ERROR: Chef failed to converge:

Chef::Mixin::Template::TemplateError (undefined method `gsub' for nil:NilClass) on line #5:

  3: # Spec:: default
  4: #
  5: <%= license_description('#') %>
  6:
  7: require 'spec_helper'

  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/generator.rb:155:in `license_description'
  (erubis):5:in `block in evaluate'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/erubis-2.7.0/lib/erubis/evaluator.rb:74:in `instance_eval'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/erubis-2.7.0/lib/erubis/evaluator.rb:74:in `evaluate'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/mixin/template.rb:161:in `_render_template'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/mixin/template.rb:147:in `render_template'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/template/content.rb:53:in `file_for_provider'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/file_content_management/content_base.rb:40:in `tempfile'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:462:in `tempfile'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:339:in `do_generate_content'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:150:in `action_create'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:162:in `action_create_if_missing'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider.rb:145:in `run_action'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource.rb:603:in `run_action'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:69:in `run_action'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:97:in `block (2 levels) in converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:97:in `each'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:97:in `block in converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/resource_list.rb:94:in `block in execute_each_resource'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:116:in `call'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:116:in `call_iterator_block'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:85:in `step'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:104:in `iterate'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:55:in `each_with_index'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/resource_list.rb:92:in `execute_each_resource'
  /opt/chefdk/embedded/lib/ruby/2.1.0/forwardable.rb:183:in `execute_each_resource'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:96:in `converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/chef_runner.rb:43:in `converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/command/generator_commands/cookbook.rb:82:in `run'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/command/generate.rb:88:in `run'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/command/base.rb:58:in `run_with_default_options'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/cli.rb:73:in `run'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/bin/chef:25:in `<top (required)>'
  /opt/chefdk/bin/chef:74:in `load'
  /opt/chefdk/bin/chef:74:in `<main>'

Caused by: (Chef::Mixin::Template::TemplateError) undefined method `gsub' for nil:NilClass

......................................
---------------------------------------------
Verification of component 'rubocop' succeeded.
Verification of component 'kitchen-vagrant' succeeded.
Verification of component 'openssl' succeeded.
Verification of component 'delivery-cli' succeeded.
Verification of component 'opscode-pushy-client' succeeded.
Verification of component 'berkshelf' succeeded.
Verification of component 'tk-policyfile-provisioner' succeeded.
Verification of component 'fauxhai' succeeded.
Verification of component 'inspec' succeeded.
Verification of component 'chef-sugar' succeeded.
Verification of component 'test-kitchen' succeeded.
Verification of component 'chef-dk' failed.
Verification of component 'chefspec' succeeded.
Verification of component 'knife-spork' succeeded.
Verification of component 'chef-client' succeeded.
Verification of component 'generated-cookbooks-pass-chefspec' succeeded.
Verification of component 'chef-provisioning' succeeded.
Verification of component 'package installation' succeeded.
Verification of component 'git' succeeded.

A: Hi everyone if anyone facing same issue that's a license issue you can find solutions here.
https://github.com/chef/chef-dk/issues/792


text:
Q: How to calculate Average of a column while ignoring the error in PowerBI?

Hi everyone,
I have a table in PowerBI as shown in the first screenshot above. I want to calculate the average WA (Weighted Average) for both Topic 1 and 2. After obtain the average value, then I want to plot the value in the column chart together with the weighted average for Topic 1 and 2 as shown in the second screenshot. The weighted average for Topic 1 is 0.43 while for Topic 2 is 0.50, hence the Average for both Topic 1 and Topic 2 should be 0.465 ~ 0.47.
One of the challenging here is that my data consist of error NaN, so somehow need to ignore the NaN when doing the calculation for Average value.
I'm still new to DAX, hope to get some help and advice on this problem, thank you!

A: Can you please try with some DAX code as below-
AVERAGEX(filter(Table, WA <> "NaN"), Table[WA])


text:
Q: Flowplayer playlist setPlaylist(array) does not change playlist dynamically On the page a have a flowplayer which play videos by provided tag (just a name of video category) using playlist plugin. And I have section "Suggested videos". When I click on suggested video, I want to reload playlist using newly selected video tag. I tried use setPlaylist(array) as described in documentation https://flowplayer.org/docs/playlist.html#methods:
var player = flowplayer();
player.setPlaylist(this.playlist);

but it's not working.
Full player method code:
updatePlayer() {
     if(document.getElementById('flow').innerHTML === "") {

                        var player = flowplayer(document.getElementById("flow"), {
                            autoplay: true,
                            playlist: this.playlist,
                            loop: true
                        });
                        // here I add all player events what I need
                   } else {
                        console.log('player updated');
                        var player = flowplayer();

                        player.unload();
                        //update flowplayer playlist
                        player.setPlaylist(this.playlist);
                    }
    }

When the player is initialized and I click to suggested videos console.log() shows me message and player.unload() works, but setPlaylist() doesn't.
The only solution what can help its to use shutdown() method, which destroys all player instances, events and so on. But it is an ugly solution I think, previous I used JW player where you can easily update playlist dynamically.
Can anyone help me? Thanks!

A: Solution is  player.setPlaylist(this.playlist).play(0);


text:
Q: How to JSON format an HTTP error response in webapp2 I am using webapp2 for development in App Engine. What I would like to do is to send a custom JSON formatted response in case of an error. For example when the request length is larger that a threshold, to respond with HTTP 400 and response body
{'error':'InvalidMessageLength'}

In webapp2, there is the option to assign error handlers for certain exceptions. For example:
app.error_handlers[400] = handle_error_400

Where handle_error_400 is the following:
def handle_error_400(request, response, exception):
    response.write(exception)
    response.set_status(400)

When webapp2.RequestHandler.abort(400) is executed, the above code is executed.
How is it possible to have different response formats (HTML and JSON) dynamically based on the above setup? That is, how it is possible to call different versions of handle_error_400 function?

A: Here is a fully working example that demonstrates how to have the same error handler for all kind of errors and if your URL starts with /json then the response will be an application/json (use your imagination on how you could make a good use of the request object to decide what kind of response you should provide):
import webapp2
import json

def handle_error(request, response, exception):
  if request.path.startswith('/json'):
    response.headers.add_header('Content-Type', 'application/json')
    result = {
        'status': 'error',
        'status_code': exception.code,
        'error_message': exception.explanation,
      }
    response.write(json.dumps(result))
  else:
    response.write(exception)
  response.set_status(exception.code)

app = webapp2.WSGIApplication()
app.error_handlers[404] = handle_error
app.error_handlers[400] = handle_error

In the above example you can easily test the different behaviours by visting the following URLs that will return a 404 which is the easiest error to test:
http://localhost:8080/404
http://localhost:8080/json/404


text:
Q: Algorithm to calculate score/rating based on multiple performance based indicators First of all,  have to confess that my math skills are not the best and i would appreciate if you could please keep your response as simple as possible (preferably in layman's term).
I'm trying to create a scoring system for some performance reporting that I'm currently working on. There's a lot of data to go through, so I thought that a way I can help with when navigating the data would be to create a system that scores our campaigns (some type of efficiency indicator) based on a couple of variables/indicators (listed below). This would allow us to promptly identify and prioritize low performing campaigns. I would appreciate if you could please help me create an algorithm that could solve for this issue.
List Variables/Indicators:

*

*Opportunities (This is an amount): This represents the amount of times a campaign has the chance to serve an impression to a user.

*Ad% (This is a percentage): This percentage represents the amount of time an impression is waiting to be loaded after an "Opportunity" occurs. The highest this number the better it is.

*Fill% (This is a percentage): This percentage represents the amount of time an impression was actually displayed. The highest this number the better it is.

*Margin (This is an amount): This represents the campaign's profitability.The highest this number the better it is.

*Error% (This is a percentage): This percentage represents the amount of time an error was generated, which prevented an impression from being displayed. The lowest this number the better it is.
Thanks in advance for the help and please let me know if there's any additional information I can provide to help.


text:
Q: Search file A for a list of strings located in file B and append the value associated with that string to the end of the line in file A This is a bit complicated, well I think it is..
I have two files, File A and file B
File A contains delay information for a pin and is in the following format
AD22 15484
AB22 9485
AD23 10945

File B contains a component declaration that needs this information added to it and is in the format:
'DXN_0':
PIN_NUMBER='(AD22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
'DXP_0':
PIN_NUMBER='(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,AD23,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
'VREFN_0':
PIN_NUMBER='(AB22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';

So what I am trying to achieve is the following output
'DXN_0':
PIN_NUMBER='(AD22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
PIN_DELAY='15484';
'DXP_0':
PIN_NUMBER='(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,AD23,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
PIN_DELAY='10945';
'VREFN_0':
PIN_NUMBER='(AB22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
PIN_DELAY='9485';

There is no order to the pin numbers in file A or B
So I'm assuming the following needs to happen

*

*open file A, read first line

*search file B for first string field in the line just read

*once found in file B at the end of the line add the text "\nPIN_DELAY='"

*add the second string filed of the line read from file A

*add the following text at the end "';"

*repeat by opening file A, read the second line

I'm assuming it will be a combination of sed and awk commands and I'm currently trying to work it out but think this is beyond my knowledge.  Many thanks in advance as I know it's complicated..

A: FILE2=`cat file2`
FILE1=`cat file1`
TMPFILE=`mktemp XXXXXXXX.tmp`
FLAG=0
for line in $FILE1;do
    echo $line >> $TMPFILE
    for line2 in $FILE2;do
    if [ $FLAG == 1 ];then
        echo -e "PIN_DELAY='$(echo $line2 | awk -F " " '{print $1}')'" >> $TMPFILE
        FLAG=0
    elif [ "`echo $line | grep $(echo $line2 | awk -F " " '{print $1}')`" != "" ];then
        FLAG=1
    fi
    done
done
mv $TMPFILE file1

Works for me, you can also add a trap for remove tmp file if user send sigint.

A: awk to the rescue...
$ awk -vq="'" 'NR==FNR{a[$1]=$2;next} {print; for(k in a) if(match($0,k)) {print "PIN_DELAY=" q a[k] q ";"; next}}' keys data

'DXN_0':
PIN_NUMBER='(AD22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
PIN_DELAY='15484';
'DXP_0':
PIN_NUMBER='(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,AD23,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
PIN_DELAY='10945';
'VREFN_0':
PIN_NUMBER='(AB22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)';
PIN_DELAY='9485';

Explanation: scan the first file for key/value pairs.  For each line in the second data file print the line, for any matching key print value of the key in the requested format.  Single quotes in awk is little tricky, setting a q variable is one way of handling it.

A: FINAL Script for my application, A big thank you to all that helped..
# ! /usr/bin/sh

# script created by Adam with a LOT of help from users on stackoverflow

# must pass $1 file (package file from Xilinx)
# must pass $2 file (chips.prt file from the PCB design office)

# remove these temp files, throws error if not present tho, whoops!!
rm DELAYS.txt CHIP.txt OUTPUT.txt

# BELOW::create temp files for the code thanks to Glastis@stackoverflow https://stackoverflow.com/users/5101968/glastis I now know how to do this
DELAYS=`mktemp DELAYS.txt`
CHIP=`mktemp CHIP.txt`
OUTPUT=`mktemp OUTPUT.txt`

# BELOW::grep input file 1 (pkg file from Xilinx) for lines containing a delay in the form of n.n and use TAIL to remove something (can't remember), sed to remove blanks and replace with single space, sed to remove space before \n, use awk to print columns 3,9,10 and feed into awk again to calculate delay provided by fedorqui@stackoverflow https://stackoverflow.com/users/1983854/fedorqui

# In awk, NF refers to the number of fields on the current line. Since $n refers to the field number n, with $(NF-1) we refer to the penultimate field.
# {...}1 do stuff and then print the resulting line. 1 evaluates as True and anything True triggers awk to perform its default action, which is to print the current line.
# $(NF-1) + $NF)/2 * 141 perform the calculation: `(penultimate + last) / 2 * 141
# {$(NF-1)=sprintf( ... ) assign the result of the previous calculation to the penultimate field. Using sprintf with %.0f we make sure the rounding is performed, as described above.
# {...; NF--} once the calculation is done, we have its result in the penultimate field. To remove the last column, we just say "hey, decrease the number of fields" so that the last one gets "removed".

grep -E -0 '[0-9]\.[0-9]' $1 | tail -n +2 | sed -e 's/[[:blank:]]\+/ /g' -e 's/\s\n/\n/g' | awk '{print ","$3",",$9,$10}' | awk '{$(NF-1)=sprintf("%.0f", ($(NF-1) + $NF)/2 * 169); NF--}1' >> $DELAYS

# remove blanks in part file and add additional commas (,) so that the following awk command works properly
cat $2 | sed -e "s/[[:blank:]]\+//" -e "s/(/(,/g" -e 's/)/,)/g' >> $CHIP

# this awk command is provided by karakfa@stackoverflow https://stackoverflow.com/users/1435869/karakfa Explanation: scan the first file for key/value pairs. For each line in the second data file print the line, for any matching key print value of the key in the requested format. Single quotes in awk is little tricky, setting a q variable is one way of handling it. https://stackoverflow.com/questions/32458680/search-file-a-for-a-list-of-strings-located-in-file-b-and-append-the-value-assoc
awk -vq="'" 'NR==FNR{a[$1]=$2;next} {print; for(k in a) if(match($0,k)) {print "PIN_DELAY=" q a[k] q ";"; next}}' $DELAYS $CHIP >> $OUTPUT

# remove the additional commas (,) added in earlier before ) and after ( and you are done..
cat $OUTPUT | sed -e 's/(,/(/g' -e 's/,)/)/g' >> chipsd.prt


text:
Q: How Can I call nested function in function? I have a program like that
func Mom(){
    func isCalledFunc(){
    }
    //some code
    isCalledFunc()
}

But Swift whow Error. How can I call nested function in function? Thank

A: I think the reason is about OOP. You only can call the function from method of Object


text:
Q: Android Jelly Bean Strange behaviour of notifications I have integrated notifications in my app, and I have handle 2 cases :
Pre Jelly bean notifications with NotificationCompat.Builder, and,
Post Jelly bean notification with builder.
This makes me able to manage big text, and actions in post jelly bean version, and works for 2 or 3 time, but in a strange way, today I got the same result in JB and below.
Code for Pre JB :
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pint = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    NotificationCompat.Builder notif = new NotificationCompat.Builder(context)
    .setContentTitle(nMessage.getTitle())
    .setContentText(nMessage.getMessage())
    .setTicker(nMessage.getTitle())
    .setWhen(when)
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setSmallIcon(R.drawable.ic_ttd_petales)
    .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
    .setAutoCancel(true)
    .setContentIntent(pint);
    notification= notif.build();
    notificationManager.notify(0, notification);

Code for JB and above :
Builder bigTextNotification = new Notification.Builder(context)
        .setContentTitle(nMessage.getTitle())
        .setTicker(nMessage.getTitle())
        .setContentText(nMessage.getMessage())
        .setWhen(when)
        .setPriority(Notification.PRIORITY_HIGH)
        .setSmallIcon(R.drawable.ic_ttd_petales)
        .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
        .setAutoCancel(true)
        .setContentIntent(pint);
        if(nMessage.getHasPhone()){
        Intent iCall = new Intent(Intent.ACTION_CALL,Uri.parse(nMessage.getPhone()));
        PendingIntent pintCall = PendingIntent.getActivity(context, 0, iCall, Intent.FLAG_ACTIVITY_NEW_TASK);
        bigTextNotification.addAction(R.drawable.ic_menu_call, context.getResources().getString(R.string.call_ttd), pintCall);
    }

    String[] recipients = new String[]{context.getResources().getString(R.string.default_email)};
    String subject = context.getResources().getString(R.string.about_offer);

    Intent iEmail = new Intent(android.content.Intent.ACTION_SEND);
    iEmail.setType("text/html");
    iEmail.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
    iEmail.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    PendingIntent pintEmail = PendingIntent.getActivity(context, 1, iEmail, Intent.FLAG_ACTIVITY_NEW_TASK);
    bigTextNotification.addAction(R.drawable.ic_menu_compose, context.getResources().getString(R.string.call_ttd), pintEmail);

    Notification notif = new Notification.BigTextStyle(bigTextNotification)
    .bigText(nMessage.getMessage())
    .build();
    notificationManager.notify(1000, notif);

Have you ever encountered such behaviour or am I missing something?

A: I had a similar experience: I would send the notification and it would show the content text instead of the big text. Then when I unplugged the USB, it would show the big text expanded.
Now notice that when you plug in to USB, you get an ongoing notification: "Connected as a Media Device". Take a look and see if you get the same behavior with some other ongoing notification, like "Searching using GPS". I do. (My test device is a Samsung Galaxy Rush, and its vertical space is severely limited.)
So while the Android Notifications documentation says that only the top notification shows as expanded, it looks like there's another rule as well:
If the notifications list is running out of room, it will collapse even the top notification.
You can expand the collapsed notification by double- or single-finger dragging, depending on the OS version.

A: I'm sorry for this dummy question, I'm not using emulator to test this app, but real phone, and the strange thing is that when usb debugging cable is plugged, there's no actions in the notifications (JB) and when unplugged, we get our buttons working :) this solves my issue, but I have no idea about this behaviour.


text:
Q: How to change order status in Woocommerce with my custom plugin I want to know how to change order status in WooCommerce with my custom plugin not woocommerce's plugin.
function changeStatus($order_id)
{
   $order = wc_get_order($order_id);
   $order->set_status('pending');
   $order->save();
}

If I use wc_get_order() function, I got that error:
Fatal error: Call to undefined function wc_get_order()

How to include or require woocommerce wc_get_order() function in order to use properly.

A: Updated
You should first check that woocommerce plugin is active before in your plugin like:
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     // Your plugin code
}

Also you should NOT need to use this kind of function in your plugin, as you can get in your plugin code the WC_Order Object from a valid order ID and better use WC_Order method update_status() which already includes save() method.
You can also use WC_Order class checking before that the class exist (and then set or update order status) from a valid order Id, using:
if( class_exists('WC_Order') && $order_id > 0 ) {
    $order = new WC_Order( $order_id );

    if ( is_a($order, 'WC_Order') ) {
        // Set or update order status
        $order->update_status('pending'); // save() method is already included
    }
}

Related documentation: WooCommerce Plugin Developer Handbook


text:
Q: invalid token error on "01" in python I have started learning today the python. And during my lecture on variables I found that whenever I try to assign a value starting with 0 it gives:
syntax error :Invalid token

Like
zip=01290
zip=01

but when I tried simple
zip=0

it does not give any error.
I guess I am writing the code right because I have checked the syntax on internet.
Is it a problem in python or something else?


text:
Q: RequireJS and Mocha I have a web app using RequireJS. Here is my js/main.js file:
require.config({
    baseUrl: 'js/',
    paths: {
        jquery: 'libs/jquery/jquery',
        lodash: 'libs/lodash/lodash',
        backbone: 'libs/backbone/backbone',
        // [other dependencies...]
    }
});

require(['views/AppView'], function (AppView) {
    var app_view = new AppView;
});

here is my js/views/AppView.js file:
define([
    'jquery',
    'underscore',
    'backbone',
    'joint',
    'views/ProjectView',
    'models/Command',
    'views/detailsview',
    'views/newcellview'
], function ($, _, Backbone, joint, ProjectView, Command, DetailsView, NewCellView) {
    var app_view = {stub: 'stub'};
    return app_view;
});

and finally here is my AppViewTest.js file which I run with mocha js/test/AppViewTest.js:
var assert = require('assert');
var requirejs = require('requirejs');

describe('AppView', function() {
    var app_view;
    beforeEach(function (done) {
        requirejs(['../views/AppView.js'], function (AppView) {
            app_view = new AppView;
        });
    });
    it('should be [...]', function() {
        assert.equal(app_view, ...);
    });
});

I get the following error:
1) AppView views "before each" hook:
   Uncaught Tried loading "jquery" at /usr/local/lib/node_modules/mocha/bin/jquery.js then tried node's require("jquery") and it failed with error: Error: Cannot find module 'jquery'

A: You start your test with:
var assert = require('assert');
var requirejs = require('requirejs');

and then you start making calls to requirejs but there's nothing in here that configures RequireJS.
If you cut and paste the require.config call you have in your main.js into your test file, that would configure your test for loading the same files as you have in your regular application.
Another way to do it would be:
before(function (done) {
    requirejs(['full-path-to/main'], function () {
        requirejs(['../views/AppView'], function (AppView) {
            app_view = new AppView;
            done();
        });
    });
});

The point is to load your configuration before you load your AppView. Note also that you need to call done, and I've changed beforeEach to before because there's no need to reload it before each test. (It was a slip of the mind earlier when I induced you to use beforeEach. My bad.)
I've also removed the .js from your requirejs call because you should not use .js. Sometimes it is warranted but unless you can explain why you need it, you should not use it.