text:
Q: The type 'NDArray' exists in both 'NumSharp.Core, Version=0.20.4.0, 'NumSharp.Lite, Version=0.1.7.0 I need to use NumSharp.Core Version=0.20.4.0 (particularly NumSharp.Bitmap), but when I install it, i get this error
The type 'NDArray' exists in both 'NumSharp.Core, Version=0.20.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and 'NumSharp.Lite, Version=0.1.7.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
I'm not using NumSharp.Lite, Version=0.1.7.0 (I don't even have installed it), but I figured some packages I use do call NumSharp.Lite. These Packages are:

*

*SharpCV

*SciSharp.TensorFlow

*TensorFlow.NET

Is there a way to be able to use NumSharp.Bitmap in this scenario?
Is it posible to force all dependences to use NumSharp.Core instead of Numsharp.Lite?
I am working on Microsoft Visual Studio Community 2019, Version 16.5.4, on Windows 10 home edition.
Thank you!

EDIT
I tryed to downgrade the three packages to the last version they used NumSharp.Core, unfortunately, this leads to other kind of errors, like functions that haven't been implemented on those versions, so that's not a viable alternative.
For the moment I've been able to work without NumSharp.Bitmap by doing everything by brute force, but it is not the ideal.


text:
Q: Why does chrome dev tools show the extension ID blow the iFrames? Normally, when I use the Console tab of the developer tools in Chrome, I see a list of iFrames like the following:

However, after I installed a certain extension I see the extension ID below a number of iFrames in the Console tab like following:

*

*Can anybody tell me what does that mean? I suppose that those iFrames' parent is the extension but I am not sure. Can anyone please correct me if I am wrong?

*Also, if those iFrames' parent is the extension is there any way to track them? By track them I mean that say I want to run the command window.open = function () { debugger; } for all such frames, is it possible for me to do so?

A: What you are looking at are the extensions content scripts. They are actually loaded as a child of either each tab or (in the case of this extension) each iFrame.
If you select one in the console, and do:
> chrome.runtime.getManifest()

The most relevant output is:
 { ...
 content_scripts: Array[1]
  0: Object
    all_frames: true
    js: Array[#]
       0: "content.js"
       ...

Here, the all_frames is the reason you see the extension repeated after each frame instead of once under the tab's main window.
(There may also be a background, which you can inspect from the extension's listing in settings.)
To debug content Scripts, there is actually a tab under the Developer Console->Sources. Here I have set a breakpoint on a specific line during the content scripts initialization (after expanding the code with the "{}" icon):

When changing an iFrame or reloading the entire window, each content script then pauses at this point while the developer tools are open.
There are some content script limits, so you should not be able to arbitrarily execute code in one iFrame from another though there is a message passing system which can achieve similar results if listeners are specifically setup.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS 1.0.7 locationProvider undefined I have an AngularJS 1.0.7 web application.
I´m trying to use $locationProvider in my app.js (in order to run htm5Mode), but when I run it, I get $locationProvider is undefined.
Do I need to load any extra js library? I don´t find any docs.
angular.module('myApp', [])
  .config(['$routeProvider', '$httpProvider', '$locationProvider',function($routeProvider, $httpProvider, $routeParams, $locationProvider) {

    // use the HTML5 History API
    $locationProvider.html5Mode(true);

A: You miss $routeParams in your dependency injection
['$routeProvider', '$httpProvider', '$routeParams', '$locationProvider',
function($routeProvider, $httpProvider, $routeParams, $locationProvider)


text:
Q: could not figure out the exception in this code snippet of java i have tried this code snippet but could not able to figure out the reason for this the exception.
my code is:-
import java.util.*;
class ScannerTest
{
 public static void main(String[]args)
  {
    String csv = "Sue,5,true,3";
    Scanner sc = new Scanner(csv);
    sc.useDelimiter(",");
    int age = sc.nextInt();
    System.out.println(age);
  }
}

Output is:-
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)

i am new to java so please help me out to know the reason for this exception.

A: in the javadoc example you can see how it works:
String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close();

your first token is a string. if you use next int it expects an integer.
you might want to use something like this (under the conditions that you know the structure of the csv and it doesn't change):
public static void main(String[]args)
      {
        String csv = "Sue,5,true,3";
        Scanner sc = new Scanner(csv);
        sc.useDelimiter(",");
        sc.next();
        int age = sc.nextInt();
        System.out.println(age);
      }

or
public static void main(String[] args) {
        String csv = "Sue,5,true,3";
        String ageString = csv.split(",")[1];
        System.out.println(ageString);
    }

...
to parse a string into int:
int age = Integer.parseInt(ageString);

A: The Javadoc of the nextInt method of Scanner states

Scans the next token of the input as an int. This method will throw
  InputMismatchException if the next token cannot be translated into a
  valid int value as described below. If the translation is successful,
  the scanner advances past the input that matched.

As your first token is a String, this is what's going on.  As in most cases in CSV's you will know what will be presented, you should read them one by one, and/or use the hasNextInt method and its friends to check whether what you expect is actually there.

A: The scanner is expecting an integer type but the first token is a String - "Sue", To fix, place:
sc.next(); // skip "Sue"

before the call to nextInt() to consume the String token.


text:
Q: C++: Why can't I convert a string to C-string with an initializer char foo[]? This is my code:
const char readArr[] = readWord.c_str();

This gives an error: array initializer must be an initializer list or string literal
Why must I use
const char *readArr = readWord.c_str();?

A: It's for the same reason you can't
const char *p="foo";

const char readArr[]=p;

either. An array is not a discrete object that can be initialized. The only thing that can be initialized in C++ is a discrete object, and an array is not an object per se. An array is a conceptual address of a contiguous list of values, in consecutive memory locations. When an array is used in an expression, such as:
readArr[i]

The array's name decays to a pointer to the first element in the array. Now, guess what you did when you wrote this:
const char *readArr = readWord.c_str();

Well, you just stored a pointer to the first element in an array of characters, that's owned by the readWord std::string.
In a regular array declaration:
char readArr[]="Hello";

the compiler is given the length of the string, and thus it initialize a consecutive list of character values, and the label readArr to it.

A: const char readArr[] = readWord.c_str();
The reason this is not legal is that it simply doesn't make sense to initialise an array from a pointer. A pointer is in essence a memory address: it points to some data, whether that data is dynamically or statically allocated (allocated 'on the heap' or 'on the stack' respectively). A pointer does not record how much memory is there.
This is confusing to newcomers to C and C++ because the language often allows you to treat arrays as if they were just pointers to their first element. That doesn't mean that arrays are just pointers to their first element. They aren't. But if you use them in an expression they will decay to a pointer to their first element.

A: Because arrays are not pointers. An array... is an array, period. char readArr[] (just like char arr[4]) declares something directly in the local memory space (the stack, for a function) so that something has to be statically allocated.
str.c_str() is somewhere on the heap so that can't work.


text:
Q: lazyloader does not works on AOT production mode angular-cli I am using angular-cli and lazyloader for routing.
ng serve works for me, but after building project as Production mode, then it does not work at all.
Here is my app.routing.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent } from './main/main.component';
import { AuthGuard } from './core/guards/index';
//Layouts
import { LoginComponent } from './login/login.component';

export const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '',
    component: MainComponent,
    children: [
      {
        path: '',
        loadChildren: './main/main.module#MainModule'
      }
    ],
    canActivate: [AuthGuard]
  },{
    path: '**',
    redirectTo: 'login'
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

And this is error I got after ng build --prod --aot or ng serve --prod.
ERROR Error: Uncaught (in promise): Error: Cannot find module './app/main/main.module'.
Error: Cannot find module './app/main/main.module'.
    at t (main.1f6da18….bundle.js:1)
    at t.loadAndCompile (vendor.490f84a….bundle.js:379)
    at t.load (vendor.490f84a….bundle.js:379)
    at t.loadModuleFactory (vendor.490f84a….bundle.js:428)
    at t.load (vendor.490f84a….bundle.js:428)
    at e.project (vendor.490f84a….bundle.js:428)
    at e.XO5T.e._tryNext (vendor.490f84a….bundle.js:897)
    at e.XO5T.e._next (vendor.490f84a….bundle.js:897)
    at e.next (vendor.490f84a….bundle.js:897)
    at e.RRVv.e._subscribe (vendor.490f84a….bundle.js:736)
    at t (main.1f6da18….bundle.js:1)
    at t.loadAndCompile (vendor.490f84a….bundle.js:379)
    at t.load (vendor.490f84a….bundle.js:379)
    at t.loadModuleFactory (vendor.490f84a….bundle.js:428)
    at t.load (vendor.490f84a….bundle.js:428)
    at e.project (vendor.490f84a….bundle.js:428)
    at e.XO5T.e._tryNext (vendor.490f84a….bundle.js:897)
    at e.XO5T.e._next (vendor.490f84a….bundle.js:897)
    at e.next (vendor.490f84a….bundle.js:897)
    at e.RRVv.e._subscribe (vendor.490f84a….bundle.js:736)
    at u (polyfills.1e19b2c….bundle.js:43)
    at u (polyfills.1e19b2c….bundle.js:43)
    at polyfills.1e19b2c….bundle.js:43
    at t.invokeTask (polyfills.1e19b2c….bundle.js:36)
    at Object.onInvokeTask (vendor.490f84a….bundle.js:365)
    at t.invokeTask (polyfills.1e19b2c….bundle.js:36)
    at r.runTask (polyfills.1e19b2c….bundle.js:36)
    at o (polyfills.1e19b2c….bundle.js:36)

Here is screenshot of browser console.

What is wrong on my routing configuration? PP : ng serve is working with out any errors.

A: This issue is coming from angular2-busy module.
https://www.npmjs.com/package/angular2-busy
Removing this from project solved issue.


text:
Q: Vite: Replace env vars at build time I am using Vue + Vite + TS and I am building a few libraries that I would like to build and import somewhere else.
The point is that I set some environment variables using the dotenv, hence I can use things like import.meta.env.MY_VARIABLE.
But they are being availed during the run time of the place I run them, hence the env files need to be placed in the component that requires those libs.
I would like to know if there is way so they get replaced in the build time.

A: Maybe you want to use the define option.
let commonConfig =
{

  plugins: [vue()],

  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url))
    },
  },
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        nested: resolve(__dirname, 'auth_redirect.html')
      }
    }
  }
}

export default defineConfig(({ command, mode, ssrBuild }) => {

  if (command === 'serve')
  {
//
    return commonConfig;

  }
  else
  {
    commonConfig.define = {
      "BUILD_TIMESTAMP": new Date().toISOString()

    };

    // command === 'build'
    return commonConfig;
  }
})

And then you can just assign BUILD_TIMESTAMP to any javascript variable in your appCode.
const buildNum = "BUILD_TIMESTAMP";//You will get right val in this.
define has to be compatible with https://esbuild.github.io/api/#non-analyzable-imports so gives issues in serve mode. So I have used it conditionally in build mode only.
In Dev Mode you will see just raw value of buildNum variable.


text:
Q: How remove node ID [nid:n] in NodeReference fields This is the same question of this link:
Removing [nid:n] in nodereference autocomplete
According with the first answer (Grayside) I've created my own module and activated. Then I create a new content, I look sth up in the nodereference field and finally select it -> it works (Doesn't appear the [nid:n]).
But, when I view/preview or save or edit the content, the [nid:n] appears again.
Anybody can help me?

A: When viewing the node, it is the theming function for the field that determines what is displayed, so you need to overwrite it, if you want to change the output.
The value when you edit the node, is determined by the #default_value property, so you need to change in your hook_form_alter()

A: Thanks for the answer.
I've found the solution. (At least in my case)
I change the code of this file:

drupal\modules\cck\cck\modules\nodereference.module

function nodereference_autocomplete_value($element, $edit = FALSE)
{
  ...
  // $value .= ' [nid:'. $nid .']';    --> Comment this line
  return array($field_key => $value);
}

It works very well! Doesn't appear in any case: Not in selected from the list, nor when save, edit, etc.
Regards!


text:
Q: Passing 2D array as an argument I am running my code but getting this error and I don't know how to deal with it.
My code:
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define LIMIT 5
int m;

void dfs(int i,int j,int k,int kk,int mat[][1000],bool vis[101][101],int n,int m) {
    if(i<0 || i>n-1 || j<0 || j>m-1)
        return;
    if(mat[i][j]!=kk)
        return;
    if(vis[i][j])
        return;
    mat[i][j] = k;
    dfs(i,j+1,k,kk,mat,vis,n,m);
    dfs(i,j-1,k,kk,mat,vis,n,m);
    dfs(i+1,j,k,kk,mat,vis,n,m);
    dfs(i+1,j+1,k,kk,mat,vis,n,m);
    dfs(i+1,j-1,k,kk,mat,vis,n,m);
    dfs(i-1,j,k,kk,mat,vis,n,m);
    dfs(i-1,j-1,k,kk,mat,vis,n,m);
    dfs(i-1,j+1,k,kk,mat,vis,n,m);
}

int main() {
    int t;
    cin>>t;
    while(t--) {
        int n,m;
        bool vis[101][101];
        cin>>n>>m;
        int mat[101][101];
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                cin>>mat[i][j];
        int x,y,k;
        cin>>x>>y>>k;
        int kk = mat[x][y];

        dfs(x,y,k,mat,vis,n,m);
    }
    return 0;
}

The error:
cpp:41:13: error: invalid conversion from 'int (*)[101]' to 'int' [-fpermissive]
41 |   dfs(x,y,k,mat,vis,n,m);
   |             ^~~
   |             |
   |             int (*)[101]

Thanks in advance.

A: You have a typo in the function call, it's missing a parameter, 4 int parameters are necessary before the 5th parameter, a 2D array, I'm guessing you forgot to include the 4th parameter kk. That what's causing that compilation error.
Fixing that won't solve your problem because you can't pass an array with dimensions (*)[101] to a function that receives a parameter with (*)[1000] dimensions, they must match, these are regarded as incompatible types.
Either declare mat as:
 int mat[1000][1000];

Or change the function declaration to:
void dfs(int i, int j, int k, int kk, int mat[][101], bool vis[101][101], int n, int m)
                                                ^^^

A: There's another int parameter (kk) in your dfs function, but you are ignoring it in line 41:          dfs(x,y,k,mat,vis,n,m);, you should write another integer value after k


text:
Q: How to fix "non-numeric argument to binary operator" I want to dra a waterfall plot and actually I have successfully get a good plot. Then I want to add a binary column using ifelse function. Now the function does not work, and says "non-numeric argument...". Can anyone help me? Thanks!
library(tumgr)
library(ggplot2)
library(tidyverse)
set.seed(1234)
tumorgrowth = sampleData
tumorgrowth = do.call(rbind,
by(tumorgrowth, tumorgrowth$name,
     function(subset) within(subset,
              { treatment = ifelse(rbinom(1,1,0.5), "Drug","Control")
#random classfied
                o = order(date)
                date = date[o]
                size = size[o]
                baseline = size[1]
                percentChange = 100*(size-baseline)/baseline
                time = ifelse(date > 250, 250, date)
                cstatus = factor(ifelse(date > 250, 0, 1))
              })))
 tumorgrowth1 = tumorgrowth%>%
   group_by(name)%>%
   mutate(patient=percentChange[which.max(abs(percentChange))])%>%
   select(name,patient,cstatus)
o=order(tumorgrowth1$patient,decreasing = TRUE)
tumorgrowth1=tumorgrowth1[o,]
tumorgrowth1=distinct(tumorgrowth1)

col=ifelse(tumorgrowth1$cstatus==0, "#BC5A42", "#009296")

# This function does not work after adding the "col" column
waterfall=function(data,var){
  barplot(data[,var],width=0.1,col=col, border=col,cex.axis=1.2,
  cex.lab=1.4)
}
waterfall(tumorgrowth1,"patient")

A: You were close. For the barplot you need the matrix to be transposed which can be achieved with t(). Since cstatus is a factor column, this step would transform all data into "character". Probably the column is not needed so we can fix this by simply excluding it. Naturally in your function you'll have to move var to the rows.
waterfall <- function(data,var) {
  barplot(data[var, ], width=0.1, col=col, border=col, cex.axis=1.2,
          cex.lab=1.4)
}
waterfall(t(tumorgrowth1[-3]), "patient")


text:
Q: dplyr group by RunID carry values to next group I have data of which I want to group by, perform calculations then the final result, use that for calculations in the next group.
We use conditional statements and perform calculations per group for example:
# Example Data
condition <- c(0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,0)
col_a <- c(0,0,0,2,3,4,0,0,0,2,4,5,6,0,0,0,0,0,0,0,0,1,2,0)
col_b <- c(0,0,0,10,131,14,0,0,0,22,64,75,96,0,0,0,0,0,0,0,0,41,52,0)
df <- data.frame(condition,col_a,col_b)

This is the code to do the calculations, group by RunID
# Group by RunID
# Perform calculations
# Last value, brought forward to next group
require(dplyr)
output <- df %>%
  dplyr::mutate(RunID = data.table::rleid(condition)) %>%
  group_by(RunID) %>%
  dplyr::mutate(calculation = ifelse(condition == 0,0, ifelse(row_number() == n(),first(col_a) * last(col_b),0))) %>%

dplyr::mutate(last.tag = ifelse(condition == 0,0, ifelse(row_number() == n(),2,0))) %>% # Add helper ID no. to aid with for loop below in answer
      ungroup() %>%
      select(-RunID)
    output <- data.frame(output)
    head(output,15)
With the output:
      condition col_a col_b calculation
1          0     0     0           0
2          0     0     0           0
3          0     0     0           0
4          1     2    10           0
5          1     3   131           0
6          1     4    14          28
7          0     0     0           0
8          0     0     0           0
9          0     0     0           0
10         1     2    22           0
11         1     4    64           0
12         1     5    75           0
13         1     6    96         192
14         0     0     0           0
15         0     0     0           0

What I want to do is. On the first outcome, the result in calculation column is 28. I want to carry that value over to the next group and insert in col_a, row number 10 (28 replaces, 2). Then as that value is updated. The second group calculation result will be 96 * 28 = 2688 versus (96*2 = 192)
The carry forward will always insert on the first row of each group as example above.
Expected output:
      condition col_a col_b calculation
1          0     0     0           0
2          0     0     0           0
3          0     0     0           0
4          1     2    10           0
5          1     3   131           0
6          1     4    14          28
7          0     0     0           0
8          0     0     0           0
9          0     0     0           0
10         1     28    22           0
11         1     4    64           0
12         1     5    75           0
13         1     6    96         2688
14         0     0     0           0
15         0     0     0           0

Other solution:
I subsetted to remove all 0,s. Added a 2 number identified to bottom of each group to make a continuous run, then use a for loop to go through grab and replace. Probably not most elegant but seems to work:
# Subset to remove all 0
subset.no.zero <- subset(output,condition >0)
# Loop to move values
for (i in 1:nrow(subset.no.zero)) {
  temp <- ifelse(subset.no.zero$last.tag[i-1] == 2, subset.no.zero$calculation[i-1],subset.no.zero$col_a[i])
  subset.no.zero$new_col_a[i] <- data.frame(temp)
}

# Re join by index no.
final_out <- full_join(output,subset.no.zero, by="index")

A: I can only offer a data.table solution but perhaps you can translate the logic into dplyr:
library(data.table)
setDT(df)

#first group multiply 2 and 14
df[rleid(condition) %in% 1:2 & condition != 0,
   calculation := {
     res <- rep(NA_real_, .N)
     res[.N] <- col_b[.N] * col_a[1]
     res
   }
   ]

#all groups other than first copy col_b
df[, calculation := if (condition[.N] != 0) {
  if(is.na(calculation[.N])) {
    res <- rep(NA_real_, .N)
    res[.N] <- col_b[.N]
    res
  } else calculation
} else NA_real_,
by = rleid(condition)
]

#cumulative product
df[!is.na(calculation),
   calculation := cumprod(calculation)]

#copy values into col_a
df[i = df[, .(condition = condition[1], i = .I[1]),
          by = rleid(condition)][condition == 1L][-1, i], #finds rows to replace values
   col_a := head(df[!is.na(calculation), calculation], -1)
   ]

#    condition col_a col_b calculation
# 1:         0     0     0          NA
# 2:         0     0     0          NA
# 3:         0     0     0          NA
# 4:         1     2    10          NA
# 5:         1     3   131          NA
# 6:         1     4    14          28
# 7:         0     0     0          NA
# 8:         0     0     0          NA
# 9:         0     0     0          NA
#10:         1    28    22          NA
#11:         1     4    64          NA
#12:         1     5    75          NA
#13:         1     6    96        2688
#14:         0     0     0          NA
#15:         0     0     0          NA
#16:         0     0     0          NA
#17:         0     0     0          NA
#18:         0     0     0          NA
#19:         0     0     0          NA
#20:         0     0     0          NA
#21:         0     0     0          NA
#22:         1  2688    41          NA
#23:         1     2    52      139776
#24:         0     0     0          NA
#    condition col_a col_b calculation


text:
Q: Blazor database connection to remote mysql server I'm briefly new into Blazor. I was wondering if it's possible to make a very basic connection to mysql database server hosted remotely via simple function:
string connectionString = "data source = database ip here,1600;Initial Catalog=HDSERVER;Persist Security Info=True; User ID=user_id; Password=Password()";

    int idUser = -1;

    UserModel User = new UserModel();

    public class UserModel
    {
        public string name { get; set; }
        public string pin { get; set; }
    }

    private void LoginUser()
    {
        Console.WriteLine(User.name);
        Console.WriteLine(User.pin);
        {
            try
            {
                Console.WriteLine("starting sql connection...");

                SqlConnection c = new SqlConnection(connectionString);

                Console.WriteLine("opening..");

                c.Open();

                Console.WriteLine("sql connection open..");

                SqlCommand cmd = new SqlCommand("Login", c);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@pin", pinCode);

                Console.WriteLine("getting data");

                var pId = cmd.Parameters.AddWithValue("@idUser", idUser);

                Console.WriteLine("pId: ", pId);

                pId.Direction = ParameterDirection.Output;

                cmd.ExecuteNonQuery();
                c.Close();

                Console.WriteLine("sql connection closed..");

                int id = (int)pId.Value;

                Console.WriteLine("id: ", id);

                if (id > 0)
                {
                    NavigationManager.NavigateTo("/home");
                }
                else
                {
                    Console.WriteLine("Cannot sing in!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: ");
                Console.WriteLine(e.Message);
            }
        }
    }

Or maybe there is another specific way for doing that? I usually typing code in js & react, so for me everything here is so new and a little confusing me. It would be great as well if someone could share any tips how to do such things or from where getting a knowledge about Blazor !
Thanks in advance!


text:
Q: how to define two tokens as one token? I am trying to define two words separated by space as one token in my lexical analyzer
but when I pass an input like in out it says LexToken(KEYIN,'in',1,0)
and LexToken(KEYOUT,'out',1,3)
I need it to be like this LexToken(KEYINOUT,'in out',1,0)
PS: KEYIN and KEYOUT are two different tokens as the grammar's definition
Following is the test which causes the problem:
import lex
reserved = {'in': 'KEYIN', 'out': 'KEYOUT', 'in\sout': 'KEYINOUT'} # the problem is in here

tokens = ['PLUS', 'MINUS', 'IDENTIFIER'] + list(reserved.values())

t_MINUS = r'-'
t_PLUS = r'\+'
t_ignore = ' \t'

def t_IDENTIFIER(t):
    r'[a-zA-Z]+([(a-zA-Z)*|(\d+)*|(_*)])*'
    t.type = reserved.get(t.value, 'IDENTIFIER')  # Check for reserved words
    return t

def t_error(t):
    print("Illegal character '%s'" % t.value[0], "at line", t.lexer.lineno, "at position", t.lexer.lexpos)
    t.lexer.skip(1)

lex.lex()
lex.input("in out inout + - ")
while True:
    tok = lex.token()
    print(tok)
    if not tok:
        break

Output:
LexToken(KEYIN,'in',1,0)
LexToken(KEYOUT,'out',1,3)
LexToken(IDENTIFIER,'inout',1,7)
LexToken(PLUS,'+',1,13)
LexToken(MINUS,'-',1,15)
None

A: This is your function which recognizes IDENTIFIERs and keywords:
def t_IDENTIFIER(t):
    r'[a-zA-Z]+([(a-zA-Z)*|(\d+)*|(_*)])*'
    t.type = reserved.get(t.value, 'IDENTIFIER')  # Check for reserved words
    return t

First, it is clear that the keywords it can recognize are precisely the keys of the dictionary reserved, which are:
in
out
in\sout

Since in out is not a key in that dictionary (in\sout is not the same string), it cannot be recognised as a keyword no matter what t.value happens to be.
But t.value cannot be in out either, because t.value will always match the regular expression which controls t_IDENTIFIER:
[a-zA-Z]+([(a-zA-Z)*|(\d+)*|(_*)])*

and that regular expression never matches anything with a space character. (That regular expression has various problems; the characters *, (, ), | and + inside the second character class are treated as ordinary characters. See below for a correct regex.)
You could certainly match in out as a token in a manner similar to that suggested in your original question, prior to the edit. However,
t_KEYINOUT = r'in\sout'

will not work, because Ply does not use the common "maximum munch" algorithm for deciding which regular expression pattern to accept. Instead, it simply orders all of the patterns and picks the first one which matches, where the order consists of all of the tokenizing functions (in the order in which they are defined), followed by the token variables sorted in reverse order of regex length. Since t_IDENTIFIER is a function, it will be tried before the variable t_KEYINOUT. To ensure that t_KEYINOUT is tried first, it must be made into a function and placed before t_IDENTIFIER.
However, that is still not exactly what you want, since it will tokenize
in outwards

as
LexToken(KEYINOUT,'in out',1,0)
LexToken(IDENTIFIER,'wards',1,6)

rather than
LexToken(KEYIN,'in',1,0)
LexToken(IDENTIFIER,'outwards',1,3)

To get the correct analysis, you need to ensure that in out only matches if out is a complete word; in other words, if there is a word boundary at the end of the match. So one solution is:
reserved = {'in': 'KEYIN', 'out': 'KEYOUT'}

def t_KEYINOUT(t):
    r'in\sout\b'
    return t

def t_IDENTIFIER(t):
    r'[a-zA-Z][a-zA-Z0-9_]*'
    t.type = reserved.get(t.value, 'IDENTIFIER')  # Check for reserved words
    return t

However, it is almost certainly not necessary for the lexer recognize in out as a single token. Since both in and out are keywords, it is easy to leave it to the parser to notice when they are used together as an in out designator:
parameter: KEYIN IDENTIFIER
         | KEYOUT IDENTIFIER
         | KEYIN KEYOUT IDENTIFIER


text:
Q: Best way to save video in iOS Application for offline viewing I'm in state of confusion that "What would be the best way to store video?" locally downloaded from the server.
I have two versions of same app i.e online and other offline.
For offline mode I want to download all the videos locally for watching them offline in future.
I know that there are two ways of storing videos:

*

*Feasible way would be storing it in document directory of the application and save the corresponding video file name in the sqlite database. But, there are around 200+ videos!
I just fear it might create memory problem, giving my application memory warning and make it to crash.

*Storing it in NSData format in sqlite database, but it would make the database huge which I think would not be feasible as sqlite db is meant to be light weight.
Is there some other way that we can accomplish the task. (And as per the requirement videos should not be save in the gallery on the device).
Please help me!
Thanks!

A: As far as I know, the document directory is your only option. It should not effect the memory, however, please keep in mind that if you app gets deleted, this directory will be as well.
I have recently built an app that relied on saving videos to the Document directory and we ran in to no problems.
I would avoid storing large assets in a Database. You gain no benefit from this and these videos will still be lost if the app is deleted.

A: You can save any kind of files, anywhere in your application environment directories using...
[[NSFileManager defaultManager] moveItemAtPath:[/*Your current file path*/] toPath:/*Your destination path*/ error:/* &errorObj */];

OR
[[NSFileManager defaultManager] copyItemAtPath:[/*Your current file path*/] toPath:/*Your destination path*/ error:/* &errorObj */];

and for moving 200+ files... you can use a naming convention from which you can handle it using any kind of loops.
Note :
1. For any kind of large in size files, I always use this way, rather than saving in any kind of databases.
2. One should always use "move" operation while downloading the files.


text:
Q: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.- django 1.11 After trying to implement Token Authentication using DRF, i get this error raised in my terminal. I have had seen other related relevant questions with solutions but none of them solved my issue.
Below is my wsgi.py
"""
WSGI config for myApp project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myApp.settings")

application = get_wsgi_application()

stack trace
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute
    django.setup()
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models()
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/emmnock/Desktop/peaceAppProject/peaceApp/peace/models.py", line 28, in <module>
    Token.objects.get_or_create(user=user)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 464, in get_or_create
    return self.get(**lookup), False
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 371, in get
    clone = self.filter(*args, **kwargs)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 782, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 800, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1261, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1165, in build_filter
    lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1045, in solve_lookup_type
    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1342, in names_to_path
    if field.is_relation and not field.related_model:
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/fields/related.py", line 115, in related_model
    apps.check_models_ready()
  File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/registry.py", line 132, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

A: Try editing your wsgi.py like this,
import os

from django.core.wsgi import get_wsgi_application

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = get_wsgi_application()


text:
Q: syntax 'T<...>(...)' is impossible. What's the next best thing? I have a type
class foo {
public:
    foo(int);

    template <typename T, typename U>
    foo(T, U);

    template <typename T, typename U>
    foo(std::inirializer_list<T>);

    // or other different constructors.
};

explicitly calling an exact overload of a constructor is impossible.
syntax foo::foo<int>(int()); (class<tmpl_params>::ctor<tmpl_params>(args) just like the syntax of a static member function) is ill-formed (and on top of that foo(int) isn't a template). Same story with any other overloaded version of a constructor.
is there a way (even a hacky one) to explicitly force the compiler to use one overloaded version of a constructor instead of any other?
There's automatic type deduction, but that's an implicit way.


text:
Q: How to take input value from submit form and store in redux store variable? I have made a bank account submit form. I want to save the data which is entered in the form into redux store. How can I take input value from form and store it in redux store variable ?
My client.js file has redux store and form.js is the component from which I need to get the input values.
client.js:
import { combineReducers, createStore } from 'redux';

const addUserReducer = (state={}, action) => {
    switch(action.type){
        case: "CHANGE_FIRSTNAME"{
            state = {...state, firstname:action.payload }
            break;
        }
        case: "CHANGE_LASTNAME"{
            state = {...state, lastname:action.payload }
            break;
        }
        case: "CHANGE_EMAILID"{
            state = {...state, emailid:action.payload }
            break;
        }
        case: "CHANGE_IBAN"{
            state = {...state, iban:action.payload }
            break;
        }
        case: "CHANGE_BANKNAME"{
            state = {...state, bankname:action.payload }
            break;
        }
    }
    return state;
}

const reducers = combineReducers({
    addUser:addUserReducer
})

const store = createStore(reducers);

store.subscribe(() => {
    console.log('Store changed', store.getState());
})

store.dispatch({type: "CHANGE_FIRSTNAME", payload:"Will"});
store.dispatch({type: "CHANGE_LASTNAME", payload:"Groot"});
store.dispatch({type: "CHANGE_EMAILID", payload:"xyz@gmail.com"});
store.dispatch({type: "CHANGE_IBAN", payload:3234243242});
store.dispatch({type: "CHANGE_BANKNAME", payload:"XYZ"});

form.js:
import React, { Component } from "react";
import "./form.css";

class Form extends Component {
  render() {
    return (

          <form>

              First Name:
              <input type="firstname" className="form-control" id="firstname" />

              Last Name:
              <input type="lastname" className="form-control" id="lastname" />

              Email address:
              <input type="email" className="form-control" id="email" />

              IBAN:

                <input type="bankacc" className="form-control" id="bankacc" />
                <button type="button" class="btn btn-default btn-sm">

                </button>

              Bank Name:
              <input type="bankname" className="form-control" id="bankname" />

              <button type="button" className="btn addbank">
                + Add bank account
              </button>

              <button type="button" class="btn btn-success">
                Submit
              </button>

          </form>

    );
  }
}

export default Form;

Screenshot of my form:

A: I would recommend react-redux to connect your components with redux store, however it is still doable without it:
Create action creators that will update specific variable in the store:
import { bindActionCreators } from "redux";

const updateFirstName = name => ({ type: "CHANGE_FIRSTNAME", payload: name });
const updateLastName = lastName => ({
  type: "CHANGE_LASTNAME",
  payload: lastName
});
const updateEmail = email => ({ type: "CHANGE_EMAILID", payload: email });
const updateIban = iban => ({ type: "CHANGE_IBAN", payload: iban });
const updateBankName = bankName => ({
  type: "CHANGE_BANKNAME",
  payload: bankName
});

Now bind your action creators with dispatch, so calling actionCreators.updateFirsName('something') will actually dispatch an action to the store.
export const actionCreators = bindActionCreators(
  {
    updateFirstName,
    updateLastName,
    updateEmail,
    updateIban,
    updateBankName
  },
  store.dispatch
);

Now you only need to call each store-updating function whenever theres an change on the input:
import React, { Component } from "react";
import "./form.css";
import { actionCreators } from "/path/to/store";

class Form extends Component {
  render() {
    return (

          <form>

              First Name:
              <input
                type="firstname"
                className="form-control"
                id="firstname"
                onChange={e => actionCreators.updateFirstName(e.target.value)}
              />

              Last Name:
              <input
                type="lastname"
                className="form-control"
                id="lastname"
                onChange={e => actionCreators.updateLastName(e.target.value)}
              />

              Email address:
              <input
                type="email"
                className="form-control"
                id="email"
                onChange={e => actionCreators.updateEmail(e.target.value)}
              />

              IBAN:

                <input
                  type="bankacc"
                  className="form-control"
                  id="bankacc"
                  onChange={e => actionCreators.updateIban(e.target.value)}
                />
                <button type="button" class="btn btn-default btn-sm">

                </button>

              Bank Name:
              <input
                type="bankname"
                className="form-control"
                id="bankname"
                onChange={e => actionCreators.updateBankName(e.target.value)}
              />

              <button type="button" className="btn addbank">
                + Add bank account
              </button>

              <button type="button" class="btn btn-success">
                Submit
              </button>

          </form>

    );
  }
}

export default Form;


text:
Q: "to be/is/get used" Why in this sentences use phrase "to be" instead of is or get?
What did the author wants to say?

Polymorphism is a feature that allows one interface to be used for a general class of actions.

A: Under a traditional analysis, only finite verbs form predicates and require subjects.  Using a finite verb like "is" or "gets" would break the clause structure because there just aren't enough subjects to go around.

Polymorphism is1 a feature that allows2 one interface to be used for a general class of actions.

The first finite verb in this sentence is "is".  Its clause takes "polymorphism" as its simple subject, and "feature" is the verb's simple argument.  The second finite verb is "allows".  That clause takes "that" as its subject, with "interface" as the verb's simple object, and the rest of the sentence as an object complement.

One interface is1 used for a general class of actions.

This sentence has one finite verb, and the clause takes "interface" as its simple subject.
Here's the conflict:  In the first sentence, "interface" isn't available as a simple subject for anything.  It already has a role as an object.

* Polymorphism is1 a feature that allows2 one interface is3 used for a general class of actions.

If we treat "interface" as the simple subject of "is3", then "allows2" has no object and the sentence makes no sense.  Alternately, if we treat "interface" as the simple object of "allows2", then "is3" has no subject and the sentence makes no sense.
We could, of course, make sense of things if we split the relevant clauses into separate sentences:

One interface can1 be used for a general class of actions.  Polymorphism is2 a feature that allows3 this behavior.

Here, "this behavior" refers to the entire contents of the preceding sentence.  Each finite verb has its own subject, and no constituent has any conflict regarding what grammatical role it should play.


text:
Q: Bounced email on Google App Engine I'm developing application for google app engine (python), witch needs not only to send emails, but also know which ones bounce back.
I created special account for my domain noreply@example.com, added it as an app admin and sending messages from it.
The problem is (and it was described here http://code.google.com/p/googleappengine/issues/detail?id=1800) - GAE sets the Return-Path to some internal email address, not allowing to receive bounced email messages.
Anyone aware of any possible workaround for this? Thanks.

A: It looks like someone bypassed this problem by switching to Yahoo's Mail API, which uses OAuth and can be used over HTTP. Until google fixes your problem, this looks like a viable solution.

A: Until the issue is resolved, workaround for my project is using typhoonae, bind mail service to google app's gmail as SMTP (to send messages from noreply@example.com). When sending this way, noreply@example.com receives bounced messages.

A: Google has actually since added a method for receiving bounced messages via an HTTP Request. It requires adding to your app.yaml:
inbound_services:
- mail_bounce

Which will cause a request to hit /_ah/bounce each time a bounce is received. You can then handle the bounce by adding a handler for it. See the section there on Handling Bounce Notifications for more details on how to glean the additional information from those requests.

A: You could use use a third party "email marketing" API like CampaignMonitor that keeps track of the bounced addresses:
http://www.campaignmonitor.com/api/method/subscribers-getbounced/
But you'd have to send mail through them, and sync your user list with theirs through their API.


text:
Q: Execute command set results as variable Can anyone tell me how to set the output of a command to a variable?
Basically, I'm looking for the Python equivalent to this bash example:
blah="ajsdlk akajl <ajksd@ajksldf.com>"
blah=$(echo "$blah" | cut -d '<' -f 2 | cut -d '>' -f 1)
echo "$blah"
ajksd@ajksldf.com

A: You may use string.split
>>> blah="ajsdlk akajl <ajksd@ajksldf.com>"
>>> blah.split('<')[1].split('>')[0]
'ajksd@ajksldf.com'

A: If a function returns a string, just capture its return value. If you're looking to capture the standard output from a function, wrap it with a StringIO wrapper.


text:
Q: sorting a string array and an int array I am working on making a dating website on java. I want to find the three most compatible matches for a user. So i have an array of three ints and if a user is more compatible the least compatible score will be replaced. I do this using selection sort. I also need the references to be correct so i Can return the proper names. I can't figure our how to sort the string array. Thanks for the help and heres the code:
  public void findMatches(String matchName)
  {
  String nameA = null;
  String nameB = null;
  String nameC = null;
  int matchA = -1;
  int matchB = -2;
  int matchC = -3;
  Member ref = userList.get(matchName);
  if(ref.getDesiredAge()>=45 && ref.getDesiredSex().equalsIgnoreCase("Male"))
  {
     for(String na : userListMaleOld.keySet())
     {
        Member refA = userListMaleOld.get(na);
        int numberOfMatches=findQuestionMatches(ref, refA);
        int [] counts = {matchA, matchB, matchC};
        String [] names = {nameA, nameB, nameC};
        counts = doSelectionSort(counts);
        if(numberOfMatches>counts[0]);
        {
           counts[0] = numberOfMatches;
           ?!?!?!?!?!??!??!??!WHAT HERE?!?!
        }

A: Use a Map instead.
Concrete this means that you can do something like this:
Map<User, Integer> bestMatches = new HashMap<>();

void validateUser(User user, int value) {
  if(bestMatches.size() < 3) {
     bestMatches.put(User, 3);
     return;
  }

  Map<User, Integer> newMap = new HashMap<User, Integer>();
  User minValue = Collections.min(bestMatches.values());
  if(value > minValue) {
     for(Map.Entry<User, Integer> entry: bestMatches.entrySet()) {
           if(entry.getValue() != minValue) {
              newMap.put(entry.getKey(), entry.getValue());
           }
     }
     newMap.put(user, value);
  }

  bestMatches = newMap;
}

It's probably not very optimized, but you can fix that as you wish. Basically just check if the value of the current user is higher than the lowest value among the existing users in the collection. If it is, create a new collection with the 2 other users and assign that to your first collection.
For large datasets this would be impractical, but we're talking about 3 users here so it shouldn't be an issue.

A: If these are actually supposed to be name / score pairs (i.e. scoreA is the score for nameA, scoreB is the score for nameB and so on), then the simple solution is something like this:
  public class Score {
     private String name;
     private int score;
     // Declare a constructor and getters
  }

... and to use this appropriately.  For instance, you could now sort a list or array of these Score objects, by name or by score.
Unfortunately, it is not possible to figure out what the code you've shown us is supposed to do, and how it is supposed interact with the rest of your code.  Therefore, it is not entirely clear how you should modify your code to use this.  And it maybe that you are best of starting over following Jeroen's advice and completely redesigning your data structures.


text:
Q: J2EE to Java standalone applications communication What are the best practices to have two applications on the same host, one J2EE and the other Java standalone, communicate one with the other?
More infos:

*

*The j2ee application will be deplyed in Wildfly AS

*The Java stand alone is a Netty NIO Server

EDIT ONE
Even more infos:

*

*The Netty server is a cardgame server that will hold the business logic for the game itself and will allow players to play synchronously one with the other (up to four players per game, up to a max amount of games allowed from my hw server resources)

*The J2ee application (deployed in Wildly) will take care of authentication&authorization

*The J2ee application will take care of the DB connection and Persistence

*The J2ee application will have to forward to the java standalone server the remote-socket-address of the authenticated player and eventually an object holding the state of that player

*The J2ee application will potentially be the one triggering the communication although for my current flow, i am in need of a full duplex communication from both ends (hence my fear about a WS or Rest, isn't it kind of asymmetrical for a full duplex communication channel?)

*The Netty server may be seen as a background task of the AS that will start it (and eventually other cardgame servers) in an attempt of pseudo horizzontal scalability

A: Have one open a socket and communicate to the other.
You could do more exotic stuff, but if anything about the environment changes, it will break.  For a few ideas of "exotic stuff"

*

*Write and read from named pipes

*Set up a shared memory buffer, or two.
etc ...

A: I think it is not possible to give a good implementation pattern when you are not clear/explicit about the following relevant questions:

*

*Is the standalone application a background task (possibly launched
with the container)?

*If yes, do both J2EE and standalone have to
share session or conversation data?

*Who triggers the communication
when communicating?

*Do both applications possibly share the same back-end database?


text:
Q: How to make scrollIntoView() work on first click (Angular 6)? Previous solution to similar StackOverflow question is focused on Jquery and no possible solution found for angular 6/Javascript.
Currently, I am using scrollIntoView() with behavior as smooth to scroll to a dynamically created div using router outlet, but it only scrolls after the second click, is there anything wrong in my code or is it possible to achieve it in the first click?
Html:
<div>
  <mat-card-title (click)="articleNavigation(documents._id)">{{documents.title}}</mat-card-title>
</div>
<div #test style="width:50%; margin-left: auto; margin-right: auto;">
  <router-outlet></router-outlet>
</div>

ts:
articleNavigation(documentId) {
 this.router.navigate(['./document' , documentId], { relativeTo: this.route });
 this.test.nativeElement.scrollIntoView({behavior: 'smooth'});
}

If I use behavior auto instead of smooth, it works on the first click, but a smooth transition is preferred. One of the possible reason which I think is on the first click, div is created and on the second click scrollIntoView() transits to the div.

A: Try this :
setTimeout(() => {
    this.test.nativeElement.scrollIntoView({behavior: 'smooth'});
});


text:
Q: Eclipse DLTK central database on server We're using Eclipse (with PDT) for several projects. The main load seems to come from the DLTK indexing process, which is quite a lot resources per client.
It would offload the clients a lot if a server could perform this indexing task (DLTK indexing could be switched off).
So I wonder; is it possible to create and use a central (H2) database/repository for indexing the projects for multiple clients?

A: Though I have not attempted this, it seems entirely possible to configure the H2's Connection profile to utilize an external URL. Follow these steps for configuring H2 but point the connection URL from local to the server.
After transferring the database and pointing the driver's URL Connection at the server, you could disable the DLTK indexing on every machine  except the server. I also recommend you have a look at the article suggested in this answer.


text:
Q: JQuery плагин DataTable вопрос с AJAX В данном плагине присутствуют паддинги и они считаются от кол-ва строк, но если у меня 100к данных в бд - это глупо выполнять 1 запрос и рендерить страницу в плане оптимизаций. Есть ли возможность эти паддинги вывести статично зная заранее сколько будет данных. Например я сделаю запрос в бд на кол-во строк и уже буду ориентироваться сколько мне нужно паддингов и при нажатий на следующий пункт выполнять запрос в бд на получение данных. Т.е сделать подобие ленивой загрузки

A: Если решать проблему не через serverside, то можно запрашивать на бэке общее кол-во строк,
задавать кол-во страниц,
затем забирать с бэка данные в рамках этого пейджа и добавлять строки руками.
Но возможна проблема с сортировкой, поиском...поэтому, если есть возможность, лучше через serverside, ссылку вам уже дали в комментарии.


text:
Q: How to split datetime? I am sending sms to user after successful transaction,in that sms i am adding date.
During sending sms taking that date from database, as that is datetime field it gives me date up to nano seconds while i want only date of transaction, how can i split it?

A: I think date instance method should do the job -
date = transaction_datetime.date() # assuming transaction_datetime is a datetime object

Reference - https://docs.python.org/2/library/datetime.html


text:
Q: Stop the cursor from jumping to the end of the line when typing a colon in the VS2017 C++ editor When I type a colon before the end of a word in VS2017, the cursor jumps to the end of the line:

This only happens when the word is last on a line.
I don't see an option to disable this in the autoformatting settings:

Tried disabling all these checkboxes, but didn't solve the annoyance.
Is there a way to prevent this from happening? I feel constantly defeated by it.

A: Corrections:
Delete the specific symbols in it, and it will be normal. These specific symbols will commit member list.


text:
Q: How to convert a dynamically added property(using metaClass) to JSON I am trying to add a dynamic property to each instance of a class and then convert a list of such objects to json. Refer to the example below
class Author{
    String name
    static hasMany=[books:Book]
}

class Book{
    String title
    static belongsTo=[author:Author]
}

my controller

class AuthorController{
    def listAuthors={
        def authorsList=Author.list()
        def details=['address':'xyz', phone:'123']
        authorList.each{
            it.metaClass.getDetails={->details}
        }

        render authorsList as JSON
    }
}

now i want this dynamically added "details" property to also get rendered as JSON. please help

A: Does it work if instead of creating a setter, you just add a property like:
it.metaClass.details = details

If not, your best path is probably to create a List of Maps from your authorsList (adding the details key/value pair to each map), and then serialize this...


text:
Q: Populating Images from WP7 Gallery to ImageList with Collection Flow Here is what I wanted to do . I have created an ImageList in XAML code
<local:CollectionFlow x:Name="ImageList" ItemTemplate="{StaticResource DataTemplate1}"
       ItemsPanel="{StaticResource ItemsPanelTemplate1}"/>
<Image Source="Images/imgBack.png" Width="48" Height="48" HorizontalAlignment="Left"
       VerticalAlignment="Center" Margin="15,0,0,0" MouseLeftButtonDown="Left"/>
<Image Source="Images/imgfORWARD.png" Width="48" Height="48" HorizontalAlignment="Right"
       VerticalAlignment="Center" Margin="0,0,15,0" MouseLeftButtonDown="Right" />`

Now I m trying to populate the above list using pictures from MediaLibrary like this
ImageList.ItemsSource = mediaLib.Pictures;
I cannot see the pictures from mediaLibrary. Is there something I'm doing wrong . Previously I populated the list using static values like below which works.
ImageList.ItemsSource = new string[] { "SampleImages/1.png", "SampleImages/2.png", "SampleImages/3.png", "SampleImages/4.png", "SampleImages/5.png", "SampleImages/6.png", "SampleImages/7.png", "SampleImages/8.png", "SampleImages/9.png", "SampleImages/10.png", "SampleImages/11.png", "SampleImages/12.png" };

A: A PictureCollection is not just an array of strings it is an enumerable of Picture objects.
Also note that you cannot get the path to images in the medialibrary only streams.


text:
Q: Fatal Errors after moving site A client has moved a magento installation to a new server, I believe they have just copied the lot over - files and database.
The site is now kinda functional but there is lots of stuff missing. Product categories are there but no products are displayed and no errors are showing. On the home page under special offers the following error showed:

Fatal error: Class
  'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Groupprice_Abstract' not found in
  /path/to/magento/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Groupprice.php
  on line 36

in Mage/Catalog/Model/Resource/Product/Attribute/Backend/Groupprice there is a file called Abs (just Abs, no extension) which looks like a regular php file and which declares the following class:
abstract class Mage_Catalog_Model_Resource_Product_Attribute_Backend_Groupprice_Abstract
    extends Mage_Core_Model_Resource_Db_Abstract

So I saved it to the same location as Abstract.php and it cleared up the above error.
Now in the admin area when I go to Catalog->Manage Products the following error shows:

Fatal error: Call to a member function createFromConfiguration() on a
  non-object in
/path/to/magento/includes/src/Mage_Adminhtml_Block_Widget_Grid_Massaction_Item.php
  on line 92

Does this look like a familiar story? Is it likely something has gone wrong while the files were copied? Do I need to see if the old site is still there and copy it again?

A: It seems some files are missing or were not copied correctly. Try to copy them again and overwrite everything you have in your new hosting.
FTP is the often used option but it does not provide security or consistncy, try using rsync or SCP if you have SSH access.


text:
Q: How to solve second order differential equations? There are questions on the site regarding second order differential equations, but none of the rules seem to apply to this question.
So $y''= e^{-2t}+10e^{4t}$, and some conditions are $y(0)=1$ and $y'(0)=0$.
How do I find y? I understand how to do first order differential equations.

A: Approach 1:
$$y'' = 0$$
gives $y_c = c_1t + c_2$. Guessing the particular solution as $Ae^{-2t} + B e^{4t}$ we have
$$4Ae^{-2t} + 16Be^{-4t}= e^{-2t} + 10e^{4t} \implies A=\frac{1}{4} \quad \quad B = \frac{5}{8}$$
So we have
$$y(t) = c_1 t + c_2 + \frac{1}{4}e^{-2t} + \frac{5}{8}e^{4t}$$
subject to $y(0) = 1$ and $y'(0) = 0$. Imposing these conditions we see
$$1 = c_2 + \frac{1}{4} + \frac{5}{8} \implies c_2 = \frac{1}{8}$$
$$0 = c_1 - \frac{1}{2} + \frac{5}{2} \implies c_1 = -2$$
$$y(t) =  \frac{1}{8} - 2t + \frac{1}{4}e^{-2t} + \frac{5}{8}e^{4t}$$
Approach 2:
Let $v(t) = y'(t)$. We then have
$$\frac{dv}{dt} = e^{-2t} + 10e^{4t}$$
$$v(t) = -\frac{1}{2}e^{-2t} + \frac{10}{4} e^{4t} + c_1$$
Using $v(0) = 0$ we see
$$0 = -\frac{1}{2} + \frac{10}{4} + c_1 \implies c_1 = -2$$
Now plugging back in $y'(t)$ we have
$$\frac{dy}{dt} = -\frac{1}{2}e^{-2t} + \frac{10}{4} e^{4t} - 2$$
$$y(t) = \frac{1}{4}e^{-2t} + \frac{5}{8} e^{4t} - 2t + c_2$$
Using $y(0) = 1$ we see
$$1= \frac{1}{4} + \frac{5}{8} - 2 + c_2 \implies c_2 = \frac{1}{8}$$
We again get
$$y(t) =  \frac{1}{8} - 2t + \frac{1}{4}e^{-2t} + \frac{5}{8}e^{4t}$$


text:
Q: Django DST Time change issue with django datetimefield I am facing problem in my django app while working with DateTimeField.Its mainly because of DST time changes.
I have created an event on 30-oct-2015(DST last week).
I created a copy of first event which will be on 06-Nov-2015(Non DST day)
I applied timedelta of 7 days , So it chaned days to 7+. But I did not aplly timedelta for hours.
Due to Day Light saving , its reduced by one hour. I dont need this. I just want to have same hours. How Can I do that.?
I tried with this , but did not help me.
DST timezone issue in django app
Please see this screenshot

my models.py
from django.db import models
from datetime import timedelta

class Event(models.Model):

    name = models.CharField(max_length=100)

    created = models.DateTimeField(auto_now_add=True)

    start_date = models.DateTimeField()

    def __unicode__(self):
        return self.name

    def copy_event(self, add_days=timedelta(days=7)):

        start_date = self.start_date + add_days
        name = self.name +' (copy)'
        new_event = Event(name = name,created = self.created,start_date=start_date,)

        new_event.save()

        return new_event

A: Since USE_TZ=True you are always dealing with aware datetimes, which represent a precise moment in time. That moment in time will, in general, be displayed differently depending on the current time zone. Some time zones have DST and some don't, so in general there's no way you can store the datetime such that all users in all timezones will see the clock time you want (i.e. the same clock time as the event being copied).
I can think of a couple workarounds:

*

*If it's the case that you're only serving one time zone (that is, the current time zone is always going to be the same), you can just do your arithmetic in that time zone.
from django.utils.timezone import localtime
new_start_date = localtime(self.start_date) + add_days

The addition of add_days will always keep the clock time the same (that is, it doesn't take DST into account). The new_start_date will be converted to and stored in UTC, and then converted back to the desired local time for display.

*What you're really trying to represent is a particular clock time on a particular day, not an exact moment in time. So perhaps you don't want to be using aware datetimes at all. One option is to set USE_TZ=False, but that's a global, far-reaching change that you may not want to make. Another option is to use a different representation for this field. For example, you could use a DateField and a TimeField instead of a DateTimeField.

A: I was having this same problem creating repeated events in Django, and here's the solution I found that's pretty clean and - thus far - works. Using your code, where you have:
start_date = self.start_date + add_days

Try:
start_date = self.start_date.replace(tzinfo=None) + add_days

That converts the self.start_date parameter to a naive datetime, and allows the addition of days without accounting for the timezone. I've tested this extensively on my own, and it works both springing forward and falling back.
Reference: Converting timezone-aware datetime to local time in Python

A: Found this to be the best solution
from django.utils.timezone import localtime

l = Event.objects.get(...)
time = localtime(l.time + timedelta(days=7))
time += localtime(l.time).dst() - time.dst()


text:
Q: Substring Error in C++ I am writing a program that will calculate password strength according to two formulas. It requires the user to enter 2 passwords, one being eight characters or less and the other being 20 characters or more. The first parts executes with out problem. But, when I go to execute the second part, it works but the substring function that extracts the next twelve characters keeps extracting 18 characters.  I have looked over my code several times and do not understand why it is doing this. Any help would be greatly appreciated!
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
//All variables and constants are declared
string eight_password, first_char, next_seven, twenty_password, first_char_twenty, next_seven_twenty, next_twelve, remaining;
int ep_length, character_set, first_char_length, next_seven_length, character_set_20, twenty_length, first_char_twenty_length, next_seven_twenty_length, next_twelve_length, remaining_length;
double eight_ent_strength, eight_nist_strength, twenty_ent_strength, twenty_nist_strength;
const int NIST_FIRST = 4, NIST_SEVEN = 2, NIST_REM = 1, NIST_CHARACTER=94, NIST_BONUS=6;
const double NIST_TWELVE = 1.5;
//Console prompts for user to input password and character set
cout << "Hello! Please enter a password of 8 characters or less (including spaces!):" << endl;
getline(cin, eight_password);
cout << "What character set is being used?";
cin >> character_set;
cout << endl;
//Password length and information entropy strength are calculated and saved to the appropriate variables
ep_length = eight_password.length();
eight_ent_strength = (ep_length*((log(character_set))/(log(2))));
//First character and next seven characters are extracted and saved to the appropriate variables
first_char = eight_password.substr(0, 1);
next_seven = eight_password.substr(1, 7);
//First character and next seven characters lengths are calculated and saved to the appropriate variables
first_char_length = first_char.length();
next_seven_length = next_seven.length();
//NIST strength is calculated and saved to the appropriate variable
eight_nist_strength = (first_char_length*NIST_FIRST) + (next_seven_length*NIST_SEVEN)+((character_set/NIST_CHARACTER)*NIST_BONUS);

//The information that was calculated is now printed back out on the console to be viewed by the user
cout << "Your password " << eight_password << " is " << ep_length << " characters long. According to the information " << endl;
cout<<"entropy formula, it has a strength of " << eight_ent_strength << "." << endl;
cout << "The first character is \"" << first_char << "\" and the next seven characters are \"" << next_seven << "\". " << endl;
cout << "According to the NIST formula, it has a strength of " << eight_nist_strength << "." << endl << endl;

cin.ignore();

cout << "Now, please enter a password of 20 characters (including spaces!):" << endl;
getline(cin, twenty_password);
cout << "What character set is being used?";
cin >> character_set_20;
cout << endl;

twenty_length = twenty_password.length();

twenty_ent_strength = (twenty_length*((log(character_set_20)) / (log(2))));

first_char_twenty = twenty_password.substr(0, 1);
next_seven_twenty = twenty_password.substr(1, 7);
next_twelve = twenty_password.substr(8, 19);
remaining = twenty_password.substr(19);

first_char_twenty_length = first_char_twenty.length();
next_seven_twenty_length = next_seven_twenty.length();
next_twelve_length = next_twelve.length();
remaining_length = remaining.length();

twenty_nist_strength = (first_char_twenty_length*NIST_FIRST) + (next_seven_twenty_length*NIST_SEVEN) + (next_twelve_length*NIST_TWELVE) + (remaining_length*NIST_REM) + ((character_set_20 / NIST_CHARACTER)*NIST_BONUS);

cout << "Your password " << twenty_password << " has a length of " << twenty_length << "." << endl;
cout << "According to the information entropy formula, it has a strength of " << twenty_ent_strength << endl;
cout << "The first character is \"" << first_char_twenty << "\"." << endl;
cout<< "The next seven characters are \"" << next_seven_twenty <<"\"."<< endl;
cout << "The next twelve characters are \"" << next_twelve << "\"." << endl;
cout<< "The remaining characters are \"" << remaining << "\"." << endl;
cout << "According to the NIST formula, it has a strength of " << twenty_nist_strength <<"." << endl;
return 0;
}

A: next_twelve = twenty_password.substr(8, 19); will extract 19 chars
next_twelve = twenty_password.substr(8, 12); will extract 12 chars
First parameters is start position. Second parameter is length.
string substr (size_t pos = 0, size_t len = npos) const;


text:
Q: jquery accordion help I have a horizontal accordion on my website, and regardless of what page you on the tab furthest right does not act like the rest, you click the tab and no accordion action happens, I am not sure if this is IE all versions problem or just an IE9 problem, but if someone could spread some light on it that would be great. As I have been looking for bugs for 2 days now and cannot find anything wrong.
Accordion Link

A: Works fine in IE7 and IE9, IE8 doesn't seem to work at all though for clicking (still cycles through).  FF6 works too.  Haven't checked anythign else.  You sure its not a cache issue?  If you made any recent changes, make sure that you are getting the most up to date files.
EDIT:
IE8 only works when clicking the top portion.  38px high.

A: It worked very well in IE8.
It works quite well in Chrome 13.0.782.215 too.
You've got a great looking site!!! Very well done.


text:
Q: Pauses between jobs We run a Bosh deployment on GCE and it is generally very stable. We scale workers from 2 at off-peak to 6 during the day. 4 core / 3.6 GB RAM / 100GB SSD machines.
Performance is generally good, but on occasion there are long pauses in between jobs (2-3 minutes), particularly if a lot of jobs are in progress. The spinner in the UI stops moving for the previous completed job, but the next does not start.
I presume this is related to provisioning containers for the next job, but is there some way we can speed up that operation. Is there some resource we can increase or tune that would improve that lag.
Thanks.


text:
Q: Installing node on Windows - AWS Codebuild I'm running a codebuild build server based on mcr.microsoft.com/dotnet/framework/sdk:4.8
During the install phase, I'm installing nodejs with Chocolatey:
version: 0.2
phases:
  install:
    commands:
      - Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
      - Import-Module "C:\ProgramData\chocolatey\helpers\chocolateyProfile.psm1"
      - C:\ProgramData\chocolatey\bin\choco.exe install nodejs-lts -y
      - refreshenv
      - node -v

After installation, node still shows up as missing:
nodejs-lts has been installed.
  nodejs-lts may be able to be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The install of nodejs-lts was successful.
  Software installed as 'MSI', install location is likely default.

Chocolatey installed 1/1 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).
Refreshing environment variables from registry for cmd.exe. Please wait...Finished..
node : The term 'node' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.

However, it does work if it is all chained into a single line:
version: 0.2
phases:
  install:
    commands:
      - Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
      - Import-Module "C:\ProgramData\chocolatey\helpers\chocolateyProfile.psm1"; C:\ProgramData\chocolatey\bin\choco.exe install nodejs-lts -y; refreshenv; node -v

How can node be made available on subsequent commands?


text:
Q: How to get network manager working with a wired connection in a new installation of Ubuntu 22.04 nmcli con up Wired\ connection\ 1
Error: Connection activation failed: No suitable device found for this connection
(device eno1 not available because profile is not compatible with device (permanent MAC address doesn't match)).

$ ping google.com
PING google.com (142.251.33.14) 56(84) bytes of data.
64 bytes from dfw25s44-in-f14.1e100.net (142.251.33.14): icmp_seq=1 ttl=58 time=28.9 ms
64 bytes from dfw25s44-in-f14.1e100.net (142.251.33.14): icmp_seq=2 ttl=58 time=32.9 ms

$ ping -c4 archive.canonical.com
PING archive.canonical.com (185.125.188.12) 56(84) bytes of data.
64 bytes from canonical-archive-0.canonical.com (185.125.188.12): icmp_seq=1 ttl=47 time=121 ms
64 bytes from canonical-archive-0.canonical.com (185.125.188.12): icmp_seq=2 ttl=47 time=122 ms

$ ping6 -c4 archive.canonical.com
$ ping6: connect: Network is unreachable

I tried sudo apt-get update and sudo apt-get upgrade but it didn't solve the problem.
Ethernet controller: Intel Corporation Ethernet Connection I217-LM (rev 04)

A: nmcli con up Wired\ connection\ 1
Error: Connection activation failed: No suitable device found for this connection
(device eno1 not available because profile is not compatible with device (permanent MAC address doesn't match)).

The ethernet.mac-address property seems wrong.
Check the content of the profile with nmcli connection show "$PROFILE" or nmcli -o connection show "$PROFILE" -- where "$PROFILE" is 'Wired connection 1'.
Then adjust ethernet.mac-address to a suitable value. Possibly, just unset it and set connection.interface-name instead.
nmcli connection modify "Wired connection 1" ethernet.mac-address '' connection.interface-name eno1.
Then reactivate the profile with nmcli connection up Wired\ connection\ 1.
See man nm-settings for the meaning of the properties of the connection profile.


text:
Q: How can I resolve compilation errors in vue using tailwind {
  "name": "active-tracker",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@supabase/supabase-js": "^1.24.0",
    "@tailwindcss/postcss7-compat": "^2.0.2",
    "core-js": "^3.6.5",
    "uid": "^2.0.0",
    "vue": "^3.2.33",
    "vue-router": "^4.0.0-0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^5.0.4",
    "@vue/cli-plugin-eslint": "^5.0.4",
    "@vue/cli-plugin-router": "^5.0.4",
    "@vue/cli-service": "^5.0.4",
    "@vue/compiler-sfc": "^3.0.0",
    "autoprefixer": "^10.4.7",
    "babel-core": "^6.26.3",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.2.5",
    "babel-preset-vue": "^2.0.2",
    "eslint": "^6.8.0",
    "eslint-plugin-vue": "^7.0.0",
    "postcss": "^8.4.13",
    "sass": "^1.51.0",
    "sass-loader": "^8.0.2",
    "tailwindcss": "^3.0.24",
    "vue-cli-plugin-tailwind": "~2.0.6",
    "webpack": "^5.72.0"
  }
}


text:
Q: Restricted web page can be accessed via URL Hello guys, Please be kind enough to tell me my errors as this is my first stackoverflow post...
So, I was creating a small API to access my ESP32 development board from the Internet. I have created that successfully, but, anyone who visits my website can talk to my ESP. I want to create a login page that asks for a Uname and Pword that are stored in a MySQL database. Then, I want it to redirect to my main API page only if uname and pword are typed in correctly. I have already done something like this, but if anyone types the URL of the API page, example.com/esp-control or something the whole ESP control page can be accessed. If there would be any way to mitigate this issue, I would really like to know how. Thank you.


text:
Q: How can I find the missed utterances rate per day from Lex using CloudWatch? We want to find the missed utterance rate per day from Lex logs.
For example:

*

*Day 1 - 10 total utterances, 1 missed utterance

*Day 2 - 20 total utterances, 4 missed utterance

*...

We want to be able to plot (missed utterances/total utterances x 100) per day (essentially, %) for one week, however we also need to include Lambda exceptions as part of our "missed utterances" count.
How do we calculate the total & missed utterance count and then obtain a %?
Is this possible in CloudWatch Insight Logs?
Expectd output is a graph for 7 days that has the percentage of missed utterances+exceptions to total utterances for the day.

*

*<date 1> 1%

*<date 2> 4%

*...

One query we tried is:
 fields @message
| filter @message like /Exception/ or missedUtterance=1
| stats count(*) as exceptionCount, count(@message) as messageCount by bin(1d)
| display exceptionCount, (exceptionCount/messageCount) * 100
| sort @timestamp desc

A: This is unfortunately not possible to do within CloudWatch Log Insights as you would need to have 2 filter & 2 stats commands.
One filter would be used for getting the total count & another for getting the exception + missed utterance count.
While you can filter after one another, you can't get the counts of the result of each filter as 2 stats commands are not supported from within Log Insights (yet).
The most you can do within CloudWatch is to create a dashboard (or 2 Log Insights) with the below queries and calculate the percentage yourself:
fields @message
| stats count(*) as totalUtteranceCount by bin(1d)

fields @message
| filter @message like /Exception/ or missedUtterance = 1
| stats count(*) as exceptionAndMissedUtteranceCount by bin(1d)

In an enterprise chatbot project that I was an engineer on, I configured logs to be exported to ElasticSearch (OpenSearch in AWS Console), which then opened a whole new world of data analysis & gave me the ability to run statistics like the above.
If this is a must, I would look to implementing a similar solution until AWS improves CloudWatch Log Insights or provides this statistic within Amazon Lex itself.
In the long run, I would go with the first option however Log Insights is not meant to be a full-blown data analysis tool & you'll need to carry out much more analysis on your data (missed utterances, intents etc.) anyway in order to be able to improve your bot.

Hopefully, something like this query works in the future!
fields @message
| stats count(*) as totalUtteranceCount by bin(1d)
| filter @message like /Exception/ or missedUtterance = 1
| stats count(*) as exceptionAndMissedUtteranceCount by bin(1d)
| display (exceptionAndMissedUtteranceCount/totalUtteranceCount) * 100
| sort @timestamp desc

A: We could get it working using the below query:
fields strcontains(@message, 'Error') as ErrorMessage
|fields strcontains(@message, '"missedUtterance":true') as @missedUtterance
| stats sum(ErrorMessage)  as  ErrorMessagCount , sum(missedUtterance) as missedCount,
 count(@message) as messageCount , (((ErrorMessagCount) + (missedCount)) /messageCount * 100) by bin(1d)

Here, we are using strcontains instead of parse because if there are no missed utterance on a particular day, the calculation (ErrorMesageCount + missedCount)/messageCount * 100 was empty.
Answer is like:


text:
Q: how to set Visual Studio 2012 to use JavaScript editor for asp files How can I tell Visual Studio 2012 to recognize Classic ASP files (extension .asp) as JavaScript? I have registered .asp extension to Script Editor. That used to do the trick in 2010, but doesn't help here. It seems like VS doesn't know what language to use for Script Editor. There is no keyword highlighting, no intelicense.

A: This can be changed by adding the extension asp with the editor HTML Editor:
Tools -> Options -> Text Editor -> File Extension

*

*For Extension type: asp

*Select the HTML Editor

*Click Add (or Apply if you are updating an existing rule)

EDIT: Played around a bit and found out that you need to use HTML Editor and not Web Form Editor.
FINAL EDIT: As per comments below, should use the following Script tags around sections of JScript code to indicate to the editor to use JScript intellisense and highlighting:
<script language="JScript" runat="server">
// place your JScript code here
</script>


text:
Q: Setup JetBrains YouTrack to connect to SVN I realize that TeamCity must be a bridge between YouTrack and SVN, but I need none of the Teamcity functionality. I just want to issue Youtrack commands via commit comments like here:
http://confluence.jetbrains.net/display/YTD3/Executing+Commands+from+Comment+to+VCS+Commit
i.e. a commit message
test #ld-1 fixed

Would mark the issue ld-1 as fixed.
I'm sure I set up youtrack, teamcity and svn correctly, however what I came to realize is that I need to make a build step in TeamCity that will be executed after a commit for it to work (am I correct?). Is there a way to bypass it completely or make the build not do anything, I just can't find a way.
I'm tearing my hair out, guys, please help me out. Again, I only need teamcity to bridge svn to youtrack. What must I do?

A: You are correct assuming that TeamCity must be a bridge. In TeamCity you have to create at least one build configuration. It does not have to do anything. After that you need to check TeamCity-SVN connection works fine: just make sure TeamCity lists your commits.
After you are done, setup YouTrack-TeamCity integration. Please also be aware of requirements related to permissions of TeamCity user which integration runs on behalf of. Please find more details here: http://youtrack.jetbrains.net/issue/JT-8233#comment=27-230640.
Did I answer your question or you're struggling with some other problem?


text:
Q: Why are eigenvectors of Matrices orthogonal to the vector 1 For transposes of Markov matrices we have eigenvalue $\lambda = 1$ with eigenvector $\vec{1}$. According to my professor, all eigenvectors with eigenvalue other than 1 of the Markov matrix must be orthogonal to $\vec{1}$. Why is this the case?

A: Sum of each column in a Markov matrix $M$ is $1$.
So ${\bf1}^TM={\bf1}^T$.
If $M{\bf v}=\lambda{\bf v}$ then
$${\bf1}^T{\bf v}={\bf1}^TM{\bf v}={\bf1}^T\lambda{\bf v}\ .$$
If $\lambda\ne1$ then ${\bf1}^T{\bf v}=0$. that is, ${\bf1}\cdot{\bf v}=0$.


text:
Q: Check laravel websocket on server Im trying to implement laravel websockets and trying to access dashboard.
http://127.0.0.1:8000/laravel-websockets Address leads me to the dashboard on my local machine but when i host it and try www.mysite.com/laravel-websockets, it shows that the page doesn't exist.
Im using this package for laravel websockets and AWS EC2 Instance for hosting.
broadcasting.php
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "ably", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'null'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => false,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http'
            ],
        ],

        'ably' => [
            'driver' => 'ably',
            'key' => env('ABLY_KEY'),
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

A: By default, access to the WebSocket dashboard is only allowed while your application environment is set to local.
However, you can change this behavior by overriding the Laravel Gate being used. A good place for this is the AuthServiceProvider that ships with Laravel.
public function boot()
    {
        $this->registerPolicies();

        Gate::define('viewWebSocketsDashboard', function ($user = null) {
            return in_array($user->email, [
               //
            ]);
        });
    }

Refer to this doc https://beyondco.de/docs/laravel-websockets/debugging/dashboard#protecting-the-dashboard


text: Q: Can you hook an existing Elasticsearch index to Elastic App search I want to integrate App Search in my project. App search runs fine out of the box. But I have an application that is running on Elasticsearch, I was wondering if I could use this existing index as a backend for App search? If No, is it because documents are indexed differently for App Search engine compared to Elasticsearch? Also, why can't I access App search documents on my elasticsearch cluster (localhost:9200)?


text:
Q: how to show value in front-end user view from php classes to html div I want to show all products by category wise. But data in is not getting properly in front-end view but when i show the classes print_r($product2); it works great in view-source mode.
I want the data to display in user view mode for example:
now data is coming like below :
Array( [0] => Array (
            [3] => Array( [id] => 3
                    [name] => Mobile Phones
                    [product] => Array(
                            [26] => Array(
                                    [id] => 26
                                    [image] => uploads/9813ba5bc5.jpg
                                    [pro_name] => iPhone 7
                                    [cat_name] => Mobile Phones
                                    [br_name] => iPhone
                                    [body] =>
this is iPhone7

                                    [price] => 70000
                                )
                            [25] => Array(
                                    [id] => 25
                                    [image] => uploads/72aca3c29b.jpg
                                    [pro_name] => iPhone 6
                                    [cat_name] => Mobile Phones
                                    [br_name] => iPhone
                                    [body] =>
this is iPhone6

                                    [price] => 60000
                                )
                        )
                )
        )

    [1] => Array(
            [5] => Array([id] => 5
                    [name] => Software
                    [product] => Array(
                            [21] => Array(
                                    [id] => 21
                                    [image] => uploads/7a683e5f82.jpg
                                    [pro_name] => Lorem Ipsum is simply
                                    [cat_name] => Software
                                    [br_name] => Nokia
                                    [body] =>
this is Nokia

                                    [price] => 5000
                                )
                            [11] => Array
                                (
                                    [id] => 11
                                    [image] => uploads/05104164e5.jpg
                                    [pro_name] => Lorem Ipsum is simply
                                    [cat_name] => Software
                                    [br_name] => Lenovo
                                    [body] =>
this is  Lenovo/span>

                                    [price] => 10000
                                )
                        )
                )
        )
[2] => Array( [4] => Array([id] => 4
                    [name] => Accessories
                    [product] => Array(
                            [20] => Array(
                                    [id] => 20
                                    [image] => uploads/5a113bf1d0.jpg
                                    [pro_name] => japan
                                    [cat_name] => Accessories
                                    [br_name] => iPhone
                                    [body] => this is  Lenovo 4
                                    [price] => 40000
                                )
                        )
                )
        )

but i want like this:
 3
Mobile Phones
   26
   uploads/9813ba5bc5.jpg
   iPhone 7
   Mobile Phones
   iPhone
   this is iPhone7
   70000

   25
   uploads/72aca3c29b.jpg
   iPhone 6
   Mobile Phones
   iPhone
   this is iPhone6
   60000

5
Software
   21
   uploads/7a683e5f82.jpg
   Lorem Ipsum is simply
   Software
   Nokia
   this is Nokia
   5000

   11
   uploads/05104164e5.jpg
   Lorem Ipsum is simply
   Software
   Lenovo
   this is  Lenovo
   10000

4
Accessories
   20
   uploads/5a113bf1d0.jpg
   japan
   Accessories
   iPhone
   this is  Lenovo 4
   40000

my code in classes : Product.php
public function getAllProduct(){
    $query = "SELECT p.*, c.cat_name, b.brand_name
              FROM product as p, category as c, brand as b
              WHERE p.cat_id = c.cat_id AND p.brand_id= b.brand_id
              ORDER BY p.product_id DESC";

    $data = $this->db->select($query);
    $result = $data->fetch_all();
    $product = array();
    $product1  = array();
    foreach($result as $row) {
        $product[$row[2]] = array(
            'id' => $row[2],
            'name' => $row[8]
        );
        $product1[$row[2]][$row[0]] = array(
            'id' => $row[0],
            'image' => $row[6],
            'pro_name' => $row[1],
            'cat_name' => $row[8],
            'br_name' => $row[9],
            'body' => $row[4],
            'price' => $row[5]
        );
    }
    $product2 =array();
    foreach($product as $id=> $val ) {
        $tmp = array(
            $id => array(
                'id' => $val['id'],
                'name' => $val['name'],
                'product' => $product1[$id],
        ));
        array_push($product2, $tmp);
    }
    return $product2;
}

And my html front-end code is : I think there is something wrong ! How to create foreach loop

     <?php
        $result = $product->getAllProduct();
         if($result){
        ?>

Latest from <?php echo $result['cat_name'];?>

                <img src="admin/<?php echo $result['image']?>" />

<?php echo $result['product_name']?>

<?php echo $result['body']?>

<?php echo $result['price']?>

            <?php }?>

A: The question is not really clear, but if you just want to foreach the array resulting from the getAllProduct() function, here is it:
    $result = $product->getAllProduct();
if($result){
    foreach ($result as $product) {
        echo $product['product_name'];
    }
}


text:
Q: Laravel 5.0 -Dev Defining Global Patterns is not working Laravel Docs provide a way to add global patterns inside the before function inside RouteServiceProvider.php.
my question is : by default there is no such function, besides, after creating it, it's not working!
/**
 * Define global rules for routes.
 * more specially for regullar expressions.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function before(Router $router){
    $router->pattern('id', '[1-9]+[0-9]*');
}

A: I had the same problem and what I did was to append the before() method body into the map() method body. It worked for me. :)

A: Just in case you're still interested (I dont have enough points to comment), you can still declare it inside boot() but just before the $route variable is passed to the parent parent::boot($router); function, like here:
/**
* Define your route model bindings, pattern filters, etc.
*
* @param  \Illuminate\Routing\Router  $router
* @return void
*/
public function boot(Router $router)
{

    ///////////////////////////
    // route global patterns //
    ///////////////////////////

    $router->pattern('id', '[0-9]+');

    parent::boot($router);
}

This worked for me


text:
Q: how to open a cmd shell in windows and issue commands to that shell using python I've tried
import os
os.system('cmd.exe')

great it opens up a cmd shell
but how do I write commands from my python script so that the opened shell executes it?
basically it's like this
open up a cmd shell and somehow get a hold of the instance of the opened shell and issue commands to it. the subprocess module doesn't seem to open a cmd shell im not trying to view the contents of the shell via the interpreter but actually
but that's what subprocess does?
so how can we open up a cmd shell and pass commands to that opened shell?

A: to anyone having the same problems as me
I needed to get a handle on the command prompt window and and wanted to activate my virtualenv and run my .py file programatically.
I used pywin32com and after hours of researching stackoverflow and the web
I managed to get a working solution
I don't know much about the subprocess module but and I don't know if it let's you send different commands  to the opened command prompt
but here is my working solution
import time
import os
from win32com import client
from  win32gui import GetWindowText, GetForegroundWindow, SetForegroundWindow, EnumWindows
from win32process import GetWindowThreadProcessId

class ActivateVenv:

    def set_cmd_to_foreground(self, hwnd, extra):
        """sets first command prompt to forgeround"""

        if "cmd.exe" in GetWindowText(hwnd):
            SetForegroundWindow(hwnd)
            return

    def get_pid(self):
        """gets process id of command prompt on foreground"""

        window = GetForegroundWindow()
        return GetWindowThreadProcessId(window)[1]

    def activate_venv(self, shell, venv_location):
        """activates venv of the active command prompt"""

        shell.AppActivate(self.get_pid())
        shell.SendKeys("cd \ {ENTER}")
        shell.SendKeys(r"cd %s {ENTER}" % venv_location)
        shell.SendKeys("activate {ENTER}")

    def run_py_script(self,shell):
        """runs the py script"""

        shell.SendKeys("cd ../..{ENTER}")
        shell.SendKeys("python run.py {ENTER}")

    def open_cmd(self, shell):
        """ opens cmd """

        shell.run("cmd.exe")
        time.sleep(1)

if __name__ == "__main__":

    shell = client.Dispatch("WScript.Shell")
    run_venv = ActivateVenv()
    run_venv.open_cmd(shell)
    EnumWindows(run_venv.set_cmd_to_foreground, None)
    run_venv.activate_venv(shell, "flask3.5/venv/scripts")
    run_venv.run_py_script(shell)

A: import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode

The command variable should be for example: cmd /k. You can also add a stdin=subprocess.PIPE to the Popen argument list and write commands to cmd:
subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,stdin=subprocess.PIPE) the final code:
import subprocess
process = subprocess.Popen('cmd /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir") #passing command
stdOutput,stdError = process.communicate()
print stdOutput
process.stdin.close()

Or alternatively:
from subprocess import *
Popen("cmd /k dir")