text:
Q: MobX React: How to only Re-render part of View I have a map react component and I'm dynamically adding markers.The problem is that when I add markers in the store, the whole map rerenders instead of just appending the markers to the map. Has anyone got any suggestions on how this could be fixed?? I'm pretty sure that I need to Inject the store into CPMap function exclusively, I'm just not sure how.
const CPMap = withGoogleMap((props) => (
        <GoogleMap
            ref={props.onMapLoad}
            style={{
                height: 100,
                width: 100,
            }}
            onCenterChanged={props.boundsChanged}
            defaultOptions={{ styles: this.mapStyles }}
            defaultZoom={props.zoom}
            defaultCenter={{ lat: props.center.lat, lng: props.center.lng }}>
            <MarkerClusterer
                gridSize={40}>
                {
                    props.markers.map(({ key, position }) => (
                        <Marker
                            key={key}
                            position={{ lat: position.lat, lng: position.lng }}
                            icon={{
                                url: require('../../images/marker.png')
                            }}
                        />
                    ))
                }
            </MarkerClusterer>
        </GoogleMap >
    ))

    return (
        <CPMap
            style={{
                height: 100,
                width: 100,
            }}
            onMapLoad={(gMap) => {
                map = gMap
                this.props.map.fetchMarkers()
            }}
            boundsChanged={() => {
                this.props.map.fetchMarkers()
            }}
            center={this.props.map.center}
            zoom={this.props.map.zoom}
            markers={mobx.toJS(this.props.map.markers)}
            containerElement={

            }
            mapElement={

            } />
    )
}

A: I'd propose you the following solution: don't pass makers directly to CMap component, but use store instead;
const markersStore = observable({
    markers: []
});

Then in your component - move MarkersClusterer to the separate component and pass markersStore one level deeper:
//import markersStore or inject via mobx-react package
class MyComponent extends Component {
   render() {
      const CMap = withGoogleMap((props) => (
         <GoogleMap
            ...
            <Clusterer markersStore={props.markersStore} />
         />
      ))
      return (
         <CMap
            ...
            markersStore={markersStore}
         />
      )
   }
}

Make your new Cluster component observable so it updates when markersStore "markers" property updates;
@observable
class Clusterer extends Component {
    render(){
       const { markers } = this.props.markersStore;
       return (
          <MarkerClusterer>
              { markers.map(...)}
          </MarkerClusterer>
       )
    }
}

The final change is to update your fetchMarkers method so it populates the markersStore with new data.
With this solution CMap component doesn't know anything about markers and it doesn't updates when new data received. At the same time MarkersClusterer component becomes more clever and "observes" changes in the markersStore.


text:
Q: Ontology/Satellite "satcat" is missing Since two weeks I am missing the property satcat of the DBpedia class Satellite.
I am trying to get all satellites and filter it by the satcat. (It worked until October.)
PREFIX dbp: <http://dbpedia.org/property/>
SELECT DISTINCT ?subject ?satcat
WHERE {    ?subject ?x <http://dbpedia.org/ontology/Satellite>.
           ?subject dbp:satcat ?satcat.

FILTER(?satcat = XXX )}

For example, extract information about http://dbpedia.org/resource/Envisat.
Do I have the opportunity to get some influence of the DBpedia database? Or can anybody fix the graph in the database? Or is there another common solution to extract a specific satellite out of dbpedia.org?

A: You appear to have run into a glitch in the data of the latest DBpedia release, which went live on October 14.
Probably best to raise this and issues like it to dbpedia-discussion and/or dbpedia-developers.
I'd provide them with comparative links, e.g., the main dbpedia.org/sparql vs live.dbpedia.org/sparql.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Infer Generic Type of Interface -- Context
I have the following 5 objects
IChangeStatus<T>
myFirstClass : IChangeStatus<firstClassEnum>
mySecondClass : IChangeStatus<secondClassEnum>

myClassHandler<TEntity>
myFirstClassHandler : myClassHandler<myFirstClass>

for the purposes of the question we can assume the interface only has the property
T Status { get; }

-- Questions
1.- How can I ask in a method in myClassHandler if an instance of TEntity implements IChangeStatus?
2.- How can I iterate over an IEnumerable of TEntity assuming their specific IChangeStatus?

A: To check if your class implements IChangeStatus, you can simply do:
public void FooMethod(ClassType myClass)
{
  var doesImplementIChange = myClass as IChangeStatus<SomeClass>
  if (doesImplementIChange != null)
  {
    // Do stuff..
  }
}

To iterate over an IEnumerable of your classes:
foreach (var data in myClass.OfType<MyType>())
        {
            // Do stuff..
        }

or, you could do:
foreach (var cls in myClass)
        {
            var myCls = myClass as IChangeStatus<SomeClass>;
            if (myCls != null)
            {
                // Do stuff..
            }
        }

A: If you want to use T from IChangeStatus<T> in MyClassHandler, you will have to add another type parameter. For example:
class MyClassHandler<TEntity, TStatus>
    where TEntity : IChangeStatus<TStatus>
{
     public IEnumerable<TStatus> Statuses
     {
          get { return _entities.Select(entity => entity.Status); }
     }
}

The where clause will ensure that the entity and status types are correlated.
If you don't want to do that, you could add an additional non-generic interface that exposes a Status property of the type Object. You'd lose some static typing that way, but you would not need the extra type parameter.

A: I found this other SO Question - Check if a type implements a generic interface without considering the generic type arguments which gave me a more generic answer which is what I was looking for:
return entity.GetType().GetInterfaces()
       .Where(i => i.IsGenericType)
       .Any(i => i.GetGenericTypeDefinition() == typeof(IChangeStatus<>));

As to the iteration over the IEnumerable assuming the specific type of IChangeStatus, since we got that to point then the type does implement the interface thus has a Status property... so I went for dynamic type.


text:
Q: Run-time error R6034 when compiling from the command prompt I tried to compile a simple "hello world" program in C (using MinGW) from the command prompt and had the following error:

R6034 : An application has made an attempt to load the C runtime library incorrectly. Please contact the application's support team for more information.

I've done a couple searches on the subject and there seems to be a consensus on stray mscvr files placed in the path variable by other programs.
I've downloaded Process Explorer and tried to find any such files, but  the msvcr files that I find (msvcr80 and msvcrt) are all loaded from the system32 folder.
This is what I have in my system path:
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\MATLAB\R2008a\bin\win32;c:\mingw\bin.

Any help on how to solve the problem would be appreciated.

A: I finally figured out what was wrong. Matlab was the culprit; taking it out of my path solved the problem! :) – Dave


text:
Q: pointer initialization and allocation issue I don't understand this:
compiler is fine with
int *p_x=&x;

but not this
int *p_x,x;
*p_x=&x;

It is confusing to me. What is the difference? Is this only a initialization convention?

A: The token * has two meanings.
In the second example it is the dereferencing operator, which gets the value a pointer points to:
int *p_x,x;
*p_x=&x;

p_x is a pointer to int.
x is an int.
&x is the address of x (pointer to int).
*p_x is the value p_x points to (an int). * here is the dereference operator.
You are trying to assign a pointer &x to an int.
In the first example int *p_x = &x the token * actually belongs to the type, which is int*, a pointer to int. It is not the dereferencing operator here. Therefore the assignment is to p_x and not to *p_x. This becomes clearer if you write the line as int* p_x = &x. Assigning &x to p_x is fine, because both are of type  pointer/address to int.
The simplest way to fix the second example is to rewrite *p_x = &x to p_x = &x. Then &x is again assigned to the pointer instead of the value the pointer points to.

A: Here:
int *p_x=&x;

You're declaring p_x as a pointer to int and assigning the value of p_x to the address of  x which is legal.
But here:
int *p_x,x;
*p_x=&x;

You're declaring p_x as a pointer to int and x as an integer. Then you're trying to assigne the address of x to the object pointed to by p_x which means, assigning the address of x to x which is not legal as x is not a pointer. And it will generate an error: invalid conversion from 'int*' to 'int'.

A: int *p_x,x;

Is the equivalent of:
int *p_x;
int x;

So you actually want to remove the leading * for this to be valid:
p_x = &x;

This is essentially the same as int *p_x=&x;, I would punctuate this as int* p_x = &x to clarify that p_x is of type int*.

A: int *p_x=&x;

Make a variable named p_x type (int *) (which is pointer to integer) and then set its value to  the address of x.
int *p_x,x;
*p_x=&x;

Make a variable named p_x type (int *) (which is pointer to integer, or in other words an address) and a variable named x type integer.
Where p_x is pointing (random location, because it wasn't initialized), put the address of x;
It's unfortunate that pointer types are defined with * and to access an address you also use *.

A: Although this is common (and I use it myself):
int *p;

it's actually a little misleading. We're not declaring an int named "*p", we're declaring an int* named "p".
This:
int *p_x=&x;

is equivalent to this:
int* p_x;
p_x=&x;    // perfectly correct

But this is incorrect:
int *p_x,x;
*p_x=&x;   // ouch!

You're assigning an address to an int (and even if you cast it correctly, you're dereferencing an uninitialized pointer, which causes Undefined Behavior).


text:
Q: Changing magnetic and electric field Does a changing electric field create 'constant' magnetic field or 'changing' magnetic
And , does a changing magnetic field create 'constant' electric field or 'changing' electric field

A: That depends on the way it changes.
For example with light. A changing magnetic field creates a changing electric field which in turn creates a changing magnetic field and so on.
I am not sure if it is possible with a changing magnetic field to produce a constant electric field and vice-versa.

A: example of changing -> constant:
Change the magnetic field through an open loop at a constant rate and you will induce a constant electric field  between the open poles


text:
Q: substitute for nested for loops in pandas dataframes for big data handling There are 2 .csv files - file1(with heads Order_ID, Amount, Commission, GST, etc.) and file2(with heads hbx_id, amount, status, etc.).
I have to tell that the "amount" in File2 matches with ("Amount" – "Commission" – "GST") in File1. This has to be performed basis "Order_ID" in File1 and "hbx_id" in File2.
I am required to put the status as "matched" against items that are matching else put "not matched".
For items in File2 which are not present in File1, I am supposed to enter the status "not present" in the status column in File2.
I solved the problem with the use of nested for loops and my code looked like this -
for i in file2.index:
    flag = 0
    for j in file1.index:
        if (file1['Order_ID'][j]).count(file2['hbx_id'][i])>0:
            flag = 1
            if file1['Amount'][j]-file1['Commission'][j]-file1['GST'][j]==file2['amount'][i]:
                file2.at[i,'Status'] = 'matched'
            else:
                file2.at[i,'Status'] = 'not matched'
    if flag == 0:
        file2.at[i,'Status'] = 'not present'

