text:
Q: Memory leakage in C# while using very big strings Inspecting memory leakage on one of my apps, I've found that the next code "behaves strange".
public String DoTest()
        {
            String fileContent = "";
            String fileName = "";
            String[] filesNames = System.IO.Directory.GetFiles(logDir);
            List<String> contents = new List<string>();

            for (int i = 0; i < filesNames.Length; i++)
            {
                fileName = filesNames[i];
                if (fileName.ToLower().Contains("aud"))
                {
                    contents.Add(System.IO.File.ReadAllText(fileName));
                }
            }
            fileContent = String.Join("", contents);
            return fileContent;
        }

Before running this piece of code, the memory used by object was approximatly 1.4 Mb.  Once this method called, it used 70MB.  waiting some minutes, nothing changed (the original object was being released a long time ago).
calling to
GC.Collect();
GC.WaitForFullGCComplete();

decreased memory to 21MB (Yet, far much more than the 1.4MB at the beginning).
Tested with console app (infinity loop) and winform app.  Happens even on direct call (no need to create more objects).
Edit:  full code (console app) to show the problem
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace memory_tester
{

    /// <summary>
    /// Class to show loosing of memory
    /// </summary>
    class memory_leacker
    {
        // path to folder with 250 text files, total of 80MB of text
        const String logDir = @"d:\http_server_test\http_server_test\bin\Debug\logs\";

        /// <summary>
        /// Collecting all text from files in folder logDir and returns it.
        /// </summary>
        /// <returns></returns>
        public String DoTest()
        {
            String fileContent = "";
            String fileName = "";
            String[] filesNames = System.IO.Directory.GetFiles(logDir);
            List<String> contents = new List<string>();

            for (int i = 0; i < filesNames.Length; i++)
            {
                fileName = filesNames[i];
                if (fileName.ToLower().Contains("aud"))
                {
                    //using string builder directly into fileContent shows same results.
                    contents.Add(System.IO.File.ReadAllText(fileName));

                }
            }
            fileContent = String.Join("", contents);
            return fileContent;
        }

        /// <summary>
        /// demo call to see that no memory leaks here
        /// </summary>
        /// <returns></returns>
        public String DoTestDemo()
        {
            return "";
        }

    }

    class Program
    {
        /// <summary>
        /// Get current proc's private memory
        /// </summary>
        /// <returns></returns>
        public static long GetUsedMemory()
        {
            String procName = System.AppDomain.CurrentDomain.FriendlyName;
            long mem = Process.GetCurrentProcess().PrivateMemorySize64 ;
            return mem;
        }

        static void Main(string[] args)
        {
            const long waitTime = 10;  //was 240
            memory_leacker mleaker = new memory_leacker();

            for (int i=0; i< waitTime; i++)
            {
                Console.Write($"Memory before {GetUsedMemory()} Please wait {i}\r");
                Thread.Sleep(1000);
            }
            Console.Write("\r\n");

            mleaker.DoTestDemo();
            for (int i = 0; i < waitTime; i++)
            {
                Console.Write($"Memory after demo call {GetUsedMemory()} Please wait {i}\r");
                Thread.Sleep(1000);
            }
            Console.Write("\r\n");

            mleaker.DoTest();
            for (int i = 0; i < waitTime; i++)
            {
                Console.Write($"Memory after real call {GetUsedMemory()} Please wait {i}\r");
                Thread.Sleep(1000);
            }
            Console.Write("\r\n");

            mleaker = null;
            for (int i = 0; i < waitTime; i++)
            {
                Console.Write($"Memory after release objectg {GetUsedMemory()} Please wait {i}\r");
                Thread.Sleep(1000);
            }
            Console.Write("\r\n");

            GC.Collect();
            GC.WaitForFullGCComplete();
            for (int i = 0; i < waitTime; i++)
            {
                Console.Write($"Memory after GC {GetUsedMemory()} Please wait {i}\r");
                Thread.Sleep(1000);
            }
            Console.Write("\r\n...pause...");

            Console.ReadKey();
        }
    }
}

A: I believe that if you use stringbuilder on fileContent instead string, you can improve your performance and usage of memory.
public String DoTest()
        {
            var fileContent = new StringBuilder();
            String fileName = "";
            String[] filesNames = System.IO.Directory.GetFiles(logDir);
            for (int i = 0; i < filesNames.Length; i++)
            {
                fileName = filesNames[i];
                if (fileName.ToLower().Contains("aud"))
                {
                    fileContent.Append(System.IO.File.ReadAllText(fileName));
                }
            }

            return fileContent;
        }

A: I refactored version of your code below, here I have removed the need for the list of strings named 'contents' in your original question.
    public String DoTest()
    {
        string fileContent = "";

        IEnumerable<string> filesNames = System.IO.Directory.GetFiles(logDir).Where(x => x.ToLower().Contains("aud"));

        foreach (var fileName in filesNames)
        {
            fileContent = string.Join("", System.IO.File.ReadAllText(fileName));
        }

        return fileContent;
    }


text:
Q: JQuery Mobile Listview Disappearing I am creating a JQuery Mobile web-app, and am experiencing a problem.
When then user clicks on an element in a Listview, a new page is loaded. However, when the user clicks the button, the elements in the Listview do not show.
The list elements are dynamically added, then enhanced with$("#landmarksList").listview().listview("refresh");
Here is a link to a page illustrating the problem:
http://jakeserver.com/Apps/BostonLandmarks/B6/landmarks.html
Any ideas about what might be causing this problem?
Thanks.

