text:
Q: Recursively sort levels of a multidimensional array by keys if associative and by values if indexed I need help sorting keys and values of the array below alphabetically:
$unsorted = [
    'D' => [
        'C' => ['c', 'b', 'a'],
        'B' => 'bvalue',
        'A' => ['a', 'c', 'b'],
    ],
    'C' => 'cvalue',
    'B' => 'bvalue',
    'A' => [
        'Z' => 'zvalue',
        'A' => 'avalue',
        'B' => 'bvalue',
    ]
];

The sort has to be recursive as the array above is multidimensional. It holds other arrays (numerically indexed and associative) as its values.
I managed to sort the array's keys recursively using this function:
function sortKeysRecursive(&$array)
{
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            sortKeysRecursive($value);
        }
    }

    ksort($array);
}

However, I was unable to sort the values without messing with already sorted keys. To sort the values I tried to apply this function:
function sortValuesRecursive(&$array)
{
    foreach ($array as &$value) {
        if (is_array($value)) {
            sortValuesRecursive($value);
        }
    }
    asort($value);
}

sortKeysRecursive($unsorted);
sortValuesRecursive($unsorted);

But it's one or the other. Both function applied to the same array always mess the other functions work.
I'd expect to produce sorted array that looks like this:
$sorted = [
    'A' => [
        'A' => 'avalue',
        'B' => 'bvalue',
        'Z' => 'zvalue',
    ],
    'B' => 'bvalue',
    'C' => 'cvalue',
    'D' => [
        'A' => ['a', 'b', 'c'],
        'B' => 'bvalue',
        'C' => ['a', 'b', 'c'],
    ],
];

A: you need to check keys are numeric or alphabetic. try below solution you may need to modify conditions for your purpose:
<?php

function isAssoc(array $arr)
{
    return array_keys($arr) !== range(0, count($arr) - 1);
}

function sortArray(&$arr){
    if(isAssoc($arr)){
        ksort($arr);
    } else{
        asort($arr);
    }
    foreach ($arr as &$a){
        if(is_array($a)){
            sortArray($a);
        }
    }
}

$unsorted = array(
    'D' => array(
        'C' => array('c', 'b', 'a'),
        'B' => 'bvalue',
        'A' => array('a', 'c', 'b'),
    ),
    'C' => 'cvalue',
    'B' => 'bvalue',
    'A' => array(
        'Z' => 'zvalue',
        'A' => 'avalue',
        'B' => 'bvalue',
    )
);
sortArray($unsorted);

print_r($unsorted);

Output
Array
(
    [A] => Array
        (
            [A] => avalue
            [B] => bvalue
            [Z] => zvalue
        )

    [B] => bvalue
    [C] => cvalue
    [D] => Array
        (
            [A] => Array
                (
                    [0] => a
                    [2] => b
                    [1] => c
                )

            [B] => bvalue
            [C] => Array
                (
                    [2] => a
                    [1] => b
                    [0] => c
                )

        )

)

A: Use following method and loop through the $unsorted array and sort conditionally:
function recursiveSort(array &$unsorted) {

    // Sort array keys
    ksort($unsorted);

    foreach ($unsorted as $key => $array) {
        if (!is_array($array)) {
            continue;
        }

        if (is_numeric(key($array))) {
            asort($array);
        } else {
            recursiveSort($array);
        }
        $unsorted[$key] = $array;
    }
}

Usage:
recursiveSort($unsorted);

Hope it helps

A: function sortKeysRecursive(&$array)
{
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            sortKeysRecursive($value);
        }
    }

    ksort($array);
}

/**
 * Sort only the arrays that doesn't have a child array, this way
 * we don't mess with what sortKeysRecursive has sorted
 */
function sortValuesRecursive(&$array)
{
    $isArray = false;

    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            $isArray = true;
            sortValuesRecursive($value);
        }
    }

    if ($isArray === false) {
        asort($array);
    }
}

sortKeysRecursive($unsorted);
sortValuesRecursive($unsorted);


text:
Q: jquery or javascript to check which div is open My page has got many divs which internal contains menus. After auto refresh it coming back to home page. i want to know before auto refresh which div was visible or shown so that after auto refresh i can again openup the same div.

A: You can store all div's display status in php code/database/session..so that whenever page get refreshed it will pull out divs status from db or session and will show expected result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using ClaimsAuthenticationManager in a console application I was playing around with new stuff in 4.5 and wrote a simple console application that is supposed to check a few things in new claims based security model. I've created custom implementations of ClaimsAuthorizationManager and ClaimsAuthenticationManager, added them to application config file, set AppDomain principal policy to windows principal, and almost everyghing works well except AuthenticationManager.Authenticate method being called.
AuthorizationManager.CheckAccess is being called as expected.
I guess that this is right behaviour as when running console app the user is already authenticated and there is no need to do it on app startup. However I would like to transform some claims based on - let us say profile stored in database.
Of course I can do it manually and deal with the CurrentPrinciapal object on my own. However I was wondering if there is a way to force app to use AuthManager to do it for me.
Just being curious :)
So, here are two managers. They basically do nothing, exist just for setting break point :)
  public class AuthorizationManager : ClaimsAuthorizationManager
{
    public override bool CheckAccess(AuthorizationContext context)
    {
        return base.CheckAccess(context);
    }
}

 public class Authenticationmanager : ClaimsAuthenticationManager
{
    public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
    {
        return base.Authenticate(resourceName, incomingPrincipal);
    }
}

App.config looks like this:
    <configuration>
  <configSections>

  </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <system.identityModel>
    <identityConfiguration>
      <claimsAuthenticationManager type="ClaimsSandbox.Authenticationmanager, ClaimsSandbox"/>
      <claimsAuthorizationManager type="ClaimsSandbox.AuthorizationManager, ClaimsSandbox"/>
    </identityConfiguration>
  </system.identityModel>
</configuration>

And the code that does nothing special:
 class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

        var principal = Thread.CurrentPrincipal;
        DescribeMe(principal);
        ClaimsPrincipalPermission.CheckAccess("foo ", "bar");
        Console.ReadLine();
    }

    private static void DescribeMe(System.Security.Principal.IPrincipal principal)
    {
        Console.WriteLine(principal);
        var claimsPrincipal = principal as ClaimsPrincipal;
        claimsPrincipal.IsInRole("Foo");
        Console.WriteLine(claimsPrincipal.Identity.IsAuthenticated);
    }
}

A: In a console app, you would have to explicitly call Authenticate() like this. In .NET 4.5, you use IdentityConfiguration. In .NET 4.0, it would have been FederatedAuthentication.ServiceConfiguration.ClaimsAuthenticationManager.
var cam = IdentityConfiguration.ClaimsAuthenticationManager;
Thread.CurrentPrincipal = cam.Authenticate
                                 ("http://badri/MyResource",
                                         incomingPrincipal);

Idea behind taking the pains of providing one's own implementation of CAM is, you will want to add, modify of delete claims on the token from STS. You can have your own logic in adding stuff based on your database and all that here and enrich the principal that was created based on the claims from STS (incomingPrincipal).

A: ClaimsAuthenticationManager is part of WIF processing pipeline.
You can derive from this class to provide claims transformation inside this pipeline.
There is no need to explicitly call Authenticate method since it does nothing in it's base implementation.
To get this method called you have to integrate WIF with either WCF or ASP.NET application (can be MVC).
Quoting msdn:

WIF also provides developers with a consistent programming experience whether they choose to build their applications in ASP.NET or in WCF environments.

You can read more here.


text:
Q: ElasticSearch update query using NOT and AND to be ES 5.5 compatible I need to update this query to be ES 5.5 compatible (NOT and AND are deprecated).
:and => [
  {
    term: {
      type: 'group'
    }
  },
  {
    :not => {
      terms: {
        group_id: group_ids
      }
    }
  },
  {
    :not => {
      terms: {
        user_id: user_ids
      }
    }
  }
]

A: Try this:
:bool => [
  :filter => [
    {
      term: {
        type: 'group'
      }
    }
  ],
  :must_not => [
    {
      terms: {
        group_id: group_ids
      }
    },
    {
      terms: {
        user_id: user_ids
      }
    }
  ]
]


text:
Q: Tikz: Is there a way to create head-less arrows width edges (angled)? I have this arrow which works fine if it is used with a node:
\node[draw, single arrow,
        minimum height=9mm, minimum width=1mm,
        single arrow head extend=0mm,
        anchor=west]

but how can I get the same arrow with \draw and in an "angled"-version like (a) |- (b)?