This worked just fine, but my question is that this would not be a feasible option if the datasets are big(coz of the for loop iterations). Is there any substitute for this method, a function from pandas, or any other library or something?
EDIT:- The expected output looks like this -
       hbx_id      tran_date    amount  Status
0   AMBLEY127928'   01-09-2019  36.00   matched
1   SIPTBT18469'    01-09-2019  65.50   not matched
2   'KITJUJ272150'  01-09-2019  37.28   matched
3   'LEGNOE40184'   01-09-2019  20.00   matched
4   hb-pay_9492291-1'   01-09-2019  313.77  not matched
5   'SF3C145362'    01-09-2019  25.00   matched
6   hb-AMBLEY127931-1'  01-09-2019  75.50   not matched
7   'HEANEM26099'   01-09-2019  19.62   matched
8   hb-COOINT242360-1'  01-09-2019  44.15   not present
9   'MUNDCT3880'    01-09-2019  142.00  matched
10  'KDA178133' 01-09-2019  24.53   matched
11  'KSCA1492699'   01-09-2019  9.81    matched
12  'FOROCH372249'  01-09-2019  14.72   matched
13  'CHAMXN202625'  01-09-2019  29.43   matched
14  'DOSFSX48229'   01-09-2019  49.06   matched
15  'ARAEZG242324'  01-09-2019  25.00   matched
16  hb-SHRWOG391499-1'  01-09-2019  19.56   matched
17  'MALSJU13377'   01-09-2019  16.50   matched
18  hb-OMKXDT420930-1'  01-09-2019  10.00   matched
19  'SCCA528997'    01-09-2019  20.00   not matched

file1.head()
       Transaction_ID                          Order_ID Transaction_Date    Updated_Date    Transaction_Type    Status  MID Customer_ID Customer_Nickname   Customer_Phone_No.  ... Commission_Rate Product_Code    GMV_Tier    Transaction_Slab    Request_Type    Refund_Type Refund_Actor    Split_Flag  Split_MID   Split_Id
0   '20190901111212800100168044885072100'   hb-SIPJZO32656-1'   '2019-09-01 00:54:14'   '2019-09-01 00:54:33'   'ACQUIRING' 'SUCCESS'   'EatGoo08603428284199'  NaN NaN 9804817853' ... NaN '51051000100000000010'  NaN NaN 'SEAMLESS'  NaN NaN NaN NaN NaN
1   '20190901111212800110168956985465456'   'SHRWOG391493'  '2019-09-01 02:14:43'   '2019-09-01 02:14:46'   'ACQUIRING' 'SUCCESS'   'EatGoo08603428284199'  NaN NaN NaN ... NaN '51051000100000000001'  NaN NaN 'SEAMLESS_3D_FORM'  NaN NaN NaN NaN NaN
2   '20190901111212800110168835885639302'   'MIDYEY245461'  '2019-09-01 00:23:36'   '2019-09-01 00:23:39'   'ACQUIRING' 'SUCCESS'   'EatGoo08603428284199'  NaN NaN NaN ... NaN '51051000100000000001'  NaN NaN 'SEAMLESS_3D_FORM'  NaN NaN NaN NaN NaN
3   '20190901111212800110168061185352899'   'KITJUJ272194'  '2019-09-01 03:40:00'   '2019-09-01 03:40:03'   'ACQUIRING' 'SUCCESS'   'EatGoo08603428284199'  NaN NaN NaN ... NaN '51051000100000000001'  NaN NaN 'SEAMLESS_3D_FORM'  NaN NaN NaN NaN NaN
4   '20190901111212800110168140285515665'   'EXLRYB3995'    '2019-09-01 00:08:21'   '2019-09-01 00:08:21'   'ACQUIRING' 'SUCCESS'   'EatGoo08603428284199'  '216810000026794940140' NaN '9515053146'    ... NaN '51051000100000000001'  NaN NaN 'AUTO_DEBIT'    NaN NaN NaN NaN NaN

file2.head()
        hbx_id      tran_date   amount
0   AMBLEY127928'   01-09-2019  36.00
1   SIPTBT18469'    01-09-2019  65.50
2   'KITJUJ272150'  01-09-2019  37.28
3   'LEGNOE40184'   01-09-2019  20.00
4   hb-pay_9492291-1'   01-09-2019  313.77

A: For a start I would simplify your data so make a new dataframe for file1 which is just the columns that you are using;
df1 = file1[['Order_ID', 'Amount', 'Commission', 'GST']]

with this you can then do you calculation in your first if statement and make a new column with these values;
df1['amount_check'] = df1['Amount'] - df1['Commission'] - df1['GST']

Assuming that the df1['Order_ID'] are unique values and some of which are in file2['hbx_id'] you could merge the two dataframes on these two columns keeping everything so you would have one dataframe with all your data aligned.
df1 = df1.merge(file1, left_on='Order_ID', right_on='hbx_id') # might need to add more parameters...

You could simply then make a new column df1['Status'] where if the df1['amount_check'] == df1['amount'] then you give the value 'matched' etc


text:
Q: django.core.exceptions.AppRegistryNotReady error in my django app I'm trying to add the django-ads module to my web app but i have few problems.
to install django ads I need to add code in my settings.py but there is the module gettext which is needed and there is some "_" who generate me error. so I imported the following things in my settings.py.
from ads.conf import gettext
from django.utils.translation import gettext as _

after that when I try to runserver that's show me this error :

django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.

don't know how to fix that, I've seen some post about de wsgi.py files but it's good.
wsgi.py:
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yufindRe.settings')

application = get_wsgi_application()

ads config in settings.py
#ads config

ADS_GOOGLE_ADSENSE_CLIENT = None  # 'ca-pub-xxxxxxxxxxxxxxxx'

ADS_ZONES = {
    'header': {
        'name': gettext('Header'),
        'ad_size': {
            'xs': '720x150',
            'sm': '800x90',
            'md': '800x90',
            'lg': '800x90',
            'xl': '800x90'
        },
        'google_adsense_slot': None,  # 'xxxxxxxxx',
        'google_adsense_format': None,  # 'auto'
    },
    'content': {
        'name': gettext('Content'),
        'ad_size': {
            'xs': '720x150',
            'sm': '800x90',
            'md': '800x90',
            'lg': '800x90',
            'xl': '800x90'
        },
        'google_adsense_slot': None,  # 'xxxxxxxxx',
        'google_adsense_format': None,  # 'auto'
    },
    'sidebar': {
        'name': gettext('Sidebar'),
        'ad_size': {
            'xs': '720x150',
            'sm': '800x90',
            'md': '800x90',
            'lg': '800x90',
            'xl': '800x90'
        }
    }
}

ADS_DEFAULT_AD_SIZE = '720x150'

ADS_DEVICES = (
    ('xs', _('Extra small devices')),
    ('sm', _('Small devices')),
    ('md', _('Medium devices (Tablets)')),
    ('lg', _('Large devices (Desktops)')),
    ('xl', _('Extra large devices (Large Desktops)')),
)

ADS_VIEWPORTS = {
    'xs': 'd-block img-fluid d-sm-none',
    'sm': 'd-none img-fluid d-sm-block d-md-none',
    'md': 'd-none img-fluid d-md-block d-lg-none',
    'lg': 'd-none img-fluid d-lg-block d-xl-none',
    'xl': 'd-none img-fluid d-xl-block',
}


text:
Q: Generating Csv with PHP - outputting unnecessary quotation marks I am generating and exporting a CSV through PHP and after some modifications from my team, now it results that inside a column, double quotation marks are being generated.
I generate it through my terminal by executing this Shell script with the CakePHP Console.
/var/www/mysite.new/trunk/app/Console/cake Csv mysite.uk

The problem is that I already tried many techniques to strip them off such as: stripslashes(), str_replace(), trim()
On my last modification, I tried to apply the str_replace function.
   foreach ($persons_csv as $person_csv){
       /* The part where I get the data for stripping off the quotation marks */
        $mail = $person_csv['Person']['email'];
        $name = str_replace('"', '', $person_csv['Person']['name']);
        $surname = str_replace('"', '', $person_csv['Person']['surname']);
         /* REST OF THE CODE */

    }

Nevertheless, it only happens to surnames and names that have more than one word in which the quotations marks are being generated.
Surnames and names that are consisting of one word, they appear to be fine.
Still, there are some anomalies probably inside names that have whitespace and therefore double quotations marks are being generated again. I am not quite sure why this is ocurring.
I can attach you two screenshots so you can have a better understanding of the problem.

If you have any idea of what it might be, it would be really appreciating.
This is the rest of my code in which I am generating the CSV.
   private function addRow($row) {
            $rows_deleted = 0;
         if (!empty($row)){
            fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
         } else {
                return false;
         }
    }

   private function renderHeaders() {
        header("Content-type:application/vnd.ms-excel");
        header("Content-disposition:attachment;filename=" . $this->filename);
    }

   private function setFilename($filename) {
        $this->filename = $filename;
        if (strtolower(substr($this->filename,   -4)) != '.csv') {
            $this->filename .= '.csv';
        }
    }

  private function render($filename = true, $to_encoding = null, $from_encoding = "auto") {
    if(PAIS) {
        if ($filename) {
            if (is_string($filename)) {
                $this->setFilename($filename);
            }
            $this->renderHeaders();
        }
        rewind($this->buffer);
        $output = stream_get_contents($this->buffer);

       $url = '/var/www/mysite.new/trunk/' .'app'.DS.'webroot'.DS.'csv'.DS.PAIS.DS.$this->filename;
        $gestor = fopen($url, "w+") or die("Unable to open file");
        if(file_exists($url)){
            file_put_contents($url, $output);
            chmod($url, 0777);
            fclose($gestor);
        } else {
            return false;
        }
    } else {
        return false;
    }
}

 public function csv_persons($persons_csv) {
    $this->array_final = [self::NAME, self::SURNAME];
    date_default_timezone_get('Europe/Madrid');
    $d = date("Ymd");
    $this->addRow($this->array_final);

    foreach ($persons_csv as $person_csv){
        $name = str_replace('"', '', $person_csv['Person']['name']);
        $surname = str_replace('"', '', $person_csv['Person']['surname']);

        $apos = ''';
        $pos = strpos($surname, $apos);
        if($pos !== false) {
            $surname = str_replace(''', '\'', $surname);
        }

        $arr = array();
        $arr[$this->getArrayKeyIndex($this->array_final, self::NAME)] = $name;
        $arr[$this->getArrayKeyIndex($this->array_final, self::SURNAME)] = $surname;

        $this->addRow($arr);
    }
    $filename = 'PERSON_PROFILE_' . $d;
    $this->render($filename);
}