A: In JQM , DOM element are handled in differently .For example, try using $(document).on('pageinit','#youpage'.. instead of $(document).ready ....ref.try
Landmarks Page
$(docuemnt).on('pageshow','#landmarks',function(){
   // load the landmark content dynamically here
   createListRow();
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Way to use webpack-rtl-plugin in vuejs I would like to add RTL support to my web application based on vuejs 2 for frontend.
I started to import my scss files in my main component
<style lang="scss">
@import '~@/assets/scss/vendors';
@import '~@/assets/scss/app';
</style>

Then i'm using webpack-rtl-plugin in my vue.config.js file to generate rtl styles when building the app.
configureWebpack: {
  plugins: [
    new WebpackRTLPlugin({
      diffOnly: true
    })
  ]
}

The rtl files are generated in the dist directory, but i don't find a way to include them directly in the main js.
I don't know if i need to build the styles separatly then include the styles depending on the app language set in the app or there is a way to use them directly without need to build them into css then import the generated files.


text:
Q: Google stacked area chart not working I want to accomplish google stacked area chart.
Here is the js fiddle:
Js Fiddle
I also tried adding the options for stacked area:
var options_fullStacked = {
          isStacked: 'relative',
          height: 300,
          legend: {position: 'top', maxLines: 3},
          vAxis: {
            minValue: 0,
            ticks: [0, .3, .6, .9, 1]
          }
        };

It is available in the documentation for google charts:stacked area
I want to display it as shown in this figure:

Please ignore everything else in this figure except the stacked area chart displayed in between the line chart and the map

A: seems to work here, is there more you can share?
see following examples...
isStacked: true

google.charts.load('current', {
  callback: function () {
    new google.visualization.AreaChart(document.getElementById('chart_div')).draw(
      google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2013',  1000,      400],
        ['2014',  1170,      460],
        ['2015',  660,       1120],
        ['2016',  1030,      540]
      ]),
      {
        title: 'Company Performance',
        isStacked: true,
        hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
        vAxis: {minValue: 0}
      }
    );
  },
  packages:['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
}

isStacked: false

google.charts.load('current', {
  callback: function () {
    new google.visualization.AreaChart(document.getElementById('chart_div')).draw(
      google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2013',  1000,      400],
        ['2014',  1170,      460],
        ['2015',  660,       1120],
        ['2016',  1030,      540]
      ]),
      {
        title: 'Company Performance',
        isStacked: false,
        hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
        vAxis: {minValue: 0}
      }
    );
  },
  packages:['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
}


text:
Q: Old portable CRT TV power socket I found a nice old portable CRT TV (model "tele star 4004") without a power cable.
The power socket on the back has six pins:

I've never seen such a design before (and google is coming up short).
I need to replace the power cable but to do this I need to identifying which pin does what. (I realize the hazard of messing with CRT units and I'm taking precautions)
This is the schematic for the power input:

My experience with power supply inputs is simple two-wire positive/negative rails so this is a bit beyond me

A: Just open it up and trace the wiring. It should be pretty obvious which pin is which by matching them up with the schematic.
But even without opening it up, I'd be willing to bet that the two pins with the greater spacing from the other four are the 220VAC pins (pins 5 and 6). You can verify this by checking for continuity to the terminals of the fuse holder. You might be able to find a 2-pin line cord that fits these pins directly.
Of the remaining four, two are shorted together, so they're the +12VDC (pins 2 and 4 — this tells you which side of the connector has the even numbers).
The last two (pins 1 and 3) are ground and +12V from the internal power supply. One of them (most likely the one in the corner) will be shorted to some other ground on the chassis, such as the head of a screw, or an earphone or antenna jack. Or you could apply AC power and see which pin has +12V on it relative to the rest — that's pin 3.

A: That diagram is showing you two power options.

*

*Mains uses a cable with 220 V AC on pins 5 and 6. Note that there is a jumper connection on 3 and 4 so I suspect that 12 V DC comes out on 3 from the transformer-powered internal DC supply and is fed back in on 4. (It could just as well be fed back in on 2 as they are connected internally.

*Battery uses a cable with negative on 1 and positive on 2. The 3 - 4 jumper is not required in this case.
You have two options:

*

*Open it up, find the mains wiring going to FU1 / S1, disconnect those from the power socket and feed them directly from a new mains cable and plug. Make sure that the original mains input pins are disconnected because they will be exposed.

*Get a 12 V power supply and feed these in on 1 and 2 (observing polarity). The TV, at a guess, is going to need 5 to 10 A from the 12 V supply. You could check it on a car battery and, if it works, measure the input current using a multimeter on the 10 A range in series with the TV. Based on this experiment you can determine what power supply to use - if it's worth the expense.


text:
Q: Group $G$ of order $p^2$: $\;G\cong \mathbb Z_{p^2}$ or $G\cong \mathbb Z_p \times \mathbb Z_p$ If the order of $G$ is $p^2$ then how do I show that $G$ is isomorphic to $\mathbb Z_{p^2}$ or $\mathbb Z_p\times\mathbb Z_p$.

A: Hints:
What are the possible orders of elements in $\,G\,$ ? And if there is no element of order $\,p^2\,$ in $\,G\,$ , then can you find two elements
$$1\neq x,y\in G\;\;s.t.\;\;\langle x\rangle\cap\langle y\rangle = 1\ldots?$$

A: You can get by without the fundamental theorem of finitely Abelian groups in this case, once you know the group is Abelian. If there is only one subgroup of order $p,$ then consider the order of an element outside that subgroup. If there are two different subgroups $A$ and $B$ of order $p$. What is $A \cap B?$ What is $|AB|?$
It wasn't clear from what you wrote whether you already have proved for yourself that $G$ ( the whole group) a Abelian, or you know it for other reasons. Depending on what you have done so far on your course, this may or may not be straightforward. Have you proved that if $G$ is a group such that $G/Z(G)$ is cyclic, then $G$ is Abelian? Have you proved that a finite $p$-group has a non-trivial center? You didn't actually say that $p$ was a prime by the way, but I suppose that is clear from the context.

A: Hint:
Argue that $G$ must be abelian (why?)
Then use the Fundamental Theorem of Finitely Generated Abelian Groups to prove that any abelian groups of order $p^2$ must necessarily be isomorphic to one of the two groups $\mathbb Z_{p^2}$ or $\mathbb Z_p\times \mathbb Z_p$, which are non-isomorphic groups, since $\mathbb Z_m\times \mathbb Z_n \cong \mathbb Z_{mn} \iff \gcd(m,n) = 1$, and clearly, $\gcd(p, p) = p \neq 1$.


text:
Q: how can i include a blade view in a controller in laravel? i have a recursive function in my controllers  that create a tree view table from an array, in this function i need to include task view when the if condition is true and this view is just a row of table with different param how can i access this view in a right way?
problem is in crate_task_view function where i need task view pleas read codes before answering
thanks... code is blow:
this is my TaskController
    namespace App\Http\Controllers;

    use App\Task;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\DB;

class TaskController extends Controller
{

private static $menu = array(
    'items' => array(),
    'parents' => array()
);
private static $params = [] ;

private static $user_id = 'حامد_تقی_زاده';

public static function create_tree_view($parent, $menu)
{

    $html = "";
    if ( isset( self::$menu['parents'][$parent] ) )
    {

        $html .= "
";
        foreach ( self::$menu['parents'][$parent] as $itemId )
        {

            $task=[

                'id' => $menu['items'][$itemId]['id'],
                'p_id' => $menu['items'][$itemId]['p_id'],
                'title' => $menu['items'][$itemId]['title'],
                'visitors' => explode( ',' , $menu['items'][$itemId]['visitors'] ),
                'members' => explode( ',' , $menu['items'][$itemId]['members'] ),
                'owners'=> explode( ',' , $menu['items'][$itemId]['owners'] ),
                'start_date' => $menu['items'][$itemId]['start_date'],
                'due_date' => $menu['items'][$itemId]['due_date'],
                'finish_date' => $menu['items'][$itemId]['finish_date'],
                'status' => $menu['items'][$itemId]['status'],
                'priority' => $menu['items'][$itemId]['priority'],
                'forecast_cost' => $menu['items'][$itemId]['forecast_cost'],
                'revenue' => $menu['items'][$itemId]['revenue'],
                'reports_count' => $menu['items'][$itemId]['reports_count'],
                'files_count' => $menu['items'][$itemId]['files_count'],
                'final_cost' => $menu['items'][$itemId]['final_cost'],
                'total_time' => $menu['items'][$itemId]['total_time'],
                'final_report' => $menu['items'][$itemId]['final_report'],
                'created_at' => $menu['items'][$itemId]['created_at'],
                'created_by' => $menu['items'][$itemId]['created_by'],
            ];
            // TASKS WITHOUT CHILD
            if( !isset( self::$menu['parents'][$itemId] ) )
            {

                $html .="
";
                if( in_array( self::$user_id , $task['members'] ) === true && in_array( self::$user_id,$task['owners'] ) === false )
                {//member

                    self::$params = [
                        'permission_level' => 1 ,
                        'parent' => false ,
                        'task' => $task ,
                    ];

                    $html .= /*task view */.'
';

                }
                if ( in_array( self::$user_id,$task['owners'] ) === true && in_array( self::$user_id, $task['members'] ) === false )
                {//owner
                    self::$params = [
                        'permission_level' => 2 ,
                        'parent' => false ,
                        'task' => $task ,
                    ];

                    $html .= /*task view */.'
';

                }
                if( in_array( self::$user_id, $task['members'] ) === true && in_array( self::$user_id,$task['owners'] ) === true)
                {//both
                    self::$params = [
                        'permission_level' => 3 ,
                        'parent' => false ,
                        'task' => $task ,
                    ];

                    $html .= /*task view */.'
';

                }
                if( in_array( self::$user_id,$task['visitors'] ) === true && in_array( self::$user_id, $task['members'] ) === false && in_array( self::$user_id,$task['owners'] ) === false )
                {//visitors
                    self::$params = [
                        'permission_level' => 0 ,
                        'parent' => false ,
                        'task' => $task ,
                    ];

                    $html .= /*task view */.'
';

                }
            }

            // TASKS WITH CHILD
            if( isset( self::$menu['parents'][$itemId] ) )
            {
                $html .= "
";
                if( in_array( self::$user_id, $task['members'] ) === true && in_array( self::$user_id,$task['owners'] ) === false )
                {//member
                    self::$params = [
                        'permission_level' => 1 ,
                        'parent' => true ,
                        'task' => $task ,
                    ];

                    $html .= /*task view */.'
';
                    $html.="

                    <input class='checkbox-chevron' id='checkbox".$task['id']."' onclick='switchClopsImgSrc(".$task['id'].")'  type='checkbox' name='subFolder'/>";
                    $html .= self::create_tree_view($itemId,$menu).'
';

                }
                if ( in_array( self::$user_id,$task['owners'] ) === true && in_array( self::$user_id, $task['members'] ) === false )
                {//owner
                    self::$params = [
                        'permission_level' => 2 ,
                        'parent' => true ,
                        'task' => $task ,
                    ];

                    $html .= /*task view */.'
';
                    $html.="

                    <input class='checkbox-chevron' id='checkbox".$task['id']."' onclick='switchClopsImgSrc(".$task['id'].")'  type='checkbox' name='subFolder'/>";
                    $html .= self::create_tree_view($itemId,$menu).'
';

                }
                if( in_array( self::$user_id, $task['members'] ) === true && in_array( self::$user_id,$task['owners'] ) === true )
                {//both
                    self::$params = [
                        'permission_level' => 3 ,
                        'parent' => true ,
                        'task' => $task ,
                    ];
                    $html .= /*task view */.'
';
                    $html.="

                    <input class='checkbox-chevron' id='checkbox".$task['id']."' onclick='switchClopsImgSrc(".$task['id'].")'  type='checkbox' name='subFolder'/>";
                    $html .= self::create_tree_view($itemId,$menu).'
';

                }
                if( in_array( self::$user_id,$task['visitors'] ) === true && in_array( self::$user_id, $task['members'] ) === false && in_array( self::$user_id,$task['owners'] ) === false )
                {//visitors
                    self::$params = [
                        'permission_level' => 0 ,
                        'parent' => true ,
                        'task' => $task ,
                    ];
                    $html .= /*task view */.'
';
                    $html.="

                    <input class='checkbox-chevron' id='checkbox".$task['id']."' onclick='switchClopsImgSrc(".$task['id'].")'  type='checkbox' name='subFolder'/>";
                    $html .= self::create_tree_view($itemId,$menu).'
';

                }

            }
        }
        $html .= "
";
    }
    return $html;
}

public static function create_array()
{
    $tasks = DB::table('tasks')->where('visitors', 'like', '%'.self::$user_id.'%')->orderBy('p_id' , 'id')->get();

    $tasks = json_decode( $tasks,true );

    for ( $i=0 ; $i < count( $tasks ) ;  $i++ )
    {
        // Create current menus item id into array
        self::$menu['items'][$tasks[$i]['id']] = $tasks[$i];

        // Creates list of all items with children
        self::$menu['parents'][$tasks[$i]['p_id']][] = $tasks[$i]['id'];
    }

    return view('home');
}

public static function test(){

    return self::create_tree_view( 0 , self::$menu );
}

}
this is my home view
<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link href="{{ asset('css/styles.css') }}" rel="stylesheet">

    @php
        use App\Http\Controllers\TaskController;
        echo TaskController::test();
    @endphp

and this is my tasks view

                ویرایش

                آپلود

                فایل ها

                گزارش

                نامه

                جستجو

                ذخیره

                لغو

                فعالسازی

                زیرگروه

{{ $params['task']['title'] }}

{{$tasks['visitors']}}

{{$tasks['members']}}

{{$tasks['owners']}}

{{$tasks['start_date']}}

{{$tasks['due_date']}}

{{$tasks['finish_date']}}

{{$tasks['status']}}

{{$tasks['forecast_cost']}}

{{$tasks['final_cost']}}

{{$tasks['revenue']}}

{{$tasks['total_time']}}

{{$tasks['priority']}}

A: Replace
 $html .= /*task view */.'
';

With
 $html .= view('task.view.name')->render().'
';


text:
Q: Unable to array values outside of function in shell script I have the following script named run.sh:
#This is run.sh

prerequisite(){

config_file=./../config/config.sh
source $config_file

    echo "VAR1 inside prerequisite: $VAR1"
    echo "country currency inside prerequisite: $country_currency[@]"
}

LIST_OF_COUNTRIES=`cat country_list.txt`

transform() {
    local country="$@"
    prerequisite
    echo "VAR1 inside transform: $VAR1"
    echo "country currency inside transform: $country_currency[@]"
}

transform ${LIST_OF_COUNTRIES[@]} &
transformpid=$!

wait $transformpid

echo "Complete"

The content of my config.sh file is:
VAR1="value1"
declare -a country_currency=( "INR" "USD" "JPY" )

When I run my run.sh file,
I get the following output:
VAR1 inside prerequisite: value1
country currency inside prerequisite: INR USD JPY

VAR1 inside transform: value1
country currency inside transform:

As I see from the output, the value of all the variables that I am sourcing from my config .sh file is getting fetching into the prerequisite function.
Whereas the values in the array are not getting fetched into the transform function. This is just a small snippet of code. I am doing multiple calls to the prerequisite function to dynamically source the values in my actual code. What am I doing wrong over here? Isn't the scope of the variable and the array that I have declared, supposed to be the same?


text:
Q: ReactNativeJS: TypeError: undefined is not an object (evaluating 't.default') App is running properly without any error in debug mode.but its crashing in release mode after splash screen. and also when i'm trying to archive it,its getting successful archive but im not getting anything under window.
package.json
"dependencies": {
"@react-native-community/async-storage": "^1.9.0",
"@react-native-community/masked-view": "^0.1.6",
"@react-navigation/drawer": "^5.0.0",
"@react-navigation/material-bottom-tabs": "^5.0.0",
"@react-navigation/native": "^5.0.0",
"@react-navigation/stack": "^5.0.0",
"babel-preset-react-app": "^9.1.2",
"mobx": "^5.15.4",
"mobx-react": "^6.2.2",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-admob": "^2.0.0-beta.6",
"react-native-animatable": "^1.3.3",
"react-native-device-info": "^5.5.6",
"react-native-gesture-handler": "^1.6.0",
"react-native-i18n": "^2.0.15",
"react-native-image-gallery": "^2.1.4",
"react-native-image-view": "^2.1.2",
"react-native-linear-gradient": "^2.5.6",
"react-native-material-ripple": "^0.9.1",
"react-native-onesignal": "^3.7.3",
"react-native-paper": "^3.6.0",
"react-native-reanimated": "^1.7.0",
"react-native-responsive-dimensions": "^3.1.1",
"react-native-responsive-screen": "^1.4.0",
"react-native-safe-area-context": "^0.7.3",
"react-native-screens": "^2.0.0-beta.8",
"react-native-share": "^3.3.0",
"react-native-slideshow": "^1.0.1",
"react-native-snap-carousel": "^3.8.4",
"react-native-svg": "^12.0.3",
"react-native-unity-ads": "^1.0.3",
"react-native-vector-icons": "^6.6.0",
"rn-fetch-blob": "^0.12.0"
},
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.8.3",
"@babel/core": "^7.6.2",
"@babel/runtime": "^7.6.2",
"@react-native-community/eslint-config": "^0.0.5",
"babel-jest": "^24.9.0",
"eslint": "^6.5.1",
"jest": "^24.9.0",
"metro-react-native-babel-preset": "^0.56.0",
"react-test-renderer": "16.9.0"
},


text:
Q: how to adjust bootstrap tabs according to our contents in existing page? i have created a "registration and login" modal to give the functionality like flipcart.com . I am using bootstrap 'nav nav-tabs' to show the 2 tabs .
When i create that modal in a separate file it works fine, like image shown bellow:

But when i put the same code of this modal into my existing project file it changes its look like in image shown bellow:

Here is code for this modal:

          <button type="button" class="close reg" id ="reg_close" data-dismiss="modal" aria-hidden="true">×</button>

Register Now

Login

Registration

                                                                     <form id="login-form" target="login-signup-iframe" method="post" action="#" name="login-form">

                                                                                Email

                                                                                <input type="text" class="fk-input form-control" name="email" autocomplete="on" id="login_email_id"
                                                                                placeholder ="Your E-mail" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your E-mail'">

                                                                                Password

                                                                                <input type="password" class="fk-input form-control" name="password" id="login_password"
                                                                                onfocus="this.placeholder = ''" onblur="this.placeholder = 'Password'" placeholder="Password">
                                                                                <input type="hidden" name="password_hash" id="login_password_hash">

                                                                                <input type="hidden" name="__FK" value="V2572135e576087a5881915c1283b7afbcd1t18eX5IEBZKdt4uNhR3jhexbEaRIFCpOF9vZskYd3zsqf3SAP283BjliKf7NmRzwKcRY2EmOyZkpoQ1oT1nS69zyA==">
                                                                                <button type="button" class="btn btn-primary btn-small" style="border-radius:0px;margin-right:10px;">Log In</button>
                                                                                Forgot your password?

                                                                           </form>

                                                                   <form id="regestration-form" target="login-signup-iframe" method="post" action="#" name="regestration-form">

                                                                            Full Name

                                                                            <select class="form-control" style="color:#000;width:72px;margin-left:-35px;height:30px;font-size:11px;">
                                                                                <option>Mr.</option>
                                                                                <option>Ms.</option>
                                                                                <option>Mrs.</option>
                                                                                <option>Dr.</option>

                                                                                </select>

                                                                               <input id="reg_name" type="text" class="fk-input " name="email" autocomplete="on"
                                                                                placeholder ="Your Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Name'">

                                                                                E-mail

                                                                                <input type="text" class="fk-input form-control" name="email" autocomplete="on" id="login_email_id"
                                                                                placeholder ="Your E-mail" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your E-mail'">

                                                                                Mobile No.

                                                                                <input type="text" class="fk-input form-control" name="mobileno" autocomplete="on" id="reg_mob_no"
                                                                                placeholder ="Mobile Number" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Mobile Number'">

                                                                                Location

                                                                                <input type="text" class="fk-input form-control" name="mobileno" autocomplete="on" id="reg_mob_no"
                                                                                placeholder ="Location" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Location'">

                                                                                <input type="hidden" name="__FK" value="V2572135e576087a5881915c1283b7afbcd1t18eX5IEBZKdt4uNhR3jhexbEaRIFCpOF9vZskYd3zsqf3SAP283BjliKf7NmRzwKcRY2EmOyZkpoQ1oT1nS69zyA==">
                                                                                <button type="button" class="btn btn-primary btn-small" style="border-radius:0px;margin-right:10px;">Save & Continue</button>
                                                                                <button type="button" class="btn btn-default btn-small" style="border-radius:0px;margin-right:10px;">Cancel</button>

                                                                           </form>

OR

Sign in with

                           <button type="button" class="btn btn-primary" style="border-radius:0px;"> facebook </button>

                           <button type="button" class="btn btn-primary"style="border-radius:0px; width:96px;">g google </button>

and a css for the same:
#reg_modal_header{ background:green;border-top-left-radius:6px;border-top-right-radius:6px;border-radius:0px;}
#reg_close{ opacity:0.5;}
#reg_close:hover{opacity:1;}

.rw{height: 32px;line-height: 32px;margin: 10px 0;text-align: left;}
.size1of4 {width: 25%;float: left;border: 0;font-size: 100%;font: inherit;vertical-align: baseline;}
.rt{overflow: hidden;}
.rw .rt input {font-size: 13px;padding: 0 0;valign:text-top; height:90%;width:90%;}

.lbl{border: 0;font-size: 100%;font: inherit;vertical-align: bottom;padding-top:3px;margin-top:2px;}
#login_email_id,#login_password,#reg_mob_no{border: 1px solid #ccc;resize: none;font-family: inherit;text-align:center;background:white;}
.fk-input{border: 1px solid #ccc;resize: none;font-family: inherit;text-align:center;background:white;font-size: 13px;}

div #OR{ height: 50px; width: 50px; border: 1px solid #ddd; border-radius: 50%; font-weight: bold; line-height: 50px; /* Equals elements height */
 text-align: center;font-size:20px;float:right;position: absolute;right: -25px;top:75px;z-index:1;background:white;
}
.reg_modal{border-radius:0px;border-bottom:4px solid green;}
.modal-body{border-bottom:4px solid green}
#reg_name{width:150px;margin-left:-50px;height:30px;}

So,please can anyone help me to overcome this problem so that look will get same in my project also. . Thank you in advance . .

A: Try setting the z-index of the tab elements because the z-index of modal might me more than that of tabs element !


text:
Q: How to remove all links from a mixed string with php i have a variable in php can be like this : $string = "hello check out this http://xx.xx/xxx & thanks !!";
i want a function to strip that link and remove it from the string, the url can be with WWW. or without it.
also, this variable can contains multiple urls .
Thanks

A: You could use regular expressions to do it:
$string = preg_replace('\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]', '', $string);

That will find every instance of a URL in the string and replace it with a blank string.

A: You can use a regular expression to match and replace all URL formats, as follows:
$string = preg_replace("/(^¦\s)(http:\/\/)?(www\.)?[\.0-9a-zA-Z\-_~]+\.(com¦net¦org¦info¦name¦biz¦.+\.\w\w)((\/)?[0-9a-zA-Z\.\-_~#]+)?\b/ie","",$string);


text:
Q: UIScrollView with paging enabled swipe issue I have a UIScrollView with paging enabled. All works good but sometimes when I scroll to the next image, 1 pixel from the last image is still displayed.

as you can see on the very left of the image, there is 1 pixel vertical line that is from the image before it. Meaning that the image was not swiped completely.
I tried a lot but couldn't find the problem.
Here is my code:
import Foundation
import UIKit
import SwiftyGif

class MBSPagingScrollView: UIScrollView, UIScrollViewDelegate {

var scrollView = UIScrollView()
var pageControl = UIPageControl()
var imagesArray = [String]()

override init (frame : CGRect) {
    super.init(frame : frame)
}

convenience init () {
    self.init(frame:CGRect.zero)
}

required init(coder aDecoder: NSCoder) {
    fatalError("This class does not support NSCoding")
}

init(frame : CGRect, imagesarray : [String]){
    super.init(frame : frame)

    imagesArray = imagesarray

    scrollView.delegate = self
    scrollView.isPagingEnabled = true
    scrollView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
    scrollView.showsHorizontalScrollIndicator = false
    self.addSubview(scrollView)

    pageControl.frame = CGRect(x: 0, y: self.frame.size.height - 50, width: self.frame.size.width, height: 50)
    pageControl.numberOfPages = imagesArray.count
    pageControl.currentPage = 0
    pageControl.tintColor = UIColor.red
    pageControl.pageIndicatorTintColor = UIColor.black
    pageControl.currentPageIndicatorTintColor = MainOrangeColor
    self.addSubview(pageControl)

    scrollView.contentSize = CGSize(width:scrollView.frame.size.width * CGFloat(imagesArray.count),height: scrollView.frame.size.height)
    pageControl.addTarget(self, action: #selector(changePage(sender:)), for: UIControlEvents.valueChanged)

    for (index, imageName) in imagesArray.enumerated() {

        var imageView = UIImageView()

        if imageName.hasSuffix(".gif") {
            let gifManager = SwiftyGifManager(memoryLimit:30)
            let gif = UIImage(gifName: imageName)
            imageView = UIImageView(gifImage: gif, manager: gifManager)
        }

        else {
            imageView = UIImageView(image: UIImage(named: imageName))
            imageView.contentMode = UIViewContentMode.scaleToFill
        }

        imageView.frame = CGRect(x: CGFloat(index) * self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        scrollView.addSubview(imageView)
    }

}

func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
    scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

}

Any help is much appreciated.
Thanks a lot!

A: Try and set clipsToBounds = true for all the imageviews.


text:
Q: How to customize page according to its order in TYPO3? Working on TYPO3 4.7 with Templavoila 1.7.0, I need a way to customize one value of the template according to the order of the current page in its navigation level.
In specific, I need to change the class attribute of a div to "left" or "right" if its even or uneven. Is there a way to do this with maybe a Templavoila Typoscript-Attribute?
For an example:

*

*Main Page

*

*Page 1

*

*Page 1.1 -> When rendering this page I want to set the class attribute to "left"

*Page 1.2 -> "right"

*Page 1.3 -> "left"

*Page 1.4 -> "right"

*Page 2

*Page 3

Thanks!

A: A TemplaVoila TypoScript Attribute would fail, if someone change the sorting of the pages.
I would try to render a menu. With allWrap.cObject = TEXT it should be possible to override the output. So just create a menu which renders the class, and depending on even or odd render the class you need.
!pseudo-code!
lib.getClass = HMENU
lib.getClass {
  1 = TMENU
  1.NO = 1
  1.NO {
    allWrap.cObject = TEXT
    allWrap.cObject.value = left
    allWrap.cObject.override = right
    allWrap.cObject.override {
      if.value = 1
      if.equals.data = REGISTER:count_HMENU_MENUOBJ
      if.equals.stdWrap.wrap = |%2
      if.equals.prioriCalc = 1
    }
  }
}

Did not test the code, so if it does not work, check for syntax. Probably deactivate override, check the value REGISTER:count_HMENU_MENUOBJ but i guess it should be the register you need.


text:
Q: Latex : incorrect nameref when custom counter is used in section name When a section name is based on a custom counter (with  \newcounter), the \nameref text is not the good one.
Below a simple example :
\documentclass{article}
\usepackage{nameref}
\usepackage{hyperref}
\hypersetup{hidelinks,colorlinks=true,linkcolor=blue}

\begin{document}
    \newcounter{my.counter}

\section{Section \arabic{my.counter}}
    \label{sct\arabic{my.counter}}
    Content of section \arabic{my.counter}.
    \begin{verbatim}
        \nameref{sct1}
    \end{verbatim}
    \nameref{sct1}

\stepcounter{my.counter}
\section{Section \arabic{my.counter}}\label{sct\arabic{my.counter}}
    \begin{verbatim}
        \nameref{sct0}
    \end{verbatim}
    \nameref{sct0}.

\end{document}

And the result is:

This example was compiled on overleaf to avoid "configuration" issue .

A: You can ensure that your title will get expanded by using \GetTitleStringSetup{expand}:
\documentclass{article}
\usepackage{nameref}
\usepackage{hyperref}
\hypersetup{hidelinks,colorlinks=true,linkcolor=blue}

\GetTitleStringSetup{expand}

\begin{document}
    \newcounter{my.counter}

\section{Section \arabic{my.counter}}
    \label{sct\arabic{my.counter}}
    Content of section \arabic{my.counter}.
    \begin{verbatim}
        \nameref{sct1}
    \end{verbatim}
    \nameref{sct1}

\stepcounter{my.counter}
\section{Section \arabic{my.counter}}\label{sct\arabic{my.counter}}
    \begin{verbatim}
        \nameref{sct0}
    \end{verbatim}
    \nameref{sct0}.

\end{document}


text:
Q: JsonParserException while trying to read json file Book.json
[{
"title": "Hunger Games",
"description": " fast paced In a not-too-distant future, the United States of America has collapsed, weakened by drought, fire, famine, and war, to be replaced by Panem, a country divided into the Capitol and 12 districts. Each year, two young representatives from each district are selected by lottery to participate in The Hunger Games. Part entertainment, part brutal intimidation of the subjugated districts, the televised games are broadcast throughout Panem as the 24 participants are forced to eliminate their competitors, literally, with all citizens required to watch. When 16-year-old Katniss s young sister, Prim, is selected as the mining district s female representative, Katniss volunteers to take her place. She and her male counterpart, Peeta, the son of the town baker who seems to have all the fighting skills of a lump of bread dough, will be pitted against bigger, stronger representatives who have trained for this their whole lives. Collins s characters are completely realistic and sympathetic as they fight and form alliances literary distant future great man and friendships in the face of distant future overwhelming odds; the plot is tense, dramatic, and engrossing. This book will definitely resonate with the generation raised on reality shows like Survivor and American Gladiator. Book one of a planned trilogy."

}]
public class FileReader {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String keywordCsv= "resources/addresses.csv";
    String booksJson ="resources/books.json";
    //Csvfilereader.processBySplit(fileName);
    Csvfilereader csvReader= new Csvfilereader();
    //ReadJson readjson =new ReadJson();
    ObjectMapper csvobj;
    ObjectMapper descriptionJsonobj=new ObjectMapper() ;
    MapType type = descriptionJsonobj.getTypeFactory().constructMapType(
            Map.class, String.class, Object.class);
    try {
        csvobj= csvReader.processByStreamApi(keywordCsv);
        Map<String,Object> jsonMap = descriptionJsonobj.readValue(booksJson, type);
        jsonMap.forEach((k,v) -> System.out.println((k +": "+ v)));
    }
    catch(Exception e) {
        e.printStackTrace();

    }

    System.out.println("Successfull");
    //JsonObjectFormatVisitor

}

}
After running the program following exception is giving
    com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'resources': was expecting ('true', 'false' or 'null')
 at [Source: (String)"resources/books.json"; line: 1, column: 10]
Successfull
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:703)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._reportInvalidToken(ReaderBasedJsonParser.java:2853)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:1899)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:757)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4141)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4000)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3042)
    at com.readcsv.FileReader.main(FileReader.java:28)

