text:
Q: Событие Тапа по элементу Windows Phone 8.1 Есть элемент, по клику на который должна происходить смена его фона, но никак не получается правильно задать для этого параметр для RoutedEvent в XAML. Мой код:
<Border Tapped="Border_Tapped"
        Height="50"
        HorizontalAlignment="Stretch"
        CornerRadius="5"
        BorderBrush="#9e9e9e"
        BorderThickness="0 0 0 3">
        <Border.Background>
            <SolidColorBrush x:Name="Background" Color="#ff567cd3"/>
        </Border.Background>
        <Border.Triggers>
            <EventTrigger RoutedEvent="Tapped">   <!-- Вот тут ошибка -->
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="Background"
                                                      Storyboard.TargetProperty="Color"
                                                      Duration="0:0:.3"
                                                      EnableDependentAnimation="True">
                            <LinearColorKeyFrame Value="#ff9e9e9e" KeyTime="0:0:0.15"/>
                            <LinearColorKeyFrame Value="#ff567cd3" KeyTime="0:0:0.3"/>
                        </ColorAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Border.Triggers>

        <TextBlock VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   FontSize="20"
                   FontWeight="SemiBold"
                   Foreground="#fff"
                   Text="Нажми меня"/>
</Border>

Текст ошибки:

Событие "Tapped" отлично от RoutedEvent

A: Казалось бы тривиальная задача и ошибка в чем-то меньшем, но попросту поддерживается только Loaded и все. Все связано из-за смены с Silverlight.
Провернуть это дело можно с помощью Behaviors SDK (XAML)
Добавляем бибилиотеку References -> Add Reference ...

Добавляем ссылки на пространство имен:
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:media="using:Microsoft.Xaml.Interactions.Media"

Ваш код немного переписываем
<Border Height="50"
        HorizontalAlignment="Stretch"
        CornerRadius="5"
        x:Name="MyBorder"
        BorderBrush="#9e9e9e"
        Background="#ff567cd3"
        BorderThickness="0 0 0 3">
    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Tapped">
            <media:ControlStoryboardAction Storyboard="{StaticResource ColorStoryboard}"/>
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>

    <TextBlock VerticalAlignment="Center"
            HorizontalAlignment="Center"
            FontSize="20"
            FontWeight="SemiBold"
            Foreground="#fff"
            Text="Нажми меня"/>
</Border>

Добавил x:Name к Border для которого будем анимировать Background. Саму анимацию расположим не внутри media:ControlStoryboardAction, это связано с тем, что Behavior находится не в дереве элементов, отсюда не имеет доступ к Border по x:Name:
<Page.Resources>
    <Storyboard x:Name="ColorStoryboard">
        <ColorAnimationUsingKeyFrames Storyboard.TargetName="MyBorder"
                                      Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                                      Duration="0:0:0.3"
                                      EnableDependentAnimation="True">
            <LinearColorKeyFrame Value="#ff9e9e9e"
                                 KeyTime="0:0:0.15"/>
            <LinearColorKeyFrame Value="#ff567cd3"
                                 KeyTime="0:0:0.3"/>
        </ColorAnimationUsingKeyFrames>
    </Storyboard>
</Page.Resources>

ОБНОВЛЕНИЕ
Если нужно изменить ещё что-то, то стоит заметить, что при объявление элементов внутри 'Storyboard' они добавляется в колелкцию TimelineCollection. Добавим  x:Name="MyTextBlock" к нашему TextBlock и обновим анимацию:
    <Storyboard x:Name="ColorStoryboard">
        <ColorAnimationUsingKeyFrames Storyboard.TargetName="MyBorder"
                                      Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                                      Duration="0:0:0.3"
                                      EnableDependentAnimation="True">
            <LinearColorKeyFrame Value="#ff9e9e9e"
                                 KeyTime="0:0:0.15"/>
            <LinearColorKeyFrame Value="#ff567cd3"
                                 KeyTime="0:0:0.3"/>
        </ColorAnimationUsingKeyFrames>

        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="MyTextBlock"
                                       Storyboard.TargetProperty="Text">
            <DiscreteObjectKeyFrame KeyTime="0"
                                    Value="Спасибо"/>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>


text:
Q: How can i select two elements with id in javascript? There's anyway to merge the elements of javascript to decrease the code size?
<form>
   <input id="input1" type="text"/>
   <input id="input2" type="text"/>
</form>

//javascrypt
document.getElementById("input1").onkeypress = function(e) {
   var chr = String.fromCharCode(e.which);
   if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};
document.getElementById("input2").onkeypress = function(e) {
   var chr = String.fromCharCode(e.which);
   if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};

A: Yes you can reduce the size by creating an event handler and use that event handler in both cases,
<form>
   <input id="input1" type="text"/>
   <input id="input2" type="text"/>
</form>

//javascrypt

const keyPressHandler = (e) => {
   var chr = String.fromCharCode(e.which);
   if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};

document.getElementById("input1").onkeypress = keyPressHandler;
document.getElementById("input2").onkeypress = keyPressHandler;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Odoo 13 CE cannot preview import I am using Odoo 13 CE with Docker when I try to import a data using csv file I got the following error:
Import preview failed due to: Unable to load "xls" file: requires Python module "xlrd".

For CSV files, you may need to select the correct separator.

I have checked the separator and everything seems ok.

I have also checked the xlrd library, it is installed in my container.

Please what am I missing here??


text:
Q: Polymorphic singleton in ActiveAdmin I have the following data structure:
class BankAccount < ApplicationRecord
  belongs_to :bankable, polymorphic: true
end

class Buyer < ApplicationRecord
  has_one  :bank_account, as: :bankable
end

class Vendor < ApplicationRecord
  has_one  :bank_account, as: :bankable
end

I defined additional routing in my routes.rb:
namespace :admin do
  resources :buyers do
    resource :bank_account
  end
  resources :vendors do
    resource :bank_account
  end
end

And my ActiveAdmin is:
ActiveAdmin.register BankAccount do
  actions :all, except: [:index, :destroy]

  controller do
    defaults singleton: true
    belongs_to :buyer, :vendor, polymorphic: true
  end
end

But when trying to create a new bank_account, via admin/buyers/1/bank_account/new,
I got the following error:
No route matches {:action=>"index", :buyer_id=>"1", :controller=>"admin/bank_accounts"}
Thanks for your help!

A: As mentioned in the comment change resource :bank_account to resources :bank_account. After modifying can you run command rails routes/rake routes in console and check if the desired route comes up.


text:
Q: How can add custom bytes to net.Conn struct or make one I have some bytes which I want to add to a net.Conn or make a new net.Conn with those bytes. I have a func that proxy 2 conn and i want to insert custom data in that proxy.
var data = []byte("Hello")

// Create My Conn With Custom Data
conn := net.Conn{
            buff: data,
        }

// some func that want net.conn
func transport(src net.Conn, dst net.Conn) {
    defer dst.Close()
    defer src.Close()
    io.Copy(dst, src)
}

A: Does this help?
func main() {
    // Create My Conn With Custom Data
    data := []byte("Hello")
    r1, w1 := io.Pipe()
    w1.Write(data)
    conn := &myConn{r1}

    // Connect to destination server
    dst, err := net.Dial("tcp", "example.com:80")
    if err != nil {
        panic(err)
    }
    defer dst.Close()

    // Proxy data from source to destination, including custom data
    transport(conn, dst)
}

myConn is a simple implementation of the net.Conn interface that wraps an io.Reader.
type myConn struct {
    r io.Reader
}

use it like so
func (c *myConn) Read(b []byte) (int, error) {
    return c.r.Read(b)
}

func (c *myConn) Write(b []byte) (int, error) {
    return 0, io.ErrClosedPipe
}

func (c *myConn) Close() error {
    return nil
}


text:
Q: Sitecore 8.1 Multivariate testing optimization shows no test status I have set up a Multivariate test in Sitecore 8.1. In Experience Editor i have a notification,it says item has a active test and Optimization tab shows red button but status shows no tests. I did check in the analytic database no test record found. I did deploy the Test from Workflow and its running. I am getting all options to stop, cancel and suspend. Sitecore is not testing my variations can any one help me to resolve this?

A: From what you are describing it sounds like the Sitecore_testing_index is erroneous. Perhaps the index is invalid, not built or not present. This index is required for Sitecore's Experience Optimisation to find the Tests in their various states.
I recommend getting a default copy of Sitecore.ContentTesting.Solr.IndexConfiguration.config from a fresh install and copy it to the path App_Config/Include/ContentTesting.
Once that is done, rebuild the Index via the Index Manager. You should then be able to find tests in the Experience Optimisation.
If you're still having trouble I recommend replacing the entire contents of App_Config/Include/ContentTesting with the files from a fresh install. And re-indexing.
I also recommend having a look against the Item which has the Multivariate test it should be within the default field Page Level Test Set. It should have values something along the lines of this

If it is populated but you are still unable to the Test, follow this guide how to create Multivariate Tests in Sitecore to identify where something is going wrong.


text:
Q: Flash drive .docx disappeared files I'm in trouble here
I have been writing important word documents and saving them on my flash drive
Some one deleated them all in another pc, I need help getting them back
I tried recovering word temporary files, couldn't find them
Please

A: Firstly, are you sure they were deleted, there are many common virus's which target USB drives that hide files. An easy way to check is to open a cmd prompt and navigate to your drive then type in dir /ah this will show all hidden files.
If the files are there but hidden, type the following into your command prompt where F: is the letter of your drive:
attrib * f: /s /d -s -h -r

this will unhide all files and folders
If there are no files showing, your other option is to use third party recovery software, there are many free ones available, just Google "recovery utility free"

A: A quick way yo know if your files are deleted or are still there in your memory is to open the "This computer" folder (Win key + E) and look if the bar which measures the amount of free space available is partially, half or fully filled. If the bar is partially filled then your files are there, but only hidden. You can follow the steps described above by @Kilisi to unhide your files.
P.S. The correct format for the attrib command is:

attrib /s /d -s -h -r *.*

And it's normal that you receive a Denied access error for the System Volume Information folder, because the folder has permissions that doesn't allow certain actions to certain users.