Thanks

A: Instead of using fputcsv, try implode.
Ref: https://www.php.net/manual/en/function.implode.php
Update 1: You have to be sure that your value does not contain , (comma)
Update 2: If you are concern with the idea about that quoted text will be problem for your CSV datasheet, than you need to know that CSV is designed to that if there is any space between the value. So you don't have to worry about that. Any CSV parser will understand the quoted values properly.


text:
Q: Как записать эти значения в переменные?

Расписание команд.
Как мне записать каждое название в отдельную переменную?
Допустим Clutch в $a1, IG в $a2, Secret в $a3 и так далее

A: Не вдаваясь в тайный смысл внедрения десятка переменных там, где напрашивается использование массива, вы можете использовать варианты, приведенные ниже:
1. использование$$
$c1data = ['Glutch', 'IG', 'Secret'];

foreach($c1data as $idx => $v){
    $n = "a".($idx + 1);
    $$n = $v;
}

print_r([$a1, $a2, $a3]);

2. использование extract()
$vars = ["b1", "b2", "b3"];
extract(array_combine($vars, $c1data));

print_r([$b1, $b2, $b3]);


text:
Q: Factoring a series of Matricies I have a graduate physics text which has an arbitrary matrix $M$. I am given the following
$M^{0} + M^{1} + M^{2}...M^{n-1}$
and then it says this is equal to
$(M^{n}-I)(M-I)^{-1}$, where $I$ is the identity matrix. I dont not see how this follows, IF anyone can show me I would appreciate it.
It looks like some sort of power series of Matrices, but I never could fill in the gap.
Thanks,
Ben

A: $$(M-I)(I+M+\cdots+M^{n-1})$$
$$(I+M+\cdots+M^{n-1})(M-I)$$
$$=(M+M^2+\cdots+M^{n-1}+M^n)$$
$$-(I+M+\cdots+M^{n-2}+M^{n-1})$$
$$=M^n-I$$

If $1$ is not the eigenvalue of $M$, that is to say $M-I$ is invertible, then
  $$I+M+\cdots+M^{n-1}=(M-I)^{-1}(M^n-I)=(M^n-I)(M-I)^{-1}$$

This approach is similar to the geometric progression。