I am new in java. I have to match keword from csv file with books.json file. I am using jackson ObjectMapper.

A: String booksJson ="resources/books.json";

is just a string that represents probably a path to your file. You are passing this string to object mapper - and this string is not a valid json. ObjectMapper's readValue method,that you are using, expects first argument to be a valid json.
Here
descriptionJsonobj.readValue(booksJson, type);

bookJson should be a valid json and currently it is not because you assigned it value "resources/books.json".
You should load your file content into some String variable, for example using Java 8 Files class or whatever. Then when you load your file content into some string variable just pass it to ObjectMapper's readValue method.


text:
Q: Dice Game Expected Value You accumulate 1 point when rolling a 1,2, or 3. You get paid out your points when rolling a  4 or 5. You get nothing if you roll a 6. What is your expected value?
I came up with the following solution. I get 1 point with probability (1/6), 2 points with probability (1/12), 3 points with probability (1/24), and so on.
So then the EV is: $\frac{1}{6}\sum_{n = 0}^\infty \frac{1}{2}^n \times (n+1)$
Two question: how do I actually evaluate that sum, and second how can I set up a recursive equation to solve the problem. It seemed like recursion would be easier but I couldn't set up the equation properly

A: You can do the sum using the differentiation trick  $$ \frac{1}{6}\sum_{n=0}^\infty (n+1)x^{n} = \frac{1}{6}\frac{d}{dx}\sum_{n=0}^\infty x^{n+1} = \frac{1}{6} \frac{d}{dx} \frac{x}{1-x} = \frac{1}{6}\frac{1}{(1-x)^2}.$$ Plugging in $x=1/2$ gives an answer of $2/3.$
As for recursion, this is trickier. The probability the game ends on a six is $1/3$ by symmetry since it is the probability you roll a six before you roll a four or five. So we may work in an imaginary world where sixes never occur. Let $V$ be the value of the game. We have a $3/5$ chance of landing on a one, two or three, in which case we gain one point and continuation. Otherwise, if we land on $4$ or $5,$ we gain nothing. The recursive equation is that $$V = \frac{3}{5}(\frac{2}{3}V+1)$$ (where the $2/3$ on the inner $V$ is to cut the continuation value to take into account the possibility of landing on a six) so that $V = 1,$ which we then multiply by $2/3$ to take into account the sixes, and get the answer of $2/3.$

