text:
Q: Como leer una variable especifica de JSON en VB.net o C#? Lo que estoy haciendo con el botón es que estoy deserializar el JSON que esta escrito en el Txt_JSONString y muestra los datos que quiero ver en un datagridview1.
Codigo del boton:
Private Sub Btn_Process_Click(sender As Object, e As EventArgs) Handles Btn_Process.Click
Tablas()
Private Sub Tablas()
        Dim json As String = Txt_JSONString.Text

        Dim rs = JsonConvert.DeserializeObject(Of Root)(json)

        For Each panel In rs.Doors
            Dgv_Accessory.DataSource = panel.Accessory
            DataGridView1.DataSource = panel.Panel.Locks
        Next
    End Sub

para deserializar los datos cree un modulo de clases para deserializar a lista de clases. Que seria la siguiente:
Imports Newtonsoft.Json

Public Class ClsJson

    Public Class Accessory
        Public Property AccessoryType As String
        Public Property AccessorySelection As String
        Public Property Quantity As Integer
    End Class

    Public Class Door
        Public Property Panel As Panel
        Public Property Opening As List(Of Opening)
        Public Property DoorInfo As DoorInfo
        Public Property MiscInfo As MiscInfo
        Public Property Accessory As List(Of Accessory)
    End Class

    Public Class DoorInfo
        Public Property Type As String
        Public Property Construction As String
        Public Property HingePosition As String
        Public Property DoorInteriorFinish As String
        Public Property DoorExteriorFinish As String
        Public Property FloorType As String
        Public Property FloorEdgeThickness As Double
        Public Property FloorRecessDepth As Integer
        Public Property FloorlessTileDepth As Integer
        Public Property RoomTemperature As Integer
        Public Property IsOutdoorExposedWall As Boolean
        Public Property SwingType As String
        Public Property DrawingDescription As String
    End Class

    Public Class Lock
        Public Property Position As Position
        Public Property Edge As String
    End Class

    Public Class MiscInfo
        Public Property HardwareFinish As String
        Public Property TuffyDoor As Boolean
        Public Property SupportWheel As Boolean
        Public Property LightAboveDoor As Boolean
        Public Property PrisonPackage As Boolean
        Public Property ForceSill As Boolean
        Public Property TrackPort As Boolean
        Public Property DoorHeaters As Boolean
        Public Property FrameHeaters As Boolean
        Public Property LightExternal As Boolean
        Public Property NSFCutout As Boolean
        Public Property SSSill As Boolean
        Public Property RaiseDoor As Boolean
        Public Property HingeSpringKits As Boolean
        Public Property AddLocksToDoorOnPartitionWall As Boolean
        Public Property PRPLoc As String
        Public Property CloserLoc As String
        Public Property NumMangneticBreaks As Integer
    End Class

    Public Class Opening
        Public Property ClearOpeningWidth As Integer
        Public Property ClearOpeningHeight As Integer
        Public Property OpeningCentreWidthOffset As Integer
        Public Property OpeningCentreHeightOffset As Double
    End Class

    Public Class Panel
        Public Property PanelRef As String
        Public Property PanelWidth As Integer
        Public Property PanelHeight As Integer
        Public Property PanelThickness As Integer
        Public Property InternalFinish As String
        Public Property ExternalFinish As String
        Public Property LeftDetail As String
        Public Property RightDetail As String
        Public Property TopDetail As String
        Public Property BottomDetail As String
        Public Property Locks As List(Of Lock)
    End Class

    Public Class Position
        Public Property X As Double
        Public Property Y As Integer
        Public Property Z As Double
    End Class

    Public Class Root
        Public Property Doors As List(Of Door)
    End Class

End Class

lo que quiero resolver es que me muestre los valores de los position X,Y,Z  junto con los Edge en un datagridview que se veria algo parecido a la siguiente imagen

pero lo que me muestra mi codigo es lo siguiente

Este es el Archivo JSON que estoy usando:
{
  "Doors": [
    {
      "Panel": {
        "PanelRef": "J01",
        "PanelWidth": 46,
        "PanelHeight": 82,
        "PanelThickness": 4,
        "InternalFinish": "26ga Embossed Galvalume",
        "ExternalFinish": "26ga Embossed Galvalume",
        "LeftDetail": "Groove",
        "RightDetail": "Tongue",
        "TopDetail": "Tongue",
        "BottomDetail": "Tongue",
        "Locks": [
          {
            "Position": {
              "X": 17.25,
              "Y": 2,
              "Z": 82
            },
            "Edge": "LE_Top"
          },
          {
            "Position": {
              "X": 28.75,
              "Y": 2,
              "Z": 82
            },
            "Edge": "LE_Top"
          },
          {
            "Position": {
              "X": 46,
              "Y": 2,
              "Z": 5.75
            },
            "Edge": "LE_Right"
          },
          {
            "Position": {
              "X": 46,
              "Y": 2,
              "Z": 40.25
            },
            "Edge": "LE_Right"
          },
          {
            "Position": {
              "X": 46,
              "Y": 2,
              "Z": 74.75
            },
            "Edge": "LE_Right"
          },
          {
            "Position": {
              "X": 0,
              "Y": 2,
              "Z": 5.75
            },
            "Edge": "LE_Left"
          },
          {
            "Position": {
              "X": 0,
              "Y": 2,
              "Z": 40.25
            },
            "Edge": "LE_Left"
          },
          {
            "Position": {
              "X": 0,
              "Y": 2,
              "Z": 74.75
            },
            "Edge": "LE_Left"
          }
        ]
      },
      "Opening": [
        {
          "ClearOpeningWidth": 34,
          "ClearOpeningHeight": 77,
          "OpeningCentreWidthOffset": 23,
          "OpeningCentreHeightOffset": 38.5
        }
      ],
      "DoorInfo": {
        "Type": "Flush",
        "Construction": "FRP",
        "HingePosition": "Left",
        "DoorInteriorFinish": "26ga Embossed Galvalume",
        "DoorExteriorFinish": "26ga Embossed Galvalume",
        "FloorType": "Floor_Type_1",
        "FloorEdgeThickness": 4.5,
        "FloorRecessDepth": 0,
        "FloorlessTileDepth": 0,
        "RoomTemperature": 35,
        "IsOutdoorExposedWall": false,
        "SwingType": "DS_Standard",
        "DrawingDescription": "34\" x 77\" LHH cooler door - includes V1600 hydraulic door closer with Z-1009 hook, (2) W-59 polished hinges, W-29NC latch, Locking Hasp, Weiss 24DT-SP-LT digital therm/switch, Fermod PRP & VXS100 (LED). Interior & Exterior of Door & Frame: 26ga Embossed Galvalume"
      },
      "MiscInfo": {
        "HardwareFinish": "Polished",
        "TuffyDoor": false,
        "SupportWheel": false,
        "LightAboveDoor": false,
        "PrisonPackage": false,
        "ForceSill": true,
        "TrackPort": false,
        "DoorHeaters": false,
        "FrameHeaters": false,
        "LightExternal": false,
        "NSFCutout": false,
        "SSSill": false,
        "RaiseDoor": false,
        "HingeSpringKits": false,
        "AddLocksToDoorOnPartitionWall": false,
        "PRPLoc": "PL_Standard",
        "CloserLoc": "CL_TopCentre",
        "NumMangneticBreaks": 0
      },
      "Accessory": [
        {
          "AccessoryType": "LIGHT",
          "AccessorySelection": "K-1806",
          "Quantity": 1
        },
        {
          "AccessoryType": "HINGE",
          "AccessorySelection": "W-59",
          "Quantity": 2
        },
        {
          "AccessoryType": "CLOSER",
          "AccessorySelection": "Z-1009 hydraulic",
          "Quantity": 1
        },
        {
          "AccessoryType": "LATCH",
          "AccessorySelection": "W-29NC-P",
          "Quantity": 1
        },
        {
          "AccessoryType": "PUSH_PLATE",
          "AccessorySelection": "None",
          "Quantity": 1
        },
        {
          "AccessoryType": "SWITCH",
          "AccessorySelection": "24-DT",
          "Quantity": 1
        },
        {
          "AccessoryType": "PRP",
          "AccessorySelection": "Fermod_PRP",
          "Quantity": 1
        }
      ]
    }
  ]

}

A: al mirar tu string json, tiene saltos de linea y espacios entre items, para que lo pueda deserializar debe ser un texto plano sin saltos de linea ni espacio entre items, a mi me rechazaba los json por ese motivo hasta que me di cuenta e hice una funcion que elimina los saltos y los espacios y hay me los deserializa sin problemas y los numeros tienen que estar entre comillas.
tu json es bastante complejo
te recomiendo que hagas un funcion que te extraiga porciones del json y asi editarlo de forma mas sencilla, por que no todos los json vienen bien construidos, por ejemplo la pagina bittrex me retorna diferentes json pero solo uno viene en el formato que se puede deserializar a los otros les falta un {}, etc.


text:
Q: How would you fix this "Promise' provides no match for the signature '(value: any): {} | PromiseLike<{}>" Error I am trying to user promises in order to do a synchronous execution.
I have followed the instructions listed in a github forum, with no luck.
getData2(user: string, guid: string) {
  return new Promise<any>((resolve, reject) => {
    //doing some stuff in here
    resolve();
  });
}

getData1(user: string, guid: string) {
  return new Promise<any>((resolve, reject) => {
    //doing some other stuff in here
    resolve();
  });
}

userCheck(user: string) {
  //checking some array in here
}

userMethod(someArray: any){
  var i: any;
  var length = someArray.length;
  for (i=0; i < length; i++){
    this.getData1(someArray[i], userID).then(
      this.getData2(someArray[i], userID)).then(
          this.userCheck(someArray[i]));
      });
    })}
  }

The idea is that I want to first finish getData1 and then do getData2 and then do userCheck.
When I do it the way I have laid out above I get the error message:
Argument of type 'void' is not assignable to parameter of type '(value: {}) => {} | PromiseLike<{}>'.

After fixing this issue I ran into the fact that the userCheck function is still executing before getData2 finishes. I am not sure why. the getData2 function looks like this.
getCCData(user: string, id: string){
    console.log('grabbing CC information', id, user);
        return new Promise((resolve, reject) =>
        {
        this._apiService.getAssertion(id).toPromise().then(assert =>
{
    return this._apiService.getToken(assert.toString(), user);
}).then((data: any) =>
{
    return this._apiService.ccMeta(data.access_token.toString(), id);
}).then(parseString(Promise)).then((information: any) =>
{
    this.ccData.push(
    {
        key: 'userStatus',
        value: information.entry
    });
});

    resolve();
        });
}

I'm not sure if this is the correct way to design this function. Any extra insight would be great.