text:
Q: Redirigir a otra vista con Get en un ListWheelScrollView Estoy usando el paquete clickable_list_wheel_view y dentro de cada child estoy queriendo usar Get para redirigir a otra vista pero no se ejecuta el metodo tap().
class Prueba extends StatelessWidget {
  final _scrollController = FixedExtentScrollController();
  static const double _itemHeight = 160;
@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ClickableListWheelScrollView(
      scrollController: _scrollController,
      itemHeight: _itemHeight,
      itemCount: _itemCount,
      animationDuration: Duration(milliseconds: 300),
onItemTapCallback: (index) {
    print("onItemTapCallback index: $index");
  },` child: ListWheelScrollView.useDelegate(
    offAxisFraction: -1.6,
    controller: _scrollController,
    itemExtent: _itemHeight,
    physics: FixedExtentScrollPhysics(),
    overAndUnderCenterOpacity: 0.5,
    perspective: 0.002,
    onSelectedItemChanged: (index) {},
    childDelegate: ListWheelChildBuilderDelegate(
      builder: (context, index) => _child(index),
      childCount: _itemCount,
    ),
  ),
));

Widget _child(int index) {
return SizedBox(
  height: _itemHeight,
  child: ListTile(
    leading: Icon(
        IconData(int.parse("0xe${index + 200}"),
            fontFamily: 'MaterialIcons'),
        size: 50),
    title: Text('Heart Shaker'),
    subtitle: Text('Description here'),
    onTap: () {
      print('hola');
      Get.to(HomePage());
    },
  ),
);

}
Este es el codigo que implemente.Si me ejecuta el print el metodo onItemTapCallback() pero no el tap() que esta en el widget de abajo.
Soy nuevo en flutter.
Gracias de antemano

A: Bueno la razón por la cuál no detecta el onTap en tu widgte ListTitle es debido a que el ClickableListWheelScrollView como tal ya es un envoltorio para ListWheelScrollView, entonces para resolver su problema solo debe de asegurar colocar su Get.to(HomePage()); en onItemTapCallback de tu clickableListWheelScrollView o onSelectedItemChanged de tu ListWheelScrollView.useDelegate, según sea tu caso. Ejemplo...
class Prueba extends StatelessWidget {
  final _scrollController = FixedExtentScrollController();
  static const double _itemHeight = 160;
@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ClickableListWheelScrollView(
        scrollController: _scrollController,
        itemHeight: _itemHeight,
        itemCount: _itemCount,
        animationDuration: Duration(milliseconds: 300),
        onItemTapCallback: (index) {
         print("onItemTapCallback index: $index");
         /*Get.to(HomePage());*/
         },
         child: ListWheelScrollView.useDelegate(
           offAxisFraction: -1.6,
           controller: _scrollController,
           itemExtent: _itemHeight,
           physics: FixedExtentScrollPhysics(),
           overAndUnderCenterOpacity: 0.5,
           perspective: 0.002,
           onSelectedItemChanged: (index) {
              /*Get.to(HomePage());*/
           },
           childDelegate: ListWheelChildBuilderDelegate(
             builder: (context, index) => _child(index),
             childCount: _itemCount,
           ),
         ),
    ));
}

Widget _child(int index) {
return SizedBox(
  height: _itemHeight,
  child: ListTile(
    leading: Icon(
        IconData(int.parse("0xe${index + 200}"),
            fontFamily: 'MaterialIcons'),
        size: 50),
    title: Text('Heart Shaker'),
    subtitle: Text('Description here'),
  ),
);
}


text:
Q: Return an .NET object reference from a Windows Service when I can't add [Serializable] I work with external HW from the PC that requires to be booted ( time consuming ). I've been asked to speed this up by writing some software that will boot the hardware and then allow client's to obtain a reference to the hardware. Currently they have to reboot the HW every time they restart their software.
All the HW we use is 3rd party and written c# and therefore I don't have the luxury of being able to modify the hardware classes.
As this all needs to run on the same PC it seems logical that a Windows Service could be used to host some software that would instantiate the hardware class, boot the HW and then return the reference upon request.
Attempt 1 was a a WCF client hosted in a Windows Service. This worked initially until I realised that WCF is a message based system and does not allow the access to the methods of the returned object...only the data. I eventually realised I was trying to make WCF do something it wasn't intended for. I also couldn't add the DataContract attributes to the 3rd party dll classes.
Attempt 2 was using .NET Remoting hosted in a Windows Service. This worked initially until I realised I was not going to be able to add the [Serializable] attribute to the 3rd party class(s). I could inherit a class and add the  MarshalByRefObject but this only lets me call the object remotely which will be too slow for our purposes.
I've looked into trying to force WCF to work using shared assemblies and also trying to add an attribute at runtime but both ideas wont fly.
My next attempt is using COM but I thought this shouln't really be this hard....and thought I would consult the SO community to see if I'm just missing something.
To clarify here is an example of the 3rd party class I want to instantiate in the Service and return a copy to the client.
    public class afDigitizer : IDigitizerHandle, IDisposable
    {
    public afDigitizerCalibrate Calibrate;
    public afDigitizerCapture Capture;
    public afDigitizerEventOnError EventOnError;
    public afDigitizerEventOnWarning EventOnWarning;
    public afDigitizerListMode ListMode;
    public afDigitizerLO LO;
    public afDigitizerLVDS LVDS;
    public afDigitizerModulation Modulation;
    public afDigitizerRF RF;
    public afDigitizerTimer Timer;
    public afDigitizerTrigger Trigger;

    public afDigitizer();
    public afDigitizer(string installDir);

    ~afDigitizer();

    public int BootInstrument(string LoResource, string RfResource, int LoIsPlugin);}

.
        // and the code to instantiate the object and boot it.
        private afDigitizer vsa = new afDigitizer();

        errorCode = vsa.BootInstrument(this.LO, this.RF,-1);
        // Now i want to return the vsa object.


text:
Q: The right php framework for multiple profile type network i am currently in the process of planning a social network project of mine. after turning ideas & inputs in my mind for a very long time i am now starting to put thoughts on paper concretely. the network will be for a very specific group of people (so no bad facebook copy) and their industry.
the problem i am facing now is the choice of a framework or the decision to sit down and program everything ourselves. i know that there is a lot of php frameworks out there and i have spent quite a while checking the options.
i have marked zend and yii as my favorites so far from what i have seen and heard, but there is one issue i could not get information about.
the network will have 3 (in the future even 4) completely different profile types. the first type will be an institution (such as a school), the second will be someone directly affiliated by it (such as a teacher) and the third will be random people (students, parents, etc..)*.
*it will be different things of course but just so you get the idea.
-> there will be different rules of interaction between the different profile types. they will have completely different fiels to fill out, so i will create 3 different databases for them.
my question: there will only be one login, one page. which framework do you think could give me some possibilities to handle 3 different usertypes and their interaction rules? should i rely on a framework at all or should i start from scratch?
thank you for the input in advance,
sebastian =)

A: Well I will also suggest Yii because it is strongly object oriented language and gives you ability to have heavy app behaving light weight application.
Very strong ORM is its beauty. I suggest you plan it first then take a start.first have a brief knowledge of its structure and then start
you can handle multiple profiles by Modules.I recently made This using Yii it has 3 roles so far Admin,Teacher,Student and two of them has profiles.
Happy programming :)

A: As mentioned before this is not a framework issue.
It might be 3 tables in one database :
- one for institutions
- one for profiles
- one for relations between those, with a status field for the relationtype.
When choosing a framework : consider it's simplicity for rapid development.

A: *

*I really Don't think you should use 3 different databases for something as futile as a User Type. Rather model user types in the single database.

*I personally use Yii, as a Php framework, which offcourse is able to handle multiple usertypes. But I wonder if you realize what you use a framework for. I think you guys rather stop searching for the right framework, but rather lookup the right content-manager

Good luck


text:
Q: Parts of code skipped when calling functions in a function I'm working on a online tutorial on Python 2.7 and on exercice is to make a basic text
game. I'm very new to programming, and still working on the basics. I wish to make "move"-function I can call in all the "rooms" in the game, and deside the movement with args. The rooms in the game will be other functions i will call in the "move"-function.
In the example below i want to make it possible to choose for 4 directions using inputs n,e,s,w but only one will take the player to the next "room"-function called room_1 (not shown in the code here).
My problem is that it does not ask for input, but jumps straight to my room_1 function. It's not even printing the print "where do you wanna go? \n"
def move(north, dest_n, east, dest_e, south, dest_s, west, dest_w):
    while True:

        print "Where do you wanna go? \n"

        movement = raw_input()

        if movement in "n":
            print north
            dest_n

        elif movement in "e":
            print east
            dest_e

        elif movement in "s":
            print south
            dest_s

        elif movement in "w":
            print west
            dest_w

        else:
            print "Not a valid direction. \n"
            print "Use n, e, s, or w to move."

move(
    "the door is locked!", '',
    "You are not going that way.", '',
    "Wall.. nope, not that way!", '',
    "You move through the corridor", room_1()
    )

Sorry if im being unclear about something, as I'm new to programming:)
Thanks!


text:
Q: What does "beds" mean here? "the peripheral beds within the body and lungs" What does "beds" mean here?

A ventricle is one of two large chambers in the heart that collect and expel blood received from an atrium towards the peripheral beds within the body and lungs. The atrium (an adjacent/upper heart chamber that is smaller than a ventricle) primes the pump.

Source: Ventricle (heart) - Wikipedia
I wonder if it means spaces, chambers or body cavities.
I've already googled it, but couldn't find anything.

bed
1.a piece of furniture upon which or within which a person sleeps, rests, or stays when not well.
2.the mattress and bedclothes together with the bedstead of a bed.
3.the bedstead alone.

(However, maybe it's a mistake from Wikipedia)

A: 'Vascular bed' is a piece of medical jargon that compares our body's tissues to a garden bed of soil for the purposes of bloodflow. When the blood leaves the heart's chambers or the lungs' periphery, it enters smaller and smaller blood vessels in an expanding pattern for the purpose of 'saturating' the body with oxygenated blood, just like watering a bed of soil causes the dry soil to slowly absorb the water outward from the point of contact. While much of our vascular system can be thought of as a self-recycling pump made of big tubes, eventually the pathways become so fine that it's more accurate to think of it as a saturated (or unsaturated) substance. That's the bed.


text:
Q: How to open an URL with swift/cordova code triggered in HTML ? (by Javascript?) I have a very sneaky problem. I'm using Cordova to embeded my web-app onto iOS app.
But we have external URL and with our technique, it's really painfull to open external URL. And Cordova plugins like InAppBrowser does not work (because our app is already use an inapp browser).
Goal : we want to open an external URL, from a HTML page, to the Safari navigator of the device.
Maybe with Javascript ? I thought about something like :
UIApplication.shared.open(url, options: [:], completionHandler: nil)

So maybe, we can add in MainViewController a command triggered by an HTML button who use Javascript to open the URL in Safari ?
Anyone have an idea ?
Many thanks

A: check for canOpenURL then open
if let url = URL(string: "https://www.google.com"),
        UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:])
}


text:
Q: Plotting the image of a curve under a flow I have some explicit time-independent vector field on the plane, and I would like to study how points evolve under the flow generated by this vector field. The flow is rather complicated and cannot be solved explicitly.
For my purposes, it is important to analyze how a "curve" of initial conditions end up after a fixed time, say $t=1$. Is there any command in Mathematica that would do this job? I have read much documentation but could not find anything like this. Any help will be greatly appreciated.
To be concrete,
s =
  NDSolve[
   {x'[t] == -y[t] + x[t]*Log[x[t]], y'[t] == x[t] + y[t]*Log[x[t]],
    x[0] == 1, y[0] == 0},
   {x, y}, {t, 1}]

and I would like to plot the image of the line segment $1<x<2,\,y=0$ after time 1.

A: Make the position along the curve be another parameter of the differential equation.
s = NDSolve[{D[x[t, x0], t] == -y[t, x0] + x[t, x0]*Log[x[t, x0]],
   D[y[t, x0], t] == x[t, x0] + y[t, x0]*Log[x[t, x0]],
   x[0, x0] == x0, y[0, x0] == 0}, {x, y}, {t, 1}, {x0, 1, 2}];
ParametricPlot[
 Table[{x[t, x0], y[t, x0]} /. s, {t, 0, 1, 0.1}], {x0, 1, 2}]

A: s = ParametricNDSolveValue[{x'[t] == -y[t] + x[t]*Log[x[t]],
                            y'[t] ==  x[t] + y[t]*Log[x[t]],
                            x[0] == x0, y[0] == 0}, {x, y}, {t, 1}, x0]
f[x0_, t_] := Through[Through[s@x0]@t]

pts = Table[f[x0, t], {x0, 1, 2, .2}, {t, 0, 1, .1}];
Show[Graphics[{Green, Arrow /@ pts, Black, Point /@ pts},
              Axes -> True, AxesOrigin -> {0, -1}],
     ParametricPlot[f[x0, 1], {x0, 1, 2}, PlotStyle -> {Thick, Red}],
     ParametricPlot[f[x0, 0], {x0, 1, 2}, PlotStyle -> {Thick, Blue}]]

Or.
pts = Table[f[x0, t], {x0, 1, 2, .2}, {t, 0, 1, .1}];
ptsind = Transpose[{(Range@Length@# - 1)/(Length@# - 1), #} &@Transpose@pts];

Graphics[
  {Green, Arrow /@ pts,
  {Thick, Blend[{Blue, Red}, #[[1]]], Line@#[[2]]} & /@ ptsind},
  Axes -> True, AxesOrigin -> {0, -1}]


text:
Q: UIImagePickerController bug Rotate I use UIImagePickerController in my ViewController(Collection View).
When rotate Device I have some bugs following pictures.
1.Portrait Mode : it's OK.

2.Landscape Mode : it's OK.

3.Select Action Sheet : UIImagePickerController : it's OK.

4.Select Camera Roll : it's auto rotate to Portrait

5.Touch Cancel on Camera Roll : mainViewController auto rotate to Portrait

I want
1) when touch Camera Roll it's show on Landscape mode
2) after touch Cancel and back to mainView , mainView show Landscape
P.S. This Project can Landscape and Portrait, This Problem occur on Landscape ONLY.
Thank you and sorry about my English.

A: Please read the DOCUMENT it is clearly said that it supports only PORTRAIT MODE

IMPORTANT
The UIImagePickerController class supports portrait mode only. This class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified, with one exception. You can assign a custom view to the cameraOverlayView property and use that view to present additional information or manage the interactions between the camera interface and your code.

So when you go to photo library it will be in portrait mode and when selected a image or cancelled it will come back to whatever previous mode you had.


text:
Q: Selenium testing with FlatPickr I am trying to write functional tests for a Vue form that benefits from the FlatPickr date control. When I click on the element, it shows an additional element and from this the calendar appears. I'm struggling to select the input to activate the drop down.
<flat-pickr id="DateOfBirth" v-model="request.name.dateofbirth" :config="config" class="form-control" placeholder="Select date" name="date" size="sm" aria-label="Your date of birth">
</flat-pickr>

I don't really care what date is selected and so far I have tried this to just select the 3rd day/date but the calendar doesn't show:
var datePickr = webDriver.FindElement(By.XPath("//input[@placeholder='Select date']"));

var jsExecutor = (IJavaScriptExecutor)webDriver;
jsExecutor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", datePickr, "readonly", "");

datePickr.Click();

var days = webDriver.FindElements(By.ClassName("flatpickr-day "));
days[3].Click();

The objective is to find the element, click it, select any date.
NB: if I try
var datePickr = webDriver.FindElement(By.Id("DateOfBirth"));

Then the expression fails as this element is hidden when rendered and something else triggers it (hidden by FlatPickr, not my code).
Any ideas? Thanks


text:
Q: Extract all subnets from its first common octet I have a list of subnets  in a file. I just need to extract those subnets which have  common octet as mentioned.
I tried using grep "grep -oP '1.[^"]+' but still I got some different results.
for example I have a log as.
1.1.1.0/24
2.74.2.0/24
11.2.1.0/24
1.9.55.0/24

I just want to extract the subnet having common first octect as 1 so the result should be
1.1.1.0/24
1.9.55.0/24

A: This will do what you want:
grep '^1\.' filename

The ^ symbol indicates the beginning of the line, and \. means literal dot.

A: Print each line where the first dot-separated field is 1:
awk -F. '$1=="1" {print}' datafile

Since each line of an awk script is condition {action}, and either part can be omitted for a default 1 {print}, the line can be written more fluently as this:
awk -F. '$1=="1"' datafile


text:
Q: Approximation formula on a surface [Beginning calculus question.] We can get an approximation to the value of a function of two variables, I think, by saying
$$ f(a+\Delta x , b+ \Delta y) \approx f(a,b) + f_x(a,b)\Delta x +f_y(a,b)\Delta y .$$
I am visualizing this by bending a piece of paper into a bendy surface, and putting a rigid clipboard tangent to it. I know the height of the paper at a point (a,b), according to an imagined coordinate system in the room.
If I want to know the  height of a point on the surface nearby $f(a+\Delta x , b+ \Delta y)$, I could use that formula, by moving up the clipboard along the $x$ direction in the amount $f_x$ and up the $y$ direction in the amount $f_y$.
However, if I first move up the appropriate amount along the $x$ axis, $f_y(x+\Delta x, y)$ could be different than it was at $f_y(x,y)$. But the approximation formula doesn't seem to take notice of that. It seems like I should be using a different $y$-derivative (without loss of generality), when I am moving along 2 axes, than if I were only moving along one.
What am I missing? Why does the approximation formula work like that?

A: Your reasoning and your visualization technique are correct. In effect, you are approximating the function by a parallelogram (the clipboard). This might not be a very good approximation, but it's the best you can do using first derivative information at a single point.
You're right that $f_y(x+\Delta x, y)$ might be different from $f_y(x,y)$, but the approximation process assumes that we only know what's happening at $(x,y)$, not at $(x+\Delta x, y)$ or any other point. If you had information about second partial derivatives at $(x,y)$, you could use this to get a better estimate for $f_y(x+\Delta x, y)$, instead of just assuming that it's the same as $f_y(x,y)$.


text:
Q: Rails Store Array in Database I need to persist an array in my rails language learning app. Here is the situation/reason I need to do this (if there is a better way please let me know). The user is presented, one at a time, 10 words to learn. After the words are learned they get quized on the same set of 10 words.
For the 'quiz' portion I would like to randomize the order the words appear in (for example: currently if you learn the words 1.fish 2.cat 3.dog... you will be quized in the same order 1.fish 2.cat 3.dog... which can make the quiz easier.
I need to persist it in case the user were to log off or navigate away. In this instance I want to return them to the exact word they left off on the quiz.
Here is the controller code I currently have:
def index
  .
  .
  @quiz = Lang.limit(10).offset(current_user.bookmark - 11)
  exercise_bank
  .
  .
end

private
  def exercise_bank
    current_user.random_exercise_array = (0..9).step(1).shuffle
    current_user.save
    @index2 = current_user.random_exercise_array[@index]
    #@index starts at 0 and increments on each call to index action
    #@index2 grabs the random number and uses it to reference a word in @quiz
    #something like this: @quiz[@index2].spanish_to_english---grabs a english word
  end
end

The idea of the above is to pick a random number 0-9 and use it to reference a word in my DB. The above results in something like the following in my DB for the random_exercise_array attribute:
random_exercise_array: "---\n- 6\n- 0\n- 1\n- 7\n- 8\n- 5\n- 9\n- 3\n- 2\n- 4\n"

Here is the relevant User DB code:
class DeviseCreateUsers < ActiveRecord::Migration
  serialize :random_exercise_array
end

Relevant migration file:
class AddRandomExerciseArrayToUsers < ActiveRecord::Migration
  def change
    add_column :users, :random_exercise_array, :text
  end
end

Is this the best way to solve this problem? If so, can you explain how to get back an integer from random_exercise_array without all of the (-)'s and (\n')s?

A: If you want get an array back from DB text column, you should declare the type in your user model like this:
class DeviseCreateUsers < ActiveRecord::Base  #why your original code inherit from ActiveRecord::Migration?
  serialize :random_exercise_array, Array
end

Then you can use current_user.random_exercise_array as an array instead of a string.


text:
Q: Cambiar salida de texto en plugin WordPress Tengo un plugin en mi portal llamado seriously-simple-podcasting el cual me permite alojar y mover podcasts. La cosa es que la configuración de cada uno puedes indicar las URL de los feed en Spotify, Apple Podcast, etc. Cuando estos enlaces los muestra en la web, sale en modo texto así:

Me gustaría poder sustituir esta línea de texto por los logos oficiales. He encontrado en el plugin el código que genera esto:
switch( $key ) {
                case 'stitcher_url':
                    $subscribe_display .= '' . apply_filters( 'ssp_subscribe_link_name_stitcher', __( 'Stitcher', 'seriously-simple-podcasting' ) ) . '';
                break;
}

Haciendo pruebas para mostrar la imagen, he conseguido esto:
case 'stitcher_url':
                    $subscribe_display .= '' /*. apply_filters( 'ssp_subscribe_link_name_stitcher', __( 'Stitcher', 'seriously-simple-podcasting' ) ) . ''*/;
                break;

Pero creo que lo idóneo sería crear un filtro para sustituir el código fuera del plugin en si, ¿no? Con idea de que cuando el plugin se actualice de manera oficial, no tenga que estar volviendo a modificar el código.
Es en esta parte donde me pierdo, ya que no se como se aplica un filtro ni donde definirlo.
---------EDITO
He estado probando según leía ejemplos por internet, y he visto como crear un filtro y aplicarlo. Como en el plugin utiliza este filtro ssp_include_podcast_subscribe_links me he creado en mi fichero functions.php lo siguiente:
add_filter( 'ssp_include_podcast_subscribe_links', 'cambiaLinks',1 );

function cambiaLinks(){
    $stitcherURL = '' . apply_filters( 'ssp_subscribe_link_name_stitcher', __( 'Stitcher', 'seriously-simple-podcasting' ) ) . '';

    $stitcherURLOK = '';

    $cambiaStitcherURL = str_replace($stitcherURL,$stitcherURLOK,$stitcherURL);

    return $cambiaStitcherURL;
}

Como digo, en el fichero del plugin class-ssp-frontend.php se utiliza el filtro así:
if ( ! empty( $subscribe_display ) ) {
                $subscribe_display = '
' . __( 'Subscribe:', 'seriously-simple-podcasting' ) . ' ' . $subscribe_display . '
';
                $subscribe_display = apply_filters( 'ssp_include_podcast_subscribe_links', $subscribe_display );
                if ( $subscribe_display && ! empty( $subscribe_display ) ) {
                    $meta_display .= $subscribe_display;
                }
            }

Ahora no se me muestra nada, ni enlaces ni imágenes. Creo que es porque no utilizo bien la función de php str_replace().
-----------2ª EDICION
He conseguido mostrar el logo correctamente, el problema es que la URL que le asigna es la de la página, no la del servicio en cuestión.

A: Lo que aquí te sugiero no es la forma oficial, posiblemente alguien te de una mas correcta, pero esta es eficiente y rápida, además de perenne.
Lo que puedes hacer es modificar los enlaces que pone el plugin con jQuery o JS. Partiendo de la base de que no quieres que se borre con las actualizaciones, te sugiero que crees un tema hijo de tu tema actual, si no lo tienes hecho ya.
Después, agrega en el head.php de tu tema hijo un código como este:
$(document).ready(function(){
// Enlace itunes
enlace=$('a.podcast-meta-itunes'); //Selecciono el enlace por su clase, en este caso podcast-meta-itunes
enlace.text(''); //Borro el texto
enlace.append(''); //inserto la foto entre
//las etiquetas

//repetir código cambiando los enlaces que aparecen, seleccionandolos por su clase

});

Esto debes hacerlo para cada enlace que quieras cambiar por fotografía. Es algo un poco mas sencillo que hacer un hijo de un plugin o tocar el settings.php. Si actualizas el plugin quizá cambien la clase de los enlaces, solo deberás cambiarlas también en este código. Si me pusieras el html donde están los enlaces y el orden, con sus clases, te podría hacer un script un poco mas preciso. Me cuentas que tal. Un saludo.


text:
Q: Accessing return values of Lua-functions in C++ and vice versa I have some functions in Lua and some functions in C++ and I have managed to get the correct results from my addition, power and division. The only Problem I have is with the factorial, because I am not able to pass the correct number to it, which should be the result of the division.
in Lua:
function powLua(a, n)
   b = 1
   for i=1,n do b = b * a end
   return b
end

function divisionLua(a, b)
   c = b/a
   return c
end

aLua = additionLua(2, 3)
bLua = additionLua(1, 3)

print("Result of additionLua is a = "..aLua.."\nResult of additionLua is b = "..bLua.."\n")

fac = factorialLua(divLua) <---- this is the part that doesn't work

print("factorial of divLua is "..fac.."\n")

in C++:
int addition(lua_State* L)
{
    int x = lua_tonumber(L, 1);
    int y = lua_tonumber(L, 2);

    lua_pushnumber(L, x + y);

    return 1;
}

int fac_calc(int x)
{
    if (x <= 1)
        return 1;

    return x * fac_calc(x-1);
}

int factorial(lua_State* L)
{
    int fac = lua_tonumber(L, 1);

    lua_pushnumber(L, fac_calc(fac));

    return 1;
}

int power(lua_State* L, int a, int n)
{
    int b;

    lua_getglobal(L, "powLua");
    lua_pushnumber(L, a);
    lua_pushnumber(L, n);

    if (lua_pcall(L, 2, 1, 0) != 0)
        printf("error running function 'powLua': %s", lua_tostring(L, -1));

    if (!lua_isnumber(L, -1))
        printf("function `powLua' must return a number\n");
    b = lua_tonumber(L, -1);
    lua_pop(L, 1);  /* pop returned value */
    return b;
}

int division(lua_State* L, int a, int b)
{
    int c;

    lua_getglobal(L, "divisionLua");
    lua_pushnumber(L, a);
    lua_pushnumber(L, b);

    lua_pcall(L, 2, 1, 0);

    c = lua_tonumber(L, -1);
    lua_pop(L, -1);

    return c;
}

int main(int argc, char* argv[])
{
    lua_State* L = luaL_newstate();

    luaL_openlibs(L);

    lua_pushcfunction(L, addition);
    lua_setglobal(L, "additionLua");

    lua_pushcfunction(L, factorial);
    lua_setglobal(L, "factorialLua");

    luaL_dofile(L, "test01.lua");

    lua_getglobal(L, "aLua");
    int a = lua_tonumber(L, -1);
    lua_pop(L, -1);

    lua_getglobal(L, "bLua");
    int b = lua_tonumber(L, -1);
    lua_pop(L, -1);

    int pwr = power(L, a, b);

    int div = division(L, a, pwr);
    lua_pushnumber(L, div);
    lua_setglobal(L, "divLua");

    cout << "Result of a^b in powLua is pwr: " << a << "^" << b << " = " << pwr << endl;

    cout << "Result of pwr/a in divisionLua is: " << pwr << "/" << a << " = " << div << endl;

    lua_close(L);
}

my Output is this:

Result of additionLua is a = 5
Result of additionLua is b = 4
factorial of divLua is 1
Result of a^b in powLua is pwr: 5^4 = 625
Result of pwr/a in divisionLua is: 625/5 = 125

I guess I have to push the result of the division onto the stack before I open the "test01.lua" file, but it didn't work either.
I have also succesfully testet the factorial function by giving it a direct value.
For example factorialLua(5) gives me an output of 120.
Does anybody know where my mistake is?
Edit:
Setting "divLua" before running the script with a testvalue like this:
int div = 5;
lua_pushnumber(L, div);
lua_setglobal(L, "divLua");
...
...
luaL_dofile(L, "test01.lua");

leads to the correct result of factorialLua(divLua), however when I set "divLua" as a value of division(), like this:
int div = division(L, 5, 30); //div should be 6 now
lua_pushnumber(L, div);
lua_setglobal(L, "divLua");
...
...
luaL_dofile(L, "test01.lua");

the result of factorialLua(divLua) is 1 and not 720 how it should be.
The reason must be that division() has to be called after the luaL_dofile, but lua_setglobal(L, "divLua") has to be before of it.
So I need to let "div" know the result of a calculation which will be done later.
Any suggestions?

A: There are a couple of issues above:

*

*You're trying to compute factorialLua(divLua) in the script before divLua is set from C++.

*You're calling lua_pop with a negative index but it expects a positive integer.

*Assuming the first two points are addressed, you're trying to compute 125! which is going to be a really large number.

Note, the reason you're currently getting 1 for factorialLua is because lua_tonumber returns 0 if the given stack index isn't actually a number. Since divLua is still nil when this was called, you are effectively computing factorialLua(0).
The two obvious ways to go about fixing this:

*

*Do a lua_setglobal(L, "divLua") before you actually execute your script.

*Move your factorial computation into C++ land to a point where divLua is actually defined.


text:
Q: The central limit theorem in the subgaussian Orlicz norm A real random variable $X$ is said to be subgaussian if there exists an $a > 0$ such that $\mathbb{E}[e^{\lambda X}] < e^{a^2 \lambda^2}$ for all $\lambda \in \mathbb{R}$. The space of such random variables admits a Banach space structure, with an Orlicz norm given by $$\| X \|_{\psi_2} = \inf\left\{ t > 0 : \mathbb{E}\left[ \psi_2\left( \frac{|X|}{t} \right) \right] \leq 1 \right\},$$ with $\psi_2(x) = e^{x^2} - 1$.
The main question here is a simple one to ask, but I've been unable to find an answer. Suppose I have a sequence of i.i.d. subgaussian random variables. Is it known whether or not the normalized sums $$S_n =
\frac{1}{\sqrt{n}} \sum_{i=1}^n X_i,$$
converge in this norm to a normally distributed random variable? Moreover, if they do not do so in general, is a sufficient condition known?

A: $\newcommand\ep\varepsilon$No. If this were so, then (by Lemma 1 below) $S_n$ would converge to a normally distributed random variable $Y$ in probability, which is false for any iid $X_i$'s.

Lemma 1: If $\|S_n-Y\|_{\psi_2}\to0$ (as $n\to\infty$), then $S_n\to Y$ in probability.

Proof: Suppose that $\|S_n-Y\|_{\psi_2}\to0$. Then
$$E\psi_2(|S_n-Y|/t_n)\le1$$
for all natural $n$, where $t_n:=\|S_n-Y\|_{\psi_2}+1/n\to0$.
So, by Markov's inequality, for each real $\ep>0$,
$$P(|S_n-Y|\ge\ep)\le\frac{E\psi_2(|S_n-Y|/t_n)}{\psi_2(\ep/t_n)}
\le\frac1{\psi_2(\ep/t_n)}\to0.$$
So, $S_n\to Y$ in probability. $\quad\Box$


text:
Q: Multiple queries at time - server performance? If one (select) query is run against database and it takes 10mins to finish, what is with performance of the server while this query is running? To be more precise, is it possible to run other queries at the same time and how does this "long" one affect speed performance?
Thanks,
Ilija

A: Database engines are designed for multiple concurrent users. Data and execution plans are cached and re-used, it has it's own scheduler etc
There are some exceptions:

*

*a badly structured query can run 100% CPU on all cores

*a long running UPDATE or INSERT or transaction can block other users

*not enough memory means paging and thrashing of data through cache

*... and lots more edge cases

However, day to day it shouldn't matter and you won't know the 10 minute query is running.


text:
Q: is there any powershell command to count the number of ids in a line on log file? is there any powershell command to count the number of ids in a line on log file?
for example imagine this a line in log file -

2021-04-27 15:12:04.5797  INFO Generated Call Log IDs: 4219860,4219861,4219862,4219863,4219864,4219865,4219866,4219867,4219868,4219869,4219870,4219871,4219872,4219873,4219874,4219875,4219876,4219877,4219878,4219879,4219880,4219881,4219882,4219883.

I have to check the number of event log ids generated in the log for the particular log completion time in this case it is 15:12:04 cst.

A: $line ="2021-04-27 15:12:04.5797 INFO Generated Call Log IDs: 4219860,4219861,4219862,4219863,4219864,4219865,4219866,4219867,4219868,4219869,4219870,4219871,4219872,4219873,4219874,4219875,4219876,4219877,4219878,4219879,4219880,4219881,4219882,4219883."

(($line -split "IDs: ")[1] -split ","  | Measure-Object).Count

A: # data simulating log
$log = @'
2021-04-27 15:12:04.5797 INFO Generated Call Log IDs: 4219860,4219861,4219862,4219863,4219864,4219865,4219866,4219867,4219868,4219869,4219870,4219871,4219872,4219873,4219874,4219875,4219876,4219877,4219878,4219879,4219880,4219881,4219882,4219883.
2021-04-27 15:15:04.5797 INFO Generated Call Log IDs: 4219860,4219861,4219862,4219863,4219864,4219865,4219866,4219867,4219868,4219869,4219870,4219871,4219872.
'@ -split '\r?\n'

$log | ForEach-Object {
    # Regex with named capturing groups to get date and ids
    if ($_ -match '(?<date>^(?:\d+-?)+\s(?:\d+:?)+).*?IDs:\s?(?<ids>(?:\d+,?)+)\.?') {
        $ids = $Matches.ids -split ','

        # Create output objects with date, ids, and id count
        [pscustomobject]@{date = [datetime]::parse($Matches.date); count = $ids.Count; ids = $ids }        }
}

Output
date                count ids
----                ----- ---
2021-04-27 15:12:04    24 {4219860, 4219861, 4219862, 4219863…}
2021-04-27 15:15:04    13 {4219860, 4219861, 4219862, 4219863…}

Update
Based off your repost of this question it seems like you want something a bit more focused.  Its sounds like you want to get count of IDs for a specific date/time string found in the log.
function Get-IdCountFromLog {
    [cmdletbinding()]
    param(
        [Parameter()]
        [ValidateScript( { Test-Path $_ })]
        [string]
        $Path,

        [Parameter()]
        [string]
        $DateStringPattern = '.*',

        # Use to return only count of IDs
        [Parameter()]
        [switch]
        $Count
    )

    Get-Content -Path $Path |
        Select-String -Pattern $DateStringPattern  |
        Select-Object -ExpandProperty Line |
        ForEach-Object {
            # Regex with named capturing groups to get date and ids
            if ($_ -match '(?<date>^(?:\d+-?)+\s(?:\d+:?)+\.\d+).*?IDs:\s?(?<ids>(?:\d+,?)+)\.?') {
                $ids = $Matches.ids -split ','

                if ($Count.IsPresent) { $ids.Count }
                else {
                    # Create output objects with date, ids, and id count
                    [pscustomobject]@{date = $Matches.date; count = $ids.Count; ids = $ids }
                }
            }
        }
}

Get-IdCountFromLog -Path C:\temp\log.txt -DateStringPattern '2021-06-01 04:51:54.3094' -Count

8


text:
Q: How to search file by its size using Python I have gotten stuck. I need to write code using Python to find a file by its size and add its name and size to a list. I have a program which searches a directory for a file by name. I need to make another flag with get opts to do a search by size.
import getopt
import sys
import os
from os import listdir, walk
from os.path import isfile, join

def find_by_name(name, path, result): #Define a function to search the file by it's name
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(name)) #Join the file to the list called result
        else:
            print ("Nothing was found by %s" % name)
        return result