A: If you have $$S=1 \times \frac16 + 2 \times \frac1{12} + 3 \times \frac1{24} + \cdots$$
then $$2S=1 \times \frac13 + 2 \times \frac1{6} + 3 \times \frac1{12} +4 \times \frac1{24} + \cdots$$
and so by subtraction $$S=2S-S= \frac13 +  \frac1{6} +  \frac1{12} +  \frac1{24} + \cdots$$
and if you do not know this then do the same thing again
$$2S=\frac23 +  \frac1{3} +  \frac1{6} +  \frac1{12} +  \frac1{24} + \cdots$$
so by subtraction $$S=2S-S = \frac23$$


text:
Q: Why is $-1=e^{\pi i }=e^{2\pi i\frac{1}{2}}\neq (e^{2\pi i})^{\frac{1}{2}}=1^{\frac{1}{2}}=1$ true? I thought there was this rule that $e^{xB}=(e^x)^B$?
Also what I don't understand is that $x^{\frac{1}{2}}$ is defined as the square root of $x$. And because the square root may also be in $\mathbb{C}$ it doesn't matter which number $x$ is because every complex number has a n-th root.
But for $1^{\frac{1}{2}}$ we have the roots $-1$ and $1$, so I could also write $-1$ on the right side then the Statement above would be true and not true at the same time.
But we said the Expression in the Question is correct and to write $-1$ is false. Can somebody explain the reason we choose one Version over another altough they are equivalent?

A: If one is working in real analysis, the expression $x^{1/2}$ ($x>0$) is by definition $\sqrt{x}$, which is defined to be the positive real number $y$ such that $y^2=x$. Hence one has
$$
1^{1/2}=1.
$$
If one is working in complex analysis, $1^{1/2}$ can be viewed as the multivalued function $f(z)=z^{1/2}$ evaluated at $z=1$. In this context, since $f$ is multivalued, it is incorrect to write $1^{1/2}=1$.

The identity $(e^x)^y = e^{xy}$ holds for real numbers $x$ and $y$, but assuming its truth for complex numbers leads to paradox like the one you have observed.
To quote Wikipedia:

Some identities for powers and logarithms for positive real numbers will fail for complex numbers, no matter how complex powers and complex logarithms are defined as single-valued functions.

See Failure of power and logarithm identities for more examples.


text:
Q: echo on query result buggin I am trying to extract the $row elemts with:
$sql = "SELECT date, email, journal, section FROM selection_loggedin WHERE email = '$email' and date in (SELECT max(date) FROM (SELECT date, email FROM selection_loggedin WHERE email = '$email') as x)";
$result = $dbc->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
    $journal = row['journal'];
    $section = row['section'];
    print_r($row);
    //echo "'$journal'"."'$section'";
    echo "
".row['email']."
";
    echo row['date']."
";

And I get this:
Array (
      [date] => 2017-05-07 12:45:45
      [email] => benoitkoen@gmail.com
      [journal] => Wall Street Journal
      [section] => Economy
)

Why doesn't it print the right stuff ('Wall Street Journal' and 'Economy')?

A: $sql = "SELECT date, email, journal, section FROM selection_loggedin WHERE email = '$email' and date in (SELECT max(date) FROM (SELECT date, email FROM selection_loggedin WHERE email = '$email') as x)";
$result = $dbc->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
    $journal = $row['journal'];
    $section = $row['section'];
    print_r($row);
    //echo "'$journal'"."'$section'";
    echo "