A: If I have correctly understand the OP, this is my attempt:
\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\newcommand{\angledArrowDown}[3]{
\coordinate (A) at #2;
\coordinate (B) at #3;
\node[anchor=south west,inner sep=#1/4] (StPoint-1)at (A){};
\node[anchor=north west,inner sep=#1/4] (StPoint-2) at (A){};
\node[anchor=south west,inner sep=#1/2] (EndPoint-1)at (B){};
\node[anchor=south east,inner sep=#1/2] (EndPoint-2) at (B){};
\draw (StPoint-1.north west) -| (EndPoint-1.north) -- (EndPoint-1.north east) -- (B)
-- (EndPoint-2.north west) -- (EndPoint-2.north) |- (StPoint-2.south west) -- cycle;}

\newcommand{\angledArrowUp}[3]{
\coordinate (A) at #2;
\coordinate (B) at #3;
\node[anchor=south west,inner sep=#1/4] (StPoint-1)at (A){};
\node[anchor=north west,inner sep=#1/4] (StPoint-2) at (A){};
\node[anchor=north east,inner sep=#1/2] (EndPoint-1)at (B){};
\node[anchor=north west,inner sep=#1/2] (EndPoint-2) at (B){};
\draw (StPoint-1.north west) -| (EndPoint-1.south) -- (EndPoint-1.south west) -- (B)
-- (EndPoint-2.south east) -- (EndPoint-2.south) |- (StPoint-2.south west) -- cycle;}
\begin{document}
\begin{tikzpicture}
%\angledArrowDown{thick}{star point}{end point below start point}
\angledArrowDown{5mm}{(0,1)}{(1,-1)}

%\angledArrowUp{thick}{star point}{end point above start point}
\angledArrowUp{5mm}{(0,-3)}{(1,-1)}
\end{tikzpicture}
\end{document}

A: Just for fun: some arrow style of that sort. The advantage is that you can draw the arrow with simple commands like
\draw[outlined arrow] (-1,3) -| (0,0);

The disadvantage is that, unlike vi pa's nice answer or this answer, it overpaints the interior in white. The appearance is controlled by various pgf keys (see the examples in the shifted scope).
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{tikzpicture}[outlined arrow/.code={\tikzset{oarrow/.cd,#1},
    \def\pv##1{\pgfkeysvalueof{/tikz/oarrow/##1}}%
    \edef\locallw{\the\pgflinewidth}%
    \tikzset{-{Triangle[open,fill=white,line width=\locallw,
        length=\pv{head length},width=\pv{head width}]},
    line width=\pv{line width},
    postaction={-,draw=white,line width=\pv{line width}-2*\locallw,
        shorten <=\locallw,shorten >=\pv{head length}-1.5*\locallw}%
    }},oarrow/.cd,line width/.initial=0.6cm,head width/.initial=1.2cm,
    head length/.initial=1cm]
 \draw[outlined arrow] (-1,3) -| (0,0);
 \draw[outlined arrow] (-1,-3) -| (0,0);
 \begin{scope}[xshift=5cm]
  \draw[blue,thick,outlined arrow={line width=0.7cm,head width=1.4cm}] (-1,3) -| (0,0);
  \draw[red,outlined arrow={line width=0.5cm,head length=0.8cm}] (-1,-3) -| (0,0);
 \end{scope}
\end{tikzpicture}
\end{document}

Curved arrows do not work with this style, you may want to look e.g. here for a possible way to do curved arrows.


text:
Q: Multiple callback cause ConcurrentModificationException I am having a for loop that call a callback for each object, each will do some modification to the same SharedPreference data. How do I prevent them from modifying the data (while another is reading/modifying it)?
ArrayList<Object> arrayList = ... //initialize with data
for(Object i: arraylist){
    Callback cb = new Callback(){
        @Override
        public void onResult(String info, float v)
        {
           //modify the data in SharedPreference (not in the arraylist)
        }
    };
}


text:
Q: Which vs. What in regards to Continuous Numbers (like Temperature)? As this question makes clear, "which" is used when there is a set number of choices available, while "what" is used when there is not a set number of choices available.
Which term do we use, however, when we are referring to continuous numbers as opposed to discrete numbers? How about numbers that are technically continuous but are in practice discrete?
Discrete number example: Which parking spot were you assigned to? (There are a discrete set of parking spots which one could be assigned to).
Continuous number example: Which/what temperature do you brew your beer at? (There are an infinite amount of temperatures available; however, brewers typically brew between the ranges of 40*F and 85*F, so it would seem to be discrete. On the other hand, there are an infinite amount of numbers between two consecutive integers, i.e 41.1, 41.2, 41.22, 41.3333 ...)
When referring to time, which is another example of continuous or discrete (there are 24 hours in a day, but an infinite number of units in between two consecutive hours), I always hear people use "what"-- "What time is it? What time shall I pick you up?"

A: 'What' is usually used for continuous data treated as, or rather being considered as, continuous: 'what time is it?' / 'what temperature do you brew your beer at?' / 'what speed are you doing?'
For days and years, both 'what day/year was that?' and 'which day/year was that?' are used. Time is continuous, but is often treated as if it were discrete, and is probably then being considered as discrete. This gets even more complicated, as you point out, because age in years is almost always treated as being (and is often thought of as being) discrete, but 'what age is he?' would be used.


text:
Q: Unable to receive flutter notification in ios with firebase and flutter local notification <12 Hi the plugin i am using are firebase_messaging: ^14.1.2 and flutter_local_notifications: ^12.0.4
Firstly it works fine with android however in ios i have no notification,
I set up my AppDelegate.swift as follows
import UIKit
import Flutter
import background_locator_2
import flutter_local_notifications

func registerPlugins(registry: FlutterPluginRegistry) -> () {
    if (!registry.hasPlugin("BackgroundLocatorPlugin")) {
        GeneratedPluginRegistrant.register(with: registry)
    }
}

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    BackgroundLocatorPlugin.setPluginRegistrantCallback(registerPlugins)
     if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

nextly in my main.dart
final FlutterLocalNotificationsPlugin notificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();

  print('Handling a background message ${message.messageId}');
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  AndroidInitializationSettings androidSettings =
      AndroidInitializationSettings("@mipmap/ic_launcher");

  DarwinInitializationSettings iosSettings = DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestCriticalPermission: true,
      requestSoundPermission: true);

  InitializationSettings initializationSettings =
      InitializationSettings(android: androidSettings, iOS: iosSettings);

  bool? initialized = await notificationsPlugin.initialize(
      initializationSettings, onDidReceiveNotificationResponse: (response) {
    log(response.payload.toString());
  });

  log("Notifications: $initialized");

  await Firebase.initializeApp();
  currentFirebaseUser = FirebaseAuth.instance.currentUser;
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true, badge: true, sound: true);

  await UserSimplePrefences.init();
  //await FirebaseAuth.instance.currentUser;
  runApp(MyApp());
}

This is where I handle the messages and move to other window and do stuffs
class PushNotificationService {
  FirebaseMessaging firebasemessaging = FirebaseMessaging.instance;
  Future initialize(context) async {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message
          .notification; //assign two variables for remotenotification and android notification
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        retrieveRideRequestInfo(getRideRequestId(message.data)!, context);

        notificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            iOS: DarwinNotificationDetails(
              presentAlert: true,
              presentBadge: true,
              presentSound: true,
            ),
            android: AndroidNotificationDetails("Driver", "You have a new ride",
                priority: Priority.max, importance: Importance.max),
          ),
        );
        print('AndroidNotification after clicking ' + notification.title!);
        print('AndroidNotification after clicking ' + notification.body!);
        print("This is message map");

        //getRideRequestId(message);
      }
    });

    //on message open
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      // same as above
      RemoteNotification? notification = message
          .notification; //assign two variables for remotenotification and android notification
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        // if (doublenotification.isOdd)
        retrieveRideRequestInfo(getRideRequestId(message.data)!, context);

        print('AndroidNotification after clicking ' + notification.title!);
        print('AndroidNotification after clicking ' + notification.body!);

        //getRideRequestId();
      }
      //}
    });
  }
}

In android it works fine however in IOS, there is absolutely nothing happening, no logs ,notifications or error, what am I missing here ?


text:
Q: If virtual photons are just mathematical constructs, what is the real physical principle that allows EM field to give momentum to a charged particle? If virtual photons are just mathematical constructs, what is the "real" (if such an adjective makes sense) physical principle that allows electromagnetic field to deliver momentum to a charged particle?

A: tl;dr See the bold paragraph below.
Your question is how the vector field $A^\mu$ "really" causes an electromagnetic force. But let's start with a toy problem: how would a scalar field $\varphi$ cause a force?
I'll work in $+---$ with $c=\hbar=1$, and denote $\varphi$'s source current by a scalar $J$. The basic idea is a brief timeslice has probability amplitude of the form$$e^{iW}=\int\mathcal{D}\varphi\exp(iS)=\langle0|e^{-iHT}|0\rangle=e^{-iET},$$where$$S=\int d^4x\left[J(x)\varphi(x)-\frac12\varphi(\square+m^2)\varphi\right]$$is an action over the timeslice, not all of spacetime. After some Fourier transforms (see e.g. Quantum Field Theory in a Nutshell Secs. I.2-I.4 for the calculation), one unit "charge" at $\vec{x}_1$ gives another at $\vec{x}_2$ the potential energy$$E=-\int\frac{d^3\vec{k}}{(2\pi)^3}\frac{\exp i\vec{k}\cdot(\vec{x}_1-\vec{x}_2)}{\vec{k}^2+m^2}=-\frac{e^{-mr}}{4\pi r}<0,$$implying an attractive force. But we need to talk about how $W$ looks, for an arbitrary matter distribution:$$W=-\frac12\int\frac{d^4k}{(2\pi)^4}\frac{|J(k)|^2}{k^2-m^2+i\varepsilon},\,J(k):=\int d^4xJ(x)e^{-ik\cdot x}.$$The $\varepsilon\to0$ later; it's just a way of being careful with the complex analysis. But notice the integral is over all of $k$-space, so it looks like $W$ is caused by particles of every $4$-momentum, including the unphysical ones with $k^2-m^2\ne0$. That's where the idea of "virtual particles" comes from, but they're symptoms of the field $\varphi$, not observable particles, which are often described as "bumps on the field".
Fields, not particles, are fundamental; "virtual particles" are just a description of the mathematical appearance of an odd way fields work in $W$. But the real physical principle by which $\varphi$ causes a potential energy $E$ is that it causes a $k$-space integral that gives the phase $W$ of the path integral.
What about the vector case, then? It's very similar (ibid. I.5, which gets the massive case, then takes $m\to0$ for electromagnetism's photon when we're ready):$$W=-\frac12\int\frac{d^4k}{(2\pi)^4}\frac{\overline{J^\mu(k)}(m^{-2}k_\mu k_\nu-g_{\mu\nu})J^\nu(k)}{k^2-m^2+i\varepsilon}.$$The charge conservation law $k_\nu J^\nu(k)=0$ simplifies this to$$W=\frac12\int\frac{d^4k}{(2\pi)^4}\frac{\overline{J^\mu(k)}J_\mu(k)}{k^2-m^2+i\varepsilon}.$$The $-$ sign on $g_{\mu\nu}$ has ensured like charges repel this time. The general rule is a spin-$s$ field attracts (repels) like charges for $s$ even (odd).

A: If you are asking at the elementary particle level, light is  a sum of a large number of real photons, by real meaning the photons have a four vector which has an invariant mass of zero, i.e. on mass shell. These photons carry momentum and can transfer a dp/dt in interacting.
The interactions of a photon with a particle or field are mathematically modeled with Feynman diagrams( second page in link). That is where virtual particles are presumed to exit, they are the carriers of the quantum numbers that are needed for correct conservation, but the mass of  their  four vectors is not zero, as it should be for the photon. The virtual particle, photon in your question,  is off mass shell. It is named as a "photon" for convenience in keeping track of the interactions.
My answer here may help in understanding photons and fields.

A: Coulomb's Law:
$$ {\bf F} = \frac 1 {4\pi\epsilon_0} \frac{q_1q_2}{r^2}{\bf \hat r}$$
There's also some magnetism, depending on spin an kinematics.