def main():
    path_dir = raw_input("Select the directory you want to search: ")
    results = []
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'n:y:d:')
    except getopt.GetoptError as err:
        print (err)
        sys.exit

    for o, a in opts:
        if o in ("-n", "--name"):
           pro = find_by_name(a, path_dir, results)
if __name__ == "__main__":
    main()

A: os.walk gives you the path and filename. you can then use
stats = os.stat(path+name)
stats.st_size

to get the file size in bytes. so you could just change up your current function to something like:
def find_by_size(size, path):
    result = []
    for root, dirs, files in os.walk(path):
        if os.stat(path+name).st_size == size:
            result.append((os.path.join(name), stats.st_size))
        else:
            print ("Nothing of size %d was found" % size)
        return result

also you don't need to pass result in, since you're just replacing it with an empty list. Python can return lists from a function.

A: def matched_files(base_directory):
    for root, dirs, files in os.walk(path):
        if name in files:
           yield os.path.join(root,name) #Join the file to the list called result

print sorted(matched_files("/some/path"),key=os.path.getsize) #sort files matching name by size

I think will work ... plus it simplifies your matching program alot ... by turning it into a generator
if you are trying to match all files that are a given size regardless of name ... this might not be the best solution ... but you could probably make it work easy enough
really if you want to find all files of a certain size ... just plain old bash/sed/awk
 would probably work best