text:
Q: How can I generate a random percentage between a defined range in C#? I'm brand new to C# and programming in general and I'm having trouble generating a random percentage from a defined range (i.e. between .5 and 1.0)
I've had success with a generating random int variables, however, my code for random percentages is not working:
Random r = new Random();
double percentage = r.Next(.5, 1.0);
WriteLine(percentage);

I'm expecting an output between .5 and 1, but I'm getting the following errors:
Compilation error (line 9, col 23): The best overloaded method match for 'System.Random.Next(int, int)' has some invalid arguments
Compilation error (line 9, col 30): Argument 1: cannot convert from 'double' to 'int'
Compilation error (line 9, col 34): Argument 2: cannot convert from 'double' to 'int'

Line 9 is referring to the last line of code I provided where the percentage variable is written. Thanks in advance for any help!

A: r.Next() just gives you integers. But there is r.NextDouble(), but it gives you only a value between 0.0 and 1.0. So you need to put it into the desired range yourself:
double percentage = min + (max - min) * r.NextDouble();

with min = 0.5 and max = 1.0.

A: This code works 100% for me.
        double one=0.5;
        double two=1;
        double Res=0;
        Random rand = new Random();
        Res = Math.Round(one + rand.NextDouble() * (two - one), 1); \\ This 1 is for rounding to minimum digit 1==> .7  , if 2==> .75 ... and so on.
        MessageBox.Show(Res.ToString());

^_^


text:
Q: Why does require('underscore') return undefined when executed at the node.js REPL? When I run node in my console and type var _ = require('underscore');, _ ends up undefined. If I put the same code in a file and execute it, the underscore library gets included as expected.
$ node
> var _ = require('underscore');
> console.log(_)
undefined // underscore library does not load
> var async = require('async');
undefined
> console.log(async) // async library does
{ noConflict: [Function],
  nextTick: [Function],
  forEach: [Function],
...
>

But the same code in a .js file executed as node test.js shows both libraries loading as expected. What's going on?

A: The Node repl binds _ to the value of the last evaluated input; which overwrites your _ binding in var _ = ...;. Also see the node.js documentation on the repl.
This is true no matter what replaces ..., for example:
$ node
> var _ = "any value";
undefined
> _
undefined


text:
Q: Oracle json path compound expression using multiple context does not work I have the following json:
{
   "signedOffTasks":[
      "TASK2"
   ],
   "taskDeadlines":[
      {
         "taskKey":"TASK1",
         "deadline":"2016-05-02"
      },
      {
         "taskKey":"TASK2",
         "deadline":"2016-05-02"
      },
      {
         "taskKey":"TASK3",
         "deadline":"2016-05-02"
      },
      {
         "taskKey":"TASK4",
         "deadline":"2016-05-02"
      },
      {
         "taskKey":"TASK5",
         "deadline":"2016-05-02"
      },
      {
         "taskKey":"TASK6",
         "deadline":"2020-05-18"
      }
   ]
}

and the following json path expression:
$.taskDeadlines[?(@.deadline == "2020-05-18" && $.signedOffTasks.indexOf(@.taskKey) == -1)]

that is I want to return something where the deadline is 2020-05-18, and the appropriate task key is not in the signedOffTasks array.
This works very well in
https://codebeautify.org/jsonpath-tester
but unfortunately, if I use the same JSON in an Oracle 12c CLOB column, Oracle does not allow me to mix contexts. It has problems with the $ in the second predicate.
How can I express what I want with Oracle Json path implementation?
This is how I want to make the Oracle query:
SELECT
     *
 FROM
     TABLE MY_TABLE T
 WHERE
    JSON_EXISTS ( T.JSON_COLUMN,'$.taskDeadlines[?(@.deadline == "2020-05-18" && $.signedOffTasks.indexOf(@.taskKey) == -1)]')

Thanks

A: The indexOf method is unsupported (as of Oracle Database 19c). So you can't use this to check if the task exists within signedOffTasks.
I'm not sure how you'd write this using JSON path expressions in Oracle Database. But it's possible with SQL!
You can convert the arrays to rows-and-columns using json_table:
select j.* from t, json_table (
  c1, '$.taskDeadlines[*]'
  columns (
    taskKey path '$.taskKey',
    deadline path '$.deadline'
  )
) j
where  deadline = '2020-05-18';

TASKKEY    DEADLINE
TASK6      2020-05-18

select j.* from t, json_table (
  c1, '$.signedOffTasks[*]'
  columns (
    task path '$'
  )
) j;

TASK
TASK2

From there you could use not exists/minus to return the deadline tasks not in the signed off array:
select j.taskKey from t, json_table (
  c1, '$.taskDeadlines[*]'
  columns (
    taskKey path '$.taskKey',
    deadline path '$.deadline'
  )
) j
where  deadline = '2020-05-18'
minus
select j.task from t, json_table (
  c1, '$.signedOffTasks[*]'
  columns (
    task path '$'
  )
) j;

TASKKEY
TASK6

It's a little fiddly, but you can do this all in the where clause if needed:
select * from t
where  exists (
  select * from json_table (
    c1, '$.taskDeadlines[*]'
    columns (
      taskKey path '$.taskKey',
      deadline path '$.deadline'
    )
  ) j1
  where  deadline = '2020-05-18'
  and    not exists (
    select * from json_table (
      c1, '$.signedOffTasks[*]'
      columns (
        task path '$'
      )
    ) j2
    where  j1.taskKey = j2.task
  )
);

C1
{
   "signedOffTasks":[
      "TASK2"
   ],
   "taskDeadlines":[ ...


text:
Q: How to merge CSV files in Java My first CSV file looks like this with header included (header is included only at the top not after every entry):
NAME,SURNAME,AGE
Fred,Krueger,Unknown
.... n records

My second file might look like this:
NAME,MIDDLENAME,SURNAME,AGE
Jason,Noname,Scarry,16
.... n records with this header template

The merged file should look like this:
NAME,SURNAME,AGE,MIDDLENAME
Fred,Krueger,Unknown,
Jason,Scarry,16,Noname
....

Basically if headers don't match, all new header titles (columns) should be added after original header and their values according to that order.
Update
Above CSV were made smaller so I can illustrate what I want to achieve, in reality CSV files are generated one step before this (merge) and can be up to 100 columns
How can I do this?

A: I'd create a model for the 'bigger' format (a simple class with four fields and a collection for instances of this class) and implemented two parsers, one for the first, one for the second model. Create records for all rows of both csv files and implement a writer to output the csv in the correct format. IN brief:
 public void convert(File output, File...input) {

   List<Record> records = new ArrayList<Record>();
   for (File file:input) {
     if (input.isThreeColumnFormat()) {
        records.addAll(ThreeColumnFormatParser.parse(file));
     } else {
        records.addAll(FourColumnFormatParser.parse(file));
     }
   }
   CsvWriter.write(output, records);
 }

From your comment I see, that you a lot of different csv formats with some common columns.
You could define the model for any row in the various csv files like this:
public class Record {
  Object id; // some sort of unique identifier
  Map<String, String> values; // all key/values of a single row
  public Record(Object id) {this.id=id;}
  public void put(String key, String value){
    values.put(key, value);
  }
  public void get(String key) {
    values.get(key);
  }
}

For parsing any file you would first read the header and add the column headers to a global keystore (will be needed later on for outputting), then create records for all rows, like:
//...
List<Record> records = new ArrayList<Record>()

for (File file:getAllFiles()) {
  List<String> keys = getColumnsHeaders(file);
  KeyStore.addAll(keys);  // the store is a Set
  for (String line:file.getLines()) {
    String[] values = line.split(DELIMITER);
    Record record = new Record(file.getName()+i);  // as an example for id
    for (int i = 0; i < values.length; i++) {
      record.put(keys.get(i), values[i]);
    }
    records.add(record);
  }
}
// ...

Now the keystore has all used column header names and we can iterate over the collection of all records, get all values for all keys (and get null if the file for this record didn't use the key), assemble the csv lines and write everything to a new file.

A: Read in the header of the first file and create a list of the column names.  Now read the header of the second file and add any column names that don't exist already in the list to the end of the list.  Now you have your columns in the order that you want and you can write this to the new file first.
Next I would parse each file and for each row I would create a Map of column name to value.  Once the row is parsed you could then iterate over the new list of column names and pull the values from the map and write them immediately to the new file.  If the value is null don't print anything (just a comma, if required).
There might be more efficient solutions available, but I think this meets the requirements you set out.

A: Try this:
http://ondra.zizka.cz/stranky/programovani/ruzne/querying-transforming-csv-using-sql.texy
crunch input.csv output.csv "SELECT AVG(duration) AS durAvg FROM (SELECT * FROM indata ORDER BY duration LIMIT 2 OFFSET 6)"


text:
Q: Validação DataAnnotation exibindo mensagem em ingles Boa tarde,
No meu sistema fiz as validações com data annotations, localmente as mensagem são exibidas em portugues, quando publico no servidor de hospedagem a mensagem de texto é exibida em ingles, alguem sabe como faço para manter em portugues? Desde já gradeço

A: Isso acontece, respondendo de forma simples, porque a configuração do seu IIS local está em português e o seu IIS remoto está em Inglês.
Para mudar essa configuração de globalização do seu IIS você deve adicionar a seguinte linha no seu arquivo web.config.
<configuration>
    <system.web>
        <globalization culture="pt-BR" uiCulture="pt-BR"/>
    </system.web>
</configuration>


text:
Q: Reference request - spectral radius formula for linear transformations in char p I am finishing up a paper and I would like to be able to quote a theorem that does what
is said in the title. To be specific let me introduce some notations:
${\bf F}$ is a local field of charateristic $p>0$, $|\cdot|$ is the absolute value on ${\bf F}$ normalized by requiring that $|\pi|=q^{-1}$ where $\pi$ is a uniformizer for the valutation ring ${\bf A}$ of ${\bf F}$. Now let  $X$ be a ${\bf F}$-vector space of finite dimension, $\|\cdot\|$ is a norm on $X$ having the same value group as the normalized absolute value. Given an endomorphism $T:X\rightarrow X$ let $\|T\|$ be the standard operator norm with respect to the norm $\|\cdot\|$. What I would like to have a reference for is the following assertion:
Assume that $T$ has all its eigenvalue in ${\bf F}$, and denote the set of eigenvalues of $T$ by $Sp(T)$, then
$ \lim_{d\to\infty} \|T^d\|^{\frac1d}= \max_{\lambda {\in}Sp (T)} |\lambda|$
note: I am not asking for a proof, I just would like to be able to point to some precise reference instead of asking the reader to adapt result obtain in different setting to this situation.

A: I don't know of a reference off hand, but I don't see any harm in just claiming that the assertion easily follows from the Jordan decomposition of $T$.
After all, if you know that the limit on the left hand side exists you just write $T = D + N$ for some diagonalizable over $\mathbf{F}$ endomorphism $D$, and some nilpotent endomorphism $N$ where $D$ and $N$ commute, and observe that for large $n$,
$$||T^{p^n}||^{p^{-n}} = ||D^{p^n}||^{p^{-n}} = ||D|| = \max_{\lambda \in Sp(T)}|\lambda|.$$
You can also show in this way that the limit exists by being a bit more careful.


text:
Q: How to auto hide label after 10 sec and after label hide redirect to the ~/Default.aspx? I have a label and button on label in my asp.net webform ....i want when i click on button then label1 will be visible with text "Success" and then it will hide automatically after some time say 10 seconds ,,,
I M using asp.net (VB)
How to auto hide label after 10 sec and after label hide redirect to the ~/Default.aspx ?

A: Use jQuery:
var doRedirect = function() { location.href='http://www.example.com' };
$("#button1").click(function() {
    $("#label1").show();
    window.setTimeout("$('#label1').fadeOut('slow', doRedirect)", 10000);
});


text:
Q: Android Django connection through WSGI I am trying to access django project (mysite) on my android virtual device.
Content of /var/www/mysite/apache django.wsgi file is:
import os
import sys
from django.conf.urls.defaults import *
sys.path.insert(0, '/var/www')
sys.path.insert(1,'/var/www/mysite')
sys.path.insert(1,'/var/www/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()

My /etc/apache2/httpd.conf file:
MaxRequestsPerChild 1
ServerName localhost
PythonPath "['/var/www','/var/www/mysite','/var/www/mysite/books','/var/www/templates'] + sys.path"
DocumentRoot /var/www/mysite
<Location "/mysite/">
SetHandler python-program
    PythonHandler django.core.handlers.modpython
    SetEnv DJANGO_SETTINGS_MODULE mysite.settings
    PythonOption django.root /mysite
    PythonDebug On
</Location>

My /etc/apache2/sites-available/localhost file:
<Virtualhost 192.168.1.2:80>
ServerName localhost
DocumentRoot /var/www/mysite
<Directory /var/www/mysite>
  Order allow,deny
  Allow from all
  SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</Directory>
WSGIDaemonProcess mysite processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup mysite
WSGIScriptAlias / /var/www/mysite/apache/django.wsgi
</Virtualhost>

Now when I try to access url="http://192.168.1.2/mysite/login" in android avd it is giving me the following error:
 "error Cannot connect to destination (192.168.1.2)"

I am able to access the site by typing "http://localhost/mysite/login" in browser but not in android avd.
Can anyone help me here please?

A: Host computer (the one running the emulator) is available on the virtual Android device using 10.0.2.2 IP and not using the actual IP of the PC.
See the emulator networking reference.


text:
Q: Find a function whose derivative matches another function derivative multiplied by a function of derivative indexes Given $g(z)$ an holomorphic function in the whole $\mathbb{C}$. Is there a way to find $f(z)$ such as:
$$f^{(2k)}(z_0) =   g^{(2k)}( z_0 ) \frac{(2k)!}{ (k!)^2}$$
where $f^{(2k)}(z_0)$ denotes the 2kth derivative of $f(z_0)$ for a fixed $z_0$ ?
This question is particularly interesting when $k \to \infty$.
A suboptimal solution could be just finding $f(z)$ such as:
$$ |f^{(2k)}(z_0)| \ge   |g^{(2k)}(z_0)| \frac{(2k)!}{ (k!)^2}, \forall k>1$$

A: With the Stirling formula you get
$$
\binom{2k}{k}=\sqrt{\frac{2k+\theta_{2k}}{2\pi(k+\theta_k)^2}}2^{2n}\simeq\frac{4^k}{\sqrt{\pi k}}<4^k,~~ θ_j\in (0,1)
$$
so that a simple re-scaling of the argument will give an example for the inequality case with
$$
f(z)=g(z_0+2(z−z_0))=g(2z−z_0)\implies |f^{(2k)}(z_0)|=2^{2k}|g^{(2k)}(z_0)|>\binom{2k}{k}|g^{(2k)}(z_0)|.
$$


text:
Q: Getting timeout on vagrant up Today I have started learning Vagrant. Creating first, base virtual machine ( hashicorp/precise32) went pretty smooth. So I wanted to test another box, this time :puppetlabs/ubuntu-14.04-32-puppet. However im getting this msg : default: Warning: Connection timeout. Retrying... I have read that it might be because of disabled virtualization, but as I understand virtualization it's only needed for 64bit machines. So what can be problem here? Could anyone help me, please? Thanks in advance.

A: try

*

*increase 'ssh_wait_timeout'

*increase 'boot_wait'

*activate the vb.gui options in Vagrantfile

*increase the 'config.vm.boot_timeout options in Vagrantfile

*disable the shared folder with this line config.vm.synced_folder '.', '/vagrant', disabled: true in vagrantfile

*update Vagrant (latest is 1.8.1)

*update VirtualBox (latest is 5.0.12)

*cross the finger


text:
Q: render json data and partial view with single ajax request Code given below sends an ajax request to the controller.
 if (btid === '01') {
                var allData = {
                    "sessionName": $('#sessionname').val(),
                    "foundStudent": $('#studentId').val(),
                    "code":btid
                }
                var mySession = JSON.stringify(allData);
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("RenderView", "ManualFeesCollection")',
                    contentType: "application/json; charset=utf-8",
                    data: mySession,
                    success: function (data) {
                          $('#maindiv').html('')
                          $('#maindiv').html(data)
                          $.each(data.myMonths, function (index, item) {
                           //Here I want to access myMonths as Json
                        })
                    },
                })

Below in the Controller Action.
public ActionResult RenderView(int code,long foundStudent,int sessionName)
        {
            var months = //get some months
            var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        });// Want access this data in ajax success function
            return PartialView("MonthwiseFees",myMonths);

    }

But the problem is I am getting the view in the #maindiv,but not not getting

myMonths

as json, in the success function of ajax. I need to do something in view with those myMonths.Currently I am sending two ajax request(in the success of another) to accomplish.But I wish I could do it with a single ajax request.Thanks for spending time on my Issue.

*

*Update1: code of partial view
{

     @x

      @months[no]

        @Html.CheckBox(" " + @x, new { @class="check",id="check"})
        @Html.Label(" ", new { @class="lbl"})

x = x + 1;

}

             <input type="button" class="mybutton btn btn-small btn-primary" value="Show >"/>

A: You cannot send text/html and application/json for a single request. You could send either one.
If you are returning PartialView from controller, then the content type will be set to text/html. But still you can render the JSON as part of partial view.
public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });
        ViewBag.Months=myMonths;
    return PartialView("MonthwiseFees");

}