A: Heuristic explanation: We know that there is no instantaneous action at distance, two electrons for example in interaction must undergo a variation of the parameters of their environments caused by the presence of the other, if they are separated by a distance d, the variation of the parameters happens in a time $t+d/c$ (a time of delay to act), we know that for a central field (Newton's law) $\mathbf{F}dt=-\mathbf{\nabla}U dt=dp$, that we can transform in $\Delta U \Delta t= \Delta x \Delta p $, but according to Heisenberg's uncertainty principle : $\Delta U \Delta t= \Delta x \Delta p\geq \hbar $.
A violation of the law of conservation of energy up to a quantity $\Delta E=\Delta U$(change in the energy of the environment brought by the energy of the photo) will be hidden by the uncertainty on the energy provided that the time available to make the observation $\Delta t$ is sufficiently large such that $\Delta t = \frac{\hbar}{\Delta U }$, if the emissaries of the one towards the other to prevent him of its presence in its environment are photons of energy $h\nu$ and that $\Delta t =\frac{\hbar}{ h\nu }$ .
These photons are then observable on a maximum distance of: $R= c \Delta t=\frac{c}{4\pi\nu }<d$,
and as the frequency can be arbitrarily small, the range of the force transmitted by the massless photon is unlimited. It may appear from this relation that the range is limited for a free photon. But this would be forgetting that a free photon does not exist, because it would have a totally undetermined frequency. So the interaction distance would be too.
These exchange quanta, which are unobservable, are called "virtual photons". As photons are not charged, we also say that the interaction is carried out by "neutral current".
A much more satisfactory approach is to use mass as the energy term:  $\Delta t \le \frac{\hbar}{mc^{2} }$
Using this relation, it is possible to know the time during which a virtual particle can travel a distance that would correspond to:$ R= c \Delta t= \frac{\hbar}{mc^{2} }$ which intervenes in the  Yukawa potential.


text:
Q: What is the role of empirical risk minimization in support vector machines? While learning about SVMs, I have come across a term called empirical risk minimization (EMR). I have learnt about this in this paper by Smola and Schölkopf but failed to understand what is the role of empirical risk minimization in support vector machines? And please also tell me how sequential minimal optimization implements EMR in the LibSVM package?

Smola, Alex J., and Bernhard Schölkopf. "A tutorial on support vector
  regression." Statistics and computing 14.3 (2004): 199-222.


text:
Q: How to find count of one column based on two columns How I can get last column based on the "competition" and "user" columns? the following query gives error!

SELECT DISTINCT COUNT(*) AS countofcomments
FROM k
GROUP BY competition, user

A: I don't know is that a good practice you trying to achieve, On considering the result set you can try something like this
CREATE TABLE #Example(
       [competition]      [nvarchar](50)   NULL,
       [user]   [nvarchar](50)   NULL,
       [comments]   nvarchar(50) NOT NULL,
)
GO

INSERT   #Example  ([competition],[user],  [comments])   VALUES ('INDIA','CHENNAI','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('INDIA','KOCHI','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('INDIA','BANGLORE','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('INDIA','HYDERABAD','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('US','MAIAMI','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('US','SANFRANC','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('US','MOUNT','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('US','LOSANGELS','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('UK','MANCHESTER','ssss')
INSERT   #Example  ([competition],[user],  [comments])   VALUES ('UK','CHELSEA','ssss')

SELECT * from (
SELECT * FROM #Example
) tab1 join

(
SELECT [competition] , count([comments] )count FROM #Example
group by [competition]
) tab2 on tab1.[competition]= tab2.[competition]

DROP table #Example

A: You can do this using window function:
SELECT *, COUNT(*) OVER(PARTITION BY competition, user) as [Count of comments]
FROM k


text:
Q: Security Attacks possible on TokenBased Authentication? I have designed a web application which uses very simple implementation of JWT token's to provide Authentication/Authorization.
My Implementation :

*

*There are two types of urls's public and secure.

*Public urls are to generate token with username/password.

*I have added filter on secure url to check for the Authorization Header and JWT Token.
@Bean
public FilterRegistrationBean jwtFilter()
{
     final FilterRegistrationBean registrationBean = new
     FilterRegistrationBean();
     registrationBean.setFilter(new JwtFilter());
     registrationBean.addUrlPatterns("/secure/*");

     return registrationBean;

}

*Filter will validate the token. I haven't added expiration date yet.
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final String authHeader = request.getHeader("authorization");

if ("OPTIONS".equals(request.getMethod())) {
    response.setStatus(HttpServletResponse.SC_OK);

    chain.doFilter(req, res);
} else {

    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServletException("Missing or invalid Authorization header");
    }

    final String token = authHeader.substring(7);

    try {
        final Claims claims = Jwts.parser().setSigningKey(secretKey.toString).parseClaimsJws(token).getBody();
        request.setAttribute("claims", claims);
    } catch (final SignatureException e) {
        throw new ServletException("Invalid token");
    }

    chain.doFilter(req, res);
}

This is providing authentication and also its is immune to CSRF.No one can create valid token without secret Key.
Are there other attacks possible on token base authentication service which i have missed?


text:
Q: jQuery Strange duplicate iteration I have a form with 5 file upload fields and a '[+] Add more file' link. It works fine by displaying one field per click, but after I an attachment the DOM structure changes as can be seen below and therefore when I hit [+] Add more files, it displays me twice fields at once (instead one). I don't clearly understand why

Here is the HTML structure

Here is jQuery code:
//FETCH THE ARRAY OF 5
var webform_divs = $('.webform-client-form').find('div[id$="-ajax-wrapper"]');
//INITIAL STATE
    if (!($("#addmore").length > 0)) {
                    webform_divs.hide();
                   webform_divs.first().show();
                    webform_divs.last().after(''+"[+] Add more files"+'');
                }
//FUNCTION CALL
more_upload_fields(webform_divs);

//FUNCTION BODY
                function more_upload_fields(field_wrappers) {

                    $("#addmore").click(function(e) {
                        e.preventDefault();

                        field_wrappers.each(function(index) {
                           if ($(this).is(":hidden")) {
                                //console.log(index);
                                //console.log($(this));
                                $(this).show();
                                if ($(this).next().is('#addmore')) {
                                    $("#addmore").hide();
                                }
                                return false;
                            }
                        });
                        return false;
                    });
                }


text:
Q: typescript errors in .spec files in visual studio web application I have set up visual studio web app using angular 4 and typescript 2.4.2.
But i'm still getting some errors related to typescript from the karma and jasmine files.
I tried changing the es5 to es6 but still the error persists.I have read a lot of solutions but none of them are working.
Screenshot of the errors

Below is the package.json
{
  "name": "angularapp",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@types/bootstrap": "^3.3.35",
    "@types/jquery": "^3.2.10",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "rxjs": "^5.4.1",
    "systemjs": "^0.20.16",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.2.3",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "^6.0.85",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.4.2"
  }
}

tsconfig.json
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es6", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "types": [
      "jquery",
      "bootstrap",
      "node"
    ],
    "typeRoots": [
            // add path to @types
            "node_modules/@types"
         ]
  }
}

A: So this is what i did

*

*npm upgrade

*npm install --save-dev "@types/jasmine"

*then in app.component.spec.ts
import { } from 'jasmine';
clean and build it works fine.
Thanks


text:
Q: On Screen Keyboard not working in Custom Shell, Windows 10 Pro 1709 and 1803 We are using the On Screen Keyboard in Windows 10 Pro for our Custom Shell application.
Since release 1607 and for 1703 the registry setting "EnableDesktopModeAutoInvoke" in "HKCU\SOFTWARE\Microsoft\TabletTip\1.7" set to DWORD=1 has provided the On Screen Keyboard for the user running the application, but since relase 1709 this is not working anymore. I have also tried latest 1803 release with the same negative result.
Is there any other solution than the registry setting that can help us out here?
What have changed in the 1709 (and 1803) release? Is this "by design" or a mistake?
The 1703 support is ending fall 2018.
Thanks.


text:
Q: box-java-sdk - Normal Authentication I am trying to build an application with Box SDK in Java. Currently, I am connecting to my Box with a developer token:
BoxAPIConnection api = new BoxAPIConnection("MY-DEVELOPER-TOKEN");

I have to generate a new developer token every 60 minutes, therefore I would like to make it so this is done automatically. According to the Box API authentication doc, we can do it with:
BoxAPIConnection api = new BoxAPIConnection("MY-CLIENT-ID", "MY-CLIENT-SECRET", "MY-AUTH-CODE");

However, I get:
Exception in thread "main" com.box.sdk.BoxAPIException: The API returned an error code: 400
{"error":"invalid_grant","error_description":"Auth code doesn't exist or is invalid for the client"}

I get my Client ID and Client Secret from the configuration page of my Box account, so I assume these are correct. Where can I get my authentication code? The one I am using is the one from a pop-up window when I first connected to my account.

A: You can get the authentication code like this:

*

*go to a browser and type in with your client_id:

https://account.box.com/api/oauth2/authorize?response_type=code&client_id=xxxxxx&state&state=security_token%3DKnhMJatFipTAnM0nHlZA

*authorize the app and you'll get a code back (make sure your redirect is something like localhost

*then use postman and do this (fill in the code w/ what you just got back)


