text:
Q: Android SQLite Syntax Error creating a view with RANK() I'm trying to create a view in SQLite using RANK() window function. When I execute the following code:
val txt = "CREATE VIEW VW_CAPITULOS_ORDER AS\n" +
          "    SELECT id_libro, capitulo,\n" +
          "            RANK() OVER (\n" +
          "                ORDER BY id_libro, CAST(SUBSTR(capitulo, 1, INSTR(capitulo||' ', ' ')) AS INTEGER)\n" +
          "                ) ranking\n" +
          "        FROM tbl_capitulos;\n"

db.execSQL(txt)

and at runtime I'm receiving the following exception:
*E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.systango.bibliacatolica, PID: 20837
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.systango.bibliacatolica/com.systango.bibliacatolica.MainActivity}: android.database.sqlite.SQLiteException: near "(": syntax error (Sqlite code 1 SQLITE_ERROR): , while compiling: CREATE VIEW VW_CAPITULOS_ORDER AS
        SELECT id_libro, capitulo,
                RANK() OVER (
                    ORDER BY id_libro, CAST(SUBSTR(capitulo, 1, INSTR(capitulo||' ', ' ')) AS INTEGER)
                    ) ranking
            FROM tbl_capitulos;, (OS error - 11:Try again)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3897)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4076)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
        at android.os.Handler.dispatchMessage(Handler.java:110)
        at android.os.Looper.loop(Looper.java:219)
        at android.app.ActivityThread.main(ActivityThread.java:8349)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
     Caused by: android.database.sqlite.SQLiteException: near "(": syntax error (Sqlite code 1 SQLITE_ERROR): , while compiling: CREATE VIEW VW_CAPITULOS_ORDER AS
        SELECT id_libro, capitulo,
                RANK() OVER (
                    ORDER BY id_libro, CAST(SUBSTR(capitulo, 1, INSTR(capitulo||' ', ' ')) AS INTEGER)
                    ) ranking
            FROM tbl_capitulos;, (OS error - 11:Try again)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1030)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:637)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:610)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:66)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
        at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1899)
        at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1817)*

I suspect that it's a problem with the SQLite version present in Android (checked version 3.22 on Huawei P40 Lite), or something like that. SQLite documentation says that window functions appear in version 3.25 (https://sqlite.org/windowfunctions.html). This script executes without problem in the DB Browser for SQLite app. Exist a way to use a new version of SQLite that the version that comes with the phone?

A: Your app can't change the version of SQLite of your phone.
As a workaround you can use a correlated subquery to imitate the functionality of the window function RANK():
CREATE VIEW VW_CAPITULOS_ORDER AS
SELECT c.id_libro, c.capitulo,
       (
         SELECT COUNT(*) FROM tbl_capitulos
         WHERE id_libro < c.id_libro
            OR (id_libro = c.id_libro AND (capitulo + 0) < (c.capitulo + 0))
       ) + 1 ranking
FROM tbl_capitulos c;

Note that you don't need to take the substring of capitulo up to the first ' ' in order to convert it to an integer.
You can do an implicit conversion by adding 0.


text:
Q: How can I collect multiple values into an array and later use the array with IN clause I need to do this inside a stored procedure in Oracle 10g/11g:
SELECT COLUM1 INTO SOME_ARRAY FROM TAB1 WHERE COLUMN2=P_COL2;

And then I want to be able to use that SOME_ARRAY in another query with IN clause, like this:
SELECT * FROM TAB2 WHERE TAB2.COLUMN1 IN SOME_ARRAY

Is this possible without needing to create a TYPE? Maybe a dynamic array? A little code will be appreciated.

A: Let's create a Type as an Oracle Object to be reference from both PL/SQL and SQL
CREATE TYPE SOME_ARRAY_REC AS OBJECT
(
   COLUM1 VARCHAR2(100)
);
/

Now, DB object as nested table of the type we created above
CREATE TYPE SOME_ARRAY_TAB AS TABLE OF SOME_ARRAY_REC;
/

The PL/SQL
DECLARE
      PL_ARRAY_REC TAB1%ROWTYPE;
      TYPE PL_ARRAY_TAB IS TABLE OF PL_ARRAY_REC
                INDEX BY PLS_INTEGER;

      v_PL_ARRAY PL_ARRAY_TAB;

      v_ARRAY SOME_ARRAY_TAB := SOME_ARRAY_TAB();
BEGIN
      /* Bulk collect the records into local PL/SQL type */
      SELECT COLUM1
      BULK COLLECT INTO v_PL_ARRAY
      FROM TAB1 WHERE COLUMN2=P_COL2;

      /* To use it in SQL we have to use a SQL compatible Type*/
      /* So copy the contents from local type to SQL compatible type */
      FOR I IN 1..v_PL_ARRAY.COUNT
      LOOP
           v_ARRAY.EXTEND;
           v_ARRAY(I) := SOME_ARRAY_REC(v_PL_ARRAY(I).COLUM1);
      END LOOP;

      /* Use TABLE() to cast the SQL compatible Nested table as normal table */
      SELECT * BULK COLLECT INTO SOME_VARRAY
      FROM TAB2
      WHERE COLUMN1 IN (SELECT COLUM1 FROM TABLE(v_ARRAY));

END;
/

PS: I would rather prefer the SubQuery

redpajama_set_name: RedPajamaStackExchange


text:
Q: ReactiveStreamCrudRepository not returning data from postgres DB I'm new to reactive programming and micronaut. I'm basically working on simple CRUD APIs. I'm using Kotlin with micronaut. I'm not sure why the DB is not returning any Data and I'm stuck with this.
@JdbcRepository(dialect = Dialect.POSTGRES)
interface EmployeeCrudRepository: ReactiveStreamsCrudRepository<EmployeeMaster, Int>, EmployeeRepository {
}

interface EmployeeRepository {
    fun findByEmployeeIdAndTcin(employeeId: UUID, tcin: String): Mono<EmployeeMaster>
}

@MappedEntity
@Table(name="employee")
data class EmployeeMaster (

    @Id
    @Column(name = "transaction_id")
    val transactionId: Int,

    @Column(name = "employee_id")
    val employeeId: UUID,

    @Column(name = "item_id")
    val itemId: UUID
)

fun getEmployeeDetailsResponse(registryId: UUID, itemId: String) : Mono<EmployeeDetailsDTO> {

        return getEmployeeDetails(employeeId, itemId)
            .map {
                    employeeDetails -> EmployeeDetailsDTO(employeeDetails)
            }
            .switchIfEmpty {
                logger.info("No records found")
                Mono.just(ItemDetailsDTO())
            }
    }

fun getEmployeeDetails(employeeId: UUID, itemId: String) : Mono<EmployeeDetailsDTO> {

        return employeeRepository.findByEmployeeIdAndTcin(registryId = registryId, tcin = itemId)
            .map {
                    employeeDetails -> EmployeeDetailsDTO(employeeDetails)
            }
            .switchIfEmpty {
                logger.info("No records found")
                Mono.just(EmployeeDetailsDTO())
            }
    }

I'm confused as to how to debug this to find the issue. The credentials all seem to be fine and the record I'm searching for exists in the DB.
flyway {
        // ./gradlew -Ppostgres_host=localhost -Ppostgres_ssl='' -Ppostgres_user=postgres -Ppostgres_pwd=postgres flywayMigrate -i
        url = "jdbc:postgresql://${postgres_host}:5432/postgres${postgres_ssl}"
        user = "${postgres_user}"
        password = "${postgres_pwd}"
        schemas = ['public']
    }

Issue Found:
My Bad, I was sending some other value and didn't realise that the value was incorrect. The implementation was fine and returning the response as expected. I'm writing kotlin and micronaut code for the first time and at the back of my head it always feels like the implementation was wrong.

A: Take a look at Access a Database with Micronaut Data R2DBC.
There are a number of things in your example that look wrong:

*

*@JdbcRepository(dialect = Dialect.POSTGRES) should be @R2dbcRepository.

*@Table and @Column are JPA.

*

*@MappedEntity("employee")

*@MappedProperty("item_id")
You might not need @MappedProperty("item_id"), itemId should be mapped to item_id.


text:
Q: How can I get a QR code without JavaScript tracking? I am helping design a small web site for a local nonprofit group and wanted to include a QR code for easy access. I have generated a few such codes from "free" web-based services, and then examined the codes. All the generated codes do contain the web site, but I also noticed that all of the QR codes have JavaScript calls to PageTracker quietly appended to the end of the code block. In all the articles I have read about QR codes, nobody has discussed these largely invisible additions.
Given that I was not asked if I wanted these functions appended, I assume that the use of these QR codes is tracked by Google Analytics for the various sites that provide the QR code generation service (I have included an example of the JavaScript at the bottom of this question.)
I am not thrilled about my website user's (and their mobile phones) being tracked by a third party without either my or their permission. So given that, my question is two-fold: 1) Is there an easy way to get a QR code without the stealthy tracking (i.e. it just opens my web site)?  --and if not--  2) Is there any way that I can benefit from the Google Analytics data generated?
Thank you!
`<script type="text/javascript">`
`var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");`
`document.write(decodeURIComponent("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));`
`</script>`

`<script type="text/javascript">`
`var pageTracker = _gat._getTracker("UA-788492-5");`
`pageTracker._initData();`
`pageTracker._trackPageview();`
`</script>`

A: I don't think the ZXing QR code generator does any funny business. It's open source so you can inspect the generator source code to check it.

A: I've used Google Charts for this in a few projects and while I can't say what kind of logging they do on their side it certainly doesn't add anything on your side.
Just insert this as an image on your site: https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=Hello%20stackoverflow&choe=UTF-8

You can find more info about it here: https://developers.google.com/chart/infographics/docs/qr_codes


text:
Q: NSIS CopyFiles not working for .py files I am creating an installer for a Python program using NSIS. I have to copy the source files to C:\Program Files\Snakecharmer, so I am first making sure it is created, then copying the source files to C:\Program Files\Snakecharmer. There are three .py files that I am copying, plus __pycache__, and some other things.
The contents of __pycache__ are copied,  but they do not stay in __pycache__, they are just copied loose into the directory.
The three .py files are not copied at all. Everything else copies correctly.
Here is my code
CopyFiles "$R0\SnakeCharmer.py" "$INSTDIR"
CopyFiles "$R0\snakecharmerupdater.py" "$INSTDIR"
CopyFiles "$R0\cobracrypt.py" "$INSTDIR"
CopyFiles "$R0\__pycache__" "$INSTDIR"
CopyFiles "$R0\Run_SnakeCharmer.bat" "$INSTDIR"
CopyFiles "$R0\icon.ico" "$INSTDIR"
CopyFiles "$R0\SnakeCharmer.lnk" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs"

The first three are the .py files that didn't copy.
Why is this happening and how can I fix it?

A: NSIS uses SHFileOperation internally, there is no special handling of any file types.
Just make sure the destination directory exists before you start the operation: CreateDirectory "$InstDir"
Process Monitor will probably give you some clues as to why it fails...