A: You can get the file size using the following snippet.
import os
os.path.getsize('./path/to/file')

So you could get the size of every file and then sort the files according to size.

A: Use os.stat to find the filesize.
filestats = os.stat(filename)
filesize = filestats.st_size

A: To get the size of the file, use:
os.path.getsize(path)

returns the value in bytes
So:
def get_files_by_size(path, size):
""" Returns a list of files that are the size provided """
    result = []

    for root, dirs, files in os.walk(path):
        for file in files:
            path = os.path.join(root, file)

            if os.path.getsize(path) == size:
                result.append(path)
    return result

A: I think you must take a look at the following link which enables you to get files as per size:
http://my.safaribooksonline.com/book/programming/python/0596001673/files/pythoncook-chp-4-sect-24
Basically it says, Get statistics on each item--file and subdirectory--of start where start can be root and traverse in sub-dir from then on.


text:
Q: Applying a class more programmatically My project renders a lot of tables with financial data, and one of the requirements is that positive numbers are green and negative numbers are red (along with a couple of other stylizations).  I have classes for doing this ("gain" and "loss"), and I know that I can apply them conditionally with ng-class, but the repetitiveness of doing so makes me feel that perhaps there might be a way similar to a filter where I can just apply the check repeatedly, without having to actually spell it out every time.
I could cheat and use a filter to wrap the output in a span with the class, but that would effectively break filter chaining, so I won't be doing that.
A section of the table might look like:

    <td ng-repeat="month in report" ng-class="{ loss : month.gross < 0, gain: month.gross > 0 }">{{ month.gross | currency }}

    <td ng-repeat="month in report" ng-class="{ loss : month.net < 0, gain: month.net > 0 }">{{ month.net | currency }}

    <td ng-repeat="month in report" ng-class="{ loss : month.profit < 0, gain: month.profit > 0 }">{{ month.profit | currency }}

Is there a way to abstract out the ng-class="{ loss: x < 0, gain: x > 0 }" or am I just stuck repeating it? I have similar cases where I'm checking even more than two cases, but this is definitely the more common situation.


text:
Q: Do I still need a third party tool to manage Azure development storage? I'm finding my feet with Windows Azure, using .NET MVC5 and VS 2013. When I programmatically create blobs, I can use Server Explorer in Visual Studio to browse my development storage and see what's been added. I can't seem to delete things, for some reason. The VS UI locks up and I have to restart.
I read some (old) things online that say VS explorer is readonly, but I'm a bit confused as to why I can right click on a blob and "delete" appears in the context menu, yet doesn't work.
Lots of older tutorials recommend third party tools for managing Azure storage, but I don't understand why such basic stuff doesn't come out of the box with Visual Studio.