text:
Q: Apache Oltu unsupported_response_type This is the problem when I try to receive an access token from github.
OAuthProblemException{error='unsupported_response_type', description='Invalid response! Response body is not application/json encoded', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
I want to keep it as general as possible so I don't want to use the GithubTokenResponse class. What options do I have left to avoid the exception ?
            OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
            OAuthClientRequest request = OAuthClientRequest
                    .tokenLocation("https://github.com/login/oauth/access_token")
                    .setCode(code)
                    .setGrantType(GrantType.AUTHORIZATION_CODE)
                    .setClientId(id)
                    .setClientSecret(secret)
                    .buildQueryMessage();

            OAuthAccessTokenResponse  tk = oAuthClient.accessToken(request); //this causes the problem

"Ugly" solution :
GitHubTokenResponse  tk = oAuthClient.accessToken(request, GitHubTokenResponse.class);

A: It also works with OAuthJSONAccessTokenResponse. Here is the following code what I try and it is working fine.
OAuthClient client = new OAuthClient(new URLConnectionClient());

            OAuthClientRequest request =
                    OAuthClientRequest.tokenLocation(TOKEN_REQUEST_URL)
                    .setGrantType(GrantType.CLIENT_CREDENTIALS)
                    .setClientId(CLIENT_ID)
                    .setClientSecret(CLIENT_SECRET)
                    // .setScope() here if you want to set the token scope
                    .buildQueryMessage();
            request.addHeader("Accept", "application/json");
            request.addHeader("Content-Type", "application/json");
            request.addHeader("Authorization", base64EncodedBasicAuthentication());

            String token = client.accessToken(request, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class).getAccessToken();

I think we need to set the content type in the header. These two lines which fix the issue.
request.addHeader("Accept", "application/json");
request.addHeader("Content-Type", "application/json");

Hope this help.

A: Same issue at my end is fixed by below -

*

*Added missing org.json Jar

*Removed duplicate header 'content-type' in request

A: In my case I have already set these headers but still got this exception. Quoting from source from 1.0.2 tag.
try {
            this.body = body;
            parameters = JSONUtils.parseJSON(body);
        } catch (Throwable e) {
            throw OAuthProblemException.error(OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE,
                "Invalid response! Response body is not " + OAuth.ContentType.JSON + " encoded");
        }

It hides the Throwable exception e. While debugging I found that it was class not found error for org.json.JSONTokener. So adding org.json jar to the tomcat lib I could prevent this exception.


text:
Q: Unit Test debugging steps randomly through the code We've got a project which has recently been upgraded from being written under VS2010 (using .net Framework 3.5) to VS2012 (using .net Framework 4). We work with TFS, so older builds are available to work on.
When debugging the VS2010 versions of the build breakpointing the <TestMethod()> methods will work, stepping into and breakpointing on the called code works, and stepping through the code from start to finish works.
In the 2012 version, breakpoints only really work in the <TestMethod()> code. Once the code leaves the <TestMethod()> area, things get odd. Stepping into and through the code seems to simply step to random lines in the code. Values resolve strangely and the debugger seems to hop forward through the code largely at random. Once the debugger returns to the <TestMethod()> code area, things go back to normal, and the correct results are returned from the called functions even though the values shows during debugging were all strange.
I can't really think how to describe what's going on any better than that. I'm not in charge of building the software, and the people who are aren't aware of anything that they have changed that might have caused this issue.
Does any of this sound familiar enough to anyone that they can suggest what setting might have been changed to produce this behaviour, or what I need to set under .net 4 in order to get unit testing working again?

A: This usually happens when the source code that is being used by the debugger is different to the source code that has been used to compile the assembly you are debugging.


text:
Q: Multiple regex checks on same string with no overlapping results, while ignoring words I have a string in which I want to check for the existence of 2 different types of item. These two types are not mutually exclusive, so I want to also avoid overlap. They can also occur in any order. There are also words within the string that should be ignored, even though they fit the regex pattern.

*

*There must be one alpha only item, one to many characters: [a-zA-Z]+.

*Another item needs to be alphanumeric, also one to many characters: [a-zA-Z0-9]+.

*The alphanumeric item cannot also satisfy the criteria of the alpha-only item, and vice versa.

*The items in an exclusion list should be ignored.

I tried following the post Regex: I want this AND that AND that... in any order, but I still can't figure out how to exclude the words I need, and I could not figure out how to leverage that answer so that one word didn't satisfy both alphanumeric and alpha only criteria.
This is what I'm currently doing, and it seems to be working, just not very concise. If possible, I'd like to learn how I can expand this out to a single regex check. Apart from not being super concise, I feel that regex will be safer down the road in case I end up needing to add more conditions.
bool bHasAlpha = false;
bool bHasAlphaNum = false;
string Test = "123 ABC SomeWord A12";   //The string to check against.
string[] RemoveWords { "ABC", "DEF" };  //I don't want these matches to count, if found.

//Split my string into "tokens" and check each individually, ignoring the RemoveWords.
string[] TestTokens = Test.Split(' ')
            .Select(s => s)
            .Where(w => !RemoveWords.Contains(w, StringComparer.OrdinalIgnoreCase))
            .ToArray();

foreach (string s in TestTokens)
{
    //Is this item alpha-only? (Checking this before alphanumeric)
    if (!bHasAlpha && Regex.IsMatch(s, @"^[a-zA-Z]+$"))
        bHasAlpha = true;
    //Is this item alphanumeric?
    else if (!bHasAlphaNum && Regex.IsMatch(s, @"^[a-zA-Z0-9]+$"))
        bHasAlphaNum = true;
}

if (bHasAlpha && bHasAlphaNum)
    Console.WriteLine("String Passes!");

In the test code above, the string would pass because "123" is caught by the alphanumeric check, and "SomeWord" is caught by the alpha-only check. "ABC" was not because I purposely ignore it.
Examples of strings that should fail:

*

*"123 abc 456" (abc ignored, no valid alpha-only item)

*"X" (X can satisfy either alpha or alphanumeric, not both)

*"ABC DEF 123 456" (ABC and DEF ignore, no valid alpha-only item)

The following should pass:

*

*"ABCDEF 123" (ABCDEF as a whole word are not considered the same as ABC and DEF separately)

*"X X" (2 "words", neither are in the excluded list. One satisfies the alphanumeric criteria, on the alpha-only.)

*"ABC XYZ ABC DEF A1B2 ABC" (XYZ is alpha, A1B2 is alphanumeric)

*123 XYZ (order of the 2 items does not matter. Alpha-only can be 2nd)

A: I'm afraid a single regex doing all these would be overly complicated if possible at all. However, you may simplify the code by using regexes in two steps:

*

*Remove all the words to be ignored with this regex:
\b(?:ABC|DEF)\b

*Check if the remaining string matches the "alpha & alphanumeric" condition (pseudo code below for the sake of clarity):
ALPHA.*ALNUM|ALNUM.*ALPHA

In C#:
var removeRegex = new Regex(@"\b(?:" + string.Join("|", RemoveWords) + @")\b", RegexOptions.IgnoreCase);
var alpha = @"\b[a-z]+\b";
var alnum = @"\b[a-z0-9]+\b";
var matchRegex = new Regex(string.Format(@"{0}.*{1}|{1}.*{0}", alpha, alnum), RegexOptions.IgnoreCase);
foreach (var s in testStrings)
{
    var ok = matchRegex.Match(removeRegex.Replace(s, "")).Success;
    Console.WriteLine("{0}:\t{1}", ok ? "OK" : "Failed", s);
}

Demo: https://dotnetfiddle.net/Ms3uKV

A: When you found an Alpha item, you need to skip the check.
foreach (string s in TestTokens)
{
    //Is this item alpha-only? (Checking this before alphanumeric)
    if (!bHasAlpha && Regex.IsMatch(s, @"^[a-zA-Z]+$")) // Add !bHasAlpha to skip chekcing if you have found one
        bHasAlpha = true;
    //Is this item alphanumeric?
    else if (Regex.IsMatch(s, @"^[a-zA-Z0-9]+$"))
        bHasAlphaNum = true;
}


text:
Q: Is there a problem in this statement: As $\sum_{n=1}^{\infty} \mu(n)/n = 0, \sum_{n=1}^{N} \mu(n)/n = -\sum_{n=N+1}^{\infty} \mu(n)/n$. As by Landau's proof
$$\sum_{n=1}^{\infty} \mu(n)/n = 0$$
Therefore for any $N \in \mathbb{N}$,
$$ \sum_{n=1}^{N} \mu(n)/n = -\sum_{n=N+1}^{\infty} \mu(n)/n$$
Is there a problem with the above statement? A friend of mine has concerns about the conditional convergence causing issues due to Riemann's rearrangement theorem. I am of the opinion that the sequence is not being changed, just the series is being split. We aren't able to convince each other.
Thanks in advance.

A: This is always true if the series converges. It doesn't even matter if the terms are positive, the convergence is absolute, etc. Indeed, we have
$$0 = \sum_{n=1}^\infty\mu(n)/n = \sum_{n=1}^N \mu(n)/n + \sum_{n=N+1}^\infty \mu(n)/n$$
Thus, the result follows by substracting $\sum_{n=N+1}^\infty \mu(n)/n$, which is allowed because the series converges by my assumption.

A: By definition, $$\sum_{k=1}^\infty a_k=L $$
means that for every $\epsilon>0$, there exists $n_0$ such that
$$\left|\sum_{k=1}^n a_k-L\right|<\epsilon \text{ for all }n>n_0. $$
So if $n>\max\{n_0,n\}$, we have
$$ \sum_{k=1}^na_k=\sum_{k=1}^Na_k+\sum_{k=N+1}^{n}a_k$$
and hence
$$\left|\sum_{k=N+1}^{n}a_k- \left(L-\sum_{k=1} Na_k\right)\right|<\epsilon$$
for all $n>\max\{n_0,n\}$.
We conclude
$$ \sum_{k=N+1}^{\infty}a_k=L-\sum_{k=1}^Na_k.$$


text:
Q: Suppress "unknown enum constant" warning for enums used in class retention annotations When I'm compiling a project with a certain external jar dependency, javac is producing the following warning:
warning: unknown enum constant ReferenceCardinality.MANDATORY

This is due to the fact that the external jar dependency uses a class-retention annotation with an enum in its arguments. Something along the lines of this:
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
public class ExternalJarClass {
    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    public void someMethod(...) {}
}

I have found two ways to remove this warning:

*

*Including the command-line option -nowarn. However, I don't want to disable all warnings when compiling my project.

*Including the annotation library jar in the classpath.

I can live with option 2, but since my project doesn't require the annotation library, I'm wondering if there is any other way to suppress this warning.


text:
Q: is there a way that Cloud Function can deal with long run operation? If I want to use GCP Cloud Function to automate (also parallelise) image recognition using VISION API (Python3), but CF has a hard limit of 9 minutes duration. What if a image is very big, and takes a long time be recognised (longer than 9 minutes)? Any suggestions?

A: In the Cloud Function code, you can offload the work to App Engine or Compute Engine.

A: The Cloud Vision APIs offer an asynchronous version of the API calls, that will return an operation ID for the job.
I would create two Cloud Functions to handle this situation. The primary function would start the async operation and the response code should match whether you were able to start the job, with the body containing any details you want along with the OperationID to follow up on.
A second function would accept an operation id and check the current status and if the operation has finished return the result. Whether the function polls for a period of time internally or only does a quick check and immediate response is up to you and how you want the process to work. I would likely have the frontend display a 'processing' icon and check every 10s or so with an immediate response.


text:
Q: How to use RegularExpressionValidator on a TextBox for the first number? I have an TextBox in which i have to put my identity card number.
The thing about it is that i use an RegularExpressionValidator to have the FIRST number 1 or 2. And to be maximum of 13 numbers. E.g: 134563964294 or 2492048639193 ,  as i said the first number to be 1 or 2 and in total they have to be 13 numbers.
I tried something like: [1-2]/d{13} but only the part for 13 numbers in total worked. I don't know how to make the first number 1 or 2 .
I couldn't find anything useful on internet or here, on stackoverflow.
Can you guys please, help me with this regex problem ?
Also , i use Microsoft Web Developer 2010 express , if that is something important.

A: I believe the regex you were going for is ^[12]\d{0,12}$. The symbols at the start and end captures the start and end of the string and then the rest is quite similar to your attempt. Feel free to ask any specific questions in the comments or in a new thread!

A: ^[1-2][0-9]{12,12}$

^ asserts position at start of a number
[1-2] forces one digit to be 1 or 2
[0-9]{12,12} says min/max of 12 digits after this first digit above
$ asserts position at the end of a line so they can't run over

If you ommit the ^ or $, you can have it go more than 13 digits
Test it out on RegExr


text:
Q: MySQL: Update Record with only one FK record I have two tables.
Table A has the following:
UserID | ActiveFlag
000001 |    1
000002 |    1
000003 |    1
000004 |    1

Table B:
ID      | UserID    |   CustomerId
1       | 000001    |  10
2       | 000002    |  10
3       | 000002    |  11
4       | 000003    |  11

I want to update the ActiveFlag column in Table A to 0 where users in table B has a CustomerID of 10 and only 10. Meaning that since, in the example, UserID 000002 has two records in Table B: CustomerID 10 and 11. I don't want to update 00002 in table A.

A: 10 and only 10
update table a set activeflag = o where a.userid in
(
select b.userid from table b group by b.userid
having min(b.customerid) = max(b.customerid)
and min(b.customerid) = 10
)

A: exists comes to mind:
update tablea a
     set activeflag = 0
     where a.activeflag <> 0 and
           exists (select 1 from b where b.userid = a.userid and b.customerid = 10) and
           not exists (select 1 from b where b.userid = a.userid and b.customerid <> 10);

A: Try this:
UPDATE tableA
SET ActiveFlag = 0
WHERE UserID IN (
   SELECT UserID
   FROM tableB
   WHERE CustomerId = 10);

The principle is:

*

*It filters out all UserID with CustomerId = 10 in Table B, i.e. 000001 (ID=1)    and 000002 (ID=2)

*Check each UserID  from step 1, set ActiveFlag = 0. i.e. the first two rows in Table A are updated


text:
Q: Knockout js get specific DOM element ID i am using the knockout js in my web app,i am getting data from database and binding data using knockout js with checkbox its working, when i checked the checkbox i am getting all related data to it,but i need element ID of all the div when i checked the particular checkbox, is it possible or not ,how i can achieve this need help

      <input id="chkID" type="checkbox" data-bind="value:userId(), checked: $root.addItemTitle, click: $root.toggle" />

function UserDetails() {
  var self = this;

  function(userId username) {
    var self = this;
    self.userId = userId;
    self.username = ko.observable(username)
    self.Image=ko.computed(function() {
    return this.Image() + " " + this.Imagetype();
  }, this);
  }

  }
  self.addItemTitle = ko.observable();
  //Check Box Selected
  self.toggleAssociation = function(item, event) {
    if (item.Selected() === true) console.log("dissociate item " + item.userId());
    else console.log("associate item " + item.UserID() + " " + "UserName " + item.UserName(), "you clicked " + event.target.id);
    /// here i am getting userID,Username and checkbox element id=chkid, is   it possible to get userName elementID
    item.Selected(!(item.Selected()));
    return true;
  };
   }