text:
Q: NFFT Undefined Reference To NNFFT Functions So I am trying to install the NFFT3 package from https://www-user.tu-chemnitz.de/~potts/nfft/.
It seemed to install okay, using the standard configure, make, make install commands. However I get the error:
simple_test.o: In function 'simple_test_nnfft_1d':
simple_test.c:(.text+0x44): undefined reference to 'nnfft_init'
simple_test.c:(.text+0xd6): undefined reference to 'nnfft_precompute_one_psi'
simple_test.c:(.text+0x158): undefined reference to 'nnfft_trafo_direct'
simple_test.c:(.text+0x17d): undefined reference to 'nnfft_trafo'
simple_test.c:(.text+0x19d): undefined reference to 'nnfft_finalize'`

The thing is, the file simple_test.c for the regular NFFT works just fine. Does anybody know how to fix this? I know this is some kind of linking problem, but the software is so large that I am at a loss at how to fix it.
Thanks
Edit: So in the directory kernel/nnfft there is nnfft.c with all the required functions, but still no header file. Does anyone know where the header with these declarations is actually located? I included the nnfft.c file at the top of the test code and got it to compile, but that doesn't help with the problem of linking originally.

A: First run ldconfig to cache the library. Then run gcc with -lnfft3.

A: It is because the NNFFT module is not compiled by default.
You have to add the option --enable-nnfft to do that when configuring:
./configure --enable-nnfft


text:
Q: Calls to flush cout are ineffective I am attempting to have the cout buffer flush to view a string before I manipulate it. Ive attempted to flush the buffer with calls to both std::flush() and std::cout.flush() but neither actually flush my output.
Only a call to std::endl has successfully flushed the buffer for me.
Here is my code
std::istringstream stm (game.date());
int day, month, year;
char delim = '/';

std::cout << "Date before: " << game.date() << std::flush; // first flush attempt
std::cout.flush();  // second flush attempt doesnt work
//std::cout << std::endl;   // if this is executed the buffer will flush

// Split date string into integers for comparison
stm >> month >> delim;
stm >> day >> delim;
stm >> year >> delim;

std::cout << "Date after: " << " | " << month << "/" << day << "/" << year << std::endl;

Here is my output
Date after:  | 1/31/13
Date after:  | 3/21/12
Date after:  | 11/11/11
Date after:  | 10/1/10
Date after:  | 1/2/12
So as you can see the first call to cout isnt ever flushed but as I said before the buffer will successfully flush with endl, which calls flush itself. I am currently running Ubuntu 12.04 with VirtualBox on my host macbook pro running Mountain Lion.
Is there anything I may be doing wrong in my flush calls or is this potentially a system issue?

A: Both std::cout << flush; and std::cout.flush(); will flush std::cout.
It looks as if your code inserts a carriage return (\r) into the stream. Assuming you print this year, it seems you insert it as a char with value 13 which happens to be \r. The upshot of this is that your later output will just overwrite the output as it will be on the same line. You can verify this by explicitly inserting a newline (\n) before flushing the stream.

A: There's a system buffer on cout that will still buffer your output in modern Linux systems.
To disable it for a run of your program use the command stdbuf like this:
stdbuf -o 0 ./yourprogram --yourparams

If you need to disable the buffering in the debugger, use it like this:
stdbuf -o 0 gdb --args ./yourprogram --yourparams

A: Flush only writes the buffers for the stream to the actual device (file or tty).
It doesn't move to the next line, if that's what you expect.
This is by design.
Note, here's a cleaner version of the code, that appears to work as advertised (with or without the flush, for that matter):
See it Live on Coliru
#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>

struct Game {
    std::string _date;
    std::string date() const { return _date; }
};

int main()
{
    for (Game game : std::vector<Game> { {"01/02/1999"}, {"24/10/2013"}})
    {
        std::istringstream stm (game.date());
        int day, month, year;
        char delim = '/';

        std::cout << "Date before: " << game.date();

        stm >> month >> delim;
        assert(stm && '/' == delim);

        stm >> day >> delim;
        assert(stm && '/' == delim);

        stm >> year;

        std::cout << " Date after: " << " | " << month << "/" << day << "/" << year << std::endl;
    }
}


text:
Q: Eclipse : how to use azure storage in android NDK ? Actually, I work with azure storage and mobiles services. In my work, I had to do two tests :

*

*Test azure mobile service using android java

*Test azure mobile service using android ndk

Firtly test i done, work fine. I passed to second test but i don't have great idea of how to do it.

azure storage for c++ github repo
Using azure storage with c++ example
I checked these docs, for look how to do it.
Need help to done this test. Thanks

A: Not sure what your question really is, whether you are having challenges with Storage or Mobile services.
If you are looking to try out the android client library for Storage, please check this out: https://github.com/Azure/azure-storage-android


text:
Q: Error CS0556 User-defined conversion must convert to or from the enclosing type I have the following code:

public class SampleStartDateHistoryViewModel
    {
        public string modifiedBy;
        public static explicit operator SampleStartDateHistoryViewModel(SampleStartDateHistoryModel startDateRecord)
        {
            return new SampleStartDateHistoryViewModel
            {
                modifiedBy = startDateRecord.modifiedBy
            };
        }
        public static explicit operator List<SampleStartDateHistoryViewModel>(List<SampleStartDateHistoryModel> startDateRecords)
        {
            return startDateRecords.Select(zx => (SampleStartDateHistoryViewModel)zx).ToList<SampleStartDateHistoryViewModel>();
        }
    }

The cast between classes : SampleStartDateHistoryViewModel and SampleStartDateHistoryModel  works as expected.
But when converting List to List
Compilator generates an error as above
Error   CS0556  User-defined conversion must convert to or from the enclosing type

A: The message says it all. Either the input or output type of your explicit operator must be the "enclosing type" SampleStartDateHistoryViewModel, you cannot convert between other types, such as lists.


text:
Q: Specified values for a column How to create table with pre-specified values for a column.
Something like enum, but not an enum, because it works from 8.3 Postgres and I need something working with 8.1 and later versions.
for example
CREATE TABLE (
    cars ('bmw', 'audi');
)

And I shouldn't be able to insert anything else except bmw and audi when inserting a value to the cars column.

A: I think what you are looking for is the CHECK constraint.
create table mydata(
cars char(4)CONSTRAINT limit_cars_to CHECK (cars in ('bmw', 'audi'))
);

insert into mydata values('bmw'); /*this insert works*/
insert into mydata values('xxx');/*this insert fails msg: ERROR: new row for relation "mydata" violates check constraint "limit_cars_to": insert into mydata values('xxx')
*/

I have tested this with PostgreSQL 8.3 ( as that is what is availabel on SQL Fiddle). Might just work with PostgreSQL 8.1. Give it a try.
Source: http://www.postgresql.org/docs/8.1/static/ddl-constraints.html

A: There are two ways to solve this problem.
The first is to use a check constraint, and Sashikanth's answer describes it.
This approach should be used if the allowable values don't change. If they do change, you need to update the constraint which in many organisations can require a long process to get into production.
The second is to use a foreign key to another table listing the allowable values:
create table cars (
    car varchar(10) primary key
);

create table mydata (
   id serial primary key,
   car varchar(10) references cars
);

This approach should be used if you expect the values to change, or if the users need to be able to add values.


text:
Q: bootstrap menu toggle first click not working properly Im using bootstrap-collapse.js v2.3.0, but for some reason on the first click the menu just appears and doesnt slide down.
I also noticed the height doesnt say auto , it says 205px. I dont have the menu set to this height anywhere in the CSS.
After the first click, when I go to toggle it closed, everything seems perfect, the height toggles between 0 and auto and there is a smooth transition as opposed to it instantly appearing.
Im unsure as to what code to include as it seems to be the bootstrap toggle that is the problem,
however here is the html...
I removed irrelivent bits of code..

    Categories

 //more code

//more code<

//code

//code

//code

but here is a link to the site...
http://bc_mobile.hailstormcommerce.com/

A: Plz check this jsfiddle JSfiddle for you with navigation

    New Icon Menu

 Home

About Us

Portfolio

Contact Us


text:
Q: tools:RGUI disappears from globalenv R I just installed the newest version of R for my OS -- R version 3.1.3 for MAC. The tools:RGUI does not load properly. Half the time, I open R and search() does not include tools:RGUI. The other half of the time, it does appear but then quickly disappears from the global environment. As a result, I cannot use the help function or search for and install packages. My internet connection is fine. Any ideas?

A: I think I figured out the problem; I had detach() at the start of my code. I do not normally attach data as I have been told it is a bad habit that can lead to problems. They were right. I have deleted all the references to attach and detach and things seem to work fine now.


text:
Q: Setting Value of Input OnSubmit using JQuery in Symfony I am trying to set a onsubmit function that will use the google.maps.Geocoder to set the  gps positions using the address entered by a user, my code is the following
    <form onsubmit="getGPSLocation()">
            <input type='text' id='search_address' />
            <input type='text' id='search_lat' hidden='hidden'/>
            <input type='text' id='search_lon' hidden='hidden'/>
            <input type='submit'/>
    </form>

    <script>
    function getGPSLocation(){
        var string = $('#search_address').val();
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            'address': string
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var pos = results[0].geometry.location;
                $('#search_lat').attr('value',pos.lat());
                $('#search_lon').attr('value',pos.lng());
            }
        });

    }
    </script>

The problem is that when i click submit, it does properly call the geocoder function, but the problem is that:

*

*Before the geocoder can make the request to the google server and return the
  coordinate data, the Submit function has already redirected the page.

So the question is:
How to delay the submitting of the information untill the geocoder function has successfully completed its action.

A: You may use the Jquery onsubmit function. Try this code :
$('#your_form_id').submit(function() {

 var string = $('#search_address').val();
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': string
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var pos = results[0].geometry.location;
            $('#search_lat').attr('value',pos.lat());
            $('#search_lon').attr('value',pos.lng());
        }
    });

  return;
 });


text:
Q: How to change the Key and Value in a list of dict in python? Looking for an efficient python code to achieve the below functionality.
input_dir =[{'NAME': 'ABC', 'VALUE': 'USA'}, {'NAME': 'PQR', 'VALUE': 'EU'}]
expected_output= {'ABC': 'USA', 'PQR': 'EU'}

and i am using the below code.
out_key = ''
out_value = ''
output_dictionary = {}
for index, item in enumerate(input_dir):
   for key in item:
          if key == 'NAME':
                 out_key = item[key]
          elif key == 'VALUE':
                 out_value = item[key]
   output_dictionary[out_key] = out_value
print(output_dictionary)

Is there any efficient way to do this? Any suggestions!

A: Just a one liner actually. Do a dictionary comprehension as follows.
In [209]: {d["NAME"]:d["VALUE"] for d in input_dir}
Out[209]: {'ABC': 'USA', 'PQR': 'EU'}

A: I haven't yet tested the following code on a computer, but you should be able reduce your code with a lambda function and iterating through the input dictionary:
 f = lambda x: (x['NAME'], x['VALUE'])
output_dictionary = dict(f(i) for i in input_dir)

Hope that helps.


text:
Q: How to Filter array from state onChange based on category and revert to default? For my class based component, I have a state object that contains a defined array named movies. I also have a handleMoviesFilter function, that is called onChange on the select tag.
How can I filter the options dynamically from my array, filter them onChange.. and revert when I pick another movie?
state = {
    movies: [
        {
            name: 'Goodfellas',
            category: 'crime'
        },

        {
            name: 'Saving private ryan',
            category: 'war'
        },
        {
            name: 'The Shawshank Redemption',
            category: 'drama'
        }
    ]
}

handleMoviesFilter = e => {
    let currentMovie = e.target.value;

    const updateMoviesState = this.state.movies.filter(({ category }) =>
        currentMovie.includes(category)
    );

    this.setState({
        opleidingen: updateMoviesState,
        isResetButtonActive: true,
    });
}

<select id="lang" onChange={this.handleMoviesFilter}>
    <option value="select">Select</option>
    <option value="Goodfellas">Goodfellas</option>
    <option value="Saving private ryan">Saving private ryan</option>
    <option value="The Shawshank Redemption">The Shawshank Redemption</option>
</select>

A: If what you are trying to accomplish is based upon the selected option, filter the state.movies and return those in which match, then you would want to do something like the following...
state = {
    movies: [
        {
            name: 'Goodfellas',
            category: 'crime'
        },

        {
            name: 'Saving private ryan',
            category: 'war'
        },
        {
            name: 'The Shawshank Redemption',
            category: 'drama'
        }
    ]
}

handleMoviesFilter = e => {
    let currentMovie = e.target.value;

    const updateMoviesState = this.state.movies.filter(movie => movie.name.toLowerCase() === currentMovie.toLowerCase());

    this.setState({
        movies: updateMoviesState,
        isResetButtonActive: true,
    });
}

<select id="lang" onChange={this.handleMoviesFilter}>
    <option value="select">Select</option>
    <option value="Goodfellas">Goodfellas</option>
    <option value="Saving private ryan">Saving private ryan</option>
    <option value="The Shawshank Redemption">The Shawshank Redemption</option>
</select>

A: You would want to

*

*get the selected value

*uppercase all of it's characters with toUpperCase()

*filter state to get the movies that includes the selected value in it's name

*

*filter & includes method used

state = {
    movies: [
        {
            name: 'Goodfellas',
            category: 'crime'
        },

        {
            name: 'Saving private ryan',
            category: 'war'
        },
        {
            name: 'The Shawshank Redemption',
            category: 'drama'
        },
        {
            name: 'Good Riddance',
            category: 'drama'
        }
    ]
}

handleMoviesFilter = e => {
    let currentMovie = e.target.value.toUpperCase();

    //const updateMoviesState = this.state.movies.filter(movie => movie.name.toUpperCase() === currentMovie);

    const updateMoviesState = this.state.movies.filter(movie => movie.name.toUpperCase().includes(currentMovie));
    this.setState({
        movies: updateMoviesState,
        isResetButtonActive: true,
    });
}

<select id="lang" onChange={this.handleMoviesFilter}>
    <option value="select">Select</option>
    <option value="Goodfellas">Goodfellas</option>
    <option value="Saving private ryan">Saving private ryan</option>
    <option value="The Shawshank Redemption">The Shawshank Redemption</option>
</select>

Test It Out
This snippet was made so you can test it out. This does NOT include react-js framework of course.

const state = {
    movies: [
        {
            name: 'Goodfellas',
            category: 'crime'
        },

        {
            name: 'Saving private ryan',
            category: 'war'
        },
        {
            name: 'The Shawshank Redemption',
            category: 'drama'
        },
        {
            name: 'Good Riddance',
            category: 'drama'
        }
    ]
}

handleMoviesFilter = e => {
    // get requested movie
    let currentMovie = document.getElementById('textField').value.toUpperCase(); // t
    console.log("Requested Movie:", currentMovie);

    // array has a movie that equals selected movie
    //const updateMoviesState = state.movies.filter(movie => movie.name.toUpperCase() === currentMovie);

    // array has a movie whose name contain the phrase
    const updateMoviesState = state.movies.filter(movie => movie.name.toUpperCase().includes(currentMovie));

    console.log("Filter Result:", updateMoviesState);
}
<input id="textField"></input>
<button onclick="handleMoviesFilter(event)">Filter</button>


text:
Q: Grails How to show a different link name in a form In my domain i have a one to many relationship with Inventory and Inventory Item. This is the snippet from the gsp. It shows each inventory item assigned to a specific inventory.
<g:if test="${inventoryInstance?.inventoryItem}">

        <g:message code="inventory.inventoryItem.label" default="Inventory Item" />
            <g:each in="${inventoryInstance.inventoryItem}" var="i">

                   <g:link controller="inventoryItem"
                           action="show"
                           id="${i.id}">${i?.encodeAsHTML()}
                   </g:link>

            </g:each>

</g:if>

Problem is the links shown is package.InventoryItem: 1
how do you change it to the InventoryItem's name ( i have a name row in my database)

A: ${i.name?.encodeAsHTML()}

If i is null then you would get a NPE right when you use i.id. Moreover, you should not be iterating over a Collection of inventoryItems expecting it has an empty item. :)
Have a look at the second example for the answer.
If you want i to return the name by default then you have to override toString() which I  would not do.


text:
Q: summarizing the contents of a text file to an other one using awk I have a big text file with 2 tab separated fields. as you see in the small example every 2 lines have a number in common. I want to summarize my text file in this way.
1- look for the lines that have the number in common and sum up the second column of those lines.
small example:
ENST00000054666.6   2
ENST00000054666.6_2 15
ENST00000054668.5   4
ENST00000054668.5_2 10
ENST00000054950.3   0
ENST00000054950.3_2 4

expected output:
ENST00000054666.6   17
ENST00000054668.5   14
ENST00000054950.3   4

as you see the difference is in both columns. in the 1st column there is only one repeat of each common and without "_2" and in the 2nd column the values is sum up of both lines (which have common number in input file).
I tried this code but does not return what I want:
awk -F '\t' '{ col2 = $2, $2=col2; print }' OFS='\t' input.txt > output.txt

do you know how to fix it?

A: Solution 1st: Following awk may help you on same.
awk '{sub(/_.*/,"",$1)} {a[$1]+=$NF} END{for(i in a){print i,a[i]}}'   Input_file

Solution 2nd: In case your Input_file is sorted by 1st field then following may help you.
awk '{sub(/_.*/,"",$1)} prev!=$1 && prev{print prev,val;val=""} {val+=$NF;prev=$1} END{if(val){print prev,val}}'  Input_file

Use > output.txt at the end of the above codes in case you need the output in a output file too.

A: If order is not a concern, below may also help :
awk -v FS="\t|_" '{count[$1]+=$NF}
                 END{for(i in count){printf "%s\t%s%s",i,count[i],ORS;}}' file
ENST00000054668.5   14
ENST00000054950.3   4
ENST00000054666.6   17

Edit :
If the order of the output does matter, below approach using a flag helps :
$ awk -v FS="\t|_" '{count[$1]+=$NF;++i;
                     if(i==2){printf "%s\t%s%s",$1,count[$1],ORS;i=0}}' file

ENST00000054666.6   17
ENST00000054668.5   14
ENST00000054950.3   4


text:
Q: Finding and highlighting the last data point in a series/column VBA I have a macro for creating a graph and part of it identifies and highlights the final data point like below:

This works all well and good when there's data in the final row of a column, but in some cases the final row is empty therefore no point is highlighted like so:

I was wondering if there was a way to make it highlight the last point that has actual data, so even though the last row may be empty, it highlights the last row with data.
Could the following be incorporated into my code? it finds the last data point in column B:
Dim lRow As Long

lRow = Cells(Rows.Count, 2).End(xlUp).Row

Here is my code:
    With co.Chart
        .FullSeriesCollection(1).ChartType = xlXYScatter
        .FullSeriesCollection(1).AxisGroup = 1
        .FullSeriesCollection(2).ChartType = xlLine
        .FullSeriesCollection(2).AxisGroup = 1
        .SetSourceData Source:=my_range
        .Axes(xlCategory).TickLabels.NumberFormat = "m/yy"
        'highlight final dot of data
        .FullSeriesCollection(1).Points(.FullSeriesCollection(1).Points.Count).ApplyDataLabels Type:=xlShowValue
        .FullSeriesCollection(1).Points(.FullSeriesCollection(1).Points.Count).MarkerSize = 7
        .FullSeriesCollection(1).Points(.FullSeriesCollection(1).Points.Count).MarkerStyle = xlCircle
        .FullSeriesCollection(1).Points(.FullSeriesCollection(1).Points.Count).MarkerBackgroundColorIndex = 6
        .FullSeriesCollection(1).Points(.FullSeriesCollection(1).Points.Count).MarkerForegroundColorIndex = 1
        .HasTitle = True
        .ChartTitle.Text = t
        ResolveSeriesnames co.Chart
        .Location Where:=xlLocationAsObject, Name:="Graphs"

A: I found this code on https://peltiertech.com/label-last-point-for-excel-2007/ and made a couple adjustments which works
Sub LastPointLabel2()
  Dim srs As Series
  Dim iPts As Long
  Dim cht As ChartObject
  Dim vYVals As Variant
  Dim vXVals As Variant
  Set ws = ActiveSheet

  If ActiveChart Is Nothing Then
    MsgBox "Select a chart and try again.", vbExclamation
  Else
    Application.ScreenUpdating = False
  For Each cht In ws.ChartObjects
      Set srs = cht.Chart.SeriesCollection(1)
      With srs
        vYVals = .Values
        'vXVals = .XValues
        ' clear existing labels
        .HasDataLabels = False
        For iPts = .Points.Count To 1 Step -1
          If Not IsEmpty(vYVals(iPts)) Then
            ' add label
            srs.Points(iPts).ApplyDataLabels _
                ShowSeriesName:=False, _
                ShowCategoryName:=False, ShowValue:=True, _
                AutoText:=True, LegendKey:=False
            Exit For
          End If
        Next
      End With
    Next
    ' legend is now unnecessary
    Application.ScreenUpdating = True
  End If
End Sub


text:
Q: Why is there a difference in SqlGeography STDistance? I have been tracking down a bug in my code, and I've found that it's because the Microsoft c# SqlGeography 2014 library returns a slightly different result for STDistance than my regular code for calculating the distance between points.
I wrote a small console exe to demonstrate the problem, but I can't figure out why I'm getting such a different result?
static void Main(string[] args) {
        double earthRadius = 6378137; // meters => from both nad83 & wgs84
        var a = new { lat = 43.68151632, lng = -79.61162263 };
        var b = new { lat = 43.67575602, lng = -79.59586143 };

        // sql geography lib
        SqlGeographyBuilder sgb;
        sgb = new SqlGeographyBuilder();
        sgb.SetSrid(4326);
        sgb.BeginGeography(OpenGisGeographyType.Point);
        sgb.BeginFigure(a.lat, a.lng);
        sgb.EndFigure();
        sgb.EndGeography();
        SqlGeography geoA = sgb.ConstructedGeography;

        sgb = new SqlGeographyBuilder();
        sgb.SetSrid(4326);
        sgb.BeginGeography(OpenGisGeographyType.Point);
        sgb.BeginFigure(b.lat, b.lng);
        sgb.EndFigure();
        sgb.EndGeography();
        SqlGeography geoB = sgb.ConstructedGeography;

        // distance cast from SqlDouble
        double geoDistance = (double)geoA.STDistance(geoB);

        // math!
        double d2r = Math.PI / 180; // for converting degrees to radians
        double lat1 = a.lat * d2r,
            lat2 = b.lat * d2r,
            lng1 = a.lng * d2r,
            lng2 = b.lng * d2r,
            dLat = lat2 - lat1,
            dLng = lng2 - lng1,
            sin_dLat_half = Math.Pow(Math.Sin(dLat / 2), 2),
            sin_dLng_half = Math.Pow(Math.Sin(dLng / 2), 2),
            distance = sin_dLat_half + Math.Cos(lat1) * Math.Cos(lat2) * sin_dLng_half;

        // math distance
        double mathDistance = (2 * Math.Atan2(Math.Sqrt(distance), Math.Sqrt(1 - distance))) * earthRadius;

        // haversine
        double sLat1 = Math.Sin(a.lat * d2r),
                sLat2 = Math.Sin(b.lat * d2r),
                cLat1 = Math.Cos(a.lat * d2r),
                cLat2 = Math.Cos(b.lat * d2r),
                cLon = Math.Cos((a.lng * d2r) - (b.lng * d2r)),
                cosD = sLat1 * sLat2 + cLat1 * cLat2 * cLon,
                d = Math.Acos(cosD);

        // math distance
        double methDistance = d * earthRadius;

        // write the outputs
        Console.WriteLine("geo distance:\t" + geoDistance);    // 1422.99560435875
        Console.WriteLine("math distance:\t" + mathDistance);  // 1421.73656776243
        Console.WriteLine("meth distance:\t" + methDistance);  // 1421.73656680185
        Console.WriteLine("geo vs math:\t" + (geoDistance - mathDistance));     // 1.25903659632445
        Console.WriteLine("haversine vs math:\t" + (methDistance - methDistance)); // ~0.00000096058011
    }

Is Microsoft using a different calculation method?  Being off by over 1 meter when calculating distances less than 1.5Km is a huge discrepancy.

A: Ok, so after much digging I found the answer, and Microsoft is more correct.
Specifically, they are using Vincenty's formulae.  Accuracy is within 0.5mm (not metre, half a millimetre) instead of 0.3% with Haversine formula.
The reason is that Haversine (used by me, Google, and Bing Maps too apparently) is fast, but relies on a spherical Earth instead of an ellipsoid.  Microsoft uses the ellipsoid Earth to calculate distances instead of a sphere providing more accurate results.
I implemented Vincenty's method in c# like this and it's worked so far, but is no where near production ready.
    const double d2r = Math.PI / 180;  // degrees to radians
    const double EARTH_RADIUS = 6378137;  // meters
    const double EARTH_ELLIPSOID = 298.257223563; // wgs84
    const double EARTH_BESSEL = 1 / EARTH_ELLIPSOID;
    const double EARTH_RADIUS_MINOR = EARTH_RADIUS - (EARTH_RADIUS * EARTH_BESSEL); // 6356752.3142 meters => wgs84

    static double vincentyDistance(double lat1, double lng1, double lat2, double lng2) {
        double L = (lng2 - lng1) * d2r,
                U1 = Math.Atan((1 - EARTH_BESSEL) * Math.Tan(lat1 * d2r)),
                U2 = Math.Atan((1 - EARTH_BESSEL) * Math.Tan(lat2 * d2r)),
                sinU1 = Math.Sin(U1),
                cosU1 = Math.Cos(U1),
                sinU2 = Math.Sin(U2),
                cosU2 = Math.Cos(U2),
                lambda = L,
                lambdaP,
                iterLimit = 100,
                sinLambda,
                cosLambda,
                sinSigma,
                cosSigma,
                sigma,
                sinAlpha,
                cosSqAlpha,
                cos2SigmaM,
                C;
        do {
            sinLambda = Math.Sin(lambda);
            cosLambda = Math.Cos(lambda);
            sinSigma = Math.Sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
            if (0 == sinSigma) {
                return 0; // co-incident points
            };
            cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
            sigma = Math.Atan2(sinSigma, cosSigma);
            sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
            cosSqAlpha = 1 - sinAlpha * sinAlpha;
            cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
            C = EARTH_BESSEL / 16 * cosSqAlpha * (4 + EARTH_BESSEL * (4 - 3 * cosSqAlpha));
            //  if (isNaN(cos2SigmaM)) {
            //      cos2SigmaM = 0; // equatorial line: cosSqAlpha = 0 (§6)
            //  };
            lambdaP = lambda;
            lambda = L + (1 - C) * EARTH_BESSEL * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
        } while (Math.Abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0);

        if (iterLimit == 0) {
            return 0; // formula failed to converge
        };

        double uSq = cosSqAlpha * (EARTH_RADIUS * EARTH_RADIUS - EARTH_RADIUS_MINOR * EARTH_RADIUS_MINOR) / (EARTH_RADIUS_MINOR * EARTH_RADIUS_MINOR),
            A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))),
            B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))),
            deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM))),
            s = EARTH_RADIUS_MINOR * A * (sigma - deltaSigma);
        return s;
    }

This code was converted from a JavaScript implementation I found here: https://gist.github.com/mathiasbynens/354587

A: Microsoft may be more correct; but it's not correct!
According the Kallay (2010),
SqlGeography STDistance does not return the geodesic distance but the
distance along the great ellipse joining the 2 points.  The great
ellipse distance is not the shortest distance and it does not obey the
triangle inequality.  The great ellipse returns a reasonable
approximation of the geodesic distance for close points.  For distant
points the error may be as much as 33 km.
An accurate calculation of the geodesic distance is given by the C#
library
NETGeographicLib
(I wrote the underlying C++ library).  This is more accurate than
Vincenty (10 nanometers instead of 0.5 mm) and, more importantly, the
correct result is always obtained.  (Vincenty fails to converge for
nearly antipodal points.)


text:
Q: I cannot set content_security_policy for my google earth packaged app I am trying to create a packaged app that uses google earth API.  However, while running the app, I get an error that says:
Refused to load the script 'https://www.google.com/jsapi' because it violates the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

So I added a line in the manifest that says
"content_security_policy": "script-src 'self' https://www.google.com/jsapi; object-src 'self'",

However, now chrome complains and displays the following error:
There were warnings when trying to install this extension:
'content_security_policy' is only allowed for extensions and legacy packaged apps, and this is a packaged app.

A: You would need to use the API from a sandbox, or more likely in a webview.


text:
Q: convert memo field to text and eliminate excess spaces I tried looking this up in google, but couldnt find any anything... I am running Access 2007/XP/SQLBASE and need to make a query that converts a memo field to text and eliminaes any spaces more than 2 spaces long.  Please give me the SQL, based on  my snippet below.  the memo field is called "BITS".   I used to be able to accomplish this using the "SL" function, but it doesnt seem to work in Access2007 but does work in Access 2000.  thanks you very much for your help  `
SELECT SYSADM_CUST_ORDER_BINARY.CUST_ORDER_ID, SYSADM_CUST_ORDER_BINARY.BITS
FROM SYSADM_CUST_ORDER_BINARY
GROUP BY SYSADM_CUST_ORDER_BINARY.CUST_ORDER_ID, SYSADM_CUST_ORDER_BINARY.BITS;