A: The error indicates that then() expects a Function as parameter, while you provide it with the return value of another then() call, which is a Promise.
To resolve the error, change the calls inside the then()-calls to arrow functions:
for (const item of someArray) {
  this.getData1(item, userID).then(() =>
    this.getData2(item, userID).then(() =>
      this.userCheck(item)
    )
  );
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reading delimited value from file into a array variable I want to read data.txt which has a 2x2 matrix number inside delimited by tab like this:
0.5 0.1
0.3 0.2

Is there any way to read this file in bash then store it into an array then process it a little then export it to a file again? Like for example in matlab:
a=dlmread('data.txt') //read file to array variable a
for i=1:2
   for j=1:2
   b[i][j]=a[i][j]+100
   end
end
dlmwrite(b,'data2.txt') //exporting array value b to data2.txt

A: If the extent of your processing is to something simple like add 100 to every entry, a simple awk command like this might work:
awk '{ for(i = 1; i <= NF - 1; i++) { printf("%.1f%s", $i + 100, OFS); } printf("%.1f%s", $NF+100, ORS); }' < matrix.txt

This just loops through each row and adds 100. It's possible to do more complex operations too, but if you really want toprocess matrices there are better tools (like python+numpy or octave).
It's also possible to use bash arrays, but to do any of the operations you'd have to use an external program anyway, since bash doesn't handle floating point arithmetic.


text:
Q: Getting a subcategories from MYSQL Hey i have following problem: is it possible to get the categories sorted like that:
MAIN2
-sub21
-sub22
-sub23
--sub223
MAIN3
-sub31
-sub32
-sub33
MAIN4
-sub41
-sub42
-sub43

in one MySQL query? I know it will be nessesary to use foreign key but I have no idea how to merge the results.
Elements in a database table


text:
Q: Cocos2d-iphone : Handle Button Press and Release Actually I need to move my sprite as long as button is pressed and the sprite should be stopped when button is released.
My code is below:
 CCMenuItemFont *item1 = [CCMenuItemFont itemFromString: @"icon.png" target:self selector:@selector(doit)];
        CCMenu * taskMenu = [CCMenu menuWithItems:item1,  nil];
        [self addChild:taskMenu];

-void()doit
{
        spritevelocity = 80;
}

The above code makes my sprite keep on moving when the button is tapped, but I need to stop my sprite as soon as button is released.
I tried below code but no success:
-void()doit
{
    buttonpressed = YES;
    if (buttonpressed) {
        spritevelocity = 80;
    }
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
         buttonpressed = NO;
}

Note:I just wanted to make spritevelocity = 0 to stop my sprite,,That is i want spritevelocity = 0 when button is released

A: You need to subclass CCMenuItem in case to override selected, unselected and activate methods. there, you can force you button to act as you whant to. In this case, act not only on press, but on release too. Here is a good example of overriding CCMenu: http://johnehartzog.com/2009/10/easy-to-create-buttons-with-cocos2d/

A: Why don't you set the velocity directly?
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
     buttonpressed = NO;
     spritevelocity = 0;
 }

Could you explain when is doIt called?


text:
Q: Send data from Broadcast receiver to MainActivity I need to display status of connection on the screen. It seemed a simple task...
This is my receiver code below:
public class PowerConnectionReceiver extends BroadcastReceiver {

public PowerConnectionReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
    String state;
    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        state = "Charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();

    } else {
        intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
        state = "Not charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    }
}
}

How can i display my STATE var on screen textView. Can anybody help with it? Thanks!

A: You need to register a Callback. Create an Interface in PowerConnectionReceiver like:
public Interface NetworkStatusCallback {
    public void onStateChange(String state);
}

Now implement this Callback in your MainActivity like:
public class MainActivity extends AppCompatActivity implements PowerConnectionReceiver.NetworkStatusCallback  {...}

Create a reference of this Callback in  PowerConnectionReceiver and declare it like:
private NetworkStatusCallback mCallback;
mCallBack = (NetworkStatusCallback)context;

Now in onReceive(Context context, Intent intent) do this:
@Override
public void onReceive(Context context, Intent intent) {
    String state;
    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        state = "Charging";
        mCallback.onStateChange(state);
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();

    } else {
        intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
        state = "Not charging";
        mCallback.onStateChange(state);
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    }
}

You will receive state in MainActivity


text:
Q: Doubt related to memory less property of exponential distribution. Let $X$ and $Y$  be independent exponential random variables. If $E(X)=1$ and $E(Y)=\dfrac{1}{2}$ then find $P(X>2Y|X>Y).$
Now using memory less property can I claim that $P(X>Y+Y|X>Y)=P(X>Y)?$ I never saw memory less property  in two dimensional random variable case.
If it is true then $P(X>Y)=\int_{0}^{\infty}\int_{0}^{x}e^{-x}(2e^{-2y})dydx=e^{-x}(1-e^{-2x})=\int_{0}^{\infty}(e^{-x}-e^{-3x})dx=1-(\frac{1}{3})=\frac{2}{3}$


text:
Q: Replacing an element of a list with multiple values if I have
l = ['a','b','x','f']

I want to replace 'x' by sub_list = ['c','d','e']
What is the best way to do this? I have,
l = l[:index_x] + sub_list + l[index_x+1:]

A: l = ['a','b','x','f']

sub_list = ['c','d','e']

ind = l.index("x")
l[ind:ind+1] = sub_list

print(l)
['a', 'b', 'c', 'd', 'e', 'f']

If you have a list that has multiple x's using index will replace the first x.
If you wanted to replace all x's:
l = ['a','b','x','f',"x"]
sub_list = ['c','d','e']
for ind, ele in enumerate(l): # use l[:] if the element to be replaced is in sub_list
    if ele == "x":
        l[ind:ind+1] = sub_list
print(l)
['a', 'b', 'c', 'd', 'e', 'f', 'c', 'd', 'e']

A: You can find the index of the element you wish to replace, then assign the sublist to a slice of the original list.
def replaceWithSublist(l, sub, elem):
    index = l.index(elem)
    l[index : index+1] = sub
    return l

>>> l = ['a','b','x','f']
>>> sublist = ['c','d','e']

>>> replaceWithSublist(l, sublist, 'x')
['a', 'b', 'c', 'd', 'e', 'f']

A: An alternative would be to use the insert() method
l        = ['a','b','x','f']
sub_list = ['c','d','e']
ind      = l.index('x')

l.pop(ind)
for item in reversed(sub_list):
    l.insert(ind, item)


text:
Q: "Attribute redefined" - trying to add grant for each role for every schema using terraform resource "snowflake_schema_grant" "grant" {
  database_name = var.database_name
  for_each      = {for s in snowflake_schema.schema : s.name => s}
  schema_name   = each.key
  privilege = "USAGE"
  for_each  = {for s in snowflake_role.role : s.name => s}
  roles     =[snowflake_role.read_only.name]
}

roles_grant.tf trying to add grant for each role for every schema using terraform


text:
Q: Vue Js 2 / Vue-CLI 3 / When hosted shows empty blank page Vue Js app working fine in dev mode, but as I upload it on the server, it simply displays a blank page. All the resources are showing up in the developer console. I am using vue-router package.
VueJs 2 / Vue-CLI-3
Below is my App.vue
<template>

    <m-nav/>
    <router-view></router-view>

</template>

This is my main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import HomePage from './components/HomePage.vue'
import Brochure from './components/Brochure.vue'
import Register from './components/Register.vue'

Vue.config.productionTip = false

Vue.use(VueRouter);

const routes = [
    {
        path:'/',
        component: HomePage
    },
    {
        path:'/download',
        component: Brochure
    },
    {
        path:'/register',
        component: Register
    }
];

const router = new VueRouter({
    routes,
    mode: 'history'
});

new Vue({
    router,
    render: h => h(App),
}).$mount('#app');

after running npm run build, It shows a blank page, although I can see some stuff in the DOM

http://prntscr.com/lvasvo
I am not getting, where I have made a mistake! The project is complete, but stuck on this part! :(

A: follow this tips:

*

*use <%= BASE_URL %> for script and link tags which wrote on index.html

*create vue.config.js in root of project and config your public path for production and development mode like:

module.exports = {
  publicPath:
    process.env.NODE_ENV === "production" ? "/" : "/"
  }
};

just use relative path, to know more about it, read this link:
https://cli.vuejs.org/config/#publicpath
create config.vue.js

A: In my case the issue was in the Router.beforeEach function that I had in index.js file inside the router folder to add a route guard. I had to rewrite it after upgrading it from Vue 2 to Vue 3 to make it work.

A: Just encounter the same issue with vue-cli3 project.
And my main reason getting this issue is my app doesn't deploy on the root of the domain,instead on a sub-path.
There're several tricky configures:

*