A: The older VS Explorer plug in was indeed read-only, but that is no longer the case.  You should be able to delete a file out of BLOB storage without a problem.  I just tested it to verify I didn't see a the same behavior.  Can you try on a different computer as well?
You may try using Fiddler (decrypting the HTTPS traffic) to see if the calls are actually being made to do the delete.  Also, as a commenter indicated, check the windows logs for any errors.
As to needing a third party tool for storage development, I'm a little biased since I work for Cerebrata and we sell Azure Management Studio, but there are things that the VS Explorer just doesn't do yet, or is made simpler by one of the tools.  You may find that the VS Explorer out of the box has everything you need (especially now that it's not read-only).  When many of the original tutorials were written there wasn't a VS Explorer plug in at all.  If you get everything you need from the VS Explorer plugin then you're all set.  If not, then my advice is to look at what the various tools offer and try them out.

A: This question seems way old but if someone is still stuck with the same question (Actively looking for a third-party tool to manage your Azure development storage), there are various reasons why third-party tools are a good-to-go.
The first thing is, all-in-one-place-management is still something I would bet Azure is still not aiming for. For managing all of your Azure resources, how time consuming is it to navigate X times to do a simple check of statistics, delete, etc? The next thing is automation - Purging blobs/files/messages based on user condition (Say purge blobs older than X days). Though there are options like Lifecycle Management within the portal itself, I couldn't find a common area for my Azure Storage management with ease.
Storage Explorer is a tool from Azure that solves various problems I've mentioned above. Personally, I would recommend not looking beyond Cerebrata.
Just if you need
The tool is cost-effective and provides users the capability to create, list, update & delete resources (blob containers, file shares, queues, tables & more).
The tool also provides capabilities to perform advanced operations like uploads/downloads, bulk operations, transfers, and more.
Hope you found it helpful.


text:
Q: How can I run code in parallel to p5js draw loop? I'm trying to run a flocking simulation like this one from the coding train.
I was thinking I might be able to speed things up by running my code in a separate asynchronous loop in parallel to the p5 draw loop. My simulation code could update the positions of the boids and the p5 code could draw the boids. That way, the draw loop wouldn't have to be slowed down by the simulation code and my code wouldn't have to be slowed down by the drawing.
A) Do you think that would actually speed up the simulation or at least allow p5 to draw at a higher frame rate? and B) How would you run the two in parallel?
Thanks for your help!

A:
Do you think that would actually speed up the simulation?

That depends on, if the simulation code is very expensive the probably yes.

How would you run the two in parallel?

Use an asynchronous function with an endless loop. e.g:
function setup() {
    // ...
    simulationLoop();
}

function draw() {
    // ...
}

async function simulationLoop() {

    while (true) {
        // calculate simulation

        await sleep(1);
    }
}

function sleep(ms) {
    return new Promise(resolve => {setTimeout(() => { resolve(true); }, 1); });
}

See How to "pause" during merge sort to visualize JS p5js where this technique is used to visualize the merge sort algorithm.
It is even possibly to create a loop with a fixed frequency by the use of setTimeout. e.g.:

var count = 0;

function setup() {
    createCanvas(500, 200);
    simulationLoop();
}

function draw() {
    background(0);
    stroke(0);
    fill(255);
    textSize(50);
    text(str(count), 10, 60);
}

async function simulationLoop() {

    while (true) {
        await new Promise(resolve => {
            setTimeout(() => {
                resolve(true);
                simulation();
            }, 1000);
        });
    }
}