Then  in your partial view

jQuery
success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(myJSArray, function(index, item) {
        //myJSArray will be available in window scope now
    })
}

Update: Based on updated question
Controller
public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });
    return PartialView("MonthwiseFees",myMonths);

}

This will check all the check boxes as I pass true for Html.CheckBox. This needs to be determined with the model and months array
@model List<string>

@using System.Globalization;

@{

    Layout = null;
    string[] months =DateTimeFormatInfo.CurrentInfo.MonthNames;
    var countMonths=months.Count();
    int x = 1;
}

@for (int no=0;no<countMonths-1;no++)
{

         @x

          @months[no]

            //determine true/false by comparing months and Model
            @Html.CheckBox(" " + @x, model.Contains(months[x]), new { @class="check",id="check"})

    x = x + 1;
}

jQuery
success: function(data) {
    $('#maindiv').html('');
    $('#maindiv').html(data);
}

A: Lets start with your following code
var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        });

Here I am assuming your myMonths gets filled with a list of integers. I suggest adding a .ToList(); to the above code. So now it becomes :
var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        }).ToList();

Now let's check your jquery code, your ajax's success method look like this
success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(data.myMonths, function(index, item) {
        //Here I want to access myMonths as Json
    })
}

Here you write $('#maindiv').html(data), data here is a collection of integers (collection of months), .html() wont work that way.
Now since you are using this ajax call to get the JSON values only. I don't see the need to return a Partial View for that. Your return statement from your action could look like :
return Json(myMonths, JsonRequestBehavior.AllowGet);

and now when you use the following jquery, you will be able to access each month as required:
$.each(data, function(index, item) {
    // here is your month in the 'item' variable.
    $('#maindiv').html(item)
})

Update 1:
I see you are trying to load your partial view using an ajax call and then also use the data returned in that ajax call.
Why dont you load your partial view using the @Html.Partial or @Html.Action (how to). And ideally that partial view should have a call to your action which return JSON data which then you could use accordingly.
Update 2:
Your latest comment says

One page load I don't need that view.I need that view on some button clicked.

This could be helpful : https://stackoverflow.com/a/11964905/1182982

A: Thanks goes to  Murali Murugesan and yasser for help
I used the concept of Murali Murugesan by sending necessary data the in ViewBag.But since my partial view is  Not Strongly Typed ,for this reason I needed to use javascript.
I edited my controller Action like below
var months = fcDetailsService.GetStudentWiseCollectionDetail(foundStudent, sessionName, "01");
            var data = (from w in months
                        select new
                        {
                            w.Month

                        });
            ViewBag.Months = JsonConvert.SerializeObject(data);
            if (data != null)
            {
                return PartialView("MonthwiseFees", data);
            }
            else
                return Json("MonthwiseFees");