*vue.config.js (it's vue-cli3 exclusive): to set publicPath:/my-app/ ;

*router.js (assuming your vue-router config file is this): to set base:/my-app/;
And beware of the history router mode:

*

*this mode needs extra server side config, I'm using nginX, this is my config:

location /my-app {
         alias /var/www/my-app;
         try_files $uri /index.html last;
         index index.html;
}

And beware of the different between alias and root.

*

*this mode is not support relative path publicPath:./ in vue.config.js.


text:
Q: Issue with if statement pulling incorrect data from database I own a tournament script and i had a report system built into the script. Below is the code.
$this_search=array();

switch($t['bracket_size']) {

case 8:
$games_count=8;
$rounds_count=3;
break;

case 16:
$games_count=16;
$rounds_count=4;
break;

case 32:
$games_count=32;
$rounds_count=5;
break;

case 64:
$games_count=64;
$rounds_count=6;
break;

case 128:
$games_count=128;
$rounds_count=7;
break;

}

for($rounds = $rounds_count; $rounds > 0; $rounds--)
{
for($games = $games_count; $games > 0; $games--)
{
    if($b["w_r".$rounds."_s".$games.""]==$my_team_info['team_id']) {
        $this_search['round']=$rounds;
        $this_search['game']=$games;
        break;
    }
}
}

if (
$this_search['round']=='') {$smarty->assign('error', "Sorry, we couldn't find your match. Contact Live Support.");
}else{

$match_check=d_c("select * from tournaments_reports where tid='$t[id]' and round='$this_search[round]' and game='$this_search[game]'");
if ($match_check==0) {}
    else{
$match_check_info=d("select * from tournaments_reports where tid='$t[id]' and round='$this_search[round]' and game='$this_search[game]'");
    if ($match_check_info['team_A']==$my_team_info['team_id'] or $match_check_info['team_B']==$my_team_info['team_id']) {
        $smarty->assign('error', "Sorry, your team has already reported this match. If this is an error, contact live support.");
    }

}
}

if ($_POST[submit])
{
    if ($match_check==0) {$ins=d_i("INSERT INTO `tournaments_reports` (`id`, `tid`, `team_A`, `team_B`, `team_A_report`, `team_B_report`, `team_A_time`, `team_B_time`, `round`, `game`) VALUES ('', '$t[id]', '0', '0', '0', '0', '0', '0', '$this_search[round]', '$this_search[game]')");}

if ($_POST[report]==1) {
    // LOSS
    if ($match_check[team_A]==''){
        $update=d_u("update tournaments_reports set team_A='$my_team_info[team_id]',team_A_report='2',team_A_time='".time()."' where tid='$t[id]' and round='$this_search[round]' and game='$this_search[game]'");
    }
    elseif ($match_check[team_B]==''){
        $update=d_u("update tournaments_reports set team_B='$my_team_info[team_id]',team_B_report='2',team_B_time='".time()."' where tid='$t[id]' and round='$this_search[round]' and game='$this_search[game]'");
    }
}
elseif ($_POST[report]==2) {
    // WIN
    if ($match_check[team_A]==''){
        $update=d_u("update tournaments_reports set team_A='$my_team_info[team_id]',team_A_report='1',team_A_time='".time()."' where tid='$t[id]' and round='$this_search[round]' and game='$this_search[game]'");
    }
    elseif ($match_check[team_B]==''){
        $update=d_u("update tournaments_reports set team_B='$my_team_info[team_id]',team_B_report='1',team_B_time='".time()."' where tid='$t[id]' and round='$this_search[round]' and game='$this_search[game]'");
    }
}

$smarty->assign('success', "Thank you for your report.");
}

The code is supposed to search through the bracket database ($b) for the round and game that the user is currently in.
The code (not included) then displays and allows the user to report their scores for the round and game that they are currently in.
The above code is selecting incorrect column to pull the rounds and game count from.
Example:
My team is in round 1 game 2
i have been advanced to round 2 game 1
When i go to report the scored for round 2 game 1 i receive an error saying "You have already reported the round1 game 2 scores"
I am now in round 2 game 1 so it should allow me to report for that round and game but it does not. I figured out that it is the code above that needs changing but I do not know exactly what needs to be changed or altered.


text:
Q: Cannot access 'actionCreator' before initialization Worked with react class-based component with redux before, thought of trying it with a functional component with a similar redux folder structure. But when I import an action creator, say, 'increment' into a component to use it with useDispatch().dispatch() it's showing the 'increment' is not initialized.
actions/index.js
export const increment = () => {
    return {
        type: 'increment',
    };
};

export const decrement = () => {
    return {
        type: 'decrement',
    };
};

Counter.jsx
import classes from './Counter.module.css';
import { useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { increment, decrement } from '../redux/actions';
const Counter = () => {
    const dispatch = useDispatch();
    const toggleCounterHandler = () => {};
    const counter = useSelector((state) => state.counter.counter);
    console.log(increment);
    const increment = () => {
        dispatch();
    };
    const decrement = () => {
        dispatch();
    };
    return (

Redux Counter

{counter}

                <button onClick={increment}>Increment</button>
                <button onClick={decrement}>Decrement</button>

            <button onClick={toggleCounterHandler}>Toggle Counter</button>

    );
};

export default Counter;

During console logging the increment function I get:

ReferenceError: Cannot access 'increment' before initialization

A: You need to dispatch the action
It could look like this, for example:
import classes from './Counter.module.css';
import { useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { increment, decrement } from '../redux/actions';
const Counter = () => {
    const dispatch = useDispatch();
    const toggleCounterHandler = () => {};
    const counter = useSelector((state) => state.counter.counter);
    const handleIncrement = () => dispatch(increment);
    const handleDecrement = () => dispatch(decrement);

    return (

Redux Counter

{counter}

                <button onClick={handleIncrement}>Increment</button>
                <button onClick={handleDecrement}>Decrement</button>

            <button onClick={toggleCounterHandler}>Toggle Counter</button>

    );
};

export default Counter;

Ultimately, the crux of your problem is that you had defined increment twice, but you weren't dispatching the action, either.


text:
Q: How to use FB FriendPickerFragment to show you list of all your friends in order to invite them to use your app EDIT-----: So I did manage to make it show me users and be able to select some, and to send me back the selected users to my app but there is a slight problem. "Uri.parse("picker://friend");" doesn't give me the list of my friends, but only a list of the friends that I have and have my app installed.
I followed this example: https://developers.facebook.com/docs/android/scrumptious/show-friends but I am trying to modify it, so basically I took out the selectionActivity and Fragment. So I have from my activity a button that calls the PickerActivity which contains FriendPickerFragment. I can select my friends from there, but back in my activities onActivityResult i get back "data" as null.
I have an Application class in my app, where i save the FB session, and also have the login function in there.
In my MainActivity onCreate I have this:
   MyApp.getInstance().facebookLogin(PSAddFriendsActivity.this, new CrudStateCallback() {
        @Override
        public void onResponse(final String string) {
            Log.i("", "session : session is opened? : " + MyApp.getInstance().fbSession.getAccessToken());
        }
    });

After having logged in, I instantiate a list with the current friends I have in my app, and the first position of this list is a FB button:
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
    super.onListItemClick(l, v, position, id);
    if(position == 0){
            startPickerActivity(PSPickerActivity.FRIEND_PICKER, 0);
    }else if(position ==1){
        //TODO: OPEN CONTACTS PAGE TO ADD FRIENDS
    }

}

This is my onACtivityResult and the "startPickerActivity" from this class:
 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    Log.i("","--------------data is : " + data);
    Log.i("","--------------resultCode is : " + resultCode);
    Log.i("","--------------requestCode is : " + requestCode);

}

public void startPickerActivity(Uri data, int requestCode) {
    Intent intent = new Intent();
    intent.setData(data);
    intent.setClass(PSAddFriendsActivity.this, PickerActivity.class);
    startActivityForResult(intent, requestCode);
}

This is the PickerActivity, how I took it from FB:
public class PickerActivity extends FragmentActivity{
private FriendPickerFragment friendPickerFragment;
public static final Uri FRIEND_PICKER = Uri.parse("picker://friend");

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pickers);

    Bundle args = getIntent().getExtras();
    FragmentManager manager = getSupportFragmentManager();
    Fragment fragmentToShow = null;
    Uri intentUri = getIntent().getData();

    if (FRIEND_PICKER.equals(intentUri)) {
        if (savedInstanceState == null) {
            friendPickerFragment = new FriendPickerFragment(args);
        } else {
            friendPickerFragment =
                    (FriendPickerFragment) manager.findFragmentById(R.id.picker_fragment);
        }
        // Set the listener to handle errors
        friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
            @Override
            public void onError(PickerFragment<?> fragment,
                                FacebookException error) {
                PSPickerActivity.this.onError(error);
            }
        });
        // Set the listener to handle button clicks
        friendPickerFragment.setOnDoneButtonClickedListener(
                new PickerFragment.OnDoneButtonClickedListener() {
                    @Override
                    public void onDoneButtonClicked(PickerFragment<?> fragment) {
                        finishActivity();
                    }
                });
        fragmentToShow = friendPickerFragment;

    } else {
        // Nothing to do, finish
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    manager.beginTransaction()
            .replace(R.id.picker_fragment, fragmentToShow)
            .commit();
}

private void onError(Exception error) {
    onError(error.getLocalizedMessage(), false);
}

private void onError(String error, final boolean finishActivity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.error_dialog_title).
            setMessage(error).
            setPositiveButton(R.string.error_dialog_button_text,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (finishActivity) {
                                finishActivity();
                            }
                        }
                    });
    builder.show();
}

private void finishActivity() {
    setResult(RESULT_OK, null);
    finish();
}

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

@Override
protected void onResume() {
    Log.i("", "location test onResume");
    super.onResume();
    MyApp.getInstance().pref.setIsBackground(this, false);
    MyApp.getInstance().startLocationClient();
}

@Override
protected void onPause() {
    Log.i("", "location test onPause");
    super.onPause();
    MyApp.getInstance().pref.setIsBackground(this, true);
}
}

Now I looked over this fragment, do not know if I have to add something or save something from the fragment on "onDoneButtonClicked"? or what exactly, because my main activity does return null as data..

A: forgot to call this in the finishActivty:
if (FRIEND_PICKER.equals(getIntent().getData())) {
        if (friendPickerFragment != null) {
            MyApp.getInstance().setSelectedUsers(friendPickerFragment.getSelection());
        }
    }

Now I can get from my Application the list of selected users.
About my edit, after this i found out that with Graph2.0 you cannot get a list of your whole friendlist. You can only get back the info of friends that also liked the app. It is possible to invite friends to like an app but only if you set it as a Game from the FB developers page


text:
Q: I want to make place to collect all path of folder This is my code.
folder_out = []
for a in range(1,80):
    folder_letter = "/content/drive/MyDrive/project/Dataset/data/"
    folder_out[a] = os.path.join(folder_letter, str(a))
    folder_out.append(folder_out[a])

and this is an error

and this what I want

A: You are using the os method wrong, you want to use os.listdir(Your directory here) to get a list of all directories
import os

dir = os.listdir("/content/drive/MyDrive/project/Dataset/data/")
for f in dir:
    print(f)

If you just want a list of all directories, just use os.listdir("/content/drive/MyDrive/project/Dataset/data/")

A: It's simply pointless to create a variable. They are unnecessary: You can store everything in lists, dictionaries and so on. Creating a new variables inside loop is very very bad practice.
Code correction: save in list instead and access them using loops or slicing.
import os
folder_out = []

for a in range(1,80):
    folder_letter = "/content/drive/MyDrive/project/Dataset/data/"
    folder= os.path.join(folder_letter, str(a))
    folder_out.append(folder)

print(folder_out)

Gives list of folder names.
['/content/drive/MyDrive/project/Dataset/data/1', '/content/drive/MyDrive/project/Dataset/data/2', '/content/drive/MyDrive/project/Dataset/data/3', '/content/drive/MyDrive/project/Dataset/data/4', '/content/drive/MyDrive/project/Dataset/data/5', '/content/drive/MyDrive/project/Dataset/data/6', '/content/drive/MyDrive/project/Dataset/data/7', '/content/drive/MyDrive/project/Dataset/data/8', '/content/drive/MyDrive/project/Dataset/data/9',.....]

If you want to iterate over them.
for elment in folder_out:
    print(elment)

Which gives #
element 1
elem2nt 2...

Like
for x in folder_out:
    print(f"folder_out{c}: {x}")
    c= c+1