".$row['email']."
";
    echo $row['date']."
";


text:
Q: How can I get from firebase array of objects I need to get array of objects of sources from firebase grouped by category.
Firebase structure is:
enter image description here
Every authenticated user have its own array of sources.
Security rules for db is:
enter image description here
Every source have array of articles and have category.
I use vuefire to bind to firebase-database. I have written this, but I don't know what I should do next to get all sources grouped by category.
var sources=[];
var db=firebase.database();
var id=auth.user().uid;
var userDb=db.ref(id);

A: Maybe you can imagine how to retrieve your data from firebase database if I give you this example:
function getData(data) {
    var items = data.val();
    console.log(items, 'myItem') //here is your items that you need
}

function errData(err) {
    console.log('error:', err)
}

const id = firebase.auth().currentUser.uid;
const result = firebase.database().ref(id);
result.on('value', getData, errData)


text:
Q: Youtube iframe script returns 429 Trying to load the script https://www.youtube.com/iframe_api from an html page but getting a 429.
This is a static script, why would google block these type of requests?
Obviously google flagged my IP for some reason.
Any suggestions on how to resolve it or at least avoid this from reoccurring once the flagging has been removed (timed out?).

A: Hope it's still relevant.
I had the same issue and i solved it by adding a timestamp (or any other random string) in the YouTube iFrame SDK URL of the script.
So instead of  https://www.youtube.com/iframe_api i did https://www.youtube.com/iframe_api?${Date.now()} and it's working now.


text:
Q: Crafting system in my python text game is giving an error (I'm trying to get it to print something when you dont have all the items in the list) #I just have these up here for context
def ifhealthlessthan50():

    while health<=50:

        choice2 = input("YOU ARE LOW ON HEALTH WHAT WOULD YOU LIKE TO DO?\n> ")

        if choice2.lower() == 'move n':
            print(random.choice(biomes),  "IS WHERE YOU END UP")

        elif choice2.lower() == 'move s':
            print("pls ")
            print(random.choice(biomes), "IS WHERE YOU END UP")

        elif choice2.lower() == 'move e':
            print("are")
            print(random.choice(biomes), "IS WHERE YOU END UP")

        elif choice2.lower() == 'move w':
            print("gosh")
            print(random.choice(biomes), "IS WHERE YOU END UP")

        elif choice2.lower() == 'exit':
            print("NOW EXITING...")
            sys.exit()

        elif choice2.lower() == 'inventory':
            print(things)

        elif choice2.lower() == 'craft':
            craftinginput = input("WHAT WOULD YOU LIKE TO CRAFT?\n> ")
            if craftinginput.lower() == 'wpickaxe':
                things.remove('PLANKS')
                things.remove('PLANKS')
                things.remove('PLANKS')
                things.remove('STICKS')
                things.remove('STICKS')
            elif craftinginput.lower() == 'wsword':
                things.remove('PLANKS')
                things.remove('PLANKS')
                things.remove('STICKS')

            elif craftinginput.lower() == 'wshovel':
                if 'PLANKS' and 'STICKS' and 'STICKS' not in things:
                    print("YOU DON'T HAVE THE RIGHT MATERIALS!")

                elif 'PLANKS' and 'STICKS' and 'STICKS' in things:
                    things.remove('PLANKS')
                    things.remove('STICKS')
                    things.remove('STICKS')

                else:
                    print("YOU DON'T HAVE THE RIGHT/ENOUGH MATERIALS!")

            else:
                print("THAT'S NOT A CRAFTABLE ITEM!")

        else:
            print("dont work lmao")
            ifhealthlessthan50()
ifhealthlessthan50()

I'm trying to make it so when I don't have all of the materials it displays YOU DON'T HAVE THE RIGHT/ENOUGH MATERIALS! But instead, I get this error this is just one of the functions (the only one where the problem is) I'm really not sure how to fix this, I've looked at many posts here.
ValueError: list.remove(x): x not in list

A: I believe you have a logic error and these lines are causing your problem:
if 'PLANKS' and 'STICKS' and 'STICKS' not in things:

elif 'PLANKS' and 'STICKS' and 'STICKS' in things:

You need to check if each item is in things individually. Currently, you're only checking if the last item is in things. Consider this example:
things = ['STICKS']
print('PLANKS' and 'STICKS' in things)  # True

'PLANKS' on its own evaluates to True, so only the last string is being checked for in the things array. Checking to see if an item is in the array multiple times is another issue; I'd recommend turning your things array into a dictionary.


text:
Q: Is it possible to have round-robin DNS with /etc/hosts file? Is it possible to have round-robin DNS with the follwing configuration in /etc/hosts?
192.168.4.10 shaakunthala.local
192.168.4.20 shaakunthala.local

I'm on Linux.

A: No, that doesn't work.
Also /etc/hosts is a primitive form of name->address mapping that DNS is meant to replace. If you want round-robin DNS, install a DNS server.

A: dnsmasq inludes Round-robin DNS out-of-the-box
> egrep -m1 '^nameserver' /etc/resolv.conf
nameserver 127.0.0.1
> grep -i rrtest /etc/hosts
1.1.1.1 rrtest
2.2.2.2 rrtest
> /etc/init.d/dnsmasq restart
Shutting down dnsmasq:                                     [  OK  ]
Starting dnsmasq:                                          [  OK  ]
> nslookup rrtest
Server:         127.0.0.1
Address:        127.0.0.1#53

Name:   rrtest
Address: 2.2.2.2
Name:   rrtest
Address: 1.1.1.1

> nslookup rrtest
Server:         127.0.0.1
Address:        127.0.0.1#53

Name:   rrtest
Address: 1.1.1.1
Name:   rrtest
Address: 2.2.2.2


text:
Q: Masked text which fills on scroll with CSS? I saw this neat example and I was wondering if its possible to do in javascript/CSS?
Basically I see there's a text with experimental text-stroke CSS property applied, BUT when the user scrolls past it the text has a filled effect, not like filled but more like a css-mask type of effect?
This is what I'm talking about.
https://i.imgur.com/cnvav7m.mp4
How can I achieve this effect? I don't need you to write all the logic I just need someone to explain me how they did this neat effect??

A: To do a parallax effect, add these css props into your background image:
.my-background {
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover
}


text:
Q: TCP > COM1 for receiving messages and displaying on POS display pole I currently have a Java Applet running on my web page that communicates to a display pole via COM1. However since the Java update I can no longer run self-signed Java Applets and I figure it would just be easier to send an AJAX request back to the server and have the server send a response to a TCP port on the computer...the computer would need a TCP > COM virtual adapter. How do I install a virtual adapter to go from a TCP port to COM1?
I've looked into com0com and that is just confusing as hell to me, and I don't see how to connect any ports to COM1. I've tried tcp2com but it doesn't seem to install the service in Windows 7 x64. I've tried com2tcp and the interface seems like it WOULD work (I haven't tested), but I don't want an app running on the desktop...it needs to be a service that runs in the background.
So to summarize how it would work:

*

*Web page on comp1 sends AJAX request to server

*Server sends text response to comp1 on port 999

*comp1 has virtual COM port listening on port 999, sends data to COM1

*pole displays data

A: Answer found here. I eventually found a TCP > COM program that worked and ended up using another program that made a COM > TCP virtual port. All is working.


text:
Q: How to build python debian package for all versions of python2.* (2.5, 2.6, 2.7)? I know for python3, you can do something like:
%:
    dh $@ -- with python3 --buildsystem=python_distutils

override_dh_auto_build:
    dh_auto_build
    set -ex; for python in $(shell py3versions -r); do $$python setup.py build; done

......

But  how can I make python debian package for different version of python2.*? if I do:
%:
    dh $@ --with python2 --buildsystem=python_distutils

It only builds the default python2.7 version.
Help please, thanks.

A: You should Build-Depends on python-all.  All versions that are supported by the current system are then built.  For unstable, that is only 2.7.
If you want to build for 2.6, you need to run a system where that is a standard version (such as Wheezy) and built on that.  Like with other packages, if you want to build for an old release, you should build on that old release.  This is because while packages from unstable may work on stable, but quite often they will require dependencies from unstable.
So specifically, if your development machine is running unstable, set up a pbuilder chroot for stable and use that for building the package.  They will then be for the python version in stable (currently 2.6).


text:
Q: how to configure fiddler to use infopath to customize forms in sharepoint to avoid the "following URL is not valid" error in offline mode I installed vmware virtual machine on my laptop to run SharePoint server 2013, then I installed  win server 2012 and sharepoint server on the virtual machine, now when i'm gonna to use infopath to customize forms and publishing them back in sharepoint i have following error:
"the following url is not valid"
I create my own root site collection
and added verbs like PUT an et.al to IIS But still I have this error when I'm not connected to the Internet.
The point is that when I'm connected to the Internet, this error no longer exists.
By searching the internet I found that I should use fiddler,
I downloaded and installed Fiddler4 on my laptop. but when I run it in disconnected internet mode the error still exist.
I have installed windows 8.1 on my laptop and i try the win8 confige button to check all icons, But it still does not work , So, how can I use Fiddler now..... I'm waiting for your answers.........


text:
Q: Как конвертировать строку из парсера в число C# Вопрос 1: Через парсер получаем строку "10д 5ч". (10 дней и 5 часов)
Надо ее конвертировать и получить время в часах (10*24+5) и получить число 245.
Пока что идея сделать через if и замену буквы на число, но это похоже на костыль, а не решение.
Вопрос 2: Число (int) надо конвертировать в дни и часы и вывести через TextView
Что подскажете?

A: За время в C# отвечает TimeSpan и с ним вам стоит работать.
Считываем значение:
У таких объектов, как TimeSpan и DateTime (а также их аналоги) есть два метода (Parse и ParseExact), которые как раз и отвечают за "чтение" времени из String. Parse будет полезен тогда, когда время идет в стандартном формате (по типу hh:mm:ss). ParseExact в этом плане более гибкий и позволяет настраивать формат "парса" времени.
Воспользуемся ParseExact:
var time = TimeSpan.ParseExact("10д 5ч", "d'д 'h'ч'", null);

Здесь мы разбили входные данные, отделив обычный текст от значений самого времени. Сами же значения заменяем на нужный нам формат. Также метод требует культуру, тут уже сами думайте, нужна она вам или нет...
Получаем необходимые данные:

получить время в часах (10*24+5) и получить число 245

При использование нужного типа данных мы с легкостью можем оперировать этими данными так, как заходим. В данном случае все, что вам нужно, это узнать значение свойства TotalHours:
var totalHours = time.TotalHours;

Обратная конвертация:

Число (int) надо конвертировать в дни и часы

Для этого есть такие методы как FromHours(). Принимают они double значение и отдают TimeSpan:
var result = TimeSpan.FromHours(totalHours);

Ну а как выводить, это уже смотрите сами. Обычно используется .ToString(); который может также принимать настраиваемый формат, так что просто поиграйтесь с этим и думаю поймете.
В общем удачи в изучении C#!


text:
Q: Audit Plug-in in MYSQL 5.7.5 Following error occured while using installing MariaDB Audit Plugin Library (i.e. server_audit-1.1.8.tar.gz) in 5.7.5-m15 MySQL Community Server (GPL) in Centos release 6.5:
ERROR 1126 (HY000): Can't open shared library '/usr/lib64/mysql/plugin/server_audit.so' (errno: 13 /usr/lib64/mysql/plugin/server_audit.so: undefined symbol: _my_thread_var)
Based on the MariaDB documenentation claims that plugin should workin MariaDB or MySQL Server with version 5.5 or newer (MySQL 5.5.14, MariaDB 5.5.20).
I also attempt to use same plugin in MYSQL Server version: 5.6.22 MySQL Community Server (GPL), it works perfectly.
Anyone experienced and resolved above issue?

A: errno: 13 should be enough of a clue here. 13 is generally permission denied. Check the .so file in your plugindir. It will likely have privs that will prevent the user running MySQL from opening it.


text:
Q: With ASP.NET/MVC + MvcMockHelpers + RhinoMocks, who sets RouteData? I'm trying to write a test for an ASP.NET MVC controller method.  I've got RhinoMocks (since it seems to be the most popular and best supported), and MvcMockHelpers (since it seems like I need that).
My test method looks like:
var controller = new MyController();
MvcMockHelpers.SetFakeControllerContext(mocks, controller);
mocks.ReplayAll();
var result = controller.MyAction(arg1, arg2);
// then i'd make assertions on the result

This doesn't work, because the RouteData has no entries, and MyAction depends on having a bunch of values set there, like "controller" and "action".
I know I can build a custom RouteData for each controller method I want to call, but that seems silly.  What part of ASP.NET MVC is responsible for setting this, and how can I get in that code path?
(I feel completely lost here, so if I'm barking up the wrong tree, let me know that, too.)

A: I've found the best luck with MvcContrib Test Helper, which uses RhinoMocks.
This is a decent intro
And the MVC Contrib project is on CodePlex

A: I suggest that you split your unit testing into routing tests and controller tests.  The routing tests will test the routes independently of the controllers.  This frees you to test your controllers conventionally, like any other Plain Old CSharp Method.
Phil Haack and Adam Tybor have good articles on how to test your routes:
Testing Routes In ASP.NET MVC
http://haacked.com/archive/2007/12/17/testing-routes-in-asp.net-mvc.aspx
Testing Routes using Rhino Mocks
http://abombss.com/blog/2007/12/10/ms-mvc-testing-routes/

A: The CodeCampServer way of building and testing routes may be of interest to you.
RouteConfigurator: (note it clears the routes every time RegisterRoutes() is called--required for the MVCContrib route testing helper) http://code.google.com/p/codecampserver/source/browse/trunk/src/UI/RouteConfigurator.cs
IncomingRouteTester: uses the MVCContrib route testing extensions to efficiently test routes: http://code.google.com/p/codecampserver/source/browse/trunk/src/UnitTests/UI/Routes/IncomingRouteTester.cs
Browsing the source of this project (among others) has answered a lot of questions for me, and I'd recommend you download the source and take a look around the unit tests project, if nothing else.


text:
Q: What structure of a flat file would be the most efficient for a tree representation of a folder listing? Given a folder on the local file system, what I need to do is this:

*

*Get the recursive listing of all the subfolders/files in it

*Output this in a flat text file

*Then recreate this folder structure in a tree representation

So what information and how do I need to store it in that file in order to achieve this in an efficient manner?
Efficient manner in this case means spending as little time as possible creating that tree structure given a potential large number of subfolders/files.
Obviously I would need to keep aware of the parent-child relationships between folders and perhaps something like file extensions and size.
I can use the facilities of Windows at the command line and/or other software so there is no limitation there.
This question might spill through in having someone recommend some library for the third step and going back from there, and I don't mind that as long as it's clear about the rest of the question.

A: You can represent the folders as a Json string:
{"name" : "folder_name1", "children" : [{"name" : "folder_name2", "children" : []}, {"name" : "folder_name3", "children" : [{"name" : "folder_name4", "children" : []}]}]}

You can then use any Json library to parse this string into a Json tree, which you can then traverse to generate your internal tree representation.  Some libraries will even automatically (de)serialize the internal tree representation to/from a Json string.

A: Assumption: able to code C#
Regarding your comments, the question is not really an algorithm question, just plain implementation question.
To create a tree structure of your file system in memory I'd use this recursive approach, just like answer here.
And once you get the structure in memory, serialise that with Json.Net:
string json = JsonConvert.SerializeObject(treeStructure, Formatting.Indented);

this will produce you a text-representation of the tree you already created. And once you get the string, you can save it wherever you need to.
And to re-create the tree-structure from Json string, you use Json.Net again:
TreeView treeStructure = JsonConvert.DeserializeObject<TreeView>(json);

And this should be enough.


text:
Q: PDF File Editing and Read Editable file in iOS? I have a problem that PDF file editing . From my app, when an OpenIn menu is shown, I'll choose an application to open the file PDF Expert in iphone device( ex:UIDocumentInteractionController to share with PDF Expert) and the PDF file is opened for edit in PDF Expert. But after editing, how can I send it back to my app or get the link where that editable PDF is saved ? How can I get this file?

A: You can't, unless you app registers it self that it can also open PDF file. Then if PDF Expert  has an option the open the file in an other app the user will be able to open it your again.
There is not build in feature in the iOS SDK that lets you get a file from an other app.


text:
Q: How to open a file from shared storage using the NDK in Android 11 The permissions for accessing shared storage (/storage/emulated/0) are getting really really complicated and changing all the time. As I understand it when targeting Android 11 there is no way to opt out of scoped storage, which means you literally can't ever do fopen("/storage/emulated/0/foo.dat");. Apparently the preferred way to open a file will be with the ACTION_OPEN_DOCUMENT but this just returns a content:// URI, which I can't read using the NDK. I'm also unsure if you get to use that URI forever.
How are NDK libraries meant to access files in /storage/emulated/0 on Android 11?

A: Aha, it seems they have moved the permission to read/write all files to MANAGE_EXTERNAL_STORAGE. It's one of those permissions that users have to grant in settings, and there's an intent (ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) to take people directly there.
However they probably won't let you upload an app to the play store with this permission unless it's a file manager or similar, and you currently can't use it at all.

If your app includes a use case that's similar to the following examples, it's likely to be allowed to request the MANAGE_EXTERNAL_STORAGE permission:

*

*File managers

*Backup and restore

*Anti-virus apps

*Document management apps

Due to COVID-19 related considerations, apps that target Android 11 (API level 30) or higher and need the MANAGE_EXTERNAL_STORAGE permission cannot be uploaded to Google Play until early 2021.

I should also note that there seems to be an exception for opening media files only - i.e. files indexed by Android's media scanner.

A: On Android 11 devices:
All apps can write files in all the public directories like Dowload, Documents, DCIM, Pictures and so on.
If not in the directory itself then in a subdirectory of it which you create first.
For DCIM and Pictures only files with extension like .jpg,  .png and .webp are accepted.
More public directories only accept certain extensions.


text:
Q: Smarty in Prestashop parses as Javascript an Script tag even when the type is different I'm trying to use Handlebars.js in Prestashop, currently the platform uses Smarty as is main FrontEnd Template Engine.
I have the following code:
{literal}
        <script type="text/x-handlebars" data-template-name="say-hello">
            Hi Everyone!
        </script>
{/literal}

The problem is that I get a Javascript  console problem, because Hi Everyone! can't be interpretated in Javascript, also I notice that Smarty places the Hi Everyone! inside an Script tag that doesn't respects the type nor the data-template-name attribute.


text:
Q: In Android Studio since Environment.getExternalStorageDirectory() may be removed soon how to create folder in root directory After Environment.getExternalStorageDirectory() in Android Studio is deprecated , How can i cteate a folder or file in root directory of sdcard like where folders like WhatsApp , Android , Downloads , etc are present in Android
Here i want to create a file or folder


text:
Q: How to access property of an object inside a list in a DataGrid in XAML I've been searching for a while, but I'm thinking maybe I am looking in the wrong direction. I have a DataGrid where the ItemsSource is set to a list of Book objects. At the same time, the Book object contains a list of Chapter objects.
public class Book {
    public string Title;
    public List<Chapter> AvailableChapters;
}

public class Chapter {
    public int ChapterNumber;
    public int NumberOfPages;
}

I use them this way in a DataGrid:
<DataGrid SelectionMode="Extended"
              HeadersVisibility="Column"
              CanUserAddRows="False">
    <DataGrid.Columns>
            <DataGridTextColumn Header="Title" Binding="{Binding Title}" />
            <DataGridTextColumn Header="Available chapters" Binding="{Binding AvailableChapters}" />
            <!-- This is what I tried
            <DataGridTemplateColumn Header="Available chapters">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ListBox ItemsSource="{Binding AvailableChapters}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>-->
    </DataGrid.Columns>
</DataGrid>

My aim is to show the list of chapters inside the book, as a list of strings, where each string is the chapter number (ChapterNumber property). For this reason, I was trying to access in some way the ChapterNumber property in the ChapterList property. Tried to use even the ListBox or AvailableChapters.ChapterNumber, but it makes no sense).
Example:

Edit
Tried with a converter but, although the value is not null, it says its length is zero.
public class ChapterListToStringListConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            List<Chapter> chapters = value as List<Chapter>;
            if (chapters == null)
            {
                chapters = new List<Chapter>();
            }

            Debug.Print(chapters.Count.ToString());    // "0"
            Debug.Print(chapters[0].ChapterNumber);    // Error: index out of range
            string result = string.Join(" ", chapters.Select(chap => chap.Name));
            return result;
        }
    }
}

A: The source for data-binding needs to be a property, not a field as you currently have.
To get a single string with all of the available chapters, just add a calculated property to your Book class, which combines all of the chapter items from the list.
public class Book
{
    public string Title {get; set;}
    public List<Chapter> AvailableChapters; {get;}

    public string AvailableChaptersDisplay
    { get {return string.Join( " ", AvailableChapters.Select( c => c.ChapterNumber )); } }
}

A: In case you are adding Chapters after the view was initialized, AvailableChapters should be an ObservableCollection:
public class Book
{
    public string Title { get; set; }