A: You can use Replace in Access 2007:
SELECT SYSADM_CUST_ORDER_BINARY.CUST_ORDER_ID,
    Replace(SYSADM_CUST_ORDER_BINARY.BITS & "", "  ", " ")
FROM SYSADM_CUST_ORDER_BINARY
GROUP BY SYSADM_CUST_ORDER_BINARY.CUST_ORDER_ID,
    Replace(SYSADM_CUST_ORDER_BINARY.BITS & "", "  ", " ")

I have never come across SL.


text:
Q: Ordena Frequência Array PHP Gostaria de saber como faço para ordena esse Array, colocando os números repetidos no final.

$arr = array(
    5,
    4,
    2,
    3,
    2,
    1
);
sort ($arr);
foreach ($arr as $n => $valor) {
    echo "$valor\n";
}

A: Eu fiz o seguinte, ordenei o array e depois ordenei a quantidade de repetições, em seguida eu verifiquei se a quantidade era igual a 1, caso contrário ele adiciona no final, através do "for", ele vai adicionando e comparando se é o array atual da repetição:
<?php
$arr = array(
    5,
    4,
    2,
    3,
    2,
    1
);
sort($arr);
$add = array();

$contagem = array_count_values($arr);

//ordena pela quantidade de repetições
    asort($contagem);
    $add = array();