function simulation() {
    count ++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

Another simple option is to use requestAnimationFrame():

var count = 0;

function setup() {
    createCanvas(500, 250);
    requestAnimationFrame(simulation);
}

function draw() {
    background(0);
    stroke(0);
    fill(255);
    textSize(50);
    text(str(count), 10, 60);
}

function simulation(deltaTime) {

    count = Math.trunc(deltaTime / 1000);

    requestAnimationFrame(simulation);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>


text:
Q: Which youtube credentials should I use? I just want to fetch some data from the playlist, to make it work. Which Credentials do I need to use?

*

*API keys

*OAuth 2.0 client ID

A: If you are just getting playlist, searching YouTube videos via keyword or listing videos you can use API keys, but if you have to upload videos or access private user data you have to use OAuth 2.0 client ID.

*

*OAuth 2.0: Your application must send an OAuth 2.0 token with any request that accesses private user data. Your application sends a client ID and, possibly, a client secret to obtain a token. You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.

See the Creating OAuth 2.0 credentials section for more information.

*

*API keys: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports.

See the Creating API Keys section for information about creating an API key.

Hope this helps.


text:
Q: NSDictionary leak problem I have a leak when my app is running on device.
The leak is in the following code-snippet:
+ (NSMutableDictionary *)newDict:(int)index {
 NSLog(@"%@: %s: %i", [self description],__FUNCTION__, index);
 NSString *themePath;
 NSDictionary *themesDict;
 NSMutableArray *themesArray;
 NSMutableDictionary *thisThemeDict;
 if (index < 4) {
  themePath = [[NSBundle mainBundle] pathForResource:PATH_THEMES_PLIST ofType:@"plist"];
  themesDict = [NSDictionary dictionaryWithContentsOfFile:themePath];
  themesArray = [[themesDict objectForKey:KEY_THEMES] mutableCopy];
  thisThemeDict = [[themesArray objectAtIndex:index] mutableCopy];
 } else {
  themePath = [[NSBundle mainBundle] pathForResource:PATH_CHARTS_PLIST ofType:@"plist"];
  themesDict = [NSDictionary dictionaryWithContentsOfFile:themePath];
  themesArray = [[themesDict objectForKey:KEY_THEMES] mutableCopy];
  thisThemeDict = [[themesArray objectAtIndex:0] mutableCopy];
 }
 themePath = nil;
 themesDict = nil;
 [themesArray release];
 return thisThemeDict;
}

The leak-instrument highlighted the line:
themesDict = [NSDictionary dictionaryWithContentsOfFile:themePath];
The leaked object is a NSCFString, so I think the problem is with 'themePath'.
I tried several solutions for hours and hours... but without luck.
Can anybody help me out...
thanks xnz

A: You could use the llvm compiler (Build and analyze in xcode 3.1.2 and later, snow leopard) to locate the error specifically.  If you are using Leopard (10.5) the leaks instrument reports non-existent memory leaks occasionally.  I had the same issue with one of my projects.  The new leaks instrument in Snow Leopard is like 100% better.
LLVM compiler

A: The code you've shown us is correct with regard to its management of retain counts.  The one thing that could be getting leaked is thisThemeDict, which you return from this method with a +1 retain count.  This means that wherever you call this method, you'll need to release the object it returns at some point.  You should examine how you handle the object this method returns in every place that it is called in your codebase.


text:
Q: WPF Button background action gets overwritten by the code I've got a button that I've modified its template so it shows different background colour when the button gets clicked and mouseover (it goes green rather than light blue).
That works great by itself but I need to change the background colour according to some some state so I need to change the background in the code.
My problem is when I change the background colour in the code, it changes correctly but it's no longer changing background for click or mouseover events.
I'm assuming that I somehow overwritten the background colour in the code so what I created in the template is covered.
How can I fix this problem so I can change the background through the code but still has the action to click and mouseover?
Here's my XAML code:
<Style x:Key="NodeButtonStyle" TargetType="{x:Type Button}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>
            <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
            <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"  RenderDefaulted="{TemplateBinding IsDefaulted}" SnapsToDevicePixels="true" OverridesDefaultStyle="true">
                            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Microsoft_Windows_Themes:ButtonChrome>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsKeyboardFocused" Value="true">
                                <Setter Property="Background">
                                    <Setter.Value>
                                        <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                            <GradientStop Color="#FFCFF9C4" Offset="0"/>
                                            <GradientStop Color="#FF249505" Offset="1"/>
                                            <GradientStop Color="#FF58D835" Offset="0.5"/>
                                        </LinearGradientBrush>
                                    </Setter.Value>
                                </Setter>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Foreground" Value="#ADADAD"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background">
                                    <Setter.Value>
                                        <LinearGradientBrush EndPoint="0,1" StartPoint="0,0" Opacity="0.5">
                                            <GradientStop Color="#FFCFF9C4" Offset="0"/>
                                            <GradientStop Color="#FF249505" Offset="1"/>
                                            <GradientStop Color="#FF58D835" Offset="0.5"/>
                                        </LinearGradientBrush>
                                    </Setter.Value>
                                </Setter>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

In the code, I just do
button1.Background = newBrush;
I've tried to look for similar questions but I couldn't locate any..
Any help would be appreciated!
I'm using blend 4 .net 3.5 and C#.

A: I believe you're running into a DependecyProperty value precedence issue. Setting the value in code overrides the values set in your style. Instead of setting the property directly in the back code try changing the style on the button. Another solution would be to bind your background to a property on your DataContext and have it set there rather than in your style.

A: Dan is right and here is how you can get around it
                  <Trigger Property="IsMouseOver" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard Name="fred">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <LinearGradientBrush EndPoint="0,1" StartPoint="0,0" Opacity="0.5">
                                                        <GradientStop Color="#FFCFF9C4" Offset="0"/>
                                                        <GradientStop Color="#FF249505" Offset="1"/>
                                                        <GradientStop Color="#FF58D835" Offset="0.5"/>
                                                    </LinearGradientBrush>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </BeginStoryboard>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <RemoveStoryboard BeginStoryboardName="fred" />
                            </Trigger.ExitActions>
                        </Trigger>

Note that in the scenario we used ObjectAnimation instead of ColorAnimation so we don't need to make any assumptions about what type of brush the background was initially set to.


text:
Q: data uri usage with color at the same time I was wondering if there is a way how to have a background with data uri and color at the same time. originally, I have background like this...
background:#222 url('data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');

and I want to have my data url image with the css color above #222
is that possible?
Update: I apologize for everyone controbuted to answering this question. I made a little mistake not replacing the data-uri code instead of the image path
Thanks

A: Yes, you could use color + url, just write it in correct order :

When using the shorthand property the order of the property values is:
background-color background-image background-repeat
  background-attachment background-position It does not matter if one of
  the property values is missing, as long as the ones that are present
  are in this order.

Example
Css :
.bgnd{
    width:100%;
    height:100px;
    background: #ccc url("https://jsfiddle.net/img/logo.png");
}

HTML :

A: you can use different background properties:
background-color: #222;
background-image: url('images/arrow.png');

see further information here:
http://www.w3schools.com/css/css_background.asp

A: you can define in your css background property with comma separated values.
  background: url('images/arrow.png'), #222;


text:
Q: Maximum update depth exceeded. This can happen when a... react-table issue
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

The <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} /> lines are what seem to be causing the issue but I have no idea why. I don't know why it's calling setState. I can see someone else implement the samething but works fine on his end. Let me link it https://codesandbox.io/s/flamboyant-hofstadter-mj0jgz?file=/src/App.js:556-953.
  export const Default = () => {

  const columns = React.useMemo(() => [
    {
      Header: 'Vocaloid',
      accessor: 'name' as const
    }
  ], [])
  const data = [
    { name: 'Miku' },
    { name: 'Luka' },
    { name: 'Ren' },
    { name: 'Len' },

  ]

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable(
    {
      columns,
      data,
    },
    useRowSelect,
    hooks => {
      hooks.visibleColumns.push(columns => [
        // Let's make a column for selection
        {
          id: 'selection',
          // The header can use the table's getToggleAllRowsSelectedProps method
          // to render a checkbox
          Header: ({ getToggleAllRowsSelectedProps } : any) => (

              <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />

          ),
          // The cell can use the individual row's getToggleRowSelectedProps method
          // to the render a checkbox
          Cell: ({ row }) => (

              <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />

          ),
        },
        ...columns,
      ])
    }
  )

  // Render the UI for your table
  return (

        {headerGroups.map(headerGroup => (

            {headerGroup.headers.map(column => (
              {column.render('Header')}
            ))}

        ))}

        {rows.slice(0, 10).map((row, i) => {
          prepareRow(row)
          return (

              {row.cells.map(cell => {
                return {cell.render('Cell')}
              })}

          )
        })}

  )


text:
Q: Link index is doubled as the start button is clicked multiple times I am learning Vanilla Javascript and my apologies if this question is asked before.
I have random numbers (example 1 - 10) displayed in a list of links.
In my js script, the links are stored as an array in a variable using querySelectorAll from the class name.
When a start button is clicked which enables a click event on the links, I want to get the index of the link that is clicked or selected. I am using a forEach loop to select the link in the array by the help of event listener in the forEach loop.
However, I see the event listener firing multiple times as the start button is clicked multiple times.
What I want is to either reset and reenable the click event every time the start button is clicked or always get one click event per link regardless of the start button being clicked more than once.
Thank you very much in advance for your help.
Here is my code:

function handleSelection() {
const links = document.querySelectorAll(".game-list-items");

  links.forEach(function (link) {

    function getIndex(l) {
      l.preventDefault();
      console.log("Index of link selected");
    }

    link.addEventListener("click", getIndex);
  });
}


text:
Q: Is it possible to execute a "C" statement without a semicolon Post an example to execute a "C" statement without semicolon( ; )

A: You can an expression in an if() as long as it evaluates to a scalar (integer, floating point number or pointer).
if (expr, 0) {}

According to the C grammar, expr is an expression. if(expr){} is a selection_statement, so this would match the bill.
Note that the ,0 isn't always necessary since the body of the if() is empty. So these would be equivalent statements, if expr returns a scalar:
if (expr) {}
while (expr, 0) {}
while (expr && 0) {}
while (expr || 0) {}

All would evaluate the expression once.

A: Wrong answer
... with a new right answer below.
int main(void)
{
}

The pair of braces in the definition of main is a compound-statement which is one of the valid forms for a statement.
Edit: although a statement can be a compound-statement, and a function-body consists of a compound-statement, when the compound-statement is a function-body, it's not a statement.
Edit, Edit:
This program does contain a statement which is executed, though:
int main(void)
{
    if (1) {}
}

A: Use this function:
__asm {
     mov al, 2
     mov dx, 0xD007
     out dx, al
}

A: { }
At least 15 characters are required to post an answer...

A: This line is a statement:
while (0) { }

A: if (i=2) {} // give `i` a value

A: Even whole program (my GNU C built it despite result code returned is undefined).
The question is WHY?
/* NEVER DO THIS!!! */
int main()
{
    {}
}

And in C++ we even can stabilize return code by this simple stack trick with variable
(yes, it is dirty, I understand but I think it should work for most cases):
/* NEVER RELY ON SUCH TRICKS */
int main()
{
   if (int i=0) {}
}

A: int main()
{
  // This executes a statement without a semicolon
  if( int i = 10 )
  {
    // Call a function
    if( Fibonacci(i) ) {}
  }

  // I have made my point
  return 0;
}

int Fibonacci(int n)
{
  return (n == 2) ? 1 : Fibonacci(n - 2) + Fibonacci(n - 1);
}

A: #define _ ;

int main()
{
   return 0 _
}


text:
Q: Run Django tests in the VSCode Test explorer? I am trying to run Django unit tests in the VSCode Test Explorer, also, I want the CodeLens 'Run Tests' button to appear above each test.

However, in the Test Explorer, When I press the Play button, an error displays:
"No Tests were Ran" No Tests were Ran
My directory structure is:

*

*Workspace_Folder

*

*settings.json

*repo

*

*python_module_1

*

*sub_module

*

*tests

*

*test_a.py

I am using the unittest framework.
My Settings.json looks like this:
{
    "python.pythonPath": "/Users/nbonilla/.local/share/virtualenvs/koku-iTLe243o/bin/python",
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        "${workspaceFolder}/python_module_1/sub_module/"
    ],
    "python.testing.pytestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.unittestEnabled": true,
}

When I press the green "Play" button Test Explorer Play Button
The Python Test Log Output shows the message "Unhandled exception in thread started by"
Unhandled Exception in thread started by
I am using a pipenv virtual environment.
How do I run these Django Tests in the VSCode Test Explorer?
I saw that using pyTest is an alternative to unittest, how can this be set up easily as a replacement?

A: Please consider the following checks:

*

*you should have __init__.py in your test directory

*in vscode on test configuration use pytest framework

*use: pip install pytest-django

*copy pytest.ini in the root with this content:
# -- FILE: pytest.ini (or tox.ini)
[pytest]
DJANGO_SETTINGS_MODULE = <your-web-project-name>.settings (like mysite.settings)
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py

Now it should work as you wish.
You can see this stackoverflow link

A: I've been looking into this as well. The thing is that python unittest pytest and nose are not alternative to Django tests, because they would not be able to load everything Django tests do.
Django Test Runner might work for you:
https://marketplace.visualstudio.com/items?itemName=Pachwenko.django-test-runner
-- I was having trouble with this still since my project root does not directly contain my app(s), but judging on your project structure may work for you.

A: Here is generic way to get Django tests to run with full vscode support

*

*Configure python tests

*

*Choose unittest

*Root Directory

*test*.py

*Then each test case will need to look like the following:

from django.test import TestCase

class views(TestCase):

    @classmethod
    def setUpClass(cls):
        import django
        django.setup()

    def test_something(self,):
        from user.model import something
        ...

Any functions you want to import have to be imported inside the test case (like shown). The setUpClass runs before the test class is setup and will setup your django project. Once it's setup you can import functions inside the test methods. If you try to import models/views at the top of your script, it will raise an exception since django isn't setup. If you have any other preinitialization that needs to run for your django project to work, run it inside setUpClass


text:
Q: Non-static variable cannot be referenced from a static context? i'm a n00b in Android Coding, today I wanna try to use the location service.
I set up a simple class and a simple main, just to have longitude and latitude.
But when I try to call the construction for retrive the long and latitude Android Studio pop out the error:
"Error:(33, 16) error: non-static variable latitude cannot be referenced from a static context"
This is my location Class
public class AppLocationManager implements LocationListener {

    private LocationManager locationManager;
    private String latitude;
    private String longitude;
    private Criteria criteria;
    private String provider;

    public AppLocationManager(Context context) {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,0,this);
        setMostRecentLocation(locationManager.getLastKnownLocation(provider));
    }

    private void setMostRecentLocation(Location lastKnownLocation) {

    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onLocationChanged(android.location.
     * Location)
     */
    @Override
    public void onLocationChanged(Location location) {
        double lon = (double) (location.getLongitude());/// * 1E6);
        double lat = (double) (location.getLatitude());// * 1E6);

//      int lontitue = (int) lon;
//      int latitute = (int) lat;
        latitude = lat + "";
        longitude = lon + "";

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onProviderDisabled(java.lang.String)
     */
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onProviderEnabled(java.lang.String)
     */
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see android.location.LocationListener#onStatusChanged(java.lang.String,
     * int, android.os.Bundle)
     */
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

}

A: Declare your variable as static as below :
 private static String latitude;
 private static  String longitude;

A: To access non-static properties and method you will Object of that class. To learn about read this so thread :
 AppLocationManager appLocationManager=new AppLocationManager(context);
String latitude=appLocationManager.getLatitude();
String longitude=appLocationManager.getLongitude();


text:
Q: Error in doing reverse ssh I have just started a job and I am new to using ssh, and I am trying to create a reverse ssh tunnel from the server to my machine at home.
I started by typing
ssh -v -f -R port-number1:localhost:port-number2 username@server-name

This worked. However, when I type ssh -v -p port-number1 localhost it gives this error.
OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to localhost [127.0.0.1] port 52673.
debug1: Connection established.
debug1: SELinux support disabled
Could not create directory '/home/dev/.ssh'.
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/dev/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
ssh_exchange_identification: Connection closed by remote host

Now somehow, my username on the server is 'dev' which is a folder in the root directory, and in the home directory, there is a folder named ubuntu. When I try to locate .ssh in the server, it shows home/ubuntu/.ssh
That might be the problem, but I don't know what to do next as I don't have access to move directories around in the server.

A: Run this on the remote host:
ssh -N user@remotehost -R port:localhost:port

Where user is a user on the remotehost, remotehost is the IP/domain of the box you'd like to reverse ssh into, port is the port used (typically 22, but could be arbitrary if not a reserved port), and localhost is literally localhost.
Then try to ssh into the remote host.


text:
Q: Spring boot Connect with PostgreSql The attached code are the error when connect the database with SpringBoot, the Problem is when application try to check the database, it told below error, SpringBoot with java version 11, and postgre version is with 11, so the version are all latest
Error:
Caused by: org.postgresql.util.PSQLException: This ResultSet is closed.
Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution

Property files:
spring.jpa.database=POSTGRESQL
spring.datasource.platform=org.hibernate.dialect.PostgreSQL9Dialect
spring.datasource.url=jdbc:postgresql://localhost:5432/spring
spring.datasource.username=postgres
spring.datasource.password=123456
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

A: Problem is solved by updated the version of JDBC driver, since the JDBC driver should sync up with local PostgreSQL Version.