Gives what you want
folder_out0: /content/drive/MyDrive/project/Dataset/data/1
folder_out1: /content/drive/MyDrive/project/Dataset/data/2
folder_out2: /content/drive/MyDrive/project/Dataset/data/3
folder_out3: /content/drive/MyDrive/project/Dataset/data/4
folder_out4: /content/drive/MyDrive/project/Dataset/data/5
folder_out5: /content/drive/MyDrive/project/Dataset/data/6
folder_out6: /content/drive/MyDrive/project/Dataset/data/7
folder_out7: /content/drive/MyDrive/project/Dataset/data/8
folder_out8: /content/drive/MyDrive/project/Dataset/data/9
folder_out9: /content/drive/MyDrive/project/Dataset/data/10
folder_out10: /content/drive/MyDrive/project/Dataset/data/11
folder_out11: /content/drive/MyDrive/project/Dataset/data/12
folder_out12: /content/drive/MyDrive/project/Dataset/data/13
folder_out13: /content/drive/MyDrive/project/Dataset/data/14
folder_out14: /content/drive/MyDrive/project/Dataset/data/15
folder_out15: /content/drive/MyDrive/project/Dataset/data/16

If you want to create a folder for each path:
import os
for x in folder_out:

    os.mkdir(x)

which will create 79 empty folders


text:
Q: Where in my django app do I authenticate my users for dwolla? I've never really worked with APIs, JSON, or OAUTH, and I'm trying to use Dwolla for payments in my website. Since I've never seen the process of authenticating users with oauth, I'm having a hard time trying to figure out what I need to put and especially where I need to put it. The documentation available for dwolla doesn't make much sense for me.  I even did the codecademy.com lessons pretty easily and still have no idea where to begin when trying to use it in my django project.  I use django-registration to allow users to register on my website, so am I supposed to authenticate users with oauth when they register for my site so that they are assigned an oauth token? Do I send a user to the auth url with a link within my templates, or with code in a view? Do I need to create a new model with a Foreign Key field to associate it with my users? I'm really at a loss as to what this process should look like and how exactly Dwolla's API is interacting with my django app. This is the documentation from dwolla for python, and this is the documentation for oauth with dwolla. I even tried reading this oauth guide to get an idea of what's going on. The oauth2 overview on github gives an example for using twitter's API, but that left me more confused becasue it is specific to twitter's API. Also, do I need to install anything other than oauth2 and dwolla? I know all the pieces are there, I just am having a very hard time understanding how they fit together. Can anyone clarify the steps I need to take, or at least does anyone have a good tutorial for an absolute beginner to oauth and APIs? Thanks in advance for any help.

A: You can authenticate a user anywhere in your Django app that is convenient for you. A good place is on a page where the user may be editing their account details.
In order to actually write the code, you can put away any oAuth documentation from Twitter or wherever. oAuth isn't a code base like jQuery that you need to learn how to use. Its just set of guidelines as to how developers could allow their users' accounts talk to their accounts on other sites and trust that its the same user.
The core idea is that site #1 (in this case, Dwolla) gives site #2 (your site) a token, often some encrypted string of text, e.g., !432d8dk*dfas&&3, that can be used to more or less log in the user to site #1 while they are on site #2. More accurately, the token gives permissions that the user agrees to during the site #1 log in for site #2 to access parts of their site #1 account.
Here's a checklist of things to do to wire up the authentication of each user on your site with their account on Dwolla's site. This is based on Dwolla's python API posted on Github. Note this is for a Flask and not a Django app.

*

*Register your app with Dwolla so you can get your public and private key (listed as _keys.apiKey, _keys.apiSecret on Dwolla's oAuth example)

*Indicate the redirect URL, oauth_return_url which is where Dwolla will redirect the user when they are done logging in on Dwolla.

*(optional, but likely a good idea so the user only has to go through the oAuth/login on Dwolla's site once) store the token, which is specific for the user that logged in on Dwolla's site, in your database.


text:
Q: Singlton для подключения к БД sqlite Добрый вечер.
Хочу сделать Singlton для подключения к БД Sqlite.
Чтобы не использовать по 100 раз код подключения, тк таких методов много.
Подскажите как это сделать ? Код одного из запросов ниже
     {
            {
                string databaseName = @"eurocar31.db";
                SQLiteConnection connection =
                      new SQLiteConnection(string.Format("Data Source={0};", databaseName));
                connection.Open();
                SQLiteCommand command = new SQLiteCommand();
                command.Connection = connection;
                command.CommandText = "UPDATE Predoxraniteli SET cena =\"" + pr9.Text + "\" WHERE id = " + pr10.Text + ";";
                SQLiteDataReader reader = command.ExecuteReader(); int index = 0;

                while (reader.Read())
                {
                    index = index + 1;
                }
                connection.Close();
            }
            dataGridView5.Rows.Clear();
            getPred();
        }

A: Вот пример реализован синглетон, посмотрите, метод GetConnection создает обьект один раз, после того он будет отдавать обьект ранее создан.
public class ConnectionDb
    {
        private static SQLiteConnection connection = null;
        private static SQLiteCommand command = null;
        private static string filePath = AppDomain.CurrentDomain.BaseDirectory + "/Database/ItemsDb.sqlite";

        /// <summary>
        /// the method returns the link to the database
        /// </summary>
        /// <returns></returns>

        public static SQLiteConnection GetConnection()
        {
            if (connection == null)
            {
                if (!File.Exists(filePath))
                    SQLiteConnection.CreateFile(filePath);

                connection = new SQLiteConnection($"Data Source={filePath};Version=3;");
                connection.Open();

                string query = "Create table if not exists `Items`( `id` INTEGER NOT NULL,`Name` varchar(30) NOT NULL, `Type` varchar(30) NOT NULL, PRIMARY KEY(`id`))";
                command = new SQLiteCommand(query, connection);
                command.ExecuteNonQuery();
            }
            return connection;
        }
    }

    /// <summary>
    /// The method delete existing element
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public bool Delete(int id = 0)
    {
        try
        {
            var query = $"Delete from `Items` where `id` = '{id}'";
            command = new SQLiteCommand(query, ConnectionDb.GetConnection());
            return Convert.ToBoolean(command.ExecuteNonQuery());
        }
        catch
        {
            return false;
        }
    }


text:
Q: How to implement a lock in JavaScript How could something equivalent to lock in C# be implemented in JavaScript?
So, to explain what I'm thinking a simple use case is:
User clicks button B.  B raises an onclick event.  If B is in event-state the event waits for B to be in ready-state before propagating.  If B is in ready-state, B is locked and is set to event-state, then the event propagates.  When the event's propagation is complete, B is set to ready-state.
I could see how something close to this could be done, simply by adding and removing the class ready-state from the button.  However, the problem is that a user can click a button twice in a row faster than the variable can be set, so this attempt at a lock will fail in some circumstances.
Does anyone know how to implement a lock that will not fail in JavaScript?

A: Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:
var functionLock = false;
var functionCallbacks = [];
var lockingFunction = function (callback) {
    if (functionLock) {
        functionCallbacks.push(callback);
    } else {
        $.longRunning(function(response) {
             while(functionCallbacks.length){
                 var thisCallback = functionCallbacks.pop();
                 thisCallback(response);
             }
        });
    }
}

You can also implement this using DOM event listeners or a pubsub solution.

A: Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.
I suspect you need to just set a semaphore (flagging system) between your buttons.

A: Here's a simple lock mechanism, implemented via closure

const createLock = () => {

    let lockStatus = false

    const release = () => {
        lockStatus = false
    }

    const acuire = () => {
        if (lockStatus == true)
            return false
        lockStatus = true
        return true
    }

    return {
        lockStatus: lockStatus,
        acuire: acuire,
        release: release,
    }
}

lock = createLock() // create a lock
lock.acuire() // acuired a lock

if (lock.acuire()){
  console.log("Was able to acuire");
} else {
  console.log("Was not to acuire"); // This will execute
}

lock.release() // now the lock is released

if(lock.acuire()){
  console.log("Was able to acuire"); // This will execute
} else {
  console.log("Was not to acuire");
}

lock.release() // Hey don't forget to release

A: If it helps anyone in 2022+, all major browsers now support Web Locks API although experimental.
To quote the example in MDN:
await do_something_without_lock();

// Request the lock.
await navigator.locks.request('my_resource', async (lock) => {
  // The lock has been acquired.
  await do_something_with_lock();
  await do_something_else_with_lock();
  // Now the lock will be released.
});
// The lock has been released.

await do_something_else_without_lock();

*

*Lock is automatically released when the callback returns

*Locks are scoped to origins (https://example.com != https://example.org:8080), and work across tabs/workers.

*Lock requests are queued (first come-first served); (unlike in some other languages where the lock is passed to some thread at random)

*navigator.locks.query() can be used to see what has the lock, and who are in the queue to acquire the lock

*There is a mode="shared" to implement a readers-writers lock if you need it

A: JavaScript is, with a very few exceptions (XMLHttpRequest onreadystatechange handlers in some versions of Firefox) event-loop concurrent.  So you needn't worry about locking in this case.

JavaScript has a concurrency model based on an "event loop". This model is quite different than the model in other languages like C or Java.
...
A JavaScript runtime contains a message queue, which is a list of messages to be processed. To each message is associated a function. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame) The message processing ends when the stack becomes empty again.
...
Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.

For more links on event-loop concurrency, see E

A: I've had success mutex-promise.
I agree with other answers that you might not need locking in your case. But it's not true that one never needs locking in Javascript. You need mutual exclusivity when accessing external resources that do not handle concurrency.

A: Why don't you disable the button and enable it after you finish the event?
<input type="button" id="xx" onclick="checkEnableSubmit('true');yourFunction();">

<script type="text/javascript">

function checkEnableSubmit(status) {
  document.getElementById("xx").disabled = status;
}

function yourFunction(){

//add your functionality

checkEnableSubmit('false');
}

</script>

Happy coding !!!

A: Some addition to JoshRiver's answer according to my case;
var functionCallbacks = [];
    var functionLock = false;
    var getData = function (url, callback) {
                   if (functionLock) {
                        functionCallbacks.push(callback);
                   } else {
                       functionLock = true;
                       functionCallbacks.push(callback);
                        $.getJSON(url, function (data) {
                            while (functionCallbacks.length) {
                                var thisCallback = functionCallbacks.pop();
                                thisCallback(data);
                            }
                            functionLock = false;
                        });
                    }
                };

// Usage
getData("api/orders",function(data){
    barChart(data);
});
getData("api/orders",function(data){
  lineChart(data);
});

There will be just one api call and these two function will consume same result.

A: Locks still have uses in JS. In my experience I only needed to use locks to prevent spam clicking on elements making AJAX calls.
If you have a loader set up for AJAX calls then this isn't required (as well as disabling the button after clicking).
But either way here is what I used for locking:
var LOCK_INDEX = [];
function LockCallback(key, action, manual) {
    if (LOCK_INDEX[key])
        return;
    LOCK_INDEX[key] = true;
    action(function () { delete LOCK_INDEX[key] });
    if (!manual)
        delete LOCK_INDEX[key];
}

Usage:
Manual unlock (usually for XHR)
LockCallback('someKey',(delCallback) => {
    //do stuff
    delCallback(); //Unlock method
}, true)

Auto unlock
LockCallback('someKey',() => {
    //do stuff
})


text:
Q: Список с мультивыбором Подскажите как можно сделать в одной ячейке - мультивыбор (несколько вариантов одновременно) из списка, так чтобы во второй ячейке для соответствующих этим вариантов значений из второго списка происходило сложение?
Т.е есть:
Вар1-10.
Вар2-20.
Вар3-40.
В ячейке я должен выбрать Вар1,Вар3 и в другой получить 50
Про мультивыбор гугл сразу выдаёт пример макроса, но как его доработать не знаю

A: Вот код макроса мультивыбора. Только он суммирует в ту же ячейку, а не в отдельную.
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("C2:C5")) Is Nothing And Target.Cells.Count = 1 Then
    Application.EnableEvents = False
    newVal = Target
    Application.Undo
    oldval = Target
    If Len(oldval) <> 0 And oldval <> newVal Then
        Target = Target + newVal
    Else
        Target = newVal
    End If
    If Len(newVal) = 0 Then Target.ClearContents
    Application.EnableEvents = True
End If

End Sub

A: Решение по объединению данных уже есть, Вы сами его нашли по ссылке.
Для суммирования впишите формулу
=СУММПРОИЗВ(ЕЧИСЛО(ПОИСК($A$2:$A$10;C2))*$B$2:$B$10)


text:
Q: How Form handling works in PHP? I am learning PHP through w3schools. I am little bit confused of the execution flow of the page. I will attach a code example from w3schools.
<!DOCTYPE HTML>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
  }

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