A: To navigate through the HTML domain you can use these 2 JS methods
event.target.parentElement //Returns the parent object
event.target.children //Returns Children

so you can do this:
var li = event.target.parentElement;

with that you have acess to all your objects in relation to the checkbox. To get the div children you can do this:
var liChild = li.children;

that returns an array of all the elements inside the div.
to get all the ids you can do this:
function getIDs(array) {
    var output = [];
    for (var i = 0; i < array.length; i++) {
        output[i] = array[i].id;
    }
    return output;
}

and then
var ids = getIDs(liChild);

if you want to get the div you can do this
var li = event.target.parentElement;
var ul = li.parentElement;
var div = ul.parentElement;
var divChild = div.children;
var divIDs = getIDs(divChild);

EDIT : Here goes the new code for your edit

Ok, with your edit you've introduced a div that holds other divs, my awnser still holds true, but with a few enhancements. You can still use .children and .parentElement to find those elements.
var li = event.target.parentElement; //Finds parent element
var imageDiv = li.getElementsByClassName('Image')[0]; //Finds the "Image" Div (the zero is there because .getElementByClass returns an array)
var imageChild = imageDiv.children; //Gets the children
var ids = getIDs(imageChild); //Gets the IDs of the children


text:
Q: Sql query to check if the expiry date is passed I am trying to select expired contract from my data base but is not working very fine please i deed help
It was saved in data base this way
pid   | name   | booking_date | expiry_date
------|--------|--------------|-----------------
1     | home   | 2016-01-17   | 2016-11-11
2     | home+  | 2016-07-17   | 2016-10-03
3     | home++ | 2016-02-17   | 2017-13-10

SELECT * FROM hostel_client
WHERE expiry_date >= NOW() - expiry_date
ORDER BY expiry_date ASC
LIMIT 0,30

I need to output only expired contract PID 1 and 2

A: Try less than < instead of greater than >
SELECT * FROM hostel_client
WHERE expiry_date < NOW()
ORDER BY expiry_date ASC
LIMIT 0,30


text:
Q: Create Image modal I'm Trying to create an image modal in my app! I want to create a modal such as this link - https://codepen.io/koolhaus/pen/ajwcE
Here is my code:

.portfolio-list a:after {
  color: #ffff;
  content: '\f067';
  font-family: FontAwesome;
  max-width: 100%;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  background: rgba(0, 0, 0, 0.6) center center no-repeat;
  opacity: 0;
  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  text-align: center;
  align-items: center;
  justify-content: center;
}

How I can Add modal in my code?

A: My reference     JSFIDDLE
keep your div in side modal-body. I kept it once check out in your local host. don't forget to add references to html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

A: For Bootstrap Modal:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Small Modal

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
Q: MySQL Multiple Joins/Lookups for result set I'm not sure how to word this type of action to try and find help on it.
I have a table ('shifts') that is a list of dates for the start of each work week, and 5 shift fields.  The shift fields all have employee user id's (user_id).
I need to make queries to select a specific week or a range of weeks where I convert the user id's into first+last+uid combinations.
Right now, for a single week lookup, the query is taking 7 seconds to run.   Could anyone point me towards a method for multiple lookups against a single query that would run much faster?   I'm not exactly sure how to refer to what I'm trying to do here if anyone has an idea of a key word or phrase for this type of action I could search on.  Thanks for any help.
SELECT s.shift_week,
CONCAT(w1.first_name, ' ', e1.last_name, ' (', e1.user_id, ')' ) AS slot_1,
CONCAT(w2.first_name, ' ', e2.last_name, ' (', e2.user_id, ')' ) AS slot_2,
CONCAT(w3.first_name, ' ', e3.last_name, ' (', e3.user_id, ')' ) AS slot_3,
CONCAT(w4.first_name, ' ', e4.last_name, ' (', e4.user_id, ')' ) AS slot_4,
CONCAT(w5.first_name, ' ', e5.last_name, ' (', e5.user_id, ')' ) AS slot_5
FROM work_shifts.shifts AS s
LEFT JOIN employee_directroy.employees e1 ON o.slot_1 = e1.user_id
LEFT JOIN employee_directroy.employees e2 ON o.slot_1 = e2.user_id
LEFT JOIN employee_directroy.employees e3 ON o.slot_1 = e3.user_id
LEFT JOIN employee_directroy.employees e4 ON o.slot_1 = e4.user_id
LEFT JOIN employee_directroy.employees e5 ON o.slot_1 = e5.user_id
WHERE o.shift_week = '2017-11-26'