    public ObservableCollection<Chapter> AvailableChapters { get; }
        = new ObservableCollection<Chapter>();
}

In your converter just check if value is an IEnumerable:
public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{
    var chapters = value as IEnumerable<Chapter>;

    return chapters == null
        ? "-"
        : string.Join(" ", chapters.Select(chap => chap.ChapterNumber));
}

A: You could add a property that calculates that for you.
public class Book {
    public string Title;
    public List<Chapter> AvailableChapters;
    public string AvailableChaptersString
    {
        get {return list_concatenated_in_desired_format; }
    }

}


text:
Q: Automatically expand ssrs drildown report while exporting to excel or pdf I want to expand the SSRS report automatically when click export button of excel or PDF. Please share any idea.
Thanks in advance.

A: It won't happen automatically when you click the export button. If you need something expanded, consider adding a link in your report for the user to click instead. You can make it sort of look like a button - create a textbox and use background color to make it stand out. In this textbox, use a Jump to Report or Jump to URL and connect to another version of the report that is expanded the way you like. Then you can export that. If you use the Jump to URL button, you can use URL Access parameters to render the expanded version of the report automatically to Excel or PDF so the user doesn't have to take that extra step. You can see more about URL Access parameters here: http://msdn.microsoft.com/en-us/library/ms153586


text:
Q: XPage fileDownload1 control becomes editable on page full refresh? Why fileDownload1 control becomes editable (delete file attachment icon appears next to fileDownload control) when I just refresh the page. Here is my code where I use a button to refresh the page (just for the example)
<xp:button value="Label" id="button1">
    <xp:eventHandler event="onclick" submit="true" refreshMode="complete"></xp:eventHandler>
</xp:button>
<xp:this.data>
    <xp:dominoDocument var="document1" formName="myXpage"
      databaseName="${javascript:sessionScope.SUPPORT_DB_FILE}"
      action="openDocument">
    </xp:dominoDocument>
</xp:this.data>
<xp:fileDownload
     id="fileDownload1"
     rows="30"
     displayLastModified="false"
     displayType="false"
     displayCreated="false"
     hideWhen="true"
     allowDelete="true"
     value="#{document1.MyBodyRTF}">
</xp:fileDownload>

A: I tried to replicate what you're describing, but am having trouble doing so. I created a new XPage and modeled it after your sample code.
Notable differences:

*

*I never see the trash icon

*I had to compute the UNID of some document with an attachment in the appropriate field

*I set both the DB name and UNID in beforePageLoad

*I noticed an interesting change in the UI behavior (see animated gif below)

I'm not sure what you're running into without having more source code to be able to view, but I can confirm that what I tried doesn't reproduce the result you're describing.
XPage source:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
    xmlns:xp="http://www.ibm.com/xsp/core">
    <xp:this.beforePageLoad><![CDATA[#{javascript:sessionScope.myDbName = database.getFilePath();
var vw:NotesView = database.getView("SomeForms");
var first:NotesDocument = vw.getFirstDocument();
sessionScope.myFirstDoc = first.getUniversalID();
first.recycle();
vw.recycle();}]]></xp:this.beforePageLoad>
    <xp:this.data>
        <xp:dominoDocument
            var="document1"
            action="openDocument"
            formName="SomeForm"
            databaseName="${javascript:return sessionScope.myDbName;}"
            documentId="${javascript:return sessionScope.myFirstDoc;}" />
    </xp:this.data>
    <xp:fileDownload
        rows="30"
        id="fileDownload1"
        displayLastModified="false"
        value="#{document1.SomeAttachments}" />
    <xp:button
        value="Refresh"
        id="button1">
        <xp:eventHandler
            event="onclick"
            submit="true"
            refreshMode="complete" />
    </xp:button>
</xp:view>


text:
Q: Disposing objects exception While crawling through sources on the web, I've encountered a lot of boiletplate code which looks the following way:
Suppose we have some public class CustomObject: IDisposable, which has a bunch of methods.
Now, each of those methods has default sanity checks:
if (inputBuffer == null)
    throw new ArgumentNullException("inputBuffer");
if (outputBuffer == null)
    throw new ArgumentNullException("outputBuffer");
if (inputCount < 0)
    throw new ArgumentException("inputCount", "< 0");

But (due to the IDisposable interface implementation) the following check is added to each method:
if (disposed)
    throw new ObjectDisposedException("MethodName");

Now - is this a common practice? Should I start reengineering my old disposable classes and implementing these checks?

A:
Now - is this a common practice?

Yes, it is recommended. For almost all members. If you class is IDisposable and any method that needs a resource is called after Dispose() then there is a serious logic error in the calling code. Your task is to signal this.
But note that there might be methods (or properties) that do not critically rely on the owned resource(s), they can be considered safe to call after a Dispose(). For instance an IsOpen function/property. It can simply return false, no need for an exception.
But you should not put the IsDisposed check into Dispose() iteself, the guideline is that it should be safe to call Dispose() multiple times.

Should I start reengineering my old disposable classes and implementing these checks?

In general a good idea. Whether it is worth the effort is up to you.

A: It depends upon your usage, if in doubt it doesn't hurt to add it.
For a class intended to be used by other programs (e.g., libraries and frameworks) I would always perform this check and throw the correct exception as this will aid other applications in diagnosing errors and makes the class more robust.
For internal classes only intended to be consumed by my application you can skip the check if the error will surface quickly when calling the methods. E.g. if every method in the class used a stream, and that stream was disposed or set to null it would result in an exception pretty quickly.
If the internal class has methods that won't error though, I will always use an explicit check as I don't want a situation where some of the methods still work after the object has been disposed (except for methods that explicitly allow it such as IsDisposed).
Having the explicit check does have the advantage of explicitly documenting which methods are allowed to be called after the object has been disposed. More so if you add a comment at the top of methods that do not call GuardDisposed to state that it is allowed, then any method that doesn't start with GuardDisposed or a comment can be regarded as suspect.
To actually implement the check I prefer to move it to a separate method and use it like an assertion, e.g.
public class Foo
{
    private bool disposed;

    public void DoSomething ()
    {
        GuardDisposed ();
    }

    protected void GuardDisposed ()
    {
        if (disposed)
            throw new ObjectDisposedException (GetType ().Name);
    }
}

A: That code you put inside Dispose() (usually) method in order to be sure that it's not called esplicitly (and/or) not esplicitly more then one time on a single instance.
They use it in case when you do in that method something that can be executed one time (DeleteFile, CloseTransaction...) and any other  operation you may think of, that is shouldn't executed twice in your app domain.
So if this is a common practice: I would say, it depends on your app requirements.


text:
Q: hover img in fbml I'm trying to work out how to do a hover img in an fbml on a 'like to reveal content page.
If that doesn't make sense, here is an example of what I'm trying to achieve:
http://www.facebook.com/sonyericsson?v=app_6009294086
If you hover over the video and phone while you're not a fan it prompts you to like the page to view the content.
THANKS GUYS

A: Just worked it out,
you need an a href about the hover img to make it work, if anyone wants further info just let me know


text:
Q: Carrierwave file upload w/ resque job to upload to S3 What would be the best solution to upload files to file storage, upload to S3 (via Resque), and then modify the storage type for carrierwave on the record? Is this possible?
Thanks!

A: You could try the carrierwave_backgrounder gem which has Resque support for uploading files to S3 in the background after the file has hit your server.
Alternatively you could try uploading directly to S3 from the user's browser using the new CORS support. Eg. s3_direct_upload


text:
Q: Motion detection using OpenCV/C++, threshold always become zero I work on C++ crowd detection code with "OpenCV", that takes 2 frames and subtracts them. Then compare the result with threshold.
This is the first time I deal with "OpenCV" for C++ and I don't have much information about it.
These are the steps of the code:

*

*Take two video frames with α minutes in between.

*Convert frames to black and white images.

*Subtract the two frames.

*Compare the difference with the threshold.

*If Difference  <= threshold then crowd  detected else--> there is no crowd.

c++ code:
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main (int argc, const char * argv[])
{
//first frame.
Mat current_frame = imread("image1.jpg",CV_LOAD_IMAGE_GRAYSCALE);

//secunde frame.
Mat previous_frame = imread("image2.jpg",CV_LOAD_IMAGE_GRAYSCALE);

//Minus the current frame from the previous_frame and store the result.
Mat result = current_frame-previous_frame;

//compare the difference with threshold, if the deference <70 -> there is crowd.
//if it is > 70 there is no crowd
int threshold= cv::threshold(result,result,0,70,CV_THRESH_BINARY);

if (threshold==0) {
    cout<< "crowd detected \n";
}
else {
    cout<<" no crowd detected \n ";
}
}

The problem is :
The threshold always be zero!
and the output always:
crowd detected
even if there is no crowd
We don't care about the output image because we won't use it, and we just want to know the last value of threshold.
My aim is to know how much deference between 2 frames. I want to compare the deference with threshold to detect the human crowd in specific place
I hope that one of you can help me
Thank you

A: there's a couple of flaws in your usage of the threshold function

*

*it just returns the threshold value ( not what you expected )

*'We don't care about the output image'  - well, you'd better!