PHP Form Validation Example

* required field

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  Name: <input type="text" name="name">
  * <?php echo $nameErr;?>

  E-mail: <input type="text" name="email">
  * <?php echo $emailErr;?>

  Website: <input type="text" name="website">
  <?php echo $websiteErr;?>

  Comment: <textarea name="comment" rows="5" cols="40"></textarea>

  Gender:
  <input type="radio" name="gender" value="female">Female
  <input type="radio" name="gender" value="male">Male
  <input type="radio" name="gender" value="other">Other
  * <?php echo $genderErr;?>

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

<?php
echo "
Your Input:
";
echo $name;
echo "
";
echo $email;
echo "
";
echo $website;
echo "
";
echo $comment;
echo "
";
echo $gender;
?>

Can anyone explain how the execution flow goes on this form handling. Browser can't run the php script. In this example superglobal $_SERVER["PHP_SELF"] used to refer the same html page. when we try to submit the page with empty field it shows the error message in screen. This is happening due to the fact php variable got its error value after submission. I think that after triggering the submit button. This page makes a request to the same page in the server using POST method and in the server we access the same form value using superglobal $_POST["name"],["email"] etc.. and finally the server throws the new html page. Am i right? or this validation is happening entirely in the frontend.

A: In php the validation is happening entirely in the server ..
The frontend only validate things when JavaScript involved or you add field attributes like required , min , max.
I think w3 is good source to check small code snippets. but it's not good source to learn


text:
Q: How to make an Abp.Dapper multiple-table query? I have an entity model Person -> Phones(collection) and the following code
Person
[Table("PbPersons")]
public class Person: FullAuditedEntity, IMustHaveTenant
{
    public const int MaxNameLength = 32;
    public const int MaxSurnameLength = 32;
    public const int MaxEmailAddressLength = 255;

    public virtual int TenantId { get; set; }

    [Required]
    [MaxLength(MaxNameLength)]
    public virtual string Name { get; set; }

    [Required]
    [MaxLength(MaxSurnameLength)]
    public virtual string Surname { get; set; }

    [MaxLength(MaxEmailAddressLength)]
    public virtual string EmailAddress { get; set; }

    public virtual ICollection<Phone> Phones { get; set; }

}

Phones
[Table("PbPhones")]
public class Phone : CreationAuditedEntity<long>
{
    public const int MaxNumberLength = 16;

    [ForeignKey("PersonId")]
    public virtual Person Person { get; set; }
    public virtual int PersonId { get; set; }

    [Required]
    public virtual PhoneType Type { get; set; }

    [Required]
    [MaxLength(MaxNumberLength)]
    public virtual string Number { get; set; }

}

Old Application Tier with Abp.EF
This code returns a list of persons including phones
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Dapper.Repositories;
using Abp.Domain.Repositories;
using Abp.Extensions;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;

public class PersonAppService : WebAppServiceBase, IPersonAppService
{
private readonly IRepository<Person> _personRepository;
private readonly IRepository<Phone, long> _phoneRepository;

public PersonAppService(IRepository<Person> personRepository,
IRepository<Phone, long> phoneRepository)
{
    _personRepository = personRepository;
    _phoneRepository = phoneRepository;
}

 public ListResultDto<PersonListDto> GetPeople(GetPeopleInput input)
{

            var persons = _personRepository
            .GetAll()
            .Include(p => p.Phones)
            .WhereIf(
                !input.Filter.IsNullOrEmpty(),
                p => p.Name.Contains(input.Filter) ||
                        p.Surname.Contains(input.Filter) ||
                        p.EmailAddress.Contains(input.Filter)
            )
            .OrderBy(p => p.Name)
            .ThenBy(p => p.Surname)
            .ToList();

            return new ListResultDto<PersonListDto>(Mapper.Map<List<Person>, List<PersonListDto>>(persons));
}

}
New Application Tier with Abp.Dapper
However when I use Abp.Dapper the GetAll method does not allow to include any method like Include/WhereIf, I know that is because it implements IEnumerable interface. I need that also returns the list of phones for each Person. What should I do?, I tried with linq (include, it is not available) with not success.
 using Abp.Application.Services.Dto;
 using Abp.Authorization;
 using Abp.Dapper.Repositories;
 using Abp.Domain.Repositories;
 using Abp.Extensions;
 using AutoMapper;
 using Microsoft.EntityFrameworkCore;
 using System.Collections.Generic;
 using System.Linq;

 public class PersonAppService : WebAppServiceBase, IPersonAppService
 {
private readonly IDapperRepository<Person> _personRepository;
private readonly IRepository<Phone, long> _phoneRepository;

public PersonAppService(IDapperRepository<Person> personRepository,
IRepository<Phone, long> phoneRepository)
{
    _personRepository = personRepository;
    _phoneRepository = phoneRepository;
}

 public ListResultDto<PersonListDto> GetPeople(GetPeopleInput input)
{

            var persons = _personRepository.GetAll()
            .OrderBy(p => p.Name)
            .ThenBy(p => p.Surname)
            .ToList();

            return new ListResultDto<PersonListDto>(Mapper.Map<List<Person>, List<PersonListDto>>(persons));
}

}

A: See the test code that fetches the navigation data as well.
 public async Task Should_Include_Navigation_Properties_If_Requested()
        {
            using (var uow = _uowManager.Begin())
            {
                var post = await _postRepository.GetAllIncluding(p => p.Blog).FirstAsync();

                post.Blog.ShouldNotBeNull();
                post.Blog.Name.ShouldBe("test-blog-1");

                await uow.CompleteAsync();
            }
}

https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/test/Abp.EntityFrameworkCore.Tests/Tests/Repository_Tests.cs#L80


text:
Q: Is it possible to put a badge on a UIToolbarItem? Is it possible to put a badge on a UIToolbarItem? I have four items on my bottom UIToolbar, but I need to put a badge on it (similar to push notification badge with a number) to notify the user of something. How can I do this?

A: If you mean UITabBarItem, then there is a property badgeValue of type NSString. If you are talking about UIBarButtonItem you can use a customView and implement your own badge.

A: Create a UIBarButtonItem subclass, override drawRect.
To get the red badge, you can either use an image or do the drawing yourself.


text:
Q: Auto Layout: Issues > Update Frames In this Auto Layout guide https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ResolvingIssues/ResolvingIssues.html
it says:
To resolve misplacement

Do one of the following:

    Choose Issues > Update Frames.

Where do you find the menu item Issues > Update Frames?

A: In current versions of Xcode, the item is Editor > Resolve Auto Layout Issues > Update Frames.
If you ever need to find a menu item in a Mac app, pull down the app's Help menu and type the name of the menu item in the Search field. Highlight one of the hits and it will show you the menu item graphically.


text:
Q: While loops generated via Scala Macros are not equal While testing a macro (Scala 2.11.7) I ran into the following issue: generated while loops are not equal when compared with equalStructure. The following code snippet illustrates the issue:
  val actual = c.untypecheck(q"while (true) {}")
  val expected = c.untypecheck(q"while (true) {}")
  actual equalsStructure expected //is false

Is it by design or there is something which I miss ?

A: Also the same for annotations:
> q"@enum object Test" equalsStructure(q"@enum object Test")
res1: Boolean = false

Which I assume is a bug, since this works as expected:
> q"object Test" equalsStructure(q"object Test")
res1: Boolean = true

I've raised a issue on their github repo. Lets see what they say.


text:
Q: What changes to a component state can I make using React devtools? I've got a component which consists of an object, which contains an array of objects, which in turn has keys and strings
this.state = {
  dinosaurs: [
    { era: "jurassic", name: "diplodocus", diet: "herbivore" },
    { era: "cretaceous", name: "velociraptor", diet: "carnivore" },
  ]
}

When I open up the component in react devtools, I find I can edit the strings such as "jurassic" or "diplodocus" by double clicking on those strings, but I apparently can't make changes to the keys such as "era", or the array of dinosaurs. However, it could be possible to change it with React DevTools but I'm doing it incorrectly.
I'm using React DevTools within Google DevTools.
What can and can't I change in a component's state using React DevTools?
I tried looking at the GitHub readme, and I can see a mention of editing state in the section side pane, but no mention of what can and can't be edited.
I looked at How to set React component state and props from browser but there was a comment telling the user to read the friendly manual for React DevTools, plus answers that didn't address what is or isn't possible using React DevTools.

A: It appears that React DevTools locks out functionality based on whether the page you're looking at is using the "development build of React" or the "production build of React".
I'm currently trying to debug something between my local (development) version of an app and the deployed (production) version of the same app. To test something in the deployed (production) version, it would be helpful if I could open React DevTools, click into the component, and edit a prop. Alas, as far as I can tell, there is absolutely no way to edit one of the props in that production build version of the website via React DevTools.
Contrast that with my local (development) version. I can click into any component in React DevTools, then edit any props (or state) I want and the component immediately renders with the new prop value. That appears pretty easy and straightforward: just double-click what you want to edit and type away.
TL;DR: Certain prop/state editing features of React DevTools appear to be locked down depending on the React build version. If you're not sure which version you're looking at, see the link above. If you need to edit props on something that's a deployed, production build of React, you (probably*) can't. Aggravating, but I feel your pain.
[*Probably because A) I might be wrong (that would be great, someone please comment how to do it), it's not very clear in the first place about when it's editable vs not editable; B) If you could somehow trick the React DevTools into treating the page like it's a development build, it might be possible (or it might break hideously), but checking that requires more effort than I can spare.]