foreach($contagem as $valor => $qtde) {
    $current = $valor;
    if($qtde == 1) {
          $add[] = $valor;
    } else {
       //o if aqui é só para adicionar uma vez
        if ($valor === $current) {
           for($i=0; $i < $qtde; $i++) {
              $add[] = $valor;
           }
        }
    }

}
print_r($add);

Veja o exemplo aqui. E aqui com outros números

A: Por qual motivo você quer eles no final? Talvez o que esteja pensando em fazer, tem alguma outra lógica melhor. Por que basicamente tem duas coisas pra tu fazer com os repetidos: remover, ou contar. Estou pensando que você quer contar, correto?
Talvez seria melhor o array ficar assim:
// key é o valor do array original, e o value é a quantidade
$array[1] = 1
$array[2] = 2
$array[3] = 1
$array[4] = 2

E posteriormente, se realmente precisar que eles fiquem no final, você ordenaria para o valor ser crescente, com o sort.
Desculpa não dar um exemplo, mas faz tempo que não programo em PHP, somente Javascript. Mas acredito que se mudar a lógica será mais fácil.
Qualquer dúvida durante a criação o código, se estiver precisando de ajuda com a lógica, mande o código que termino pra você. Mas ao menos comece faze-lo!


text:
Q: Add Custom Invoice Data in Invoice email This is my email template file for invoice email:
\wamp\www\magento\app\locale\en_US\template\email\sales\invoice_new.html

Your Invoice #{{var invoice.increment_id}} for Order #{{var
order.increment_id}}

I don't understand how to pass the order id to this html file.
{{var invoice.increment_id}} from where this varible pass in this html file??
{{var order.getShippingAddress().getTelephone()}} where is written this function in magento ?

I want to use this variable and create function to get more data from magento table. So for that where do I have to add this function and how to call this function in invoice_new.html file?

A: The variables are set in Mage_Sales_Model_Order_Invoice::sendEmail().
See this code:
    $mailer->setTemplateParams(array(
            'order'        => $order,
            'invoice'      => $this,
            'comment'      => $comment,
            'billing'      => $order->getBillingAddress(),
            'payment_html' => $paymentBlockHtml
        )
    );

You can add your own data the same way.


text:
Q: Scrolling Progress Bar in Tkinter I have been trying to set up a progress bar in a python tkinter gui that shows that a process is running. The process is long and I have no way to really measure the progress, so I need to use an indeterminate progress bar. However, I really dislike the style of the ttk indeterminate progress bar that bounces back and forth. I want one that scrolls across the bar over and over again, kind of like this image

Is this possible with tkinter?