text:
Q: Showing uniqueness of a best approximation in a Hilbert space. To introduce some context, here I am dealing with a Hilbert space H and a linear and closed subspace $S$ of $H$ such that $(b_n)_{n \in \mathbb N}$ is an orthonormal basis for $S$. Previously, I have shown that the vector $$ y = \sum_{k=1}^\infty \langle x,b_k\rangle b_k$$
Satisfies the equality $\| x- y\| = \inf_{z \in S} \| x- z \|.$ I am now trying to prove that this $y$ is unique.
To do so, my thinking go as follows:
Suppose there exists a distinct element $y' \neq y$ ($y' \in S$) such that $\| x - y'\| = \inf_{z \in S} \| x - z \| = \|x-y\|.$ To prove what's wanted, one should find a contradiction (essentialy, should find that $y = y'$).  My only idea to reach such a contradiction is to apply the parallelogram law to the vectors $x-y$ and $x-y'.$ Doing so,
$$ \| x - y\ + x - y'\|^2 + \| (x-y)-(x-y') \|^2 = 2(\|x-y\|^2 + \|x-y'\|^2) $$
But it is easy to see that $x-y+x-y' = 2x - y - y'$ and $(x-y)-(x-y') = y' - y$ and $\|x-y'\|^2 = \|x-y\|^2$, by hipothesis. Thus, the equation above is equivalent to
$$ \| 2x-y-y'\|^2 + \|y' - y\|^2 = 4\|x-y\|^2 \Leftrightarrow \| y' - y \|^2 = 4\|x-y\|^2 - \|2x-y-y'\|^2. $$
Now, the desired result would come if I could prove that $4\|x-y\|^2 = \|2x-y-y'\|^2$ but I don't see how to do this...
Any hint is appreciated.

A: A few comments first:

*

*If you prove that $y=y'$ you already got what you want; phrasing it as a contradiction only obscures the argument.

*Nowhere in your argument do you use that $y,y'$ minimize the distance.

*And, also, nowhere in your argument do you use that $S$ is convex; and the uniqueness can fail for non-convex $S$.
With the above considered, a typical argument is as follows. It uses the paralellogram identity in a similar way as you did. The crucial piece of information is that, since $S$ is convex,
$$
\Big\|\frac{y+y'}2-x\Big\|\geq\|y-x\|.
$$
Then
\begin{align}
\|y-y'\|^2
&=\|y-x-(y'-x)\|^2=2\|y-x\|^2+2\|y'-x\|^2-\|y+y'-2x\|^2\\[0.3cm]
&=4\|y-x\|^2-4\Big\|\frac{y+y'}2-x\Big\|^2\\[0.3cm]
&\leq4\|y-x\|^2-4\|y-x\|^2=0.
\end{align}
So $y'=y$.


text:
Q: Merlin (TV) Fanfic - Modern AU Merlin inherits Gaius house and Arthur renovates it Looking for a Merlin fanfic based on the BBC series that's been bugging me for a while as I've been reading into that area again.
It was an alternate universe modern AU with a Merlin/Arthur slash. Basically Merlin inherits a house from Gaius when he dies as he's his mother's uncle or something along those lines and after visiting with Arthur they decide to keep it despite it being in bad shape and Arthur will do the building work. I remember the house being described as quite grand and perhaps Victorian styled but definitely a period property and I'm almost certain it was set in the US.
In this fic I feel like Arthur was unemployed or was looking into a career change and that's why he had time to do this, Merlin was something very time consuming I'm leaning towards student doctor but I could be wrong. Arthur does most of the work himself, restores the furniture, sands, paints etc room by room. They live in a caravan on the drive way for most of the fic until the house is ready if I remember right.
They were operating on a budget as I recall also and it ends with Arthur completing the house the progress of which Merlin hasn't been aware off outside of helping to choose fittings etc.
It wasn't a particularly long fic I feel about 10-20 thousand words maybe but I recall it being very sweet and I'd quite like to read it again. It was either Ao3 or FanFiction.Net but I'm leaning towards the latter as I've been reading extensively on the other for a few weeks and found nothing.


text:
Q: Can't reinstall properly Pipewire After purging and reinstalling pipewire and wireplumber i ended up with these errors on systemctl
screenshot
It invloves RTkit and i tried to reinstall rtkit,dbus,polkitd but error message still remains. Should I forward this question to pipewire's gitlab and open an issue?

A: fixed by following these instructions
https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Performance-tuning


text:
Q: VB equivalent to powershell I am very new to powershell and sometimes this question may be so simple
Can please anybody please tell me what is the equivalent to the following(vbscript) in PowerShell
set obj = wscript.createobject( wscript.shell )
Obj.Run $smCmnd

What is the use of wscript.shell.
After a bit of search I found first line can be presented as;
$obj  = New-Object -ComObject WScript.Shell

But have have no idea how to call Run method ($obj.run(...)???)
If I run cmd.exe with some commands as the smCmnd, How can I keep cmd.exe without close and to run another command later in same console??
EDIT
I am writing PS script and it will be call from another application. Basically it will do some folder creations and file coping etc. I would like to open CMD.exe and show all the commands running on that. How to use same cmd prompt through out my whole script.

A: Is smCmnd a string of shell commands?  If so, you can call them directly from PowerShell, without trying to get a wscript.shell COM object to run them against like you'd need to do in VBScript.
VBScript wasn't a shell.  Powershell is.  You can write shell commands directly in .ps1 or .ps2 files, just like in a batch file.
I'm not a powershell expert here, but try doing
& $smCmnd

A: Try running $smCmnd directly. If that fails, use Invoke-Expression $smCmnd.

A: If you do need to use CMD.EXE (possibly because you want to run pre-existing BAT file), and you want all of the output in a single CMD window you can pipe all the input into cmd at once like this:
# Powershell script to execute existing BAT file
cmd.exe /k "cd c:\batchfiles & firstone.bat & second.bat & echo that's all folks"
# CMD will remain open (/k). User will have to type exit to return to powershell

# Or if you want user just to hit any key to leave CMD prompt:
cmd.exe /c "c:\batchfiles\mybatchfile.bat & pause"
# /C means CMD should close after is has executed the commands on the command line

However if you want to have something execute in CMD, then make a decision in your Powershell script about what to execute next in CMD then do something similar to the answer at the following link which pipes input and output between a powershell script and CMD.exe.
How to run interactive commands in another application window from powershell


text:
Q: What causes the Pauli exclusion principle (and why does spin 1/2 = fermion)? It seems to be related to exchange interaction, but I can't penetrate the Wikipedia article. What has the Pauli exclusion principle to do with indistinguishability?

A: The exchange interaction is, on the contrary, one of the approximate low-energy consequences of the Pauli exclusion principle and the identical character of the particles.
The fundamental justification of these facts is offered by quantum field theory. Relativity requires observables to be linked to regions of spacetime - so that they don't communicate over spacelike separations.
It follows that the observables must be - or at least, in the simplest cases such as the Standard Model and its subsets, they are - functionals of quantum fields. Spacelike separated fields either commute or anticommute with each other - these are the only two ways how to make sure that they don't interact faster than light.
The Pauli exclusion principle only applies to half-integral-spin particles because of Pauli's spin-statistics theorem,

http://en.wikipedia.org/wiki/Spin-statistics_theorem

The page above also has a convincing bogus proof and a proof.

A: Indistinguishableness of particles is formulated in QM in terms of the total wave function symmetry. Then the wave functions can be symmetric or antisymmetric on their arguments. In case of antisymmetry ($\psi(x_1,x_2) = -\psi(x_2,x_1))$ the particles are called fermions and $\psi(x_1,x_2=x_1) = 0$. They say "the particles cannot occupy the same state". It's a feature of nature, an experimental fact.


text:
Q: Css Full Width and Scroll Bar issue My website
style css can be found here
I'm looking at my website on firefox, and I notice that the site is not stretching to the full width. You can tell by maximizing the page and then looking at the menu at the top right.
Also, there seems to be a horizontal scroll bar at all times which I don't need unless the site is showing the full content area in the middle.
Any suggestions on how I can fix?

A: To get rid of the horizontal scroll bar, try the following:
On DIV #master_wrapper remove:
float:left;
width:100%;

And add
overflow:hidden;
margin:0 auto;

On DIV #outer_wrapper remove:
float:left;
width:100%;

And add
overflow:hidden;

The site seems to go full width on Chrome ok.


text:
Q: Is it really harmless to use sizeof(p[0]) no matter initialized or not? I was arguing with one of my friends, if we have defined an array/pointer:
sometype * p;

if we want to know the size of the type, he said one should use:
sizeof(sometype)

I said one could also use:
sizeof(p[0]),

it should be the same. He disagreed, and his point is if p is not initialized, then this usage of p[0] may cause problems.
But to my knowledge, only when we change or depend on the value of p[0], will this be harmful. Since we don't change p[0] nor use p[0]'s value, this is totally sensible.
Since we can't persuade each other, can anyone make this concept clear.
I know this question is of no use, and almost all the developers will use sizeof(sometype), including me :). But this question is fun and I'm really curious to know if there is any case that sizeof(p[0]) will be harmful.
=================================
Let me extend this question a little bit. If I do use some irrelevant value (or considered as kind of random or whatever). Can I always use p[0] to get a value?
To make the question more clear, If I don't change the value of an uninitialized pointer, just use the value it is pointing to, can I always get a value without causing problems?

A: sizeof is evaluated at compile-time so it does not matter whether the memory is initialized or not since that's a runtime thing.
So sizeof p[0] or - what I think is even nicer since it does not look array-ish - sizeof *p is a great way to avoid typing the type again when using sizeof.

A: In C++ language the argument of sizeof is never evaluated, meaning that it is completely irrelevant whether the variables used in the argument expression hold valid values or not. Only the static type of the expression under sizeof matters, and it is determined at compile time.
Moreover, it is actually preferable to use expressions (as opposed to type names) as arguments of sizeof to make the code more type-independent.
In C the argument expression might be evaluated in some cases (variable-length arrays), but not in C++.

A: sizeof() is evaluated by the compiler, so uninitialized variables are not an issue.

A: The argument to sizeof is an unevaluated operand, so pointer dereferences and so forth don't have to refer to valid memory.  It's purely based on type information.
(As a corollary, sizeof *p is not polymorphic, it uses the static type only.)


text:
Q: start exe as non admin from admin exe When my app updates it needs admin rights and pops the uac prompt up and this is all good. However when it restarts it self its still in admin mode and thus every thing it does has admin rights. The problem comes when the next time the app is started its a normal user and thus cant read any of the files that where made before.
How do a start an exe as a normal user from an admin priviladge exe?
Visual studio 2008
vista / win 7

A: Here is an article that describes how to start non-elevated process from an elevated one.


text:
Q: Primary key violation when inserting child entity DB Schema (H2 database):
create table book (
    id_book bigint auto_increment not null primary key,
    title varchar(255) not null,
    id_author bigint not null,
    id_genre bigint not null
);

create table comment (
    id_comment bigint auto_increment not null primary key,
    id_book bigint not null,
    comment_text varchar(255) not null
);

Domain classes:
public class Book {
    @Id
    @Column("id_book")
    private Long id;

    private String title;

    @Column("id_author")
    AggregateReference<Author, Long> author;

    @Column("id_genre")
    AggregateReference<Genre, Long> genre;

    @MappedCollection(idColumn = "id_book", keyColumn = "id_comment")
    List<Comment> comments = new ArrayList<>();

    public void addComment(String commentText) {
        comments.add(new Comment(commentText));
    }
       //getters and setters
}

public class Comment {

    @Column("id_comment")
    private Long id;

    @Column("comment_text")
    private String text;

    public Comment(String text) {
        this.text = text;
    }

    public Comment() {
    }
        //getters and setters
}

I have the problem when I add a comment to the book.

```java
@Override
@Transactional
public String addComment(long bookId, String commentText) {
    var book = bookRepository.findById(bookId);
    return book.map(b -> {
        b.addComment(commentText);
        b = bookRepository.save(b);
        return bookConverter.convertToString(b);
    }).orElse("Book not found!");
}

It generates SQL like this...
    Executing SQL batch update [INSERT INTO "COMMENT" ("comment_text", "id_book", "id_comment") VALUES (?, ?, ?)]

... adds values for id_comment field like 0, 1, 2, 3 and these values intersect with existing ones. So I get Primary Key Violation. Why it adds id_comment field to the INSERT  expression?

A:
Why it adds id_comment field to the INSERT expression?

Because you told it to.
The following annotation tells Spring Data JDBC to store the index of the list in the id_comment column.
@MappedCollection(idColumn = "id_book", keyColumn = "id_comment")

Your data model is missing a column for the list index. Add that column and use it as keyColumn in the @MappedCollection annotation


text:
Q: How to compute the dimension of cohomology groups? I would like to compute the dimension of $Z^1(\Gamma,V)$ and $B^1(\Gamma,V)$, where $\Gamma$ is a finitely generated group acting on a vector space $V$.
$$Z^1(\Gamma,V)=\{\gamma : \Gamma\to V,\ \gamma(gh)=\gamma(g)+g\cdot\gamma(h)\}\ \text{and}$$ $$B^1(\Gamma,V)=\{\gamma : \Gamma\to V,\ \exists v\in V,\gamma(g)=g\cdot v\}$$
If $\Gamma=F_n=<X>$ (the free group generated by $X=\{x_1,...,x_n\}$), as each $1$-cocycle is determined by its values on the generators $x_1,...,x_n$ then
$$Z^1(\Gamma,V)\cong V^X=\{\gamma : X\to V\}\cong V^n$$
Same for $B^1(\Gamma,V)$.

*

*Is this correct?

*How to compute the dimensions of these vector spaces in the case a finitely generated (not free) group $\Gamma$?

My motivations are from the study of the symplectic geometry of character varieties (the works by Goldman):
The Symplectic Nature of Fundamental Groups of Surfaces


text:
Q: Access property from JSON string where parent object name is not fixed I have the following JSON string, and I need to access the property value named "Mode" from it:
{
  "CommomData": {
    "DateTime": {
      "Year": 2019,
      "Month": 3,
      "Day": 11,
      "Hour": 14,
      "Min": 1,
      "Second": 29
    }
  },
  "Status": {
    "Mode": "Test",
    "Loc": "Test"
  }
}

If you note here, the parent property name for "Mode", here is "Status" but this could change to "LatestStatus" or "FirstStatus" or any other value.
Currently, I have written the code below and it works fine, but it takes around 60 to 150 milliseconds for the operation (we want to reduce this time). Please note that the object has many more properties, but I only posted a few to explain the issue.
Is there any other optimal way to get the value from the JSON string without knowing the object type and the parent property name?
JObject payloadJObject = JObject.Parse(payload);

foreach (var item in payloadJObject)
{
    foreach (JProperty subitem in item.Value.ToList())
    {
        if (subitem.Name == "Mode")
        {
            return Convert.ToString(subitem.Value);
        }
    }
}

A: Depending on your definition of "optimal":
The shortest way to find a property somewhere in the JSON is to parse the JSON to a JObject and then use SelectToken with a recursive descent JsonPath expression:
public static string FindFirst(string json, string propertyName)
{
    return JObject.Parse(json).SelectToken("$.." + propertyName)?.ToString();
}

Fiddle: https://dotnetfiddle.net/JQxu9c
The fastest way that I know of to do the same thing with Json.Net is to use a JsonTextReader:
public static string FindFirst(string json, string propertyName)
{
    using (StringReader sr = new StringReader(json))
    using (JsonReader reader = new JsonTextReader(sr))
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.PropertyName &&
                reader.Value.ToString() == propertyName)
            {
                return reader.ReadAsString();
            }
        }
        return null;
    }
}

Fiddle: https://dotnetfiddle.net/aR3qVe


text:
Q: What's the proper way to overwrite system/hidden files with Windows API? When you copy files using CopyFileExA function (see Windows API Reference: winbase.h) it has the ability to "fail" or not, if the destination file already exist, using (or clearing) the flag COPY_FILE_FAIL_IF_EXISTS. However, I can not find the way to overwrite files with attributes Read Only, Hidden or System.
I am working on a backup program with specific requirements which I can't find anywhere else.
I was thinking that before copying a file with one or more of those attributes set, perhaps I could clear those attributes on an existing file and then proceed to copy the file, knowing that my program will overwrite existing file with clear attributes.
Is that the best approach?
Another option would be just delete the old file before copying a new one. But I'm afraid that if I delete the old (backup) file and only then will try to copy the new one AND if the copy for some reason fails, then I will ended up without a backup file.
Or maybe there's a way of overwriting System/Hidden files that I'm not aware of.
What would be the best method of accomplishing this - copy and overwriting files with System/Hidden/ReadOnly attributes set?


text:
Q: Adding user's photo to contest, call method with link_to I came from a JS background so Rails is weird to me. I currently have a show.html.erb for the contest model:

Contest name: <%= @contest.name %>

Contest criteria: <%= @contest.criteria %>

Photos:

<%= link_to "Enter Contest", "#" %>
<% @contest.photos.each do |photo| %>
    <%= image_tag("#{photo}") %>
<% end %>

With the link_to I'm trying to render all photos that belongs to the current_user and pick one of them to assign it to the current contest. The params passing seems all so mysterious to me. Can you guys point me in the right direction of how I should tackle this problem? Thanks

A: What I understand you need to select an image from list of images and pass the id. So, try this
<%= label_tag "Enter Contest" %>
<% @contest.photos.each do |photo| %>
    <%= link_to (image_tag("#{some photo path}")), some_controller_method_path(:photo_id => photo.id) %>
<% end %>

And in controller you can use params[:photo_id]


text:
Q: Terraria crashes Once in a while Terraria will crash and display this error message. I can't copy the text, so I took a screenshot. Not sure what this means, I have tried reinstalling the XNA framework.

A: I had the same problem. Re-installing the XNA framework did not work for me.
Re-installing Terraria fixed the issue.


text:
Q: OutofBoundsException setpixels I am trying to fill a rectangle of pixels, but I always get Arrayindexoutofbounds at the below line:
targetwr.setPixels(i, j, 3, 3, pixel);

Here is my code:
    WritableRaster sourcewr = source.getRaster();

    BufferedImage bi = new BufferedImage(source.getWidth(),
            source.getHeight(), BufferedImage.TYPE_INT_ARGB);

    WritableRaster targetwr = bi.getRaster();

    for (int i = 0; i < sourcewr.getWidth() - rate; i += rate) {
        for (int j = 0; j < sourcewr.getHeight() - rate; j += rate) {
            int[] pixel = null;
            pixel = sourcewr.getPixel(i, j, pixel);
            System.out.println(i + " " + j);

            targetwr.setPixels(i, j, 3, 3, pixel);
        }
    }

A: Pretty straightforward.  The sourcewr raster is larger than the targetwr raster.  You are iterating over the length and height of the sourcewr and never check to see if the coordinates are in-bounds for the targetwr.
You can check to see if i and j are within bounds or ensure that the rasters are the same size before the nested for loops.  e.g.,
if(i < targetwr.getWidth() && j < targetwr.getHeight()) {
    targetwr.setPixels(i, j, 3, 3, pixel);
}

This is obviously also affected by the variable rate, whatever that is.  It's not defined in your code snippet.


text:
Q: Sampling Random Rotations in $n$ Dimensions Using Bivectors I understand how bivectors can be used to represent rotations in 2 and 3 dimensions, where we start with a normalized bivector which defines the plane of rotation and an angle through which to rotate points. (I'm assuming rotations about the origin because it's simpler to understand).
I also understand that in 4+ dimensions, bivectors are not necessarily "simple" (they cannot be represented by a single wedge product of vectors). Unfortunately, this shift in complexity happens after I'm able to visualize the rotations, so I'm having trouble extending the notion to higher dimensions. I know there are single and double rotations in 4 dimensions (Wikipedia). I think, but am not sure, that these cover the cases where the bivector of the rotation is simple or not?
So here's my thought for randomly sampling rotations in higher dimensions (without having to generate massive matrices and factor them):

*

*Generate a bivector $B$ by sampling the standard basis coefficients (which I think in $n$ dimensions there should be $n \choose 2$ of) from the surface of a hypersphere (so that the coefficients are normalized)

*Generate an angle $\theta$ in $[0, 2\pi)$

*Build the rotor $R = e^{B/2}$ associated with the two (interior part $\cos(\theta/2)$ and exterior parts $\sin(\theta/2) B$)

*Rotating a vector $v$ is accomplished by doing the geometric product $R v R^{-1}$, where $R^{-1}$ simply has the coefficients of the the exterior part negated

Is this a good approach? Am I misunderstanding something fundamental? My main sources for learning were this great interactive post and the Wikipedia page on bivectors. My main goal is for doing random rotations in Euclidean spaces, but it would be very cool if this approach could be extended to more general manifolds.

A: The exponential of an arbitrary bivector $B$ in a $n$-D geometric algebra is a multivector called a versor. A versor is an operator that transforms a vector to a vector, or the (sub-)space as a whole. In a nutshell, versors represents orthogonal transformations.
As a multivector, a versor is represented as a sum of k-vectors. We call it an odd versor if k is odd and even versor if k is even. If we consider the algebra of sub-spaces (i.e., lines and planes passing through the origin) then odd versors represents reflections and even versors represents rotations.
You want to construct even versors. That means, to construct a rotor the exponential must be a 2-blade (2-blade is not the same as 2-vector). Since 2-blades coincide with bivectors in 2-D and 3-D, you don't need to care about those distinctions in those dimensions. But in 4 and more dimensions that is not the case. However, Riesz shows that in the Euclidean space $R^{n,0,0}$ (the space of your interest) a rotor can be expressed as the exponential of an arbitrary bivector. The reason is that in that n-dimensional Euclidean space, an arbitrary bivector can be written as the sum of $commuting$ 2-blades.
Also, in a Euclidean $R^{n,0,0}$ space, a rotor is the geometric product of an even number of unit vectors. So you can also do this to generate random rotors.

A: In N dimensions, the representation of rotations using the minimum set of floor(N/2) rotation angles that you describe is nontrivial, whereas using N(N-1)/2 Euler angles you can straightforwardly uniformly cover the space of orientations.
This is a very interesting problem, the structure of SO(N) in terms of these minimal rotations.  Sorry for editing my answer several times.
Apparently this is called "Weyl integration", using the angle eigenvalues as integration variables.
It is not clear what you mean by "uniformly sampled" (U.S.) rotations.  I presume that uniformly sampling orientations (uniformly covering SO(N)) is what you mean.
Uniformly covering SO(N) is easy: to randomly uniformly cover SO(N) you just need to generate random spherical vectors, see below + link.
Uniformly sampling orientations is NOT the same as uniformly covering the floor(N/2) angles!  It is very different.  SO(N) is populated mostly by matrices whose angle eigenvalues are different.  The angles repel one another.
If you follow the construction below and compute eigenvalues to extract the minimal floor(N/2) angles, you can this structure, how the eigenvalues repel one another.  If you choose random rotation planes and floor(N/2) angles independently then you will not uniformly cover SO(N).  You will grossly over-sample points near your starting orientation.  You need to do the Weyl integration properly with the proper weight (see below).
This minimal set of floor(N/2) rotation angles corresponding to pairs of conjugate eigenvalues and bivectors are defined always [0,pi].  (For N=2, instead of a random bivector you choose a random rotation direction +/-1.)
Consider N=3.  For N=3 there is one rotation angle, and one rotation axis which must be uniformly sampled on the sphere.
For N=3, in (axis, angle) Weyl convention, the average cosine of the rotation angle must be -1/2 for the average trace of the 3D rotation matrices to be zero.  The most compact quadrature for N=3 would use the single rotation angle 2pi/3 (120deg).  A tetrahedron is sufficient; you can make four 120 degree rotation matrices that average to zero.  That seems to be the minimum quadrature for N=3.
This is really interesting, considering Weyl integration by quadrature.  I am thinking about regular uniform quadrature.  But you are asking about randomly choosing the rotation planes (bivectors), a random Weyl quadrature.  I would not do that.  If you want to use random numbers, then I would just directly randomly quadrature SO(N), randomly choose vectors not bivectors, as I have done to produce the figure below.
To randomly, uniformly cover SO(N), I would directly generate a space of random orthogonal matrices SO(N), as I have done to examine its eigenvalue spectrum.
How to generate uniformly sampled random member of SO(N):
Generate N random spherical N-vectors and orthogonalize them.  If the determinant is negative, flip the sign of the last vector.
How to generate a random spherical N-vector:  The best way is to use normally distributed random numbers.  Simply generate N normally distributed numbers each with mean 0 and variance 1 (normrnd in matlab).
So generate N random spherical N-vectors and put them in the columns of a NxN matrix.  (Generate N^2 normally distributed random numbers)
If the determinant is negative, flip the sign of the last vector.
Then orthonormalize the rows and columns of the matrix (e.g. Gram-Schmidt)
Really it is sufficient to generate (N-1) random N-vectors and orthonormalize them; the Nth column of the rotation matrix is then determined.
This procedure generates nontrivial distributions of eigenvalues (rotation angles) for N>2, even and odd.  For N odd, again, the average rotation angle is greater than pi/2.
.. with nAngles = M = floor(N/2),
empirically I find that the probability dtheta1 dtheta2.. dthetaM  for a set of angles theta1 theta2 ..thetaM = [0,pi]
is proportional to
product_(i,j=1..M,i<j) (cos(theta_i)-cos(theta_j))^2
times product_i=1..M (1-cos(theta_i)) for odd N.
This is the Weyl integration metric (see link below).  In other words, the eigenvalues strongly repel one another.  You cannot simply choose M = floor(N/2) angles independently.  That will not evenly cover SO(N).
In other words, with Weyl integration by quadrature, what you are talking about, the angles should be different to efficiently cover SO(N).  At the lowest level of quadrature, use just one one operation defined by an evenly spaced, fixed set of rotation angles and vary the rotation planes (the orientation of that operation) to cover the sphere.  (If you can do this systematically, you reduce the space that you have to cover by 2^N using Weyl quadrature.  But you are talking about choosing the rotation planes randomly, so I don't think Weyl quadrature helps you).
For instance, choose these angles
N=3: 120
N=4: 0, 180
N=5: 60, 180
N=6: 0, 90, 180
N=7: 36, 108, 180
etc.  For Weyl integration by quadrature, at the lowest level of quadrature, choose a single operation with M=floor(N/2) angles evenly spaced like that, so that the average trace of the rotation matrices is zero.
I include a plot of the distribution of the eigenvalues for SO(5):  You can see how they cluster near (60,180).
https://i.stack.imgur.com/82mVQ.png
But again I don't really think this helps you.  If you are going to choose the rotation planes randomly, then you might as well randomly quadrature SO(N) directly, not use Weyl quadrature as you are talking about (angle eigenvalues).
Here are some references I found
"ROTATION MATRIX SAMPLING SCHEME FOR MULTIDIMENSIONAL PROBABILITY
DISTRIBUTION TRANSFER" - similar method to generate the random SO(N) matrix
http://research.gistda.or.th/assets/uploads/pdfs/d45e9-31.rotation-matrix-sampling-scheme-for-multidimensional-probability-distribution-transfer.pdf
"Sampling sets and quadrature formulae on the rotation group" - I am not sure whether this is consistent
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.525.2150&rep=rep1&type=pdf
Using eigenvalues as the integration variables is the Weyl integration formula, see page 7, this has the (cos theta_i - cos theta_j)^2 factor
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.179.1333&rep=rep1&type=pdf
The eigenvalue spectrum of SO(n) reflects its "simple roots" apparently.. see figure 4, showing the root diagram for D2 = SO(4) and B2 = SO(5) here
http://sites.science.oregonstate.edu/~tevian/JOMA/joma_paper_softlinks.pdf
These root diagrams, the "simple roots" of the algebra reflect the most likely eigenvalue spectrum of the ensemble, correspond to the angles above


text:
Q: How to use postgres with rails on heroku I am having the following contents in a database.yml
production:
  adapter: postgresql
  database: dbname
  host: host.compute-1.amazonaws.com
  username: user
  password: pass_word
  DATABASE_URL: postgres://user:pass_word@host.compute-1.amazonaws.com:5432/dbname

However on a git push heroku master, I am getting the following error.
could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port 5432?

Do I need changes for other environments as well?

A: heroku autogenerates database.yml on the deploy.
You need to .git ignore database.yml
You may choose another database by setting the ENV['DATABASE_URL'] (use heroku config:add DATABASE_URL=....)
For more information please check the heroku documentation

A: DATABASE_URL is not required. Or you can check this one http://railsapps.github.io/rails-heroku-tutorial.html

A: This error
could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port 5432?

is emitted during push, because be default Rails will spin up to precompile assets, and part of that is Rails trying to connect to the database.  During build time, your application configuration is not present, hence why Rails tries to fall back to the default of using localhost (which doesn't exist).
There's a couple of ways to stop this happening.  One (the recommended way) is to set
config.assets.initialize_on_precompile = false

in your production.rb.
A second way, is to enable the user-env-compile labs feature that will allow your PG config to exist at build time.
$ heroku labs:enable user-env-compile -a <YOUR_APP_NAME>


text:
Q: Dynamo DB Scan Field with value keyword I'm trying to scan a dynamo db table based on a value of a list item that has value in it's name. The field is
"TPMS.value": {
    "L": [
      {
        "N": "0"
      },
      {
        "N": "0"
      },
      {
        "N": "0"
      },
      {
        "N": "0"
      }
    ]
  }

and I'd like to get results where TPMS.value[0] != 0
I've tried
aws dynamodb scan \
    --table-name afdcm-app-demo-Telemetry-Int_Table \
    --filter-expression "TPMS.value[0] > :val"  \
    --expression-attribute-values '{":val":{"N":"0"}}'

but I keep getting Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: value. Is there a way to run the scan where field name contains value?

A: You must use the --expression-attribute-names option. According to documentation (https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html):
One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames :

*

*To access an attribute whose name conflicts with a DynamoDB reserved word.

*To create a placeholder for repeating occurrences of an attribute name in an expression.

*To prevent special characters in an attribute name from being misinterpreted in an expression.

So in your case the command should be similar to this:
aws dynamodb scan --table-name afdcm-app-demo-Telemetry-Int_Table --filter-expression "#VAL[0] > :val" --expression-attribute-names '{"#VAL":"TPMS.value"}' --expression-attribute-values '{":val":{"N":"0"}}'


text:
Q: Distance of a vector to the plane not going through the origin We have a point(3,3,3) in R3, and a plane not going through origin. Now if I wish to find a distance from the plane to the point, I could not just do the usual stuff: project $\begin{bmatrix} 3 \\ 3\\3\end{bmatrix}$ onto the normal of the plane, and find the length of it, because the vector $\begin{bmatrix} 3 \\ 3\\3\end{bmatrix}$ is not useful here since it goes from the origin to the point (3,3,3). Am I right, and what could be my course of action?
Thank you!

A: Let $a=(3,3,3)^T$.
Find a point $x$ that lies on the plane.
Compute $a-x$, then you can project it onto the normal of the plane and find the length.


text:
Q: How can I parse a month and a year without a date in Java? I tried it like this
public LocalDate parseDate(String date) {
    return LocalDate.parse(date, DateTimeFormatter.ofPattern("MM-yyyy"));
}

but this code throw an exception
java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=5, Year=2022},ISO of type java.time.format.Parsed

A: YearMonth
You cannot create a LocalDate having a month of year and the year only, it just needs a day of month (and does not provide any default value).
Since you are trying to parse a String of the format "MM-uuuu", I assume you are not interested in creating a LocalDate, which inevitably boils down to the use of a java.time.YearMonth.
Example:
public static void main(String[] args) {
    // an arbitrary mont of year
    String strMay2022 = "05-2022";
    // prepare the formatter in order to parse it
    DateTimeFormatter ymDtf = DateTimeFormatter.ofPattern("MM-uuuu");
    // then parse it to a YearMonth
    YearMonth may2022 = YearMonth.parse(strMay2022, ymDtf);
    // if necessary, define the day of that YearMonth to get a LocalDate
    LocalDate may1st2022 = may2022.atDay(1);
    // print something meaningful concerning the topic…
    System.out.println(may1st2022 + " is the first day of " + may2022);
}

Output:
2022-05-01 is the first day of 2022-05


text:
Q: Free browser memory from a JS script Is it possible freeing the browser memory from JavaScript objects?
I am designing the asynchronous navigation process of a web app, in which page parts are loaded through AJAX requests together with their necessary components (CSS, JS, images etc): I guess that without a proper scripting, a long usage of the app would load many different objects causing a brutal memory growth.
As I could imagine, the removal of a script tag from the DOM only removes the DOM node, not the objects and functions it defines, which remains loaded into the browser memory.
(A similar test: Should a "script" tag be allowed to remove itself?).
I also tried to test the browser behaviour while setting a variable as a big string and then overwriting it:

<html>
<head>
    <title>JS memory test</title>
    <script type="text/javascript">
    function allocate() {
        window.x = '';
        var s = 'abcdefghijklmnopqrstuvwxyz0123456789-';

        for (var i = 0; i < 1000000; ++i) {
            window.x += 'hello' + i + s;
        }
        alert('allocated');
    }

    function free() {
        window.x = '';
        alert('freed');
    }
    </script>
</head>
<body>
    <input type="button" value="Allocate" onclick="javascript:allocate();" />
    <input type="button" value="Free" onclick="javascript:free();" />
</body>
</html>

Data from the Chrome task manager:
page weight when loaded:
    5736 KB
page weight after having set the variable:
    81720 KB
page weight after having the variable reset:
    81740 KB
It strikes me since I thought the JS garbage collector throws away the old variable value, since it is overwritten from the new assigned value.
Firefox has not a single-task-tab management, so there's not a similar process monitor like in Chrome, but the global memory usage seems that it behaves almost like Chrome.
Is there some wrong assumption?
Can somebody provide suggestions about effective programming practices or useful resources to read?
Thanks a lot.

A: You have no direct access to memory management features. The best you can do is remove references to objects so that they are available for garbage collection, which will run from time to time as the browser sees fit.
From time to time certain browsers exhibit memory leaks, there are strategies to reduce them but usually for specific cases (e.g. the infamous IE circular reference leak, which has been fixed, even in updated versions of IE 6, as far as I know).
It's probably not worth worrying about unless you find you have issues. Deal with it then.


text:
Q: For Rails, how to access or print out config variables (as experiment or test / debugging) For example, in config/environments/production.rb in a Rails 3 app, there is
config.serve_static_assets = false

and many variables.  How can they be all printed out as a whole (perhaps in an object, instead of specifying each one-by-one) (print out in a view, such as FooController#index), just for looking into what types of values are available and to see what they are set to?
Also, how to print out the values in the .yml files (as a hash and/or in some config object?) and in config/initializers, such as for
MyAppFoo::Application.config.session_store :active_record_store

I found that we can print out the content of
ActiveRecord::Base.configurations

but not
ActionController::Base.configurations

are there ways to print out all info of the MVC components?

A: Most of the Rails config stuff can be accessed through:
Rails.application.config.<your_variable>

With regards to printing out the values of .yml files in config, you'd have to do that yourself becuase Rails will only load up the values for the current environment from database.yml, and any custom yml config files will be just that - custom. Here's one way you could load them all up...
all_configs = []
Dir[Rails.root.join("config/*.yml")].each {|f| all_configs << YAML.load_file(f) }

With regards to settings set in initializers, if it's a Rails config option (such as the session store which you've given as an example), then it will be available through Rails.application.config. If not, (for example configuration for a gem) then you will have to manually find those settings from the gem classes.

A: You can also use AppName::Application.config (where AppName is the name of your application) to access the Rails::Application::Configuration object.
$ AppName::Application.config == Rails.application.config
true

A: Like idlefingers pointed out, for newer versions of rails, Rails.application.config.my_variable should get you what you're looking for.
However, if that doesn't work because you're stuck with an older version of Rails (2.3, etc) you can use the ENV constant, like so: ENV['my_variable']

A: In modern (Rails 6, 7) versions, you can just do
Rails.configuration.<your_variable>

Because
Rails.application.config == Rails.configuration
=> true


text:
Q: Why $Result = 1 even when there is no error on database insert operation In below powershell script, I am trying to execute SQL insert statement within transaction and try/catch.
There is no errors and I am setting variable $Result with value 1 in catch block, still when I am seeing the value = 1 Write-Host $Result
[CmdletBinding()]
Param(
    [string]$SQLServer='(local)'
)
# Database Update
Write-Host "Update Database" -ForegroundColor Green
& sqlcmd.exe -S $SQLServer -Q @"
USE [Test]
BEGIN TRANSACTION
BEGIN TRY
    INSERT INTO DBO.A1 (Name) VALUES ('test1')
COMMIT TRANSACTION
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE() as ErrorMessage;
    $($Result =1)
    ROLLBACK TRANSACTION
END CATCH
"@

Write-Host $Result