Some editorializing:
I would love for the above to not be true, and it's especially aggravating because I don't see a reason why it's necessary. Perhaps I don't understand enough about the difference between the dev and prod versions, but you can still view props/state on a production version using the React DevTools: it doesn't seem like a big leap to be able to also edit it considering that the functionality is all there when it's a development version. But once again, maybe I don't see the reasons behind this.


text:
Q: I need answer of a question about binomial distribution Let X be a binomial random variable with mean Np and variance Np(1−p).
Show that the ratio X/N also has a binomial distribution with mean p and
variance p(1 − p)/N.

A: Let r = X/N. Since X has a binomial distribution, r also has the
same distribution. The mean and variance for r can be computed as follows:
Mean , E[r] = E[X/N] = E[X]/N = (N p)/N = p .
Variance , E[(r − E[r])2] = E[(X/N − E[X/N])2] = E[(X − E[X])2]/N2 = N p(1 − p)/N2 = p(1 − p)/N


text:
Q: Accessing ASP.NET C# Eval Databound Object within Object I have a rather tricky situation. I am using an ASP:Repeater which is bound to a SOAP datasource returning the below object structure.
Path: Array[6]
0: Object
   Direction: "Departing"
   Message: ""
   Operator: "myciti"
   RouteColor: "#a7a9ac"
   RouteName: "Airport"
       Stop: Object
           Name: "JFK"
           Location: Object
   Name: "Airport"
   __proto__: Object
   Time: "07:10"
   Type: ""
   Vehicle: ""

I can easily access all the first tier variables, such as "Time" by using Eval as such:
  <%# Eval("Time")%>

My problem is how would I access the nested objects still using EVAL from the ASPX page? For example how would I get to the "Name" value of the "Stop" object within this array which has the value "JFK"?

A: Try:
     <%# Eval("Stop.Name")%>

A: Eval is just a shortcut to obtain a property by name. It won't help you in some cases. Like for example, what if your object RouteName sometimes returns null.
You need to use:
<%# Container.DataItem.RouteName.Stop.Name %>

Container.DataItem is an object so you can access just about any property from it.
A better way would be to Cast that object into a more meaningful instance:
<%# Ctype(Container.DataItem, ReturnedSOAPObjectRecord).RouteName.Stop.Name %>

This method gives you the ability to check for nulls.
<%# IF(Ctype(Container.DataItem, ReturnedSOAPObjectRecord).RouteName IsNot Nothing, Ctype(Container.DataItem, ReturnedSOAPObjectRecord).RouteName.Stop.Name, "No Stop" %>


text:
Q: Can an EMR cluster be launched into a private VPC subnet with no public IPs that accesses the internet through a NAT instance in a public subnet? Is it possible to launch an EMR cluster into the private subnet of a scenario-2 VPC (http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Scenario2.html) where a NAT instance is in the public subnet, and where each instance in the private subnet does not have a public IP?
On the one hand, I see "Additionally, you cannot use Amazon EMR through a Network Address Translation (NAT) device, but you can still use a NAT for other traffic in more complex scenarios." at http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-plan-vpc-subnet.html . We also see StackOverflow questions like Create EMR Cluster with No Public IP Addresses that indicate that private clusters are not supported. However, I now understand that S3 is a valid VPC endpoint, and I'm wondering if this has changed the story.

A: At this time (as of Nov 8th, 2015), EMR only supports public subnet meaning that the default gateway (0.0.0.0/0) must route to an IGW (internet gateway in VPC).
Update:
As of December 22, 2015 starting with release 4.2.0 EMR can now work in a private subnet.  Announcement at https://forums.aws.amazon.com/ann.jspa?annID=3447 and example here https://blogs.aws.amazon.com/bigdata/post/Tx349CL210VDYQF/Securely-Access-Web-Interfaces-on-Amazon-EMR-Launched-in-a-Private-Subnet


text:
Q: How to await for the stream event to get processed in the unit-test? The unit-test implies that after some item was passed to a Sink object through the add method, than some operation will be performed in response to it.
class Subject {
  final StreamController<Item> _itemStreamController = StreamController();
  Sink<Item> get itemsSink => _itemStreamController.sink;
  Stream<Item> get _itemsStream => _itemStreamController.sink;
  final SomeService _service;

  Subject(this._service) {
    _itemsStream.listen((item) => _service.processItem(item));
  }
}

And the unit test itself:
test('description', () async {
  final Item givenItem = Item("givenValue");
  final SomeService givenService = MockSomeService();
  final Subject subject = Subject(givenService);
  subject.itemsSink.add(givenItem);
  verify(givenService.add(givenItem));
});

And as you can understand the event looping thread firstly processes verify instructions and only then dispatches the event to the listener.
If I just insert await Future.value(null); between sink interaction and method invocation verification than all works like a charm. Still, this solution is quite ugly.
Does the unit-testing framework itself offer something to schedule verification at the end of event loop? Or any measures to get this unit-test passed without resorting to something like await Future.value(null);?


text:
Q: free(struct variable) doesn't clear previous stored values associated with that variable when I malloc again? I created a struct like the following:
typedef struct header{

    int hc;
    char src[18];
    char dst=[18];
    char reason[15];
    char d[3];
    char m[3];
    char y[4];

     struct measurements{

        char h_ip[17];
         int h_ttl;
         int h_id;
        float h_rtt;

    }HOPS[100];

}HEADER;

INSIDE MAIN:

               HEADER *head;
                for(...){

                head=(HEADER*) malloc(sizeof(HEADER));
                 .....
                free(head);

                }

Will the above malloc automatically allocate memory for the inner struct as well? Also, I'm facing a weird problem here. After I free the header, I'm still able to print the values of head->HOPS[i].h_ip. Should I explicitly free the inner struct as well so that even the values get cleared?

A: Yes, it allocates memory for the inner structure. And you need not free the inner structure separately.
If you have a pointer defined inside your structure, in that case you have to allocate separately for that pointer member of the structure and free that separately.

A: Consider freeing memory as a black box. All what you know is that after freeing you shouldn't refer to freed memory.
You may find that that memory block still exists and still contains some old values. That's ok: it just was marked as freed and probably it will be used again soon by allocator.
For example when you call malloc again and realized that just allocated block contains values from the old structure. It happens and that's alright. Just use this block as usually.

A: So, after the problem with the wrong declaration of head was resolved:
free returns a previously allocated memory block to the heap. It does not clear anything (for performance reasons). However, you are not supposed to access that block anymore afterwards. Doing so results in undefined behaviour and might let your computer fly out of the window.
Worst that can happen is ... nothing ... Yes, you might even not notice anything strang happens. However, that does not mean your program run correctly, it just does not show any symptoms.
To catch illegal accesses, you might set the pointer to NULL once you freed the object it points to. Some operating systems catch accesses to addresses near the null pointer address, but there is no guarantee. It is a good practice anyway and does no harm.
For your other question: malloc allocates a block of memory large enough to store that many bytes you passed as argument. If it cannot, it will return a null pointer. You should always check if malloc & friends returned a valid pointer (i.e. not a null pointer).
int *p = malloc(sizeof(int));
if ( p == NULL ) {
    error: out of memory
}
...

Notice the omission of the cast of the result of malloc. In C you should not cast void * as returned by malloc & friends (but also elsewhere). As much as you did not for free(head). Both take the same type: void *, btw. (so why cast one and not the other?). Note that in C any object pointer can freely be assigned to/from void * without cast. Warning functions are no objects in the C standard!
Finally: sizeof(HEADER) returns the size of the struct. Of course that include all fields. A nested struct is a field. A pointer to another struct is a field. For the latter, however note: the pointer itself is a field, but not what it points to! If that was another struct, you have to malloc that seperately **and also free seperately (remember what I wrote above).
But as you do not have pointer inside your struct, that is not your problem here. (keep it in mind, if you continue programming, you will eventually need that!)


text:
Q: How to generate random numbers from a array whose sum is N (Not Defined) in Android Java? I have a specific range in an array.
 private int[] arr = {0, 1, 2, 3, 4, 6};

I've successfully generated the numbers up to the sum, but the random numbers are not in my array range.
 private ArrayList<Integer> random(int targetSum, int numberOfDraws) {
        Random r = new Random();
        ArrayList<Integer> load = new ArrayList<>();

        //random numbers
        int sum = 0;
        for (int i = 0; i < numberOfDraws; i++) {
            int next = r.nextInt(targetSum) + 1;
            load.add(next);
            sum += next;
        }

        //scale to the desired target sum
        double scale = 1d * targetSum / sum;
        sum = 0;
        for (int i = 0; i < numberOfDraws; i++) {
            load.set(i, (int) (load.get(i) * scale));
            sum += load.get(i);
        }

        //take rounding issues into account
        while (sum++ < targetSum) {
            int i = r.nextInt(numberOfDraws);
            load.set(i, load.get(i) + 1);
        }

        return load;
    }

Where I'm making a mistake? What new solution should I improve?


text:
Q: Conditioning and substituting conditioned variable for unconditioned I am in the following situation. I have two independent discrete random variables $X,Y$ and I am looking at
$$
P(f(h_1(X),h_2(Y))=k~|~E_X \cap E_Y)
$$
where $E_X$ depends only on $X$ and $E_Y$ depends only on $Y$, and $E_X$ and $E_Y$ are independent.
I have calculated the conditional distributions of
$$
P(h_1(X)=i~|~E_X)=P(Z_X=i),~~~~ P(h_2(Y) = i ~|~E_Y)=P(Z_Y=i)
$$
for some nicer looking random variables $Z_X,Z_Y$ and would like to say
$$
P(f(h_1(X),h_2(Y))=k~|~E_X \cap E_Y)=P(f(Z_X,Z_Y)=k).
$$
Intuitively it seems obvious, but when I try to write I down I stumble on how to justify it. What do I need to say to make this rigorous?

A: Using somewhat more systematic notations, one sees that the hypotheses are that $X$ and $Y$ are independent random variables, $B$ is some $X$-measurable event and $C$ some $Y$-measurable event such that, for every functions $u$ and $v$,
$$
\mathbb E(u(g(X))\mid B)=\mathbb E(u(Z)),\quad
\mathbb E(v(h(Y))\mid C)=\mathbb E(v(T)).
$$
(Note that the hypothesis that $B$ and $C$ are independent is always true since $X$ and $Y$ are independent, $B$ is $X$-measurable and $C$ is $Y$-measurable.)
One wants to prove that, for every function $w$,
$$
\mathbb E(w(g(X),h(Y))\mid B\cap C)=\mathbb E(w(Z,T)).\tag{$\ast$}
$$
The standard approach is to consider the set of functions $w$ such that $(\ast)$ holds and to decompose the proof into two steps:

*

*A specific step: show that $(\ast)$ holds for every $w=\mathbf 1_{U\times V}$.