A: have you tried ttk's determinate Progressbar?  You can make the progress just continuously scroll across the bar.
for example:
#!/usr/bin/env python3

import tkinter
import tkinter.ttk as ttk

root = tkinter.Tk()
frame = ttk.Frame()
pb = ttk.Progressbar(frame, length=300, mode='determinate')
frame.pack()
pb.pack()
pb.start(25)
root.mainloop()

A: I know its an old question, but I have found a way to do this for anyone else writing tkinter.
I've been working on a tkinter app for a bit now and have determined that to handle tkinter objects, you absolutely need a separate thread. Although it is apparently frowned upon to handle tkinter objects via something else than the mainloop() method, it has been working well for me. I've never had a main thread is not in main loop error and never experienced objects that didn't update correctly.
I edited Corey Goldberg's code a bit and got it working. Here's what I got (some explanations in the comments).
import tkinter
import tkinter.ttk as ttk
import threading

def mainProgram(): # secure the main program initialization in its own def
    root = tkinter.Tk()
    frame = ttk.Frame()
    # You need to use indeterminate mode to achieve this
    pb = ttk.Progressbar(frame, length=300, mode='indeterminate')
    frame.pack()
    pb.pack()

    # Create a thread for monitoring loading bar
    # Note the passing of the loading bar as an argument
    barThread = threading.Thread(target=keepLooping, args=(pb,))
    # set thread as daemon (thread will die if parent is killed)
    barThread.daemon=True
    # Start thread, could also use root.after(50, barThread.start()) if desired
    barThread.start()

    pb.start(25)
    root.mainloop()

def keepLooping(bar):
    # Runs thread continuously (till parent dies due to daemon or is killed manually)
    while 1:
        """
        Here's the tricky part.
        The loading bar's position (for any length) is between 0 and 100.
        Its position is calculated as position = value % 100.
        Resetting bar['value'] to 0 causes it to return to position 0,
        but naturally the bar would keep incrementing forever till it dies.
        It works, but is a bit unnatural.
        """
        if bar['value']==100:
            bar.config(value=0) # could also set it as bar['value']=0

if __name__=='__main__':
    mainProgram()

I've added if __name__=='__main__': because I feel it defines the scope a bit better.
As a side note I've found that running threads with while 1: will crank my CPU at about 20-30% usage for that one thread in particular. It's easily solvable by importing time and using time.sleep(0.05) thereafter significantly lowering the CPU usage.
Tested on Win8.1, Python 3.5.0.


text:
Q: Why so many good open source programs have websites that are very poorly managed? I was reading about gzip program and I found the official website of the gzip software.
First of all the site looks very bad, it is very hard to find useful information on it and it was not updated since several years ago.
Also, only www.gzip.org is working, but simply gzip.org is not working.
It would not be hard for people that are running those websites to make it better so that it would be more easy for more people to have acces to open source software and learn about it.
What is the reason no one cares about User Interfaces and accesibility for those software/websites ?
On the website the latest update is about a patch for version 1.2.4, but on the wikipedia page it says that the last STABLE release is 1.8.
What is the reason for these inconsistencies? Was the project abandoned by the creator and the owner of the website and is now only developed through platforms like GitHUB? Even so there has to be somebody to take care of the development process.
Wouldn't it be a good idea for the free software community should take more care about popularizing their projects ?

A: Generally, an open source software project has a large(ish) number of contributors, so it can continue even if certain individuals stop contributing either temporarily or permanently.
It is also relatively easy to give access to those contributors so that they can update GitHub pages for the project - in fact, this ability generally goes hand in hand with being a project contributor.
It is somewhat harder to do the same for a completely separate website. This is why GitHub has become popular - it allows easy collaboration on the project and the project's documentation and meta-information, and for easy deployment/release of the project.
Another factor is that contributors to a project are focused on the project itself - and not the website. Coders want to code, not get stuck with apache configuration and HTML and CSS - especially if they're not web developers. So many project sites are very basic.
As you have observed - this means that many websites that used to host a project have become somewhat unloved, especially if the original project developer has moved on to other things.

A:
I was reading about gzip program and I found the official website of the gzip software.

No, you didn't. You found the website that used to be the official website back when the original authors were still the maintainers. Now, GNU Gzip is maintained by different people, and the website is https://www.gnu.org/software/gzip/ .

First of all the site looks very bad,

That is in the eye of the beholder. I find it simple, with no extraneous fluff, it loads extremely fast, and it works well in a mobile browser on a small screen.
Sure, the markup is horrible, but the authors are C programmers, not web designers.

it is very hard to find useful information on it

That is not my experience. Also, define "useful"

and it was not updated since several years ago.

Yes, the people who own that website no longer maintain Gzip, why would they update it?

Also, only www.gzip.org is working, but simply gzip.org is not working.

Those are two completely different hostnames. There is no reason for them to work the same way or work at all.

It would not be hard for people that are running those websites to make it better so that it would be more easy for more people to have acces to open source software and learn about it.
What is the reason no one cares about User Interfaces and accesibility for those software/websites ?

What makes you say no one cares? Obviously, you care and you are not no one. It's an open source project. The work is done by the community. That is you.

On the website the latest update is about a patch for version 1.2.4, but on the wikipedia page it says that the last STABLE release is 1.8.

That's because you are looking at the website for the project that no longer maintains Gzip. If you look at the current website, you'll find Gzip 1.8 right here: https://ftp.gnu.org/gnu/gzip/

What is the reason for these inconsistencies? Was the project abandoned by the creator and the owner of the website

Gzip was originally maintained by Jean-Loup Gailly and Mark Adler, who also maintained the http://www.gzip.org/ website, and is now maintained by Jim Meyering and Paul Eggert as part of GNU, which maintains the https://www.gnu.org/software/gzip/ website.

and is now only developed through platforms like GitHUB?

No, most GNU projects are managed on Savannah, not GitHub. Here's Gzip: https://savannah.gnu.org/projects/gzip/

Even so there has to be somebody to take care of the development process.

Yes, there is. Jim Meyering and Paul Eggert and the GNU project.

Wouldn't it be a good idea for the free software community should take more care about popularizing their projects ?

Gzip is installed on more machines than Windows, OSX, Linux, Android, and iOS combined. It runs in space, and the depth of the oceans. It runs on watches and supercomputing clusters. How much more popular could it be?


text:
Q: CSS merging multiple selectors Is there a way, how to group selectors in CSS?
To be precise lets have table with some content like this.

And I want to merge these style
#my-table tr > th .my-div1,
#my-table tr > td .my-div1 {
    some styles
}

into something like this
#my-table tr > (th, td) .my-div1 {
    some styles
}

Does CSS support anything like this?

A: CSS does not support it by default. Yet there are CSS preprocessors that I'm sure can help you with this.
Just skip over specifying th or td and jump right to the class.

A

B

C

D

#my-table tr .my-div1 {
    color: red;
}

http://jsfiddle.net/gdsbLhb2/


text:
Q: Is there a formula to calculate the area of a trapezoid knowing the length of all its sides? If all sides: $a, b, c, d$ are known, is there a formula that can calculate the area of a trapezoid?
I know this formula for calculating the area of a trapezoid from its two bases and its height:

$$S=\frac {a+b}{2}×h$$

And I know a well-known formula for finding the area of a triangle, called Heron's formula:

$$S=\sqrt {p(p-a)(p-b)(p-c)}$$
$$p=\frac{a+b+c}{2}$$

But I could not a formula for finding the area of a trapezoid in the books.

A: A note for the case when only two sides are parallel,
just the set of four side lengths do not determine the area.
An additional information is needed to define,
which pair of sides are parallel.
An illustrative example for side lengths $19,23,29,31$:

A: This is how to calculate the area of a trapezoid when the four sides are known:

A: Hint (if we know the parallel sides):

From The picture:
take: $a=AB, b=BC, c=CD, d=DA,x=AE$
so we have:
$
h=ED=\sqrt{d^2-x^2}=\sqrt{b^2-(a-c-x)^2}=CF
$
solve for $x$ and find $h=\sqrt{d^2-x^2}$
Find the area $A=\frac {a+b}{2}h$

A: There can't be such a formula. The side lengths do not determine the area.
Think about all the rhombi with four sides of length $1$. They are all trapezoids (even parallelograms) with the same side lengths but different areas, which can be anything between $0$ and $1$.

A: This problem is more subtle than some of the other answers here let on.  A great deal hinges on whether "trapezoid" is defined inclusively (i.e. as a quadrilateral with at least one pair of parallel sides) or exclusively (i.e. as a quadrilateral with exactly one pair of parallel sides).  The former definition is widely considered more mathematically sophisticated, but the latter definition is more traditional, is still extensively used in K-12 education in the United States, and has some advantages.
As the other responses have pointed out, if one defines "trapezoid" inclusively, then any parallelogram is automatically a trapezoid, and as the side-lengths of a parallelogram do not determine its area, it is not possible (even conceptually) that there could be a formula for the area of a trapezoid in terms of its side lengths.
However, if "trapezoid" is defined exclusively, then things are quite different.  Consider a trapezoid with parallel bases of length $a$ and $b$ with $b>a$.  Let $\theta$ and $\phi$ respectively denote the angles formed by the legs $c$ and $d$ with the base $b$.  Then we have the following relationships:
$$c\cos\theta + d\cos\phi = b-a$$
$$c\sin\theta = d\sin\phi$$
These conditions uniquely determine $\theta$ and $\phi$, and therefore among non-parallelogram trapezoids, choosing the lengths of the parallel sides and the lengths of the bases uniquely determines the figure.  In particular we would have $$\cos\theta = \frac{(b-a)^2+c^2-d^2}{2c(b-a)}$$.
The height of the trapezoid would then be $h=c\sin\theta$ (or if you prefer $h=d\sin\phi$, which is equal to it), so the area of the trapezoid can (in principal) be computed.  If you really want to carry it out, you would have
$$\sin\theta = \sqrt{1-\left( \frac{(b-a)^2+c^2-d^2}{2c(b-a)} \right)^2}$$
so the area would be
$$A=\frac{a+b}{2}c\sqrt{1-\left( \frac{(b-a)^2+c^2-d^2}{2c(b-a)} \right)^2}$$
I am not sure if there is a simpler expression, however.

A:
-For the trapzoid abcd to have parallel sides it requires all these conditions to be set for uniqueness of area:

*

*$a+b+c>d$, $b+a<d$, $c+a<d$.

-Neverthless, a trapzoid with non parallel sides can not be defined just by his side lengths, but a fifth coordinate added should.
In this experience we show how come multiple trapzoid shapes can be formed with same lengths of edges.
Imagine we bring a fork and a knife to start dining on some digestable geometrical concepts :

A thread and two pins:

We instill the pins on some flat table:

Then take the fork and the knife, choose two fixed points in the string, then pull it from these points with those tools without changing the fulcrum points.

Distance of the chord from the pinpoints to the coordinates of fulcrums dosn't change, while the shape of the trapzoid changes infinitely!
now envisage that $h_1$ is figured by the fork, $h_2$ symbolised by the knife, h1 is directly relative to h2 always regarding the same side lengths. We will show in the following trigonometric relations:

*

*$\cos\theta=b`/a$,
$sin\theta=(h_2-h_1)/a \implies \sqrt{1-(b`/a)^2}=(h_2-h_1)/a$

*$b``/d= \sqrt{1-(h_2/d)^2}$

*$(b-b`-b``)/c= \sqrt{1-(h_1/c)^2}$

Since there is 4 unknowns $b`,b``,h_1,h_2$ we can formulate $h_1$ in function of $h_2$ and 4 side constants.
Credits for the images goes to canstockphoto.com

A: I derived the formula for the area using the same procedure as is used to show Heron's Formula. Looking at the end formula, I realized that the formula follows quite simply from Heron's Formula.
Given a trapezoid with unequal parallel bases $a$ and $b$,

consider the triangle with base $|b-a|$ and sides $c$ and $d$:

Using $s=\frac{|b-a|+c+d}2$, the area of the triangle is
$$
\text{Area of Triangle}=\sqrt{s(s-c)(s-d)(s-|b-a|)}
$$
The altitude of the trapezoid and the triangle are the same, so the area is proportional to the average of the lengths of the bases. That is,
$$
\bbox[5px,border:2px solid #C0A000]{\text{Area of Trapezoid}=\frac{b+a}{|b-a|}\sqrt{s(s-c)(s-d)(s-|b-a|)}}
$$

A: To add a derivation that puts the square root factor in a Heronian context ...

For $c := |\overline{CD}| \neq |\overline{AB}| =: a$,
$$|\square ABCD| = \frac12 (a+c) \cdot h = \frac12 (a+c) \cdot \frac{2 |\triangle AC^\prime D|}{|\overline{C^\prime D}|} = \frac{a+c}{|a-c|}\;|\triangle AC^\prime D|$$
Then, applying Heron's Formula to a triangle with side-lengths $b$, $d$, $c-a$, we have
$$|\triangle AC^\prime D| = \frac14\sqrt{((c-a)+b+d)(-(c-a)+b+d)((c-a)-b+d)((c-a)+b-d)\;}$$

A: I think you mean Brahmagupta's formula, not Heron's formula.  There is no formula for the area of trapezoid given the lengths of the sides, because the sides alone do not determine the area.  This is true even for a parallelogram.  Imagine a parallelogram made of four sticks, joined together by pins at the corners.  Then you can slide it closed by moved the top side parallel to the bottom side.  You'll get zero area when the top and bottom coincide, and maximum are when you have a rectangle.
In the case of Brahmagupta's formula, the quadrilateral is circumscribable, and you can't change the sides like that.

A: It depends on your definition of trapezoid. If it includes parallelograms, then No: here are two trapezoids, same side-lengths, different area:

A: M Weiss put
$$A=\frac{a+b}{2}c\sqrt{1-\left( \frac{(b-a)^2+c^2-d^2}{2c(b-a)} \right)^2} .$$
I would rather have that answer symmetrical in $c$ & $d$, which would be
$$A=\frac{a+b}{4(b-a)}\sqrt{(b-a)^4+2(b-a)^2(c^2+d^2)+(c^2-d^2)^2} .$$
But it's just that to my taste it looks odd that it's not symmetrical in $c$ & $d$ ... my mind just protests that it ought to be!
Or
$$A=\frac{a+b}{4(b-a)}\sqrt{(b-a)^2((b-a)^2+2(c^2+d^2))+(c^2-d^2)^2} ,$$
even.


text:
Q: Rolling sum of time series with factor I am trying to calculate a rolling sum for a time series of returns r ranging over T dates. However at each date t when I calculate the rolling sum, I want to factor in a weight w for each number in the rolling sum.
The formula would be for every date t:
[Sum from i=1 to m](w(i)*r(t-i-1))

Lets look at a very simple example. I have a return series of T=6 returns r. For each date t I want to calculate the rolling sum over the last two dates (m=2). I also want to weight the first observation twice as much as the second.
r <- c(100,110,100,110,100,110)
w <- c(1,0.5)

I know that I can easily do the rolling sum using the filter function:
filter(r, rep(1, 2))

However I am not able to include the weight factor into the rolling sum. The following line gives the wrong result of c(155, 155, 155, 155, 155,  NA)
filter(r*w, rep(1, 2))

where I would really like to have the result c(155, 160, 155, 160, 155, NA)
Any help is appreciated.

A: Here's one way to do it:
filter(r, rev(w))
# [1] 155 160 155 160 155  NA

An important information about the argument filter from the help page of ?filter:

filter
  a vector of filter coefficients in reverse time order (as for AR or MA coefficients).

A: rollapply in the zoo package can do that:
> rollapply(r, 2, crossprod, w, fill = NA)
[1] 155 160 155 160 155  NA


text:
Q: HAproxy current session is zero I have some problems on sticky sessions with HAproxy.
Haproxy counts every request as a new session.
I have a Java servlet that creates the cookie JSESSIONID.
If I refresh that page 5 times. The servlet count it as 1 session and 5 request from that sessionid.
But the HAproxy stats page shows it as 5 different sessions.
And 0 current sessions.
Haproxy prefixes the cookie  correct, cookie: "JSESSIONID=test1~3fjp6734ys78grhk50ler16r" and is persistent.
I hit the same server every time.
This is my config file:
global
    daemon
    maxconn 256

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http-in
    bind *:3333
    acl Testrule path -m beg /test
    use_backend Test if Testrule

backend Test
    option httpchk GET /test
    cookie JSESSIONID prefix
    appsession JSESSIONID len 52 timeout 20m prefix
    server test2 vm-stapp-146:9003 check cookie test2
    server test1 vm-stapp-145:9003 check cookie test1

listen stats *:3334
    mode http
    stats enable
    stats uri /proxy-stats
    stats admin if TRUE

Why do the stats page show every request as a new session? And it always shows 0 current sessions.
Thanks.

A: HAProxy session count refers to tcpip sessions not browser sessions.  The count is 0 because at the time you asked for stats there were none in progress.  That is quite typical for a non-busy loadbalancer.
If your requests from the same session are hitting the same backend server it sounds like sticky sessions are working.

A: That stats column you want to look for when testing session persistence is lbtot, which increases whenever a client makes a request without a recognized session cookie.


text:
Q: How fail-safe is \n\r as stop bytes? In my UART communication I need to know the start byte and the stop byte of the message sent. The start byte is easy but the stop byte, not so much. I have implemented two stop bytes at the end of my message, that is \n and \r (10 and 13 decimal). UART only works on bytes 0-255 values so how fail-safe is this? I can imagine, though low probability, that my message might contain the values "10 and 13" after each other when they are not the stop bytes.
Is there a better way to implement this?

A: You know, ASCII already has bytes for these functions.

*

*0x01 : start of heading -- start byte

*0x02 : start of text -- end headers, begin payload

*0x03 : end of text -- end payload

*0x04 : end of transmission -- stop byte

*0x17 : end of transmission block --  message continues in next block

It also has codes for various uses inside the payload.

*

*0x1b : escape (escape the next character -- use in payload to indicate next character is not one of the structure describing codes used in your protocol)

*0x1c, 0x1d, 0x1e, 0x1f : file, group, record, and unit separator, respectively -- used as simultaneous stop and start byte for parts of hierarchical data

Your protocol should specify the finest granularity  of ACK (0x06) and NAK (0x15), so that negative acknowledged data can be retransmitted.  Down to this finest granularity, it is wise to have a length field immediately after any (unescaped) start indicator and (as explained in other answer(s)) it is wise to follow any (unescaped) stop indicator with a CRC.

A: UART is not fail-safe by its very nature - we are talking about 1960s technology here.
The root of the problem being that UART only syncs once per 10 bits, allowing a lot of gibberish to pass between those sync periods. Unlike for example CAN which samples every individual bit multiple times.
Any double bit error occurring inside the data will corrupt an UART frame and pass undetected. Bit errors in start/stop bits may or may not get detected in the form of overrun errors.
Therefore, no matter if you use raw data or packets, there is always a probability that bit flips caused by EMI result in unexpected data.
There exist numerous ways of "traditional UART quackery" to improve the situation ever so slightly. You can add sync bytes, sync bits, parity, double stop bits. You could add checksums that count the sum of all bytes (and then invert it - because why not) or you could count the number of binary ones as a checksum. All of this is widely used, wildly unscientific and with a high probability of missing errors. But this was what people did from 1960s to 1990s and lots of weird things like these lives on today.
The most professional way to deal with safe transmission over UART is to have a 16 bit CRC checksum at the end of the packet. Everything else isn't very safe and has a high probability of missing errors.
Then on the hardware level you can use differential RS-422/RS-485 to drastically improve ruggedness of the transmission. This is a must for safe transmission over longer distances. TTL level UART should only be used for on-board communication. RS-232 should not be used for any other purpose but backwards compatibility with old stuff.
Overall, the closer to the hardware your error detection mechanism is, the more effective it is. In terms of effectiveness, differential signals add the most, followed by checking for framing/overrun etc errors. CRC16 adds some, and then "traditional UART quackery" adds a little bit.

A: There are different ways to prevent this:

*

*Make sure you never send a 10/13 combination in your regular messages (so only as stop bytes). E.g. to send 20 21 22 23 24 25:

20 21 22 23 24 25 10 13

*

*Escape 10 and 13 (or all non ASCII characters with an escape character e.g. . So to send 20 21 10 13 25 26 send: (see comment of/credits for: DanW)

20 21 1b 10 1b 13 25 26

*

*Define a packet when sending messages. E.g. if you want to send message 20 21 22 23 24 25 than instead add the number of bytes to sent, so the package is:

< nr_of_data_bytes > < data >

If your messages are max 256 bytes send:

06 20 21 22 23 24 25

So you know after receiving 6 data bytes that is the end; you don't have to send a 10 13 afterwards. And you can send 10 13 inside a message. If your messages can be longer, you can use 2 bytes for the data size.
Update 1: Another way of defining packets
Another alternative is to send commands which have a specific length and can have many variances, e.g.

10 20 30 (Command 10 which always has 2 data bytes)
11 30 40 50 (Command 11 which always has 3 data bytes)
12 06 10 11 12 13 14 15 (Command 12 + 1 byte for the number of data bytes that follow)
13 01 02 01 02 03 ... (Command 13 + 2 bytes (01 02 for 256 + 2 = 258 data bytes that follow)
14 80 90 10 13 (Command 14 that is followed by an ASCII string ending with 10 13)

Update 2: Bad connection/byte losses
All of the above only work when the UART line is sending bytes correctly. If you want to use more reliable ways of sending, there are also many possibilities. Below are a few:

*

*Sending a checksum within the package (check google for CRC: Cyclic Redundancy Check). If the CRC is ok, the receiver knows the message has been sent ok (with high probability).

*If you need a message to be resent, than an acknowledgement (ACK/reply) mechanism needs to be used (e.g. sender sends something, receiver receives corrupt data, sends a NACK (not acknowledged), sender can than send again.

*Timeout: In case the receiver does not get an ACK or NACK in time, a message needs to be resend.

Note that all above mechanism can be simple or as complicated as you want (or need) to be. In case of resending message, also a mechanism for identifying messages is needed (e.g. adding a sequence number into the package).

A:
How fail-safe is \n\r as stop bytes?

If you send send arbitrary data -> probably not fail-safe enough.
A common solution is to use escaping:
Let's define that the characters 0x02 (STX - frame start) and 0x03 (ETX - frame end) need to be unique within the transmitted data stream. This way the start and the end of a message can be safely detected.
If one of these characters should be send within the message frame, it is replaced by prefixing an escape character (ESC = 0x1b) and adding 0x20 to the original character.
Original character replaced by
0x02 -> 0x1b 0x22
0x03 -> 0x1b 0x23
0x1b -> 0x1b 0x3b

The receiver reverses this process: Anytime he receives an escape character, this character is dropped and the next character is subtracted by 0x20.
This only adds some processing overhead but is 100% reliable (assuming no transmission errors occur, which you could/should verify by additionally implementing a checksum mechanism).

A:
... I can imagine, though low probability, that my message might contain the values "10 and 13" after each other when they are not the stop bytes.

A situation when a portion of data is equal to terminating sequence should be considered when designing the format of a serial data packet.  Another thing to consider is that any character can get corrupted or lost during transmission.  A start character, a stop character, a data payload byte, a checksum or CRC byte, a forward error correction byte aren't immune to corruption.  The framing  mechanism has to be able to detect when a packet has corrupt data.
There a several ways to approach all this.
I'm making the working assumption that packets are framed only with the serial bytes.  Handshake lines aren't used for framing.  Time delays aren't used for framing.
Send packet length
Send the length of the packet in the beginning, instead of [or in addition to] the terminating character at the end.
pros:  Payload is sent in a efficient binary format.
cons:  Need to know the packet length at the start of the transmission.
Escape the special characters
Escape the special characters when sending the payload data.  This is already explained in a an earlier answer.
pros:  Sender doesn't need to know the length of the packet at the beginning of the transmission.
cons:  Slightly less efficient, depending on how many payload bytes need to be escaped.
Payload data encoded such that it can't contain start and stop characters
The payload of the packet is encoded such that it can't contain the start or stop characters.  Usually, this is done by sending numbers as their ASCII or Hex-ASCII representation.
pros:  Human-readable with common terminal programs.  No need for code to handle escaping.  No need to know the length of the packet at the start of the transmission
cons:  Lower efficiency.  For one byte of payload data, several bytes are sent.


text:
Q: Show several tooltips at the same time (DevExpress) I am working on a C# WinForm application in Visual Studio 2008 and are using DevExpress.
I have added shortcuts to Some of the buttons (DevExpress SimpleButton) which triggers a button click (CTRL + R, CTRL B and so on...). I would like to show the shortcut texts in a tooltip next to each button when the user press and hold the CTRL key.
I have tried to use the DevExpress control 'ToolTipController' and that works OK if I only have one tooltip. But I would like to show more than one tooltip at a time. It seems like only the last tooltip that is added is shown.
Is it possible to show more than one tooltip at a time? Or does anyone have any other suggestion on how to solve this problem?

A: I solved this by creating a WPF control that looks similar to a standard tooltip (small box with a label). I then did an override on ProcessCmdKey and OnKeyUp on my form to listen to CTRL key down and key up.
When the user presses and holds down the CTRL key I loop through all my controls that has a shortcut and creates a WPF control on top of that control. For each WPF control I set the corresponding shortcut text. When the CTRL key is released I remove all WPF controls in OnKeyUp.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    { if ((msg.Msg == WM_KEYDOWN) && ModifierKeys == Keys.Control && !_isKeyDown)
        {
            _isKeyDown = true;
            ShowShortCutToolTips();
            this.Focus();
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

   protected override void OnKeyUp(KeyEventArgs e)
    {
        base.OnKeyUp(e);
        if(e.KeyValue == 17 || e.Control) // 17 = Control Key
        {
            _isKeyDown = false;
            HideShortCutToolTips();
        }
    }


text:
Q: How to change page number in the ToC to sans serif? I want my ToC to display sans serif page numbers not only for chapters, but for sections as well. I had the following code used earlier (six years ago) and it worked. Can it be recognized, why it does not work now? I assume some changes in a package. However, how to fix this?
\documentclass[10pt,twoside,titlepage,headsepline,headings=small,BCOR=17mm]{scrbook}
\usepackage{scrlayer-scrpage} % scrpage2
\usepackage{cmap}
\usepackage{ulem}
\usepackage[utf8]{inputenc}
\usepackage[vietnamese=nohyphenation]{hyphsubst}
\usepackage[vietnamese,polish]{babel}
\usepackage[T5,T1]{fontenc}
\usepackage{longtable}
\usepackage{lmodern}
\usepackage{makeidx}
\usepackage[columns=2,itemlayout=abshang,initsep=1.8em plus 0.2em minus 0.2em]{idxlayout}
\usepackage{mathtools}
\usepackage{graphicx}
\usepackage{etoolbox}

\makeatletter
\let\old@dottedcontentsline\@dottedtocline
\def\@dottedtocline#1#2#3#4#5{\old@dottedcontentsline{#1}{#2}{#3}{#4}{\textsf{#5}}}
\makeatother

\begin{document}

\sffamily\tableofcontents\normalfont

\mainmatter

\chapter{A chapter}

\addsec{A section}

Some text is written here. What do you think of it?

\addsec{Another section}

Some text is written here. What do you think of it?

\chapter{Another chapter}

\addsec{Again a section}

Some text is written here. What do you think of it?

\addsec{And another section}

Some text is written here. What do you think of it?

\end{document}

A: I think that this does what you want as shown in my revised version of your MWE, for which thank you.
% tocsfprob.tex  SE 578458

\documentclass[10pt,twoside,titlepage,headsepline,headings=small,BCOR=17mm]{scrbook}
\usepackage{comment}  %% added
\usepackage{scrlayer-scrpage} % scrpage2
\usepackage{cmap}
\usepackage{ulem}
\usepackage[utf8]{inputenc}
\usepackage[vietnamese=nohyphenation]{hyphsubst}
\usepackage[vietnamese,polish]{babel}
\usepackage[T5,T1]{fontenc}
\usepackage{longtable}
\usepackage{lmodern}
\usepackage{makeidx}
\usepackage[columns=2,itemlayout=abshang,initsep=1.8em plus 0.2em minus 0.2em]{idxlayout}
\usepackage{mathtools}
\usepackage{graphicx}
\usepackage{etoolbox}

\begin{comment}
\makeatletter
\let\old@dottedcontentsline\@dottedtocline
\def\@dottedtocline#1#2#3#4#5{\old@dottedcontentsline{#1}{#2}{#3}{#4}{\textsf{#5}}}
\makeatother
\end{comment}

\usepackage{tocloft}  %% added plus next 2 lines
\renewcommand{\cftchappagefont}{\sffamily}
\renewcommand{\cftsecpagefont}{\sffamily}

\begin{document}

\sffamily\tableofcontents\normalfont

\mainmatter

\chapter{A chapter}

\addsec{A section}

Some text is written here. What do you think of it?

\addsec{Another section}

Some text is written here. What do you think of it?

\chapter{Another chapter}

\addsec{Again a section}

Some text is written here. What do you think of it?

\addsec{And another section}

Some text is written here. What do you think of it?

\end{document}

A: KOMA-Script offers \DeclareTOCStyleEntry (introduced in version 3.20) and  \DeclareTOCStyleEntries (introduced in version 3.26) to change the font settings of entries and page numbers:
\DeclareTOCStyleEntries[
  entryformat=\textsf,
  pagenumberformat=\textsf
]{tocline}{section,subsection,subsubsection,paragraph,subparagraph,figure,table}

Example:
\documentclass[10pt,twoside,titlepage,headsepline,headings=small,BCOR=17mm]{scrbook}
\usepackage{scrlayer-scrpage}
\usepackage{cmap}
\usepackage{ulem}
\usepackage[utf8]{inputenc}
\usepackage[vietnamese=nohyphenation]{hyphsubst}
\usepackage[vietnamese,polish]{babel}
\usepackage[T5,T1]{fontenc}
\usepackage{longtable}
\usepackage{lmodern}
\usepackage{makeidx}
\usepackage[columns=2,itemlayout=abshang,initsep=1.8em plus 0.2em minus 0.2em]{idxlayout}
\usepackage{mathtools}
\usepackage{graphicx}
\usepackage{etoolbox}

\DeclareTOCStyleEntries[
  entryformat=\textsf,
  pagenumberformat=\textsf
]{tocline}{section,subsection,subsubsection,paragraph,subparagraph,figure,table}

\begin{document}
\tableofcontents
\mainmatter
\chapter{A chapter}
\addsec{A section}
Some text is written here. What do you think of it?
\addsec{Another section}
Some text is written here. What do you think of it?
\chapter{Another chapter}
\addsec{Again a section}
Some text is written here. What do you think of it?
\addsec{And another section}
Some text is written here. What do you think of it?
\end{document}


text:
Q: Where to we implement AbstractControl in angular2 I have written a code , I do no where to write the AbstractControl
here is the code
 @Component({
     selector: 'page-sinup',
     templateUrl: 'home.html'
 })

 export const Validate = (control: AbstractControl): { [key: string]: any } => {
  const firstname    = control.get('firstname');
  const useridphone  = control.get('useridphone');
  const password     = control.get('password');
  const email        = control.get('email');
  };
  export class SinupPage {
  }

i have written the Abstract Control in first  class, its showing error
{ [key: string]: any } => {}
firstname is undefined all the fields are showing error, I do no where to erite a code, for displaying error messageswhen it is build in the ionic2 app


text:
Q: How can I detect UIStatusBar hide and show? I'm trying to detect hidden and show of iPhone's UIStatusBar but failed. Are there any solution can help me, like KVO or something else?

A: You can observe the statusBarHidden property of the shared UIApplication instance.
Simple example:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // Do something here...
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[UIApplication sharedApplication] addObserver:self forKeyPath:@"statusBarHidden" options:NSKeyValueObservingOptionNew context:NULL];
    [[UIApplication sharedApplication] setStatusBarHidden:YES]; // Will notify the observer about the change
}

A: From iOS 11 and up you can subclass the UIView of the view controller and override safeAreaInsetsDidChange:
override func safeAreaInsetsDidChange() {
  super.safeAreaInsetsDidChange()
  // adapt your view
}

Your view must share the top rect with the status bar for this to work. (But if it doesn't, you probably wouldn't need to detect changes anyway).

A: In UIApplication class there is a property statusBarHidden...this tell status bar hidden or not...if it return YES mean status bar is hidden...try this.

A: iOS 13
Since isStatusBarHidden and setStatusBarHidden are deprecated from iOS 13 you can check visibility of the status bar with UIStatusBarManager.isStatusBarHidden and Timer since it is not supported by KVO:
timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { timer in
    if let statusBarManager = UIApplication.shared.delegate?.window??.windowScene?.statusBarManager {
        print(statusBarManager.isStatusBarHidden)
    }
}


text:
Q: jvisualvm is not working with eclipse For who knows what is the jvisualvm, I downloaded a plugin to eclipse to initiate the application with the jvisualvm. But unlike the official site says, when I run any java application, the program does NOT appear in the left side. There's only one global tab.
Any clues?

A: Are you running the java application as the same user? I seem to recall that by default it only sees processes started by the same userid.


text:
Q: How to generate pydoc documentation for Google Cloud Endpoints method? I have a set of APIs that were developed using Google Cloud Endpoints. The API methods look something like this:
@endpoints.method(message_types.VoidMessage, SystemAboutResponse, name="about", http_method="GET")
def about(self, request):
    """
    Returns some simple information about the APIs.

    Example:
      ...
    """
    return SystemAboutResponse(version=API_VERSION)

I would like to use pydoc to generate documentation for the module that contains this method. However, when I do this, the docstring is not preserved due to the use of the endpoints.method decorator.
I have seen answers to other questions that show how to use functools.wraps (e.g. Python decorator handling docstrings) when writing your own decorators so that they will preserve the docstring of decorated methods. Is there some way to do this with Google Cloud Endpoints decorators, since I won't have control over the code for these decorators?

A: I ended up making a local modification to a copy of the endpoints library. The change is in api_config.py, specifically the apiserving_method_decorator function of the method decorator. I added the @wraps decoration to the invoke_remote function contained within apiserving_method_decorator:
def method(request_message=message_types.VoidMessage,
           response_message=message_types.VoidMessage,
           name=None,
           path=None,
           http_method='POST',
           cache_control=None,
           scopes=None,
           audiences=None,
           allowed_client_ids=None,
           auth_level=None):
    # ...

    def apiserving_method_decorator(api_method):
        # ...

        @wraps(api_method)
        def invoke_remote(service_instance, request):
            # ...

I then make sure that this locally modified copy of the endpoints library is in my PYTHONPATH when I run pydoc.


text:
Q: xcode 4.5 dependency issues with iphone 5 I am trying to build my project to my iphone 5 and I keep getting this warning
No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=armv7s, VALID_ARCHS=armv6 armv7)
Does anyone know how to fix this?

A: You get this error becuse your active Architecture is armv7s (armv7s is the architecture for iPhone 5's A6 SoC):

active arch=armv7s

but this architecture is not listed among your valid architectures:

VALID_ARCHS=armv6 armv7

Modify the "Valid Architectures" in your project target's "Build Settings" by adding armv7s (you might as well remove armv6 since Xcode 4.5 does not support that any more):

You might also need to change the "Architectures" property:

and set "Build Active Architecture Only" to NO (so your project is built for all listed architectures including armv7, which older devices, e.g. iPhone 4S, can execute):

Also, check out this answer.


text:
Q: How run script after spamc, use args in script and redirect spamc output to sendmail? I'm trying to perform custom actions after spamassassin.
I have working line in postfix master.cf
spamassassin unix - n n - - pipe user=spamd argv=/usr/bin/spamc -e
/usr/sbin/sendmail -oi -f ${sender} ${recipient}

But I want to redirect spamc output to my script, which take arguments, perform my actions and than redirect spamc output to sendmail.
I tried to do
spamassassin unix - n n - - pipe user=spamd argv=/usr/bin/spamc -e
/home/scripts/my.sh ${sender} ${recipient}

And my.sh just echoing $1 and $2 but see in mail.log
spamc[31244]: exec failed: Exec format error

In short, I want to at least show sender recipient args in echo and after that try to redirect spamc output to sendmail in my script but I even was not able to run simple echo(
UPDATE
Currently I have the following conf in postfix:
smtp      inet  n       -       -       -       -       smtpd -v -o content_filter=filter

filter unix - n n - - pipe user=spamd argv=/home/scripts/my.sh -oi -f ${sender} ${recipient}

Experimantal script works and now just sends spamc output to file (no sendmail)
/usr/bin/spamc > /home/scripts/res

How may I extract such smtp headers as From, To and X-Spam-Flag from spamc result using bash and redirect spamc result to sendmail? I want to somehow use pipes in order not to call spamc twice. I thing grep may help me, but I don't exactly know how to extract from - other headers may be taken as is but From header contains extra information + mail in <> (example - From: =?UTF-8?B?nameInBB64?= ) but I'm not sure that mail address is always inside <>. Is my suggestion correct?


text:
Q: Need advise on how to POST to PHP correctly with Angular So, I am currently trying to use PHP (still new to PHP) with Angular, and would like some advise so I can write good clean code.
Basically, I am trying to get analytics from an third-party API, but first I must retrieve a token with my username + password, and then after I receive the token, I must then call another URL and add that token in the parameter.
First, in my controller - I'll add my $http call in my services later
var username = 'test';
var pass = 'test password';

$http({
    url: 'http://example/stats.php',
    method: "POST",
    data: $.param({
        "user_id": username,
        "pass" : pass
    }),
}).success(function(data, status, headers, config) {
    console.log(data.tokenResponse.tokenId);
    // Here I get back that token Id

}).error(function(data, status, headers, config) {});

In my PHP Script, I pass the user_id & pass, and then call the API and echo back the $data.
$username = $_POST['user_id'];
$password = $_POST['pass'];

$data =
file_get_contents('https://examplestats.com/rest/auth/json?login='.$username.'&password='.$password.'');
echo str_replace("\\","", $data);

In return I get,
Object
tokenResponse: Object
tokenId: "96996a53-6464-42d6-9726-47be0971f323"
universe: Array[3]
__proto__: Object
__proto__: Object

Now that I have the Token, I must get the analytics. The third party states that I must pass the token in the url as a parameter i.e
example.com/rest/data/json?tokenId=96996a53-6464-42d6-9726-47be0971f323&indicator=Analytics
Now the question is, how can I call stats.php just one time and retrieve the data? At the moment, I could create another php file and do the same process, but then I would be repeating code.  In the meantime, I will try to figure it out.

A: Use json_decode in your PHP script to get the tokenID and make another request:
$username = $_POST['user_id'];
$password = $_POST['pass'];

$data =
file_get_contents('https://examplestats.com/rest/auth/json?login='.$username.'&password='.$password.'');
$data = json_decode($data);
$analytics = file_get_contents('https://examplestats.com/rest/data/json?tokenId=' . $data->tokenResponse->tokenId . '&indicator=Analytics');
echo str_replace("\\","", $analytics);


text:
Q: Recoverable fatal error on WordPress site I'm having a problem with my WordPress site
I've updated some plugins and after updating, I now receive the following error message when trying to access my site:

Recoverable fatal error: Object of class WP_Term could not be
  converted to string in
  /homepages/35/d395311677/htdocs/clickandbuilds/MEDICALpromotion671654/wp-content/themes/Divi/includes/builder/class-et-builder-settings.php
  on line 633

I've checked that line of code and also tried deleting and reuploading that particular Divi file - that didn't help. You can see the the code in question below
return is_array( $terms ) ? implode( ',', $terms ) : '';

is line 633, that's apparently causing a problem.  Since I'm a total PHP beginner, the code doesn't really tell me anything... :(
I hope you can help!
I've tried:
Updating all plugins.
Deleting an reuploading the original Divi file in question.
Replaced the code in the file with the code from a brand new Divi file download.
protected static function _get_object_terms( $post_id, $taxonomy ) {
        $terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
        return is_array( $terms ) ? implode( ',', $terms ) : '';
    }

I expected: To be able to access my site.
The actual output is: An recoverable fatal error message.


text:
Q: CSS to change the opacity of tab background witout affecting text on tab how can I reduce the opacity of the background of a tab in navbar without affecting the text in the tab itself?
For example, opacity of the text "About Us" to be 1, but the background color to have an opacity of 0.5.
Here is my CSS code.

.navbar-default .navbar-nav > li > a:hover,
   .navbar-default .navbar-nav > li > a:focus{
       color: #FFFFFF;
       background-color: #009eff;
   }

A: You should use rgba format for the color instead of hex. Use:
background-color: rgba(0, 158, 255, 0.5);
Here's a definition of rgba from Mozilla Developer website:

Colors can be defined in the Red-green-blue-alpha model (RGBa) using
  the rgba() functional notation. RGBa extends the RGB color model to
  include the alpha channel, allowing specification of the opacity of a
  color.
a means opacity: 0=transparent; 1=opaque;

A: You could set the background as an RGBA value, for example:
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    color: #FFFFFF;
    background-color: rgba(0, 158, 255, 0.5);
}

Here the opacity (alpha) level is set as the 4th argument to the rgba(...) function. Support for rgba is pretty good now (http://caniuse.com/#search=rgba) but if you want to support IE8 then this isn't going to work.

A: RGBA is definitely the way to go. Think of it like this: you are actually affecting the opacity of the background of the object, by implementing an opacity (alpha) factor straight to the background's color, and not the opacity of the object itsef. Thus, your code should be like this.
.navbar-default .navbar-nav > li > a:hover,
   .navbar-default .navbar-nav > li > a:focus{
       color: #FFFFFF;
       background-color: rgba(0, 158, 255, 0.5);
   }


text:
Q: Does A Web Service Have To Be Registered? I'm learning about web services and most of the resources I've been reading talk about registering your web service once it's ready for use by others. Is registering a web service required to use the service?
For example, let's say I have a web application on a company intranet and I create another web service app that retrieves some sort of useful information to be displayed on this private intranet site. Would this new web service require being registered just so my web app can use it or can the web app simply interface directly to the new web service (following the WSDL file) without the need of some sort of UDDI registry?

A: You can certainly use the service without the UDDI registry.
I have created several Web Services and have immediately used them without registering them.  Registration gives others confidence that your Web Service is legitimate and descriptions of how to interact with those services.
Imagine doing development where you have to register any Web Service before using it.  Yikes!

A: No, not at all.
You are probably talking about API directories you may register your WS at. Like UDDI or what it's named. Entirely optional.

A: Nobody uses UDDI anymore. It's an idea whose time has come and gone.
It was thought that there would be public registries of web services that everyone would use to find a web service to meet their needs. That never happened.

A: How could either the service or the app know whether or not the service was registered?
Furthermore, why would they care?

A: If you're trying to use service orientation the right way, your web services should be registered within a service registry. The registry should contain the published contract of the services and any meta-data that helps the discovery process.
A different questions is: does a service consumer program need to look up a registry and dynamically bind the service it needs to call? NO, NOT AT ALL.
But then, what discovery process am I talking about?
I'm referring to a human (developer, architect, etc.) who is designing/developing a program that needs to call a service. This person should have means to search what services are available in his/her organization. If not, the benefit of reusing services is compromised.
Discovery is also about humans finding out there's a service somewhere in the IT organization that offers the functionality they want.
In this case, the registry can be as simple as an html report that is created and updated manually or generated by parsing (xslt comes handy) the wsdl files.


text:
Q: Get last boot/start time on Windows I want to know when the Windows PC (Windows 10 or Windows Server 2019) was restarted. Today I tried it on my freshly booted machine (10 minutes ago) and I got the 17th August 2021 at 11:51:26 PM. So it seems the PC was hibernating, while being completely turned off (without power!).
How do I get the last time the PC was restarted? I tried with this
Command line:

systeminfo /s localhost

PowerShell:

Get-CimInstance -ClassName win32_operatingsystem | select csname, lastbootuptime

but they are giving me the wrong information.