*if you want to threshold against a value of 70, that should be your 3rd arg, not the 4th (the 4th arg is the value, anything >thresh is set to
what you probably wanted, is :
cv::threshold(result,result,70,1, CV_THRESH_BINARY); // same as : result = result>70;
int on_pixels = countNonZero(result);
// or:
int on_pixels = sum(result)[0];

[sidenote: if you really want to detect human crowds, you'll have to put much more sweat into this.  just diff'ing frames is prone to err with illumination changes, also, there's birds, cars and traffic lights]


text:
Q: Additional source directories using Geany I'm using Geany in Ubuntu as an IDE for a C++ Project, and I want to use some external libraries (from Webots). However, I don't find the option to specify additional library paths (as one can find in Code::Blocks or Netbeans). Must I specify the paths manually as a build option? If so, how do I do it? I'm not exactly an expert at this kind of stuff.

A: As far as I know, we can specify additional libraries in the Project Properties (Project -> Properties) as shown in the picture


text:
Q: How can I customize the Lion login screen to remove the vignette effect? Just upgraded to Lion, but the new login screen needs some colour. I found someone online who posted the address of the image that's in the background, so I went and replaced that.
Only, after doing that, I realized that there's an additional overlay being drawn that adds a vignette effect by brightening the center of the screen.
Does anyone know of a way to remove this?

A: I suspect that the effect is actually something that's drawn programmatically. I dug around for a while and I can't seem to find it anywhere. My suggestion: Open your image in a graphics editor and modify it to account for the shadow.


text:
Q: Draw a curve using multi plane in A-Frame and Three.js I'm creating a A-Frame Application (with Three.js) draw a road using THREE.CatmullRomCurve3.
The application's concept is draw a road which connects multi points, I want to draw the road with exact width (eg: a road with 3 meters width), I'm using THREE.PlaneGeometry to connect 2 points.
My result, and my code snippet

var scene, camera, renderer;
var cube;
var controls;

function initScene() {
  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 30;

  renderer = new THREE.WebGLRenderer({
    alpha: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);

  controls = new THREE.OrbitControls(camera);
  controls.update();

  document.body.appendChild(renderer.domElement);
}

function render() {
  requestAnimationFrame(render);

  // required if controls.enableDamping or controls.autoRotate are set to true
  controls.update();

  renderer.render(scene, camera);
}

function drawRoadByLine() {
  //Create a closed wavey loop
  var curve = new THREE.CatmullRomCurve3([
    new THREE.Vector3(-10, 0, 10),
    new THREE.Vector3(-5, 5, 5),
    new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(5, -5, 5),
    new THREE.Vector3(10, 0, 10)
  ]);

  var points = curve.getPoints(50);
  var geometry = new THREE.BufferGeometry().setFromPoints(points);

  var material = new THREE.LineBasicMaterial({
    color: 0xff0000
  });
  // Create the final object to add to the scene
  var curveObject = new THREE.Line(geometry, material);
  scene.add(curveObject);
}

function drawRoadByPlane() {
  //Create a closed wavey loop
  var curve = new THREE.CatmullRomCurve3([
    new THREE.Vector3(-10, 0, 10),
    new THREE.Vector3(-5, 5, 5),
    new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(5, -5, 5),
    new THREE.Vector3(10, 0, 10)
  ]);

  var points = curve.getPoints(50);
  var group = new THREE.Group();

  var currentPos;
  var nextPos;
  var distance;
  var plane;
  var rotationMatrix;

  for (var i = 0; i < points.length - 1; i++) {
    currentPos = new THREE.Vector3(points[i].x, points[i].y, points[i].z);
    nextPos = new THREE.Vector3(points[i + 1].x, points[i + 1].y, points[i + 1].z);

    distance = currentPos.distanceTo(nextPos);

    plane = createPlane(distance);
    plane.position.set(currentPos.x, currentPos.y, currentPos.z);

    // rotationMatrix = getRotationMatrix(currentPos, nextPos);
    // plane.applyMatrix(rotationMatrix);

    group.add(plane);
  }

  scene.add(group);
}

function createPlane(distance, position) {
  var geometry = new THREE.PlaneGeometry(1, distance);
  // Dummy random color each plane, true color is red (0xff0000)
  var color = Math.floor((Math.random() * 0xffffff) + 1);
  var material = new THREE.MeshBasicMaterial({
    color: color,
    side: THREE.DoubleSide
  });
  var plane = new THREE.Mesh(geometry, material);

  return plane;
}

function getRotationMatrix(v1, v2) {
  var quaternion = new THREE.Quaternion();
  quaternion.setFromUnitVectors(v1, v2);

  var matrix = new THREE.Matrix4();
  matrix.makeRotationFromQuaternion(quaternion);

  return matrix;
}

initScene();
drawRoadByPlane();
render();
body {
  margin: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

My now issue is how to make the planes display continously (without space between 2 plane). I think I need rotate each plane, but I don't know to to calculate right rotation between 2 points.

A: Update:
I've just changed my solution to use THREE.Face3 instead of THREE.PlaneGeometry.
Here is my code snippet

var scene, camera, renderer;
var cube;
var controls;

function initScene() {
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 30;

    renderer = new THREE.WebGLRenderer({ alpha: true });
    renderer.setSize(window.innerWidth, window.innerHeight);

    document.body.appendChild(renderer.domElement);

    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.update();
}

function render() {
    requestAnimationFrame(render);

    renderer.render(scene, camera);
}

function draw() {
    var dummyPoints = [
        new THREE.Vector3(-10, 0, 10),
        new THREE.Vector3(-5, 5, 5),
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(5, -5, 5),
        new THREE.Vector3(10, 0, 10)
    ];

    //Create a closed wavey loop
    var curve = new THREE.CatmullRomCurve3(dummyPoints);

    var material = new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, side: THREE.DoubleSide });

    //create a triangular geometry
    var points = curve.getPoints(100);

    var roadPoints = [];

    var length = points.length;

    for (var i = 0; i < length - 1; i++) {
        roadPoints = roadPoints.concat(extractRoadPoint(points[i], points[i + 1]));
    }

    roadPoints = roadPoints.concat(extractRoadPoint(points[length - 1], points[length - 2]));
    var geometry = new THREE.Geometry().setFromPoints(roadPoints);

    // var face = new THREE.Face3(0, 1, 2);
    //add the face to the geometry's faces array
    // geometry.faces.push(face);

    for (var i = 0; i < roadPoints.length - 2; i++) {
        var face = new THREE.Face3(i, i + 1, i + 2);
        geometry.faces.push(face);
        face.color.set(new THREE.Color(Math.random() * 0xffffff - 1));
    }

    //the face normals and vertex normals can be calculated automatically if not supplied above
    geometry.computeFaceNormals();
    geometry.computeVertexNormals();

    scene.add(new THREE.Mesh(geometry, material));
}

function extractRoadPoint(point1, point2) {
    var result = [];

    var vector = {
        x: point2.x - point1.x,
        y: point2.y - point1.y,
        z: point2.z - point1.z,
    }

    var uOxz = {
        x: 0,
        y: 1,
        z: 0
    };

    var vectorVertices = {
        x: vector.y * uOxz.z - vector.z * uOxz.y,
        y: vector.z * uOxz.x - vector.x * uOxz.z,
        z: vector.x * uOxz.y - vector.y * uOxz.x,
    };

    var t = Math.sqrt(1 * 1 / (vectorVertices.x * vectorVertices.x + vectorVertices.y * vectorVertices.y + vectorVertices.z * vectorVertices.z));

    var sidePoint11 = {
        x: point1.x + vectorVertices.x * t,
        y: point1.y + vectorVertices.y * t,
        z: point1.z + vectorVertices.z * t,
    }

    var sidePoint12 = {
        x: point1.x - vectorVertices.x * t,
        y: point1.y - vectorVertices.y * t,
        z: point1.z - vectorVertices.z * t,
    }

    var sidePoint21 = {
        x: point2.x + vectorVertices.x * t,
        y: point2.y + vectorVertices.y * t,
        z: point2.z + vectorVertices.z * t,
    }

    var sidePoint22 = {
        x: point2.x - vectorVertices.x * t,
        y: point2.y - vectorVertices.y * t,
        z: point2.z - vectorVertices.z * t,
    }

    return [sidePoint11, sidePoint12, sidePoint21, sidePoint22];
}

initScene();
draw();
render();
body {
    margin: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: #000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>


text:
Q: Winston logger with chrome extension tool I am trying to implement Winston logger with my chrome extension tool. I am not able to do it.
Also I am not very familiar with Node.js and npm.

A: Winston doesn't work in a browser context, so this isn't reasonably possible until that's fixed.
https://github.com/winstonjs/winston/issues/287


text:
Q: Possible to cut an image based on the shape of another image? In Windows Presentation Foundation, I can't seem to find a way of how to cut an image based on the shape of another image.
E.g. I'd like to display someone's photo in the shape of a heart.
There are answers like this one which crop an image into a rectangle or like this one which draw a radius to clip the image into a circle.
But is cropping really the only way?
Can WPF overlay the image on top of a shape and have the image be cut based on the shape dimensions?
The code that I have so far does the inverse of what I'm trying to do. What I have so far uses an overlay layer as a mask to cover the image:
<Image
    Name="HeartOverlay"
    VerticalAlignment="Stretch"
    HorizontalAlignment="Stretch"
    Panel.ZIndex="2"
/>
<Canvas
    Name="Canvas"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch">
    <Image
        Name="Image"
        Stretch="Uniform"
        Panel.ZIndex="1"
    />
/>

HeartOverlay.Source = new Bitmap(@"C:\heart.png");
Image.Source = new Bitmap(@"C:\image.png");

The problem here is that overlay is merged together with the image and saving/printing the image also shows the overlay.
See image below as an example. Note the white borders, which are especially evident when viewing the image in something like the Mac Preview app. I'm looking to save/print the image without the white borders.
Appreciate any pointers!

A: You could simply fill a Path with a heart-shaped Geometry with an ImageBrush:
<Path Width="100" Height="150" Stretch="Uniform"
      Data="M1,2 L0,1 A0.5,0.5 1 1 1 1,0 A0.5,0.5 1 1 1 2,1 Z">
    <Path.Fill>
        <ImageBrush ImageSource="C:\image.png"/>
    </Path.Fill>
</Path>


text:
Q: PowerQuery Working W/ Duplicates and Combining Unique Lines when combining duplicates, you are left with unique lines (which is great) but now I am looking for ways to combine this info into one line. Here is a sample data:
Current:

Person
Member
Alum

A
null
Y

A
Y
null

B
null
Y

B
Y
null

B
Y
Y

Z
null
null

Goal:

Person
Member
Alum

A
Y
Y

B
Y
Y

Z
null
null

A: How about below, assuming null means it is a null value and not the text "null", and there is only ever one unique value option
let  Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Grouped Rows" = Table.Group(Source, {"Person"}, {
    {"Member", each try List.RemoveNulls(List.Distinct(_[Member])){0} otherwise null},
    {"Alum", each try  List.RemoveNulls(List.Distinct(_[Alum])){0} otherwise null}
    })
in #"Grouped Rows"

A: This is my work, made to match the desired output table layout.
Source is 'Table1'.
    let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    Custom1 = Table.AddColumn(Source, "MemberY", each try(if Character.ToNumber([Member])=89 then 1 else 0) otherwise 0),
    Custom2 = Table.AddColumn(Custom1, "AlumY", each try(if Character.ToNumber([Alum])=89 then 1 else 0) otherwise 0),
    OtherColumnsRemoved = Table.SelectColumns(Custom2,{"Person", "MemberY", "AlumY"}),
    GrouedRows = Table.Group(OtherColumnsRemoved, {"Person"}, {{"Member", each List.Max([MemberY]), type number}, {"Alum", each List.Max([AlumY]), type number}}),
    ChangedType1 = Table.TransformColumnTypes(GrouedRows,{{"Member", type text}, {"Alum", type text}}),
    ChangedValue = Table.ReplaceValue(ChangedType1,"1","Y",Replacer.ReplaceText,{"Member", "Alum"}),
    FinalTable = Table.ReplaceValue(ChangedValue,"0","NULL",Replacer.ReplaceText,{"Member", "Alum"})
in
    FinalTable