*A non-specific step: deduce from the specific step that $(\ast)$ holds for every (properly integrable) function $w$.

Specific step: when $w=\mathbf 1_{U\times V}$, the LHS of $(\ast)$ is $\mathbb P(g(X)\in U,h(Y)\in V\mid B\cap C)$. Using $u=\mathbf 1_U$ and $v=\mathbf 1_V$, one knows that
$$
\mathbb P(g(X)\in U\mid B)=\mathbb P(Z\in U),\qquad
\mathbb P(h(Y)\in V\mid C)=\mathbb P(T\in V).
$$
The independence assumptions yield $\mathbb P(B\cap C)=\mathbb P(B)\mathbb P(C)$ and
$$
[g(X)\in U,h(Y)\in V,B\cap C]=[g(X)\in U]\cap B\cap[h(Y)\in V]\cap C,
$$
yields
$$
\mathbb P(g(X)\in U,h(Y)\in V,B\cap C)=\mathbb P(g(X)\in U,B)\mathbb P(h(Y)\in V,C).
$$
Put all of these together, shake, and try to deduce the specific step. You will reach the formula
$$
\mathbb P(Z\in U)\mathbb P(T\in V),
$$
which you want to equal $\mathbb P(Z\in U,T\in V)$ for $(\ast)$ to hold for  $w=\mathbf 1_{U\times V}$. This is true if $Z$ and $T$ are independent, a hypothesis which is not made in the question and which should be made for the result to hold.
Non-specific step: note that $(\ast)$ is stable by linear combinations, by monotone convergence, and again by linear combinations. This yields that $(\ast)$ holds for nonnegative simple functions, then for nonnegative functions, then for real-valued functions. QED.
Finally:

The result holds adding the hypothesis that $Z$ and $T$ are independent (and forgetting the hypothesis that $B$ and $C$ are, since this is always true).


text:
Q: Magento2: Exception invalid block I have installed my module in a server in app/code folder and I executed

bin/magento setup:upgrade

and

bin/magento di:compile

and after I show this error:

The block is in Block folder.
I use it in front layout
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="before.body.end">
            <block class="Oct8ne\Oct8ne\Block\Oct8neJS" template="Oct8ne_Oct8ne::oct8nejs.phtml" name="oct8nejs" cacheable="false"/>
        </referenceContainer>
</page>

In localhost works fine. I tried to flush cache, recompile di, deploy static files, delete var folders... any idea?


text:
Q: How to search for a tuple in a table in mysql I have the following table
CREATE  TABLE IF NOT EXISTS `friends` (
  `userid` INT NOT NULL ,
  `friend` INT NOT NULL ,
  `status` INT(1) NOT NULL ,
  INDEX `user_id_fk_idx` (`userid` ASC) ,
  INDEX `friend_id_fk_idx` (`friend` ASC) ,
  PRIMARY KEY (`userid`, `friend`) ,
  CONSTRAINT `user_id_fk`
    FOREIGN KEY (`userid` )
    REFERENCES `network`.`users` (`userid` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `friend_id_fk`
    FOREIGN KEY (`friend` )
    REFERENCES `network`.`users` (`userid` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

When I want to insert a new tuple in this table, I want to check if that tuple already exists or not.
Example: when i insert (1,2,0) in table it must run if and only if (1,2,) or (2,1,) is not present in table. Or if i search for tuple (1,2,) in table it must search for (1,2,) and (2,1,*) and give results back.
Currently i am running two queries for this, can this be combined in one query?

A: One way to do this is to follow the "bi-directional" example here (it's pretty good)
How to implement a bidirectional unique index across multiple columns
Once you've got this in place you can either

*

*SELECT and if nothing there INSERT your new data.

or

*INSERT and catch error if one is thrown because the data is already there.

A: Say a and b are your userID's, then this will give TRUE if either of the tuples exists, FALSE if not
SELECT COUNT(*) > 0
FROM friends
WHERE
    (friends.userid = a AND friends.friend = b)
OR  (friends.userid = b AND friends.friend = a)

You can also construct a bidirectional relation from your table
SELECT friends.userid AS userid, friends.friend AS friend FROM friends
UNION ALL
SELECT friends.friend AS userid, friends.userid AS friend FROM friends

IF you want to do it all in one INSERT query you'll need to use INSERT ... SELECT combined with WHERE NOT EXISTS in the SELECT part. Working example
INSERT INTO friends (userid, friend)
SELECT a,b FROM dual
WHERE NOT EXISTS (
    SELECT friends.userid
    FROM friends
    WHERE
        (friends.userid = a AND friends.friend = b)
    OR  (friends.userid = b AND friends.friend = a)
)


text:
Q: ElasticSearch aggs returns 10 buckets only I am running an aggs query and specifying the size of 100, but ES only returns 10 buckets back. Why? What am I missing?
{
  "size": 100
   ,"query": {
      "bool": {
        "must": [
          { "term": {"app": "cnn"} }
        ]
      }
    }
   ,"aggs": {
    "unique_client": {
      "terms": {"field": "client"}
      }
    }
}

A: outer size is for total number of documents you get back for your query, so size = 100 returns 100 documents, for getting 100 aggregations bucket, specify size inside your unique_client aggs like this
{
  "size": 0
   ,"query": {
      "bool": {
        "must": [
          { "term": {"app": "cnn"} }
        ]
      }
    }
   ,"aggs": {
    "unique_client": {
      "terms": {"field": "client"},
      "size" : 100
      }
    }
}

By Default size of aggregations is 10, that is why you get 10 results, I have made outer size = 0 to get only aggregations.

A: Set the top size parameter to zero to signify that it is an aggregation. The number of buckets returned is set by specifying the size INSIDE the terms aggregation braces.
{
  "size": 0
   ,"query": {
      "bool": {
        "must": [
          { "term": {"app": "cnn"} }
        ]
      }
    }
   ,"aggs": {
    "unique_client": {
      "terms": {
        "field": "client",
        "size" : 100
      }
     }
    }
}

If you set it to 0 the value will default to Integer.MAX_VALUE


text:
Q: C++11: when move ctor/operator= is called? #include <iostream>

class Class
{
    public:
    Class() { std::cerr << "ctor" << std::endl; }
    ~Class() { std::cerr <<"dtor" << std::endl; }

    Class(Class&)  { std::cerr << "copy ctor" << std::endl; }
    Class & operator=(const Class &)
    {
            std::cerr << "copy operator=" << std::endl;
            return *this;
    }

    Class(Class&&) { std::cerr << "move ctor" << std::endl;}
    Class & operator=(Class &&)
    {
            std::cerr << "move operator="<< std::endl;
            return *this;
    }
 };

int main(int, char**)
{
    Class object;
    Class && rvr = Class();
    object = rvr; // (*)
}

Output is
ctor
ctor
copy operator=
dtor
dtor

1) Why "copy ctor" is called at line (*)?
2) If i have to use std::move() every-time, what is the difference between "move semantics" and any method that will move data, like object.destructive_move();?
3) when exactly move ctor/operator is called?
thanks!

A: The copy ctor is not called at line (*), the copy assignment operator is called. I guess that's what you meant.
It is the copy assignment operator that is called rather than the move assignment operator since rvr is an lvalue. Note that the type of an expression is orthogonal to whether it's an lvalue or not.
If you modified your assignment statement to object = Class(); or even object = static_cast<Class&&>(rvr), you would find the move assignment operator being called, since the RHS is an rvalue in those two cases.
This behavior is sensible: consider the implementation of a move assignment operator, say. Its parameter has type rvalue reference, but it is still an lvalue. If it were an rvalue, then the first use of the parameter could modify its state to become an 'empty' object (move semantics), and then a second use of the parameter would probably not work as expected.
The way it actually works, you would explicitly use std::move when you wanted to use the parameter in a way that left it an 'empty' state.

A: Class && rvr = Class();

What I'm going to say isn't going to make sense, but this is the C++11 rule.
rvr is a variable that is an rvalue reference to a Class. That's easy to understand. But it is important to understand this: a named variable is never an rvalue expression. Even if it is an rvalue reference!
Again, I know that doesn't make sense, but that's the rule. An rvalue reference variable is not an rvalue expression.
A temporary is an rvalue expression, so Class() gives you an rvalue. The temporary returned from a function is also an rvalue expression, so if you had some function that returned Class by value, you would get an rvalue back.
This matters because if you have two functions overloaded based on lvalue and rvalue references (like copy/move constructors/assignment), C++11 will select the rvalue reference version only if the expression type is an rvalue.
This is why std::move exists. It exists to explicitly state when you want to move something. It does this by converting the value you give it into an rvalue expression. Namely, it returns Class&&.
This is the part that's really confusing. If you have a named rvalue reference variable, that isn't an rvalue expression. But if you have an unnamed rvalue reference, such as returning Class&& from a function, that is an rvalue expression.
std::move returns Class&&. So if you want to move from a named variable, you must always call std::move on it. So if you want to move from rvr, you must do this:
object = std::move(rvr); // (*)

This will return a Class&& to rvr. C++11 overload resolution will happen. Since the parameter to operator= is an rvalue expression, it will select the rvalue reference version of operator=. Thus invoking a move.
Note that std::move is really just a wrapper around a semi-complex cast. It doesn't do the moving; it's the operator= that does the moving.


text:
Q: How to immobilize widget layout when keyboard is open? I am developing a Flutter App. In a specific screen, I have a Cupertino style text field. (The whole app is Cupertino, I have four TabBars below the screen). Whenever I click on the textfield, the virtual keyboard opens and all the widgets squeeze between the textfield and the keyboard (with yellow-black bands of course).
The widgets are Expandable rows and columns (Flexible also has the same result).
resizeToAvoidBottomPadding is disabled.
resizeToAvoidBottomInset does not have any functionality.
SingleChildScrollView does not work.
ListView is meaningless, since my widgets are stateless and static.
What I need is to have keyboard open on top of the current widgets, instead of moving them. This problem exists both in iOS and Android.

A: After couple of weeks, I finally reached the solution. Despite indicating 'resizeToAvoidBottomInset' as not working above, I was using that in one of the folders of tabs. However this should be added where you build the tabs.


text:
Q: transform a pandas datetime into a numerical value I have a panda datetime series:
>>> desc1.startTime.head()
0   2008-10-18 12:08:49
1   2008-10-18 12:22:52
2   2008-10-18 12:40:26
3   2008-10-18 12:57:52
4   2008-10-18 13:15:17
Name: startTime, dtype: datetime64[ns]

I would like something like
t(0)=0 and t(i) = desc1.startTime(i) - desc1.startTime(0)
is there a good way to do this with pandas?
EDIT:
This is what I have tried. It's not working
>>> desc1.head()
   Wafer_Slot  Summary_GroupName           startTime    LotNum     time
0           1                  1 2008-10-18 12:08:49  Q3968075 00:00:00
1           5                  1 2008-10-18 12:22:52  Q3968075 00:14:03
2          10                  1 2008-10-18 12:40:26  Q3968075 00:31:37
3          15                  1 2008-10-18 12:57:52  Q3968075 00:49:03
4          20                  1 2008-10-18 13:15:17  Q3968075 01:06:28
>>> desc1['time'].head()
0   00:00:00
1   00:14:03
2   00:31:37
3   00:49:03
4   01:06:28
Name: time, dtype: timedelta64[ns]
>>> desc1['time'].apply(lambda x:x.seconds)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/donbeo/MyApps/phd_python/lib/python3.4/site-packages/pandas/core/series.py", line 2169, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/src/inference.pyx", line 1059, in pandas.lib.map_infer (pandas/lib.c:62578)
  File "<stdin>", line 1, in <lambda>
AttributeError: 'numpy.timedelta64' object has no attribute 'seconds'
>>>

A: You can use tolist() with dt and iloc as Edchum's comments says:
print df['startTime']
#0   2008-10-18 12:08:49
#1   2008-10-18 12:22:52
#2   2008-10-18 12:40:26
#3   2008-10-18 12:57:52
#4   2008-10-18 13:15:17
#Name: startTime, dtype: datetime64[ns]

print (df['startTime'] - df['startTime'].iloc[0]).dt.seconds.tolist()
#[0, 843, 1897, 2943, 3988]

Or you can use converting timedelta to seconds docs:
print ((df['startTime']-df['startTime'].iloc[0])/np.timedelta64(1, 's')).astype(int).tolist()
#[0, 843, 1897, 2943, 3988]

print (df['startTime']-df['startTime'].iloc[0]).astype('timedelta64[s]').astype(int).tolist()
#[0, 843, 1897, 2943, 3988]

If you need float, you can omit astype:
print ((df['startTime'] - df['startTime'].iloc[0]) / np.timedelta64(1, 's')).tolist()
#[0.0, 843.0, 1897.0, 2943.0, 3988.0]

You can use microseconds:
print (df.startTime - df.startTime.iloc[0]).astype('timedelta64[ms]').astype(int).tolist()
#[0, 843000, 1897000, 2943000, 3988000]

Timing:
These timings are going to be very dependent on the size of s as well as the number (and position) of values:
In [54]: %timeit (df['startTime'] - df['startTime'].iloc[0]).dt.seconds.tolist()
The slowest run took 4.29 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 1.38 ms per loop

In [55]: %timeit ((df['startTime'] - df['startTime'].iloc[0]) / np.timedelta64(1, 's')).astype(int).tolist()
1000 loops, best of 3: 1.82 ms per loop

In [56]: %timeit (df['startTime'] - df['startTime'].iloc[0]).astype('timedelta64[s]').astype(int).tolist()
The slowest run took 4.31 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 1.01 ms per loop


text:
Q: Boost asio ip tcp iostream Error Detection Greetings. I'm just getting started with the boost::asio library and have run into some early difficulty related to boost::asio::ip::tcp::iostream.
My question has two parts:
1.) How does one connect an iostream using simply host and port number?
I can make the client and server [boost.org] examples work fine as coded. The server specifies the port explicitly:
boost::asio::io_service io_service;