Then in my javascript, I did below
$(function () {
        var i = 0;
        var myarray = new Array();
        myarray =@Html.Raw(@ViewBag.Months)
            $('.check').each(function () {
                for (var x = 0; x < myarray.length; x++)
                {
                        var me = (JSON.stringify(myarray[x].Month))
                        if ($.trim(this.name) === $.trim(me)) {
                            $(this).prop("checked", true)
                            $(this).attr("disabled", true)
                            return true;
                    }
                }
            });
    });


text:
Q: Analyze performance issues, client, server, and database without source code? I work in a support and have now found performance problems from a customer. There is a Windows client application where the customer works in that communicate with a Windows Server and a MS SQL database. I have access to the client computer, windows server and database server but not the source code. The client works good when I test it on the Windows server (good performance or just luck).
How can I find out where the problem is? I have run MS SQL profile and found nothing and I have looked in the Windows event viewer, same there. I have looked in Windows task manager -> performance but I think it's hard to see if the data I see is good or bad.
How can I find out if the problem is on the client, server, database server, network and so on?


text:
Q: C++ Segfault on simple sorting example Take a look at this fairly straightforward sorting code:
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

struct Student
{
    string Firstname;
    string Sirname;

    Student(const string& firstname, const string& sirname)
        : Firstname(firstname), Sirname(sirname)
    {
    }
};

bool Comparer(const Student& s1, const Student& s2)
{
    return s1.Firstname.compare(s2.Firstname);
}

int main()
{
    vector<Student> students;

    for (int i = 0; i < 1000; i++)
        students.push_back(Student(string("John") + to_string(i), "Smith"));

    sort(students.begin(), students.end() - 1, Comparer);

    for (auto& student: students)
        cout << student.Firstname << endl;
}

On g++, std=c++11
g++ why.cpp -o why -std=c++11 -g

It causes a segfault. On GDB, a backtrace will show the code trying to copy memory from one location to another.
#0  __memcmp_sse4_1 () at ../sysdeps/x86_64/multiarch/memcmp-sse4.S:1011
#1  0x00007ffff7b76278 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::compare(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) const () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x0000000000401929 in Comparer (s1=..., s2=...) at why.cpp:21

I suspected that one of the strings was invalid so I added a conditional breakpoint like so:
break why.cpp:21 if s1.Firstname.empty()

And sure enough it hits it. The really weird thing is that if I change the iterator position like so:
sort(students.begin(), students.begin(), Comparer);

It works. I mean, what the heck? :)

A: The Comparer function is supposed to return true if the first item in the parameter list is placed before the second parameter when the list is sorted, false otherwise
Unfortunately, your Comparer function doesn't return true or false.  Instead it is returning the value of calling the std::string::compare function, which returns -1, 0, or 1 depending on the results of the comparison.
To fix your function, do this:
bool Comparer(const Student& s1, const Student& s2)
{
    return s1.Firstname.compare(s2.Firstname) < 0;
}

That will return true if s1.FirstName < s2.FirstName, and false otherwise.
Or simply do this:
bool Comparer(const Student& s1, const Student& s2)
{
    return s1.Firstname < s2.Firstname;
}


text:
Q: Quais são as diferenças estruturais e de sintaxe entre Sass, Less e Stylus? Hoje em dia é difícil ver pessoas escrevendo "CSS à moda antiga" por causa dos pré-processadores que facilitam a escrita removendo repetições de código, e simplificação de sintaxe.
Gostaria de entender quais as diferenças (de sintaxe e eventuais vantagens/desvantagens) que eles possuem, se eles cumprem o mesmo  papel, ou se possuem uma abordagem diferente.

A:
se eles cumprem o mesmo papel, ou se possuem uma abordagem diferente.

Essa sua frase define o tom da sua pergunta. Vou procurar basear minha resposta em ambos os pontos citados.
Eles cumprem o mesmo papel?
Basicamente, sim. O papel do pré-processador é fornecer o ferramental necessário para que seja possível contornar alguns problemas recorrentes da última especificação do CSS. Já existe um draft para a próxima, que promete facilitar bastante a nossa vida, e quando a maioria dos browser já a tiver implementado, o cenário dos pré-processadores vai, com certeza, mudar bastante. Vale lembrar que SASS, LESS, Stylus tem como propósito gerar arquivo(s) .css que respeitem a terceira especificação. Então, quando o os seletores do CSS 4 chegarem, o seu código vai continuar funcionando sem problema nenhum, mas algumas das features dos pré-processadores vão tornar-se obsoletas. Para efeitos de curiosidade, existem coisas como o Post CSS, cuja intenção é permitir que o desenvolvedor escreva código contendo os novos seletores e faça uma espécie de downgrade para o CSS 3. Não vou falar sobre isso pois não é esse o foco da resposta, mas aqui tem um artigo que trás o básico.
É interessante notar que esse cenário é mutável. Amanhã, o CSS 4 vai estar aí, e existiram pré-processadores que irão solucionar problemas que deverão ser corrigidos na especificação 5, e por aí vai. Alguns dos principais pontos que os pré-processadores facilitam hoje são

*

*Variáveis, loops, condicionais, ...
CSS não é uma linguagem de programação. CSS é uma folha de estilos, i.e., uma série de regras que devem ser seguidas para a apresentação das tags. Essa folha é uma lista, e o browser a interpreta como tal. Isso significa que, sem os pré-processadores, quando era necessário atribuir a mesma cor para diferentes seletores, você tinha que rebolar para fazer uma jogada inteligente misturando os conceitos de herança (inherit) e cascateamento, mas eventualmente teria que declarar um color: #f09363 em diversos pontos do seu código. E, eventualmente, esses valores mudam, e aí você paga todos os seus pecados fazendo essa modificação manualmente. Ou então, sprites. Na empresa que trabalho, usamos sprites para servir nossas imagens, e fazer o calculo das background-position na mão só serve pra atormentar o estagiário. Com pré-processadores, da pra resolver isso com um loop.

*Manutenção
Os exemplos acima já servem para mostrar que o CSS pode se tornar um monstro na hora da manutenção. Pré-processadores tornam esse processo muito menos doloroso.

*Frameworks
Existem frameworks construídos com base em pré-processadores que fazem coisas excelentes. O susy é um framework de grids agnóstico, construído em cima do SASS. O Compass, além de trabalhar muito bem com vendor prefixes, consegue criar sprites pra você a partir de uma imagem. Bom, não?
A lista de vantagens é grande, mas tem até gente dizendo que você não deve usá-los. Claro que isso varia de pessoa pra pessoa. O fato é que a ideia de todos os pré-processadores é a mesma: facilitar a vida do desenvolvedor. Essa lista tem 10 pré-processadores diferentes, além dos 3 que são o foco da pergunta. Se você analisar cada um deles, vai ver que a proposta é a mesma.
Possuem uma abordagem diferente?
Sim. Falando especificamente dos 3 principais:

*

*SASS
SASS é escrito em ruby, e tem duas sintaxes diferentes, conhecidas como .scss e .sass. A primeira é equivalente a do .css, e a segunda é uma linguagem indentada, como o Python. É o mais popular dos 3 e tem uma série de frameworks disponíveis. Vale apontar que as versões do Ruby SASS e do LibSASS são levemente diferentes.

*LESS
Foi originalmente escrito em ruby, mas mais tarde portado para o JavaScript. Pode funcionar server-side, como um módulo do node, é o único dos 3 compatível com Rhino (até onde eu sei) e, o mais incrível, pode ser usado do lado do cliente. Não sei porquê alguém faria algo desse tipo, sendo que onera mais ainda o lado do cliente, e não consigo ver nenhum ponto positivo nessa abordagem. Se alguém souber de alguma vantagem, diz aí.

*Stylus
Também escrito em JavaScript, o Stylus é o que possuí a sintaxe mais flexível dentre os três. Este código
p
   color black

span{
   color blue
}

div
   color: green;

compila para
p {
   color: #000;
}
span {
   color: #00f;
}
div {
  color: #008000;
}

Você pode omitir os caracteres especiais {}, ;, : e fazer uma combinação dessas omissões que o Stylus vai entender sem problemas. Eu, particularmente, acredito que isto não seja muito inteligente. Se você se torna conivente com erros de sintaxe em uma linguagem, vai acabar portando isso para outra, e basicamente nenhuma outra permite esse tipo de coisa.
Em termos de variáveis, o SASS exige que elas iniciem com o caracter $. O LESS, por sua vez, determina o caracter @. Já o Stylus é (novamente) mais flexível, e permite praticamente qualquer coisa (cuidado com palavras reservadas). A única obrigatoriedade é um espaço entre o sinal de igual e o nome da variável e entre o sinal de igual e o valor. Ou seja
minha_cor = blue

é permitido, enquanto
minha_cor=blue

não.
De resto, eles são parecidos entre sí, uma vez que tem o mesmo intuito. Claro que cada um deles tem seus métodos próprios e suas particularidades, o que podem os tornar mais ou menos viáveis para um determinado projeto. Neste link você encontra uma comparação feita quase que exclusivamente em cima de sintaxe. E neste último, uma tabelona comparando quase que tudo entre os 3. Caso você pense em migrar de um pré-processador para outro, receba mais esta tabela

A: Pré-processadores de CSS3 são linguagens com o propósito de ajudar
na criação de estilos compatíveis com todos os navegadores e com diversos
recursos para nos ajudar, principalmente quando temos CSS's enormes.
O mais importante é reconhecer a sintaxe, e para nossa sorte todos esses pré-processadores usam uma linguagem semelhante entre si.
Sass e LESS
Ambos usam sintaxe padrão CSS e isso faz com que ele se torne muito fácil.
Sass usa a extensão .scss e o LESS usa .less.
O código abaixo funciona no Sass ou LESS.
/* style.scss or style.less */
h1 {
  color: #0565CC;
}

É importante notar que Sass também tem uma sintaxe mais antiga, que omite ponto e vírgula e chaves. Embora este ainda esteja por aí, é velho e não poderá usá-lo para além deste exemplo.
A sintaxe usa a extensão de arquivo .sass e se parece com isto:
/* style.sass */
h1
  color: #0565CC

Stylus
A sintaxe para Stylus é muito mais detalhada. Usando a extensão do arquivo .style, Stylus aceita a sintaxe CSS padrão, mas também aceita algumas outras variações,
dois pontos e ponto e vírgula são todos opcionais. Por exemplo:
/* style.styl */
h1 {
  color: #0982C1;
}

/* omitor colchetes */
h1
  color: #0982C1;

/* omitir dois pontos e virgular */
h1
  color #0982C1

Usar diferentes variações do mesmo estilo também é válido, então o seguinte exemplo irá compilar sem erros:
h1 {
  color #0982c1
}
h2
  font-size: 1.2em

Cada um dos arquivos acima irá compilar para o mesmo CSS.
Você pode usar sua imaginação para ver o quão útil pode ser para seu projeto.
Com essas técnicas você não precisará escrever a mesma cor ou padrão várias vezes, utilizando variáveis você consegue diminuir e simplificar muito seu código.
Não vejo vantagem em usar uma técnica X em relação a Y, vai do gosto do programador.
Mas uma coisa sem sombra de dúvidas é o ganho em relação a organização do código, como você monta seu CSS e trabalha nele.


text:
Q: How to verify the assertion returned by navigator.id.get in node.js? Alright, so I'm trying to verify an assertion returned by browserID to sign in a user. To do so I was trying to use the browserid-verifier package. However I wasn't able to install it. There's an error in the node-bigint package as shown below:
npm http GET https://registry.npmjs.org/browserid-verifier
npm http 304 https://registry.npmjs.org/browserid-verifier
npm http GET https://registry.npmjs.org/jwcrypto/0.1.1
npm http GET https://registry.npmjs.org/express/2.5.1
npm http 304 https://registry.npmjs.org/jwcrypto/0.1.1
npm http 304 https://registry.npmjs.org/express/2.5.1
npm http GET https://registry.npmjs.org/mime
npm http GET https://registry.npmjs.org/connect
npm http GET https://registry.npmjs.org/qs
npm http GET https://registry.npmjs.org/mkdirp/0.0.7
npm http GET https://registry.npmjs.org/browserify/1.8.1
npm http GET https://registry.npmjs.org/vows/0.5.13
npm http GET https://registry.npmjs.org/optimist/0.2.6
npm http GET https://github.com/benadida/node-bigint/tarball/2ac68
npm http 304 https://registry.npmjs.org/mime
npm http 304 https://registry.npmjs.org/qs
npm http 304 https://registry.npmjs.org/mkdirp/0.0.7
npm http 304 https://registry.npmjs.org/connect
npm http 304 https://registry.npmjs.org/browserify/1.8.1
npm http 304 https://registry.npmjs.org/vows/0.5.13
npm http GET https://registry.npmjs.org/formidable
npm http 304 https://registry.npmjs.org/optimist/0.2.6
npm http 200 https://github.com/benadida/node-bigint/tarball/2ac68

> bigint@0.3.7 install /home/aaditmshah/struggleforlife/node_modules/browserid-verifier/node_modules/jwcrypto/node_modules/bigint
> node-waf configure build

npm http GET https://registry.npmjs.org/wordwrap
npm http GET https://registry.npmjs.org/eyes
Checking for program g++ or c++          : /usr/bin/g++
Checking for program cpp                 : /usr/bin/cpp
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for g++                         : ok
Checking for node path                   : not found
Checking for node prefix                 : ok /usr
'configure' finished successfully (0.022s)
Waf: Entering directory `/home/aaditmshah/struggleforlife/node_modules/browserid-verifier/node_modules/jwcrypto/node_modules/bigint/build'
[1/2] cxx: bigint.cc -> build/Release/bigint_1.o
npm http GET https://registry.npmjs.org/detective
npm http GET https://registry.npmjs.org/deputy
npm http GET https://registry.npmjs.org/resolve
npm http GET https://registry.npmjs.org/nub
npm http GET https://registry.npmjs.org/commondir
npm http GET https://registry.npmjs.org/coffee-script
npm http 304 https://registry.npmjs.org/formidable
../bigint.cc:9:17: fatal error: gmp.h: No such file or directory
compilation terminated.
Waf: Leaving directory `/home/aaditmshah/struggleforlife/node_modules/browserid-verifier/node_modules/jwcrypto/node_modules/bigint/build'
Build failed:  -> task failed (err #1):
    {task: cxx bigint.cc -> bigint_1.o}
npm ERR! error installing bigint@0.3.7
npm ERR! error installing jwcrypto@0.1.1
npm ERR! error installing browserid-verifier@0.0.4

npm ERR! bigint@0.3.7 install: `node-waf configure build`
npm ERR! `sh "-c" "node-waf configure build"` failed with 1
npm ERR!
npm ERR! Failed at the bigint@0.3.7 install script.
npm ERR! This is most likely a problem with the bigint package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-waf configure build
npm ERR! You can get their info via:
npm ERR!     npm owner ls bigint
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Linux 3.0.0-17-generic
npm ERR! command "node" "/usr/bin/npm" "install" "browserid-verifier"
npm ERR! cwd /home/aaditmshah/struggleforlife
npm ERR! node -v v0.6.14
npm ERR! npm -v 1.1.4
npm ERR! code ELIFECYCLE
npm ERR! message bigint@0.3.7 install: `node-waf configure build`
npm ERR! message `sh "-c" "node-waf configure build"` failed with 1
npm ERR! errno {}
npm http 304 https://registry.npmjs.org/resolve
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/aaditmshah/struggleforlife/npm-debug.log
npm not ok

So instead I tried writing my own code to verify the assertion. This is what I came up with:
var mongoLife = "mongodb://nodejitsu:02a0f2d1cacb5259588ddfdfad59cf49@staff.mongohq.com:10088/nodejitsudb449201704656";

var querystring = require("querystring");
var mongoose = require("mongoose");
var express = require("express");
var https = require("https");
var nowjs = require("now");

mongoose.connect(mongoLife);
var app = express.createServer();
app.use(express.static(__dirname + "/public"));
var everyone = nowjs.initialize(app);

everyone.now.login = function (assertion) {
    var client = this.now;

    var postData = querystring.stringify({
        audience: "http://life.nodejitsu.com/",
        assertion: assertion
    });

    var options = {
        host: "browserid.org",
        path: "/verify",
        method: "POST",
        port: 80,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": postData.length
        }
    };

    var request = https.request(options, function (response) {
        response.setEncoding("utf8");
        response.on("data", function (responseText) {
            var user = JSON.parse(responseText);
            client.loggedIn(user.status === "okay" ? user.email : null);
        });
    });

    request.write(postData);
    request.end();
};

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

app.listen(8080);

However when a user tries to sign in I get the following error:
[Error: 139723080664896:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:683:]
Error: 139723080664896:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:683:

    at CleartextStream._puller (tls.js:501:24)
    at CleartextStream._pull (tls.js:432:19)
    at SecurePair.cycle (tls.js:727:20)
    at EncryptedStream.write (tls.js:130:13)
    at Socket.ondata (stream.js:38:26)
    at Socket.emit (events.js:67:17)
    at TCP.onread (net.js:367:14)
{ [Error: socket hang up] code: 'ECONNRESET' }
Error: socket hang up
    at createHangUpError (http.js:1107:15)
    at CleartextStream.<anonymous> (http.js:1210:27)
    at CleartextStream.emit (events.js:88:20)
    at Array.0 (tls.js:792:22)
    at EventEmitter._tickCallback (node.js:192:40)

Any help will be appreciated. All I'm trying to do is create an HTTP POST request to https://browserid.org/, pass the assertion and the audience, and check the return status. I would like to know exactly where I'm going wrong.

A: I figured out what was wrong. In my options I had set the port to 80. Since I'm using HTTPS the port should have been 443. So I removed the port to allow it to select a default port. Also since it receives data in chunks I just collected all the chunks into a single message and parsed the entire message when it was received. Yay, I'm so proud of myself.
everyone.now.login = function (assertion) {
    var client = this.now;

    var postData = querystring.stringify({
        audience: "http://life.nodejitsu.com/",
        assertion: assertion
    });

    var options = {
        host: "browserid.org",
        path: "/verify",
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": postData.length
        }
    };

    var request = https.request(options, function (response) {
        var responseText = "";

        response.on("data", function (chunk) {
            responseText += chunk;
        });

        response.on("end", function () {
            var user = JSON.parse(responseText);
            client.loggedIn(user.status === "okay" ? user.email : null);
        });
    });

    request.write(postData);
    request.end();
};


text:
Q: any playframework dynamic combobox pulldown menu examples out there? I am looking for an example that has some good patterns for doing a combo box....select html element in playframework and helping with the post as in seam it was nice that it auto translated it to the id of the entity I wanted....can I be storing the id with the item somehow in the pulldown so that when selected, I can give the id and label to the server?
Any examples on this would be great!!!! or links to blogs that have some good pattern for this.
thanks,
Dean

A: Use the select tag.
From the hotel sample application:
#{select 'booking.beds', value:booking?.beds}
    #{option 1}One king-size bed#{/option}
    #{option 2}Two double beds#{/option}
    #{option 3}Three beds#{/option}
#{/select}

A: I found the answer.  The code is the following where id goes as the value(guess I need to brush up on my basic html....previous java frameworks keep you so far away from the basics :( ).
<select name="parent" size="1">
     #{list items:projects, as:'project'}
        <option value="${project.id}">${project.name}</option>
     #{/list}
</select>

okay, a better example may be this one so you don't have to worry about setting selected="selected" in the correct option field...
#{select 'parentId', items:projects, valueProperty:'id', labelProperty:'name', value:project?.parent?.id/}

The parentId is the variable name passed into the action post method.  The items is the variable passed out from the get into the render.  The value prop is the property on your entity.  The value is what will be set on the option's value for each item and what gets seet into your parentId variable.....this is all working for me now...sweet.
NOTE: labelProperty cannot be xxx.xxx.xxx.  It must be a first level property.   and value is what you want read from or written to (a different entity that you passed into the page than the list itself perhaps).  In my case above, I passed in projects and I passed in a project as well so items is projects and value is project.parent.id above.


text:
Q: Creating Excel file and when saving it the size doubles I'm using EPPlus to create and save an Excel file.
The method looks like this:
public static void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear, string path)
    {
        var StartValue = cList[0].StartValue;
        var radio = form["advanceOrArrears"];
        string fileName = cList[0].CalculationName;
        FileInfo info = new FileInfo(path);
        using (ExcelPackage package = new ExcelPackage(info))
        {
            ExcelWorksheet ws = package.Workbook.Worksheets.Add(fileName);
            //Styles for the sheet

            package.Save();
        }
    }

I have also tried using .SaveAs(info) but the result is the same for me.
Well, I now have the file saved under C:\ExcelFiles\ and let's say it's about 6kb, but when I open it in Excel and try to close it Excel want's me to save it. When I do, the size doubles (~12kb).
I did try open the unsaved, and the saved file, in notepad++ and I can see there is some difference in the files.
They really don't make much sense buy looking at them in notepad++, but here is how it looks:

The picture above is from the unsaved version. The saved one is looking pretty much the same (unreadable) just a lot bigger.
I now wonder if anyone could identify the problem? Have you had the same problem before?
It's not making a big trouble for me but it would be nice if the file was created "as it should" right away. Because when I try to upload and read the file, it has to be the saved version or everything crashes...

A: If you save the file in Excel, a lot of styles and Excel-specific stuff is added automatically.
You can verify that by

*

*unzipping the file before opening it in Excel into a directory (several files and folders)

*open the file in Excel and save it

*unzipping the new (larger) file into a different directory

*do a directory-compare of the two unzipped files.

You should see the additional styles that were added by Excel.
UPDATE: If the file getting larger is still an issue, you could try is to open a file created in Excel and add your content instead of creating a new document.


text:
Q: Please suggest me controls for weekly view of calendar I want a control like to get weekly view of calendar in boxes.User need to be navigated  to another week and default view is current.I don't know how to achieve this.I tried calendar weekly view.But its not fitting to requirements.I want to add this control for webpart

A: Recently I use FullCalendar, a free JavaScript based solution with a lot of references, samples in SharePoint (like this, this, this, this or this), and a great amount of flexibility and customizations.
However, if you are looking for a complete solution and would not like to bother with CSS and JavaScript, then this tool is not ideal for you.


text:
Q: Can't run two standalone instances on one server that use local Infinispan containers It seems I am unable to run two standalone servers on one server, for an application that uses local Infinispan containers. This fails because both instances will start up the same default local Infinispan cache containers, and one tries to register them within the JGroups context of the other (because even though JGroups is not included in the standalone configuration, using Infinispan seems to boot up a JGroups instance listening to a local port that disobeys the jboss.socket.binding.port-offset).
It fails with:
  2018-02-16 15:25:51,045 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "iris-server.war")]) - failure description: {
      "WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"iris-server.war#athena\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"iris-server.war#athena\": javax.persistence.PersistenceException: [PersistenceUnit: athena] Unable to build Hibernate SessionFactory
      Caused by: javax.persistence.PersistenceException: [PersistenceUnit: athena] Unable to build Hibernate SessionFactory
      Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
      Caused by: org.hibernate.cache.CacheException: HHH025009: Unable to start region factory
      Caused by: org.infinispan.manager.EmbeddedCacheManagerStartupException: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.remoting.transport.jgroups.JGroupsTransport.start() on object of type JGroupsTransport
      Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.remoting.transport.jgroups.JGroupsTransport.start() on object of type JGroupsTransport
      Caused by: org.infinispan.commons.CacheException: Channel connected, but unable to register MBeans
      Caused by: javax.management.MBeanRegistrationException: The @MBean objectName is not unique
      Caused by: javax.management.InstanceAlreadyExistsException: org.infinispan:type=protocol,cluster=\"infinispan-hibernate-cluster\",protocol=UNICAST3"},
      "WFLYCTL0412: Required services that are not installed:" => ["jboss.persistenceunit.\"iris-server.war#athena\""],
      "WFLYCTL0180: Services with missing/unavailable dependencies" => undefined
  }

And the full stack trace:
2018-02-16 15:25:41,404 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 66) MSC000001: Failed to start service jboss.persistenceunit."iris-server.war#athena": org.jboss.msc.service.StartException in service jboss.persistenceunit."iris-server.war#athena": javax.persistence.PersistenceException: [PersistenceUnit: athena] Unable to build Hibernate SessionFactory
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:179)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:121)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:193)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: athena] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:967)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:161)
    ... 7 more
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.getService(SessionFactoryServiceRegistryImpl.java:80)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:244)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
    ... 9 more
Caused by: org.hibernate.cache.CacheException: HHH025009: Unable to start region factory
    at org.hibernate.cache.infinispan.InfinispanRegionFactory.start(InfinispanRegionFactory.java:476)
    at org.hibernate.cache.spi.RegionFactory.start(RegionFactory.java:63)
    at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:71)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:59)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
    ... 15 more
Caused by: org.infinispan.manager.EmbeddedCacheManagerStartupException: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.remoting.transport.jgroups.JGroupsTransport.start() on object of type JGroupsTransport
    at org.infinispan.factories.GlobalComponentRegistry.start(GlobalComponentRegistry.java:249)
    at org.infinispan.manager.DefaultCacheManager.start(DefaultCacheManager.java:663)
    at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:310)
    at org.hibernate.cache.infinispan.InfinispanRegionFactory.createCacheManager(InfinispanRegionFactory.java:517)
    at org.hibernate.cache.infinispan.InfinispanRegionFactory.createCacheManager(InfinispanRegionFactory.java:513)
    at org.hibernate.cache.infinispan.InfinispanRegionFactory.start(InfinispanRegionFactory.java:464)
    ... 21 more
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.remoting.transport.jgroups.JGroupsTransport.start() on object of type JGroupsTransport
    at org.infinispan.commons.util.ReflectionUtil.invokeAccessibly(ReflectionUtil.java:172)
    at org.infinispan.factories.AbstractComponentRegistry$PrioritizedMethod.invoke(AbstractComponentRegistry.java:859)
    at org.infinispan.factories.AbstractComponentRegistry.invokeStartMethods(AbstractComponentRegistry.java:628)
    at org.infinispan.factories.AbstractComponentRegistry.internalStart(AbstractComponentRegistry.java:617)
    at org.infinispan.factories.AbstractComponentRegistry.start(AbstractComponentRegistry.java:542)
    at org.infinispan.factories.GlobalComponentRegistry.start(GlobalComponentRegistry.java:236)
    ... 26 more
Caused by: org.infinispan.commons.CacheException: Channel connected, but unable to register MBeans
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.startJGroupsChannelIfNeeded(JGroupsTransport.java:217)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.start(JGroupsTransport.java:191)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.infinispan.commons.util.ReflectionUtil.invokeAccessibly(ReflectionUtil.java:168)
    ... 31 more
Caused by: javax.management.MBeanRegistrationException: The @MBean objectName is not unique
    at org.jgroups.jmx.JmxConfigurator.internalRegister(JmxConfigurator.java:184)
    at org.jgroups.jmx.JmxConfigurator.register(JmxConfigurator.java:122)
    at org.jgroups.jmx.JmxConfigurator.registerChannel(JmxConfigurator.java:59)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.startJGroupsChannelIfNeeded(JGroupsTransport.java:214)
    ... 37 more
Caused by: javax.management.InstanceAlreadyExistsException: org.infinispan:type=protocol,cluster="infinispan-hibernate-cluster",protocol=UNICAST3
    at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
    at org.jboss.as.jmx.PluggableMBeanServerImpl$TcclMBeanServer.registerMBean(PluggableMBeanServerImpl.java:1527)
    at org.jboss.as.jmx.PluggableMBeanServerImpl.registerMBean(PluggableMBeanServerImpl.java:871)
    at org.jgroups.jmx.JmxConfigurator.internalRegister(JmxConfigurator.java:181)
    ... 40 more

Hopefully someone can help me with constructing a standalone.xml workaround so that both instances have an isolated JGroups instance as well.

A: What Hibernate region factory are you using?  Can you post your hibernate.cfg.xml?
Given the stack trace, I would guess that you are using org.hibernate.cache.infinispan.InfinispanRegionFactory, when you ought to be using
org.jboss.as.jpa.hibernate5.infinispan.InfinispanRegionFactory.  This implementation was designed to use the cache configurations included in WildFly's Infinispan subsystem.


text:
Q: Block specific url for specific country via .htaccess I'm looking to achieve blocking specific urls for 1 specific country via .htaccess. What I got so far is a block to the entire site, but what I'm looking is to block a specific url of the site. Here is what I got.
<Limit GET POST>
order allow,deny
deny from 2.20.179.0/24
deny from 2.20.185.0/24
deny from 2.22.230.0/24
deny from 2.136.0.0/15
deny from 2.138.0.0/15
allow from all
</Limit>

Having that, how could I block the url http://domain.com/en/profiles/kasper, for that specific IP ranges / country? What is the right way to include that url in the htaccess?
Thank you in advance

A: You can use mod_rewrite if you are in htaccess and want to block URLs for certain IPs:
RewriteEngine On

RewriteCond %{REMOTE_ADDR} ^2\.20\.(179|185)\.(\d|1\d|2[0-4])$ [OR]
RewriteCond %{REMOTE_ADDR} ^2\.22\.230\.(\d|1\d|2[0-4])$ [OR]
RewriteCond %{REMOTE_ADDR} ^2\.(136|138)\.0\.0$
RewriteRule ^en/profiles/kasper(/.*)$ - [F,NC]


text:
Q: Compare two arrays of objects and merge some fields I'm working with Angular and RxJs and I have two arrays of objects. I need to change one specific field of the first array, if the second one has the field with the same value (all of the four fields has different names). I did it with nested loops, but I need to find a better solution, my code is down below
My solution is working, but it's not the best, because arrays can be really large - so the code will work slow. If there's 1000 items in each array, it will be 1000000 iterations - that's why I need to find a better solution. I got advice to use multiple consecutive loops, but I don't really get how to use it here
this.api
  .getFirstArray()
  .pipe(
    mergeMap((firstArray) =>
      this._secondApi.getSecondArray().pipe(
        map((secondArray) => {
          for (const item2 of secondArray) {
            for (const item1 of firstArray) {
              if (item1.someField === item2.otherField)
                item1.someOtherField = item2.anotherField;
            }
          }

          return firstArray;
        }),
      ),
    ),
  )
  .subscribe((value) => {
    this.gridApi?.setRowData(value);
  });

So for example my data is
 firstArray: [
    { id: 445; name: 'test' },
    { id: 4355; name: 'test1' },
    { id: 234_234; name: 'test2' },
  ];

secondArray: [
    { firstName: 'test3'; newId: 445 },
    { firstName: 'test5'; newId: 2 },
    { firstName: 'test6'; newId: 234_234 },
  ];

And the result should be
result: [{ id: 445; name: 'test3' }, { id: 4355; name: 'test1' }, { id: 234_234; name: 'test6' }];

Note: the ids of the first array objects may be repeated - all of the objects names need to be updated

A: here is the working example of your problem, may be it will help you.

 let firstArray = [
    { id: 445, name: 'test' },
    { id: 4355, name: 'test1' },
    { id: '234_234', name: 'test2' },
  ];

let secondArray = [
    { firstName: 'test3', newId: 445 },
    { firstName: 'test5', newId: 2 },
    { firstName: 'test6', newId: '234_234' },
  ];

secondArray.forEach(sec => {
  let see = firstArray.findIndex(first => first.id === sec.newId);
  if (see > -1) {
    firstArray[see].name = sec.firstName
  }
})

console.log(firstArray)

A: You still end up with O(N²) complexity (there are two nested loops that he wants to avoid).
Instead, You can use map
const firstArray = [
  { id: 445, name: 'test' },
  { id: 4355, name: 'test1' },
  { id: '234_234', name: 'test2' },
];

const secondArray = [
  { firstName: 'test3', newId: 445 },
  { firstName: 'test5', newId: 2 },
  { firstName: 'test6', newId: '234_234' },
];

const secondMap = new Map();

secondArray.forEach((item) => {
  secondMap.set(item.newId, item.firstName);
});

for (const item of firstArray) {
  if (secondMap.has(item.id)) {
    item.name = secondMap.get(item.id);
  }
}

console.log(firstArray)


text:
Q: Selenium C# Not able to redirect after the click for login I met problems of not able to log in with selenium. I think the login button is clicked successfully. But the website that I am testing against has some login-check or rest-assured Ajax handling which I don't know. So after I click the login button on the website, I am not able to log in and redirect. I am not sure what's going on.
The website I am practising is https://www.catch.com.au/.

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System.Threading;
using System;

namespace Selenium429ErrorDemo
{
    public class Tests
    {

        string url = "https://www.catch.com.au/";
        private IWebDriver _driver;

        [Test]
        public void Test1()
        {
            _driver = new ChromeDriver();
            _driver.Navigate().GoToUrl(url);
            _driver.Manage().Window.Maximize();

            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(30));

            _driver.FindElement(By.CssSelector("[data-testid='myaccount-reference']")).Click();
            _driver.FindElement(By.Id("login_email")).SendKeys("EMAIL");
            _driver.FindElement(By.Id("login_password")).SendKeys("PASSWORD");

            IWebElement btn = _driver.FindElement(By.Id("button-login"));
            wait.Until(ExpectedConditions.ElementToBeClickable(btn));
            btn.Click();

            IWebElement ert = _driver.FindElement(By.CssSelector(".css-n11h0l"));
            wait.Until(ExpectedConditions.UrlMatches("https://www.catch.com.au/"));

        }
    }
}


text:
Q: How to setup Amplify Datastore schema for single table design For my project, I need to be able to query and change my data offline, syncing the changes whenever the connection is restored. Therefore, DynamoDB with Amplify Appsync and Datastore seems like the best option, but we are struggling with some conflicting recommendations.
Our data is structured around Items, which have Locations that should be changed and synced in real-time. As a Location could contain multiple Items and an Item could have multiple Locations, we deal with many-to-many relations. We should be able to query all Items, all Locations, all Locations for a single Item, all Items for a Location. This is the base requirement of the data structure, but we should be able to add queries for things like last modified items etc. Next to this, we have a multi-tenant setup, so there should be a way to authorize users to parts of the data. We will probably use user groups to filter the data.
Most resources online state that in order to take full advantage of DynamoDB, a single table design approach is the way to go. This would mean that we could use a structure as shown in this documentation, adding sortkeys to make additional queries.
The Datastore documentation says the @model directive should be used to be able to set up all mutations, queries and subscriptions. In order to make the relations between the Items and Locations, we should use the @manyToMany directive as stated here. All together this would result in the following schema:
type Item
    @model
    @auth(rules: [{ allow: groups, groupsField: "groups" }])
    {
        ID: ID!
        groups: String!
        locations: [Location] @manyToMany(relationName: "ItemLocation")
        ...
    }

type Location
    @model
    @auth(rules: [{ allow: groups, groupsField: "groups" }])
    {
        ID: ID!
        groups: String!
        items: [Item] @manyToMany(relationName: "ItemLocation")
        ...
    }

When we deploy this schema using the Amplify CLI, all resources are generated without problems. However, if we look at the DynamoDB tables, we find that there are multiple tables generated: Item, Location and ItemLocation. The @model directive automatically deploys a table, as does the  @manyToMany directive. Dynamodb documentation does not use these directives, so it should be possible to make a single table from the given requirements. I am not able to find how to do this from the Datastore/Amplify side, or how to connect Datastore to an existing DynamoDB as Datastore relies on the @model directive to store data locally (or that is what I suspect). This is not in line with the DynamoDB standard, and we would like to change this setup to a single table design.
I have been looking in the Amplify, Datastore and DynamoDB documentation and in online rescources, but was not able to find any guidance or solutions. Hopefully someone can push me in the right direction, thanks!

A: TL;DR  Amplify's backend tools create the DynamoDB and Appsync boilerplate for you.  This high-level convenience comes at the cost of low-level control, including control over how many tables your app has.
You are right that the terminology can be confusing.  Here are some clarifications for you:

For my project, I need to be able to query and change my data offline, syncing the changes whenever the connection is restored. Therefore, DynamoDB with Amplify Appsync and Datastore seems like the best option

Datastore is not a constraint.  The Amplify js client, including the client-side DataStore offline-synching magic works directly with AppSync.  You can build DynamoDB and AppSync resources yourself (without Amplify's backend abstractions) and still use DataStore in the client.

Most resources online state that in order to take full advantage of DynamoDB, a single table design approach is the way to go.

Often, not always.  Single-table design can have an efficiency payoff for many uses cases and is a solid default choice.  However, there are also cases in which the pattern is less helpful.

The @model directive automatically deploys a table, as does the @manyToMany directive. Dynamodb documentation does not use these directives, so it should be possible to make a single table from the given requirements

Only when you ditch Amplify backend for a DIY solution.  The @model and @manyToMany directives are Amplify backend syntax that hints to the Amplify CLI how it should build the AppSync schema and DynamoDB tables.  Single-table designs use sophisticated compound key structures, which are beyond even the great powers of the Amplify backend CLI.

how to connect Datastore to an existing DynamoDB as Datastore relies on the @model directive

It connects via AppSync.  DataStore is a client-side tool (think Apollo Client) that works with AppSync.  DataStore has no instantiation in the Cloud.  AppSync resolvers call DynamoDB to read/write data.

This is not in line with the DynamoDB standard, and we would like to change this setup to a single table design.

In sum, your choice is between Amplify backend convenience + multiple tables or DIY flexibility + single table.  DataStore works with either option.


text:
Q: I have seen some tutorials that lead you to add a device ID into the valid IDs in the drivers of another device. How does this work? Let's say I have a generic bluetooth adapter, and the default drivers don't support A2DP. So I download some drivers for another bluetooth adapter that do support A2DP.
First, when I try to install them as drivers for the generic adapter, it says that those are not valid drivers. But if I add the generic device hardware ID into an *.ini of the other device, I can install them as the drivers for the generic device, and it sometimes works!
How is this possible? Do both devices actually use the same hardware? What happens if the hardware is different, does it raise an error somewhere? Does it causes a Kernel panic? Does it make the system unstable?
Thanks!


text:
Q: What's the codeceptjs equivalent of expect? I'm making an API call and want to verify that it succeeded. Something like this:
var response = await api.ensureSettings(data);

expect(response.code).toBe(200);

How can I check equivalence in codeceptjs?

A: You can use it with chai http://chaijs.com/. After install chai just do:
var expect = require('chai').expect;

on top of your test script, than you can use
expect(response.code).to.be.equal(200);

I recommend you use postman/newman to testing your Api, but you could do it too with codeceptjs.

A: you have to use additional libraries either codeceptjs chai or codeceptjs assert library
"codeceptjs-assert": "0.0.4",
"codeceptjs-chai": "^1.0.0",
I.assertStrictEqual(response.code, 200)


text:
Q: possible to change a script when it is running? Suppose a script has 1000 lines, and the 10 line has a command takes a long time to run and when I find it is running line 10, I find I need to change line 100, is it possible to do that without stop the script first?
We can also stop a process by using command pstop, but I don't know how to let the process to re-read the script and continue to run from where it paused.

A: I don't think that is possible. Scripts are usually fully loaded (read) into the memory before execution.


text:
Q: How to convert HtmlEncode/HtmlDecode to pure text in C#? I used CKEditor ASP.NET version and adjust to my writing space.  When click btn_Post button, then should post written text in this editor field. I want to get this text in C# because for saving at database. So I searched how to use(here) and found the way using HtmlEncode. Here is codes what I found.
asp

  <CKEditor:CKEditorControl ID="CKEditor1" BasePath="/ckeditor/" runat="server">
  </CKEditor:CKEditorControl>

  <asp:button ID="btn_Post" runat="server" Text="등록하기" CssClass="btn_Post" onclick="btn_Post_Click" />

CS
string str = CKEditor1.Text;
string str1 = Server.HtmlEncode(str);
string str2 = Server.HtmlDecode(str);
//str =
1234
\r\n
//str1 = <p>1234</p>\r\n
//str2 =
1234
\r\n

But the problem is, I need to save text with none html codes. As you can see, all variable shows html code. How can I change this result to pure text 1234 ?

A: You can use this method
public static string RemoveHTMLTags(string content)
        {
            var cleaned = string.Empty;
            try
            {
                string textOnly = string.Empty;
                Regex tagRemove = new Regex(@"<[^>]*(>|$)");
                Regex compressSpaces = new Regex(@"[\s\r\n]+");
                textOnly = tagRemove.Replace(content, string.Empty);
                textOnly = compressSpaces.Replace(textOnly, " ");
                cleaned = textOnly;
            }
            catch
            {
                //A tag is probably not closed. fallback to regex string clean.

            }

            return cleaned;
        }

Or use HTML Agility Pack to remove all HTML tags.


text:
Q: TypeError when trying to retrieve data from Microsoft CRM 2011 REST endpoint via JQuery ajax I have the following javascript on the onChange event of a field:
$.ajax({
    type: "GET",
    dataType: "json",
    url: Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/rdi_departmentSet(guid'" + departmentId + "')",
    success: function (data, textStatus, xhr) {
        alert("Success");
    },
    error: function (xhr, textStatus, errorThrown) {
        alert(errorThrown.name + " - " + errorThrown.msg + " -- " + textStatus);
    }
});

The error callback is firing and I'm getting "TypeError - undefined -- error" in the alert. If I alert what I'm passing in as the url I can browse to it in IE and see the correct results. Any idea what's causing the TypeError?

A: In this case, I think you're missing the "?" after the "rdi_departmentSet".
Additionally, I always use filter syntax like so: http://msdn.microsoft.com/en-us/library/gg309461.aspx#BKMK_filter


text:
Q: How can I enhance the built-in JavaScript types in node.js? I have written the following code snippet to enhance all the objects in JavaScript and would like to make this method available to all the JavaScript libraries that I write.  How should I go about doing this in node.js?
Object.prototype.copy = function() {
    var that = this,
        obj = {};

    for (var key in that) {
        if (that.hasOwnProperty(key)) {
            obj[key] = that[key];
        }
    }

    return obj;
}

A: ...removed: I was wrong...
Just as Scott Gress and barry-johnson pointed out in cimments, It's a very bad practice to change build-in types.


text:
Q: Invertible matrix iff Gram matrix is invertible? Let $A\in\mathbb{R}^{m\times n}$. Is $A$ invertible if and only if $A^\intercal A$ is invertible?
First of all, this statement makes sense only if $m=n$ since only square matrices are invertible.
So let's assume $m=n$. In this case, if $A$ is invertible, its columns are linearly independent. So this means that the rows of $A^\intercal$ are linearly independent, meaning that $A^\intercal$ is invertible.
Thus $(A^\intercal A)^{-1}=A^{-1}(A^\intercal)^{-1}$ exists.
And vice versa, if $A^\intercal A$ is invertible, this means that $A^{-1}$ needs to exist.
Correct?
And for $m\neq n$ the statement is false, right?

A: Your proof of $A$ being invertible implying $A^\top A$ being invertible is valid. On the other hand, if $A$ is not invertible, then $\det A = 0$. It follows directly that $\det (A^\top A) = \det(A) \det(A^\top) = \det(A)^2 = 0$, showing $A^\top A$ is not invertible.

A: Note that even for $m\neq n$ it holds that
$$\operatorname{rank}(A^T A) = \operatorname{rank}(A). $$
This also implies that for $m=n$ we have that $A^T A$ is invertible iff $A$ is.


text:
Q: How to load css files in codeigniter? How can I load the css file in views/css/stylesheet.css in CI? My index file is in views/firstView.php
I am completely new to code igniter. Thought editing the config.php like this would work:
$config['index_page'] = 'localhost/Projects/first_CI/application/views/firstView.php';
but its not working :( . Can anyone suggest anything?

A: put a css folder in your root directory and inside the folder put your css files.
now in firstView.php filr include the css like
<link rel="stylesheet" type="text/css" href="<?=base_url()?>css/style.css" title="" charset="utf-8">  //if your css file is style.css otherwise change style.css with yours

please let me know if you face any problem.

A: I suggest you to watch some youtube videos on codeigniter
   .Css files are not added like that
   You have to set asset_url() function ,create folder assets in application directory and put css in that folder and include it ,
thats the recdomended method

A: If your style.css is placed under the static directory which is located in your website root directory, you can refer it by:
<link rel="stylesheet" type="text/css" href="/static/signup.css">

A: Try like this..
<link rel="stylesheet" type="text/css" href="<?php echo base_url()."css/style.css";?>">

Create css folder at the root and put css file in that folder.


text:
Q: Pull div content to external display in electron In my project, I need to achieve a very special function: pull div content to external display, div content include text, image, video, other html ..., enter image description here

A: You could use the screen module to detect the display and create another window and move it into there.


text:
Q: Subtract rows and create a new row name I would like to subtract Bay County from Florida in this data frame and create a new row with the name "Florida (-Bay County)".
Maybe group_modify and add_row (dplyr) would be a possibility?
year <- c(2005,2006,2007,2005,2006,2007,2005,2006,2007,2005,2006,2007)
county <- c("Alachua County","Alachua County","Alachua County","Baker County","Baker County","Baker County","Bay County","Bay County","Bay County","Florida","Florida","Florida")
pop <- c(3,6,8,9,8,4,5,8,10,17,22,22)
gdp <- c(3,6,8,9,8,4,5,8,10,17,22,22)
area <- c(3,6,8,9,8,4,5,8,10,17,22,22)
density<-c(3,6,8,9,8,4,5,8,10,17,22,22)
df <- data.frame(year, county,pop,gdp,area,density, stringsAsFactors = FALSE)

year
county
pop
gdp
area
density

2005
Alachua County
3
3
3
3

2005
Baker County
9
9
9
9

2005
Bay County
5
5
5
5

2005
Florida
17
17
17
17

2005
Florida (-Bay County)
12
12
12
12

2006
Alachua County
6
6
6
6

2006
Baker County
8
8
8
8

2006
Bay County
8
8
8
8

2006
Florida
22
22
22
22

2006
Florida (-Bay County)
14
14
14
14

2007
Alachua County
8
8
8
8

2007
Baker County
4
4
4
4

2007
Bay County
10
10
10
10

2007
Florida
22
22
22
22

2007
Florida (-Bay County)
12
12
12
12

A: You could do:
df %>%
  filter(county != 'Florida' & county != 'Bay County') %>%
  group_by(year) %>%
  bind_rows(summarise(., county = 'Florida (-Bay County)',
                      across(where(is.numeric), sum))) %>%
  arrange(year)
#> # A tibble: 9 x 6
#> # Groups:   year [3]
#>    year county                  pop   gdp  area density
#>   <dbl> <chr>                 <dbl> <dbl> <dbl>   <dbl>
#> 1  2005 Alachua County            3     3     3       3
#> 2  2005 Baker County              9     9     9       9
#> 3  2005 Florida (-Bay County)    12    12    12      12
#> 4  2006 Alachua County            6     6     6       6
#> 5  2006 Baker County              8     8     8       8
#> 6  2006 Florida (-Bay County)    14    14    14      14
#> 7  2007 Alachua County            8     8     8       8
#> 8  2007 Baker County              4     4     4       4
#> 9  2007 Florida (-Bay County)    12    12    12      12

A: If you wanted to try something with group_modify and add_row, you could consider something like this. Here, when using add_row, use map to sum up the data within the group, but not including "Florida" or "Bay County".
library(tidyverse)

df %>%
  group_by(year) %>%
  group_modify(
    ~ .x %>%
      add_row(
        county = "Florida (-Bay County)",
        !!! map(.x %>%
                  filter(!county %in% c("Florida", "Bay County")) %>%
                  select(-county),
                sum)
        )
  )

Output
    year county                  pop   gdp  area density
   <dbl> <chr>                 <dbl> <dbl> <dbl>   <dbl>
 1  2005 Alachua County            3     3     3       3
 2  2005 Baker County              9     9     9       9
 3  2005 Bay County                5     5     5       5
 4  2005 Florida                  17    17    17      17
 5  2005 Florida (-Bay County)    12    12    12      12
 6  2006 Alachua County            6     6     6       6
 7  2006 Baker County              8     8     8       8
 8  2006 Bay County                8     8     8       8
 9  2006 Florida                  22    22    22      22
10  2006 Florida (-Bay County)    14    14    14      14
11  2007 Alachua County            8     8     8       8
12  2007 Baker County              4     4     4       4
13  2007 Bay County               10    10    10      10
14  2007 Florida                  22    22    22      22
15  2007 Florida (-Bay County)    12    12    12      12


text:
Q: block expression from Sieve of Eratosthenes, twin prime, number of primes in Java I need help, do not know how I can correct the error and allow the program to run.
Program is all primes spend 3-12345. Number of primes and twin primes.
All results must be block expression.
I would be thankful for any help!
public class SieveOfEratosthenes {

    //final N and byte f[] there is provision must not be changed!

    static final int N = 12345;
    static byte f[] = new byte[(N + 1) / 2];

    public static void main(String[] args) {
    System.out.println(sieve());
    System.out.println(twinPrime());
    System.out.println(countPrime());
    }

    private static int sieve() {
    int prime;
    for (int i = 3; i < N; i++)
        return f[i] = false; //cancel all Primzahle
    /*
     * sieves with all primes i, where i is the smallest
     * prime factor of a composite number j = k*i.
     * The smallest prime factor of a complex number j
     * can not be greater than the root of j <= n
     */
    for (int i = 2; i < Math.sqrt(N); i++) {
        do {
        //now i is prime
        return i;

        } while (f[i] = true);
        //and underline its multiples, starting with i * i
        for (int j = i * i; j < N; j++) {
        return f[j] = true;
        }
    }

    //Give the prime numbers greater than n from sqrt.
    //Thus, those have not yet been deleted

    for (int i = Math.sqrt(N) + 1; i <= N; i++) {
        do {
        return i;

        } while (f[i] = true);
    }
    //now i is prime
    return i = prime;
    }

    //Twin prime
    private static int twinPrime() {
    for (int n = 1; n <= N; n++) {
        if (((6 * n - 1) % 2 != 0) && ((6 * n + 1) % 2 != 0)) {
            //mark all twin prime with "*"
        return Integer.parseInt((n + "*"));
        }
    }
    }

    //Number of primes
    private static int countPrime() {
    return Integer.bitCount(twinPrime());
    }

}