tcp::endpoint endpoint(tcp::v4(), 13);
tcp::acceptor acceptor(io_service, endpoint);

Port 13 is a well-known port for a "daytime" service.
The client example connects by specifying a host and the service name:
tcp::iostream s(argv[1], "daytime");

For my own application, I would like to put the server on an arbitrary port and connect by number as shown below:
Server:
boost::asio::io_service io_service;
tcp::endpoint endpoint(tcp::v4(), port);
tcp::acceptor acceptor(io_service, endpoint);
acceptor.accept(*this->socketStream.rdbuf());
...

Client:
boost::asio::ip::tcp::iostream sockStream;
...
sockStream.connect("localhost", port);
...

If, in the client, I try to specify the port number directly (instead of a service by name), the stream fails to connect. Is there a way to do this? It is not clear to me what the arguments to connect could/should be.

2.) What is the preferred way to test the success of a call to iostream::connect?
The function returns void, and no exception is thrown. The only method I've devised so far is to test the stream.fail() and/or stream.good(). Is this the way to do it, or is there some other method.

Advice on one or both of these would be appreciated. Also, if I am overlooking pertinent documentation and/or examples those would be nice. So far I haven't been able to answer these questions by reading the library docs or searching the 'net.

A: I don't know why asio doesn't work (at least with Boost 1.35.0) with a port number expressed as an int. But, you can specify the port number as a string. i.e.
tcp::iostream s(hostname, "13");

should work.
concerning error detection:
tcp::socket has a connect() method which takes and endpoint and a reference to a boost::system::error_code object which will tell you if it connected successfully.

A: Even though no error is returned, stream.error() contains the latest error code.  I used the code
do
{
    m_stream.clear();
    m_stream.connect(host, port);
}
while(m_stream.error());`

You could also only check for the specific error boost::asio::error::connection_refused.


text:
Q: Is there an annotation alternative of a Spring Mvc controller property declared with XML? I am reading a book and the author declared a Controller in application context file like this :
<bean name="/nominee/*"
   class="com.springinpractice.ch03.web.NomineeController"
   p:thanksViewName="nominee/thanks"/>

I have found the annotation alternative for the bean name which is this one for the controller class:
@Controller
@RequestMapping("/nominee/*")

but I want to find the annotation alternative for the thanksViewName property.
Here is the code of the controller class:
package com.springapp.mvc;

import com.springapp.model.Member;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/nominee/*")
public final class NomineeController {
    private static final Logger log = Logger.getLogger(NomineeController.class);

    private String thanksViewName;

    public void setThanksViewName(String thanksViewName) {
        this.thanksViewName = thanksViewName;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Member form()
    {
        return new Member();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processFormData(Member member)
    {
        log.info("Processing nominee: " + member);
        return thanksViewName;
    }
}

Any ideas?
Thank you.

A: Do this -
private String thanksViewName = "nominee/thanks";

If you want to read the view name from some config then use the below annotation on the property.
@Value( "${view.thanksViewName }" )


text:
Q: Add a click handler to a ref? I'm using a 3rd party package but need to add a small piece of interaction.
The package has a button with ref of "next". Is there anyway to add a click handler to this ref?

A: This may help:
public mounted() {
    const next = this.$refs.next as HTMLElement;
    next.addEventListener('click', this.onNextClick, false);
}

public onNextClick() {
    // do your stuff here
}

A: I've ran into this question seeking a solution for a similar problem. However my case was that a ref attribute was set on a Vue Component object. Using simple addEventListener on a referenced object I got an error:

addEventListener is not a function

The solution is to call the function on referenced component's $el property, being an actual HTML element.
this.$refs.next.$el.addEventListener('click', function() {
  /* do stuff here*/
}, false);

From the comment's in the previous answers I see that it might also be the case for OP.

A: something like this:
this.$refs.next.addEventListener('click', function() {
  /* do stuff here*/
}, false);


text:
Q: How can I use port 8080 on a BeagleBone Black with Debian Linux, kernel 4.14.x, when trying to use a web camera? I have successfully compiled jacksonliam/mjpg-streamer. After compiling it, I ran into issues. The end result is that the source works, but I don't know how to resolve port conflicts under Debian Linux.
...
Port 8080 it seems is used on the source for using the webcam for getting online and promoting the webcam mjpeg-streamer source for webcam use.
I found that Apache2 and NodeJS both use the 8080 port. So, I erased them. I removed them from my machine.
I still do not know how to access the camera via web page b/c of not knowing how to initialize the port in question. I hope this makes sense.
P.S. I have covered a bunch of online tutorials regarding the basics of less, ncat, ss, etc. I am not completely sure what this means or how to search my files/directories for the 8080 port is taken up or not. Are there particular commands I need to know on how to see if my port 8080 is accessible?

A: You can use netstat or ss to get the list of programs and users that are using a socket.
So for ss do
ss -lpe |grep 8080

for netstat do
netstat -ntpl |grep 8080

If nothing returns then nothing using 8080.
Both commands should return similar info in a bit different format. If you see an app using port 8080 you need to go to that apps config and change the port and restart the app (if you need that app) or if you dont need the app disable it.
(replace appUsing8080 with the app name you found using that port with above commands)
systemctl disable appUsing8080
systemctl stop appUsing8080


text:
Q: HealthConnect - Permission Dialog not working in release mode App crashes when the app is running in release mode with proguard enabled.
Here is the Crash report.
Fatal Exception: java.lang.IllegalArgumentException: Unknown data type name h0
   at android.os.Parcel.createExceptionOrNull(Parcel.java:2429)
   at android.os.Parcel.createException(Parcel.java:2409)
   at android.os.Parcel.readException(Parcel.java:2392)
   at android.os.Parcel.readException(Parcel.java:2334)
   at androidx.health.platform.client.service.IHealthDataService$Stub$Proxy.getGrantedPermissions(IHealthDataService.java:414)
   at androidx.health.platform.client.impl.ServiceBackedHealthDataClient.getGrantedPermissions$lambda-1(ServiceBackedHealthDataClient.kt:93)
   at androidx.health.platform.client.impl.ServiceBackedHealthDataClient.$r8$lambda$hhWerw-hyBNCC_kPGtX4mZNDQdM(ServiceBackedHealthDataClient.kt)
   at androidx.health.platform.client.impl.ServiceBackedHealthDataClient$$InternalSyntheticLambda$0$605e77fbbfc877805d8dd88d131a334eb9370ed10712fd7118bc908c2d0b7ca2$0.execute(ServiceBackedHealthDataClient.java:6)
   at androidx.health.platform.client.impl.ipc.Client$3.execute(Client.java:279)
   at androidx.health.platform.client.impl.ipc.internal.ServiceConnection.execute(ServiceConnection.java:243)
   at androidx.health.platform.client.impl.ipc.internal.ServiceConnection.enqueue(ServiceConnection.java:200)
   at androidx.health.platform.client.impl.ipc.internal.ConnectionManager.handleMessage(ConnectionManager.java:123)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loopOnce(Looper.java:201)
   at android.os.Looper.loop(Looper.java:288)
   at android.os.HandlerThread.run(HandlerThread.java:67)

Any Proguard rules should I need to add for health Connect API?

A: Aug. 3, 2022:
As of version 1.0.0-alpha03, this has been fixed on the library's end.
Links :

*

*https://developer.android.com/jetpack/androidx/releases/health#health-connect-client-1.0.0-alpha03

*https://android-review.googlesource.com/c/platform/frameworks/support/+/2153498/2/health/health-connect-client/proguard-rules.pro

For the meantime time, you can add these rules into your proguard file:
-keep public class androidx.health.** {
  public protected private *;
}
-dontwarn androidx.health.**

It is quite overarching to ignore the entire lib at the moment, but at least it gets your project to build under release.