text:
Q: Determine sign of sum of square roots Problem
Given positive square-free integers $r_i$ and non-zero integers $a_i$, is there an algorithm for determining the sign of $\sum_{i=1}^n a_i\sqrt{r_i}$ without calculating approximations for the square roots?
If $n=2$ it is easy and I hope it shows more clearly what I am asking:
Solution for $n=2$
If $a_1$ and $a_2$ have the same sign it is trivial.
Assume $a_1>0$, $a_2<0$ then the following statements are equivalent:
$a_i\sqrt{r_1} + a_2\sqrt{r_2} > 0$
$a_i\sqrt{r_1} > (-a_2)\sqrt{r_2}$
$(a_i\sqrt{r_1})^2 > ((-a_2)\sqrt{r_2})^2$ (because both rhs and lhs are positive)
$a_1^2 r_1 > a_2^2 r_2$
This last statement can be evaluated exactly using only integer operations.
However if I have three or more roots on either side, the squaring step does increase the number of square roots.
Edit
The keyword field extiensions by @dtldarek led me to the related question How do extension fields implement $>, <$ comparisons?. Also the comment A field that is an ordered field in two distinct ways seems to indicate that the order is defined by embedding the field in $\mathbb{R}$ and using the order of $\mathbb{R}$. I am trying to define the same order using only operations inside the field, because the reals are more difficult (impossible?) to represent exactly in a computer program.

A: I ended up solving the problem by constructing a field extension containing the number. For constructing the field extension you have to be careful not adding redundant roots. Then by the method above you can reduce the degree of the extension and repeat until the number whose sign is to be tested is rational.
Example: finding the sign of
$a= \sqrt{6}-\sqrt{2}-\sqrt{3}+1$

*

*Construct a field extension containing $a$.
   the obvious cnadidate is $\mathbb Q[\sqrt{2}, \sqrt{3}, \sqrt{6}]$ but of course
   $\sqrt{6} = \sqrt{3}\sqrt{2} \in \mathbb Q[\sqrt{2},\sqrt{3}]$. In order to avoid
   infinite loops in the algorithm it is important to have a good representation of the extension field without redundant roots. Note: it is not important which two of the three roots are chosen.

*Treat the extension as a sequence of quadratic extensions. $\mathbb Q[\sqrt{2},\sqrt{3}] = \mathbb Q[\sqrt{2}][\sqrt{3}]$. This simplifies the algorithm since it only needs to deal with quadratic extension. A number in a quadratic extension $F[\sqrt{r}]$ can be uniquely written as $u + v\sqrt{r}$ with $u$  and $v\in F$.

*Write the number in the form $u + v\sqrt{r}$. $$a = \underbrace{1-\sqrt{2}}_{\in \mathbb Q[\sqrt{2}]}+(\underbrace{\sqrt{2}-1}_{\in \mathbb Q[\sqrt{2}]})\sqrt{3}$$

*By the reasoning which is already in the question for $n=2$ we can find a number $b\in \mathbb Q[\sqrt{2}]$ which has the same sign as $a$. We find $$b=3(\sqrt{2}-1)^2-(\sqrt{2}-1)^2.$$ This reduces the problem from the field $\mathbb Q[\sqrt{2}][\sqrt{3}] $ to the field $\mathbb Q[\sqrt{2}] $.

*Analogous to step 3. Write the number $b$ in the form $u + v\sqrt{r}$. $$b = \underbrace{6}_{\in \mathbb Q}+(\underbrace{-4}_{\in \mathbb Q})\sqrt{2}.$$

*Analogous to step 4. Find $c\in\mathbb Q$ having the same sign as $b$. We find $$c=6^2-4^2\cdot2=4>0.$$
Since $a$, $b$, and $c$ all have the same sign, we conclude that $a$ is positive.


text:
Q: Extract xml using XPath in Camel I have XML similar in structure to the below example stored in a Camel header as a String:
<list>
   <library>
      <name>xxx</name>
      <address>
         <line1>aaa</line1>
         <line2>bbb</line2>
         <line3>ccc</line3>
      </address>
   </library>
   <book>
      <author>
         <name>John</name>
         <number>4324234</number>
      </author>
      <title>New Book</title>
      <isbn>dsdaassda</isbn>
   </book>
   <book>...</book>
   <book>...</book>
</list>

I would like to extract the library element into another Camel header
   <library>
      <name>xxx</name>
      <address>
         <line1>aaa</line1>
         <line2>bbb</line2>
         <line3>ccc</line3>
      </address>
   </library>

How can I achieve this using Camel Java DSL?
(My main source of confusion is applying the XPath to an exchange header item rather than the body)

A: This should work:
.xpath("[your XPath expression]", "[the name of the header to select from]")

Your use case could be done like this
from("direct:input")
    .setHeader("newHeader").xpath("[your XPath]", "[xmlHeader]")
    .to("...");

You can find this also in the Camel docs, Section Using XPath on Headers.
And it is for example used in this Camel unit test, in the route at the bottom of the file.

A: Try this.
@Override
public void configure() throws Exception {
    XPathExpression xPathExpression = new XPathExpression();
    xPathExpression.setHeaderName("completexml"); //assuming the header name of the xml as completexml
    xPathExpression.setExpression("/list/library");

    from("direct:abc")
         .setHeader("OriginalBody", simple("${body}")) //get original body
         .split(xPathExpression) //split according to xPathExpression
         .setHeader("library", simple("${body}")) //set new header with only library element
         .setBody(simple("${header.OriginalBody}")) //set the original body back
         //.log("${header.completexml}")
         //.log("${header.library}")
         //.log("${body}")
        ;
}

As per the answer here, we could give a second argument to xpath which is of type String. But With the latest version, I don't see any such method in xpath which takes a second argument as String. May be it is removed in newer versions.
What I am doing is storing the original body in a header(since after split, original body is replaced by the result of split), then replacing it.

A: Here's a working example of JUnit test:
@Override
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                    .routeId("xpathTest")
            .log(LoggingLevel.INFO, "XML input : \n${body}")
            .setHeader("XNODE").xpath("/list/library", NodeList.class)
            .setBody().xpath("/list/library", NodeList.class)
            .to("log:end?level=INFO&showAll=true&multiline=true");
        }
    };
}

Оutput log:
2018-03-22 00:50:00,141 [main           ] INFO  end                            - Exchange[
, Id: ID-BlackMirror-10897-1521668997689-0-2
, ExchangePattern: InOnly
, Properties: {CamelCreatedTimestamp=Thu Mar 22 00:49:59 MSK 2018, CamelMessageHistory=[DefaultMessageHistory[routeId=xpathTest, node=log1], DefaultMessageHistory[routeId=xpathTest, node=setHeader1], DefaultMessageHistory[routeId=xpathTest, node=setBody1], DefaultMessageHistory[routeId=xpathTest, node=to1]], CamelToEndpoint=log://end?level=INFO&multiline=true&showAll=true}
, Headers: {breadcrumbId=ID-BlackMirror-10897-1521668997689-0-1, XNODE=org.apache.xml.dtm.ref.DTMNodeList@5acf93bb}
, BodyType: org.apache.xml.dtm.ref.DTMNodeList
, Body: <library>       <name>xxx</name>       <address>          <line1>aaa</line1>          <line2>bbb</line2>          <line3>ccc</line3>       </address>    </library>
, Out: null:

So for the header you need an expression:
.setHeader("XNODE").xpath("/list/library", NodeList.class)

and for the body:
.setBody().xpath("/list/library", NodeList.class)

A: You can do it:
.setHeader("yourHeaderName", xpath("//*[local-name()='library']").stringResult())

So you will have the library structure for work

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible for a system to be chaotic but not ergodic? If so, how? In a recent lecture on ergodicity and many-body localization, the presenter, Dmitry Abanin, mentioned that it is possible for a classical dynamical system to be chaotic but still fail to obey the ergodic hypothesis, which is frankly a pretty remarkable combination of properties. Unfortunately, the lecture had a lot of ground to cover and Abanin did not elaborate.
So:

*

*Are any explicit examples known that have been shown to be both chaotic and non-ergodic?

*Is there some clear explanation for what properties of those systems allow them to show this behaviour?

A: A trivial example of a non-ergodic, chaotic system is a 2D conservative system that is not fully chaotic, i.e., with a mix of regular and chaotic regions in its phase space: each individual chaotic region is ergodic in itself, but since trajectories cannot cross the regular, invariant barriers between those regions, the systems as a whole is not ergodic.
An example of such a system is Chirikov's Standard Map:


text:
Q: Attempt to pass Variable to textView - PointerException Why it keeps throwing this pointer exception - I assume the custom layout has no problem. Would anyone tell me what is the wrong with my textview that I defined inside onCreate method. Yes am reading withing the Recall Button from text file and calling method for analysis the data, but am struggling in displaying the results in textview at same time. what is the wrong for that? am I blocking the UI? thank you in advance,and i know.. so don't tell me Nullpointer is repelciate question. Best
 TextView Peaks_num;
  @overide
  onCreate(){
   .....
   .....
 //Read data.
    Recall = (Button) findViewById(R.id.Recall);
    Recall.setOnClickListener(new View.OnClickListener() {
        StringBuilder stringBuilder = new StringBuilder();

         String line = null;

        @Override
        public void onClick(View v) {
             List<Integer> List_Of_Peaks = findPeaks(String_TO_List);
            Dialog mdialog = new Dialog(MainActivity.this);
            mdialog.setTitle("MyDialog");
            mdialog.setContentView(R.layout.customdialog);
            mdialog.show();
             Peaks_num = (TextView) findViewById(R.id.Peak_Num);

             Peaks_num.setText(String.valueOf(List_Of_Peaks));

          }
        });

   //my custom layout that should to be for the textview inside the dialog.
      <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

<TextView
    android:id="@+id/Peak_Num"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="1.7dp"
    android:background="@drawable/back"
    android:text="Peaks"
    android:textColor="#040307" />

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="@string/textView_Peaks_index"
        android:id="@+id/text_Index"
        android:layout_weight="1" />

  </LinearLayout>


text:
Q: pass data from parent to popup Apologies if this seems like a duplicate post...
Thomas Warner kindly answeres an earlier post suggesting I use:
Popup.aspx?Data1=Piece_of_data&Data2=Piece_of_data
Just want to ask, if my code is Popup.aspx?Data1=textbox1.text&Data2=textbox2.text
whats the proper way to reference whats in the textboxes?
The way is is above, all that appears in the popup is the actual text 'textbox1.text'
rather than what is actualy in that control.
thanks again

A: Using asp.net you can litterally write the value straight into the string like:
Popup.aspx?Data1=<%=textbox1.Text%>&Data2=<%=textbox1.Text%>

A more ideal way of doing this would be to build up the URL string in your codebehind so as not to clutter up your HTML and C# code.
That way you could do something like:
String popupUrl = String.Format("Popup.aspx?Data1={0}&Data2={1}",
textbox1.Text,textbox2.Text);

This will also allow you to do any sanitization checks on the values from the textboxes before you start passing those values around.


text:
Q: Pandas: pivot_table Suppose I have a datafreme like this one:
data = [
    {'column1': 'asd', 'column2': 'a', 'column3': 'mileage', 'column4': 7889, 'column5': None},
    {'column1': 'fsd', 'column2': 'a', 'column3': 'temp', 'column4': 4557, 'column5': None},
    {'column1': None, 'column2': 'a', 'column3': 'string', 'column4': None, 'column5': 'value_string1'},
    {'column1': 'asd', 'column2': 'b', 'column3': 'mileage', 'column4': 5678, 'column5': None},
    {'column1': 'fsd', 'column2': 'b', 'column3': 'temp', 'column4': 5830, 'column5': None},
    {'column1': None, 'column2': 'b', 'column3': 'string', 'column4': None, 'column5': 'value_string2'},
    {'column1': None, 'column2': 'c', 'column3': 'temp', 'column4': 10, 'column5': None},
    {'column1': None, 'column2': 'c', 'column3': 'temp', 'column4': 8, 'column5': None},

]

df = pd.DataFrame(data)

    column1 column2 column3 column4 column5
0   asd       a      mileage 7889.0  None
1   fsd       a        temp  4557.0  None
2   None      a       string  NaN  value_string1
3   asd       b       mileage 5678.0 None
4   fsd       b        temp   5830.0 None
5   None      b       string  NaN  value_string2
6   None      c        temp   10.0   None
7   None      c        temp   8.0    None

I want to transform this dataframe  in something like:

column2 mileage temp_1  temp_2
a       7889.0  4557.0  NaN
b       5678.0  5830.0  NaN
c        NaN    10.0    NaN
c        NaN     Nan    8.0

i tried to use pandas function "pivot_table"
pivot_table = df.pivot_table(index='column2', columns='column3', values='column4')

but the result is
column3 mileage temp
column2
a       7889.0  4557.0
b       5678.0  5830.0
c         NaN    9.0

so this function combines the equal values on column 2 but if they also have the same value on column 3 the value in column 4 will be the average of the values in the original table.
Is there any way to modify this function to get the result I want? or is there another way to do it?

A: It's not exactly what you want but take a look to:
>>> (df.loc[df['column4'].notna(), ['column2', 'column3', 'column4']]
       .assign(index=lambda x: x.groupby('column3').cumcount())
       .pivot_table(index=['index', 'column2'], columns='column3', values='column4')
       .reset_index('column2').rename_axis(index=None, columns=None))

  column2  mileage    temp
0       a   7889.0  4557.0
1       b   5678.0  5830.0
2       c      NaN    10.0
3       c      NaN     8.0

A: A similar solution to @Corralien, a bit different wording:
# create a counter for duplicate values of column2 and column3
df['cumcount'] = df.groupby(['column2', 'column3']).cumcount()
# adding pivot table
df.pivot_table(index=['column2','cumcount'],
               columns='column3',
               values='column4',
               aggfunc={'column4':['first']})

                   first
column3          mileage    temp
column2 cumcount
a       0         7889.0  4557.0
b       0         5678.0  5830.0
c       0            NaN    10.0
        1            NaN     8.0

First two columns are a composite index.


text:
Q: proj.4 — problems to understanding the projection result I am using pro4js for a webproject to project data obtained from the Openstreetmap database. Basically I have this code (javascript/ES 6):
const
  //some coordinates
  we = {
    lon: 50.9802813,
    lat: 11.3290855
  },

  //the projectors
  { forward,
    reverse } = proj4('EPSG:3857')
;

let
  [  lon1,
     lat1  ] = forward([we.lon, we.lat]),

  [  lon2,
     lat2  ] = forward([we.lon + 1, we.lat + 1])
;

lon2 - lon1 = 111319.49079327378
lat2 - lat1 = 113736.3960447507

Why are those values this huge? What unit is that? Since these are projected coordinates they should represent coordinates on a flat 2d plane, don't they?


text:
Q: Apache POI excel showing cells bold on 10 percent ISSUE: 1
I see a very strange behavior of Apache POI, I wrote an excel file using POI 3.9. While writing the cell I added a font style of Arial 8 and normal and the cells are merged.
While viewing the report all the cell styles are fine but I see that the text are bold. When I checked the cell property it looks fine. If in the ms excel I unmerge and again merge the cells the bold goes away but when written from POI it shows as bold.
One thing I found today is it looks bold only when in 100% zoom, even if I make it 99% the bold goes away.
Could anyone please explain this behavior and let me know what I have to do to fix this.
ISSUE 2:
I am adding the copyright symbol to the footer, but for some reason I see a question mark in the footer. Any idea what should I add to get the copyright symbol?


text:
Q: ParameterPValues I am currently translating a Mathematica notebook for model fitting into Python, and I need to understand one property of NonLinearModelFit.
Could anyone link to a resource, or better yet explain, what ParameterPValues refers to and how they are calculated?
The only explanation I can find is that it comes from the Z-test, but not how it is actually calculated. I am sorry, but I am not very experienced in statistics, hence the problems.
Thank you


text:
Q: Find out if last caracter is a letter or a number I have an Excel sheet.
Column A, I have different values :
A6  : 1520 A7  : 9500 A8  : 9500a A9  : 12450 A10 : 13425 A11 : 13425a
A12 : 13425b

(those numbers are files numbers I've generated with the help of another vba macro using advanced filters from a database but that's not the point here.)
What I'd like to do is count the number of different file numbers listed.
For me 13425, 13425a and 13425b are from 1 file only.
So in this previous example, I'd like to get the following number of different files: 4 (1250, 9500, 12450 and 13425)
So I've tried different things :
    Dim L As Integer ' numéro de la dernière ligne
    Dim I As Integer ' compteur pour itération
    Dim K As String  ' dernier caractère de la case en partant de la droite
    Dim N As Integer ' compteur N

    L = Sheets("Stats").Range("a165536").End(xlUp).Row 'Dernière ligne utilisée

    Range("O1") = L

    N = 0 'initilisation du compteur

    For I = 6 To L
         K = Right(Range("A" & I), 1)
      If IsError(K * 1) = False Then
         N = N + 1
         Else
         N = N
      End If
    Next I
Range("O2") = N

But IsError(K*1) doesn't work, I have an error.
In MS Excel we can use the following function: =CODE(RIGHT(A6,1)).
If the value is >=48 AND <=57 I know the last caracter is a NUMBER and NOT a letter. But I think this function doesn't exist in VBA ?
SO that's the 2 things I've tried to solve my problem but I didn't manage to find out a solution yet.

A: Perhaps this is an XY problem.
If your goal is

*

*to count the number of unique files, and

*the files are defined by the numeric beginning of the full file name,

*Then you can make use of the Val function, which will ignore any trailing non-numeric characters.

For example (using a Dictionary to generate the count):
Set D = CreateObject("Scripting.Dictionary")

For Each myCell In myRange
    Key = Val(C)
    If Not D.Exists(Key) Then D.Add Key, C.Value
Next C
uniqueFiles = D.Count

A: To answer your question and question only:

*

*To find out whether a character (or a set of characters) is a number, we can use the IsNumeric() function.

*And to get the last character out of a string we can use the Right() function.

I've linked to both function's documentation, so do absolutely take a gander!
Your custom function could look something like this:
Public Function is_last_num(ByVal strng as String) As Boolean
    is_last_num = IsNumeric(Right(strng, 1))
End Function

If you're trying to count unique files based on the number then just use what @RonRosenfeld suggested


text:
Q: how to make a column Unique based on comparing grouping id I need to make sure that all View data for a specific Site element is unique, but I want to be able to reuse the value for other Site's with different id's.
Example:
Site One

*

*View one ref: ViewOne

*View two ref: ViewOne <-- error

Site Two

*

*View one ref: ViewOne <-- no error since it's a different site

*View two ref: ViewTwo

View model:
public class View : AssetsBase, IView
{
    public int SiteId { get; set; }
    public string Name { get; set; }
    public string Ref { get; set; }
    public virtual IEnumerable<MetaEntry> MetaEntries { get; set; } = new HashSet<MetaEntry>();
    public virtual IEnumerable<HreflangEntry> HreflangEntries { get; set; } = new HashSet<HreflangEntry>();
}

DB Context:
builder.Entity<View>().ToTable("SiteView").HasIndex(sw => sw.Ref).IsUnique();

the current approach works as expected, but I'm limited to only use a Ref value once. is what I want possible?

A: Thanks to user700390 who provided the solution.
DB Context:
builder.Entity<View>().ToTable("SiteView").HasIndex(sw => new { sw.Ref, sw.SiteId }).IsUnique();


text:
Q: ArcPy not seeing ArcSDE datasets from IDLE or PyScripter? I tested the code below from ArcCatalog 10.5's python console and IDLE+PyScripter. While in ArcCatalog everything works correctly(code is supposed to list available datasets and feature layers), in other python enviroments(IDLE and PyScripter) Datasets and Feature Classes are not shown, only views are listed. No error message is produced, as if my Datasets don't exist.
# Import arcpy module
import arcpy
from arcpy import env

# Local variables:
databaseConnection = r"C:\Users\UserName\AppData\Roaming\ESRI\Desktop10.5\ArcCatalog\SDENAME.sde"
arcpy.env.workspace = databaseConnection

datasets = arcpy.ListDatasets()
for dataset in datasets:
    print(dataset)


text:
Q: How do I remove emoji from string My problem is to remove emoji from a string, but not CJK (Chinese, Japanese, Korean) characters from a string using regex. I tried to use this regex:
REGEX = /[^\u1F600-\u1F6FF\s]/i

This regex works fine except it also detects the Chinese, Japanese and Korean character where I need those characters. Any idea how to solve this issue?

A: Karol S already provided a solution, but the reason might not be clear:
"\u1F600" is actually "\u1F60" followed by "0":
"\u1F60"    # => "ὠ"
"\u1F600"   # => "ὠ0"

You have to use curly braces for code points above FFFF:
"\u{1F600}" #=> ""

Therefore the character class [\u1F600-\u1F6FF] is interpreted as [\u1F60 0-\u1F6F F], i.e. it
matches "\u1F60", the range "0".."\u1F6F" and "F".
Using curly braces solves the issue:
/[\u{1F600}-\u{1F6FF}]/

This matches (emoji) characters in these unicode blocks:

*

*U+1F600..U+1F64F Emoticons

*U+1F650..U+1F67F Ornamental Dingbats

*U+1F680..U+1F6FF Transport and Map Symbols

You can also use unpack, pack, and between? to achieve a similar result. This also works for Ruby 1.8.7 which doesn't support Unicode in regular expressions.
s = 'Hi!'
#=> "Hi!\360\237\230\200"

s.unpack('U*').reject{ |e| e.between?(0x1F600, 0x1F6FF) }.pack('U*')
#=> "Hi!"

Regarding your Rubular example – Emoji are single characters:
"".length  #=> 1
"".chars   #=> [""]

Whereas kaomoji are a combination of multiple characters:
"^_^".length #=> 3
"^_^".chars  #=> ["^", "_", "^"]

Matching these is a very different task (and you should ask that in a separate question).

A: I am using one based on this script.
 def strip_emoji(text)
    text = text.force_encoding('utf-8').encode
    clean = ""

    # symbols & pics
    regex = /[\u{1f300}-\u{1f5ff}]/
    clean = text.gsub regex, ""

    # enclosed chars
    regex = /[\u{2500}-\u{2BEF}]/ # I changed this to exclude chinese char
    clean = clean.gsub regex, ""

    # emoticons
    regex = /[\u{1f600}-\u{1f64f}]/
    clean = clean.gsub regex, ""

    #dingbats
    regex = /[\u{2702}-\u{27b0}]/
    clean = clean.gsub regex, ""
  end

Results:
irb> strip_emoji("☂❤华み원❤")
=> "华み원"

A: Instead of removing Emoji characters, you can only include alphabets and numbers. A simple tr should do the trick, .tr('^A-Za-z0-9', ''). Of course this will remove all punctuation, but you can always modify the regex to suit your specific condition.

A: This regex matches all 845 emoji, taken from Emoji unicode characters for use on the web:
[\u{203C}\u{2049}\u{20E3}\u{2122}\u{2139}\u{2194}-\u{2199}\u{21A9}-\u{21AA}\u{231A}-\u{231B}\u{23E9}-\u{23EC}\u{23F0}\u{23F3}\u{24C2}\u{25AA}-\u{25AB}\u{25B6}\u{25C0}\u{25FB}-\u{25FE}\u{2600}-\u{2601}\u{260E}\u{2611}\u{2614}-\u{2615}\u{261D}\u{263A}\u{2648}-\u{2653}\u{2660}\u{2663}\u{2665}-\u{2666}\u{2668}\u{267B}\u{267F}\u{2693}\u{26A0}-\u{26A1}\u{26AA}-\u{26AB}\u{26BD}-\u{26BE}\u{26C4}-\u{26C5}\u{26CE}\u{26D4}\u{26EA}\u{26F2}-\u{26F3}\u{26F5}\u{26FA}\u{26FD}\u{2702}\u{2705}\u{2708}-\u{270C}\u{270F}\u{2712}\u{2714}\u{2716}\u{2728}\u{2733}-\u{2734}\u{2744}\u{2747}\u{274C}\u{274E}\u{2753}-\u{2755}\u{2757}\u{2764}\u{2795}-\u{2797}\u{27A1}\u{27B0}\u{2934}-\u{2935}\u{2B05}-\u{2B07}\u{2B1B}-\u{2B1C}\u{2B50}\u{2B55}\u{3030}\u{303D}\u{3297}\u{3299}\u{1F004}\u{1F0CF}\u{1F170}-\u{1F171}\u{1F17E}-\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E7}-\u{1F1EC}\u{1F1EE}-\u{1F1F0}\u{1F1F3}\u{1F1F5}\u{1F1F7}-\u{1F1FA}\u{1F201}-\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}-\u{1F251}\u{1F300}-\u{1F320}\u{1F330}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F380}-\u{1F393}\u{1F3A0}-\u{1F3C4}\u{1F3C6}-\u{1F3CA}\u{1F3E0}-\u{1F3F0}\u{1F400}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4F7}\u{1F4F9}-\u{1F4FC}\u{1F500}-\u{1F507}\u{1F509}-\u{1F53D}\u{1F550}-\u{1F567}\u{1F5FB}-\u{1F640}\u{1F645}-\u{1F64F}\u{1F680}-\u{1F68A}]

I generated this regex directly from the raw list of Unicode emoji. The algorithm is here: https://github.com/franklsf95/ruby-emoji-regex.
Example usage:
regex = /[\u{203C}\u{2049}\u{20E3}\u{2122}\u{2139}\u{2194}-\u{2199}\u{21A9}-\u{21AA}\u{231A}-\u{231B}\u{23E9}-\u{23EC}\u{23F0}\u{23F3}\u{24C2}\u{25AA}-\u{25AB}\u{25B6}\u{25C0}\u{25FB}-\u{25FE}\u{2600}-\u{2601}\u{260E}\u{2611}\u{2614}-\u{2615}\u{261D}\u{263A}\u{2648}-\u{2653}\u{2660}\u{2663}\u{2665}-\u{2666}\u{2668}\u{267B}\u{267F}\u{2693}\u{26A0}-\u{26A1}\u{26AA}-\u{26AB}\u{26BD}-\u{26BE}\u{26C4}-\u{26C5}\u{26CE}\u{26D4}\u{26EA}\u{26F2}-\u{26F3}\u{26F5}\u{26FA}\u{26FD}\u{2702}\u{2705}\u{2708}-\u{270C}\u{270F}\u{2712}\u{2714}\u{2716}\u{2728}\u{2733}-\u{2734}\u{2744}\u{2747}\u{274C}\u{274E}\u{2753}-\u{2755}\u{2757}\u{2764}\u{2795}-\u{2797}\u{27A1}\u{27B0}\u{2934}-\u{2935}\u{2B05}-\u{2B07}\u{2B1B}-\u{2B1C}\u{2B50}\u{2B55}\u{3030}\u{303D}\u{3297}\u{3299}\u{1F004}\u{1F0CF}\u{1F170}-\u{1F171}\u{1F17E}-\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E7}-\u{1F1EC}\u{1F1EE}-\u{1F1F0}\u{1F1F3}\u{1F1F5}\u{1F1F7}-\u{1F1FA}\u{1F201}-\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}-\u{1F251}\u{1F300}-\u{1F320}\u{1F330}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F380}-\u{1F393}\u{1F3A0}-\u{1F3C4}\u{1F3C6}-\u{1F3CA}\u{1F3E0}-\u{1F3F0}\u{1F400}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4F7}\u{1F4F9}-\u{1F4FC}\u{1F500}-\u{1F507}\u{1F509}-\u{1F53D}\u{1F550}-\u{1F567}\u{1F5FB}-\u{1F640}\u{1F645}-\u{1F64F}\u{1F680}-\u{1F68A}]/
str = "I am a string with emoji  and other Unicode characters 比如中文."
str.gsub regex, ''
# "I am a string with emoji  and other Unicode characters 比如中文."

Other Unicode characters, such as Asian characters, are preserved.
EDIT: I udpated the regex to exclude ASCII numbers and symbols. See comments for details.

A: Most of the answers in this thread don't remove all emojis correctly. They remove simple emojis like  fine. But they won't fully remove multi code point emojis like  or ☸, leaving some residual unicode code points behind.
You could use a gem like unicode-emoji to get the latest emoji regexes, but if you find this overkill the following code might be a good enough solution:
text.gsub(/[^[:alnum:][:blank:][:punct:]]/, '').squeeze(' ').strip

This will remove any emoji or weird-unicody-like character that is not a basic alphanum/punct/blank.

A: REGEX = /[^\u{1F600}-\u{1F6FF}\s]/

or
REGEX = /[\u{1F600}-\u{1F6FF}\s]/
REGEX = /[\u{1F600}-\u{1F6FF}]/
REGEX = /[^\u{1F600}-\u{1F6FF}]/

because your original regex seems to indicate you try to find everything that is not an amoji and not a whitespace and I don't know why would you want to do it.
Also:

*

*the emoji are 1F300-1F6FF rather than 1F600-1F6FF; you may want to change that

*if you want to remove all astral characters (for example you deal with a software that doesn't support all of Unicode), you should use 10000-10FFFF.
EDIT: You almost certainly want REGEX = /[\u{1F600}-\u{1F6FF}]/ or similar. Your original regex matched everything that is not a whitespace, and not in range 0-\u1F6F. Since spaces are whitespace, and English letters are in range 0-\u1F6F, and Chinese characters are in neither, the regex matched Chinese characters and removed them.

A: This very short Regex covers all Emoji in getemoji.com so far:
[\u{1F300}-\u{1F5FF}|\u{1F1E6}-\u{1F1FF}|\u{2700}-\u{27BF}|\u{1F900}-\u{1F9FF}|\u{1F600}-\u{1F64F}|\u{1F680}-\u{1F6FF}|\u{2600}-\u{26FF}]

A: CARE the answer from Aray have some side effects.
"-".gsub(/[^\p{L}\s]+/, '').squeeze(' ').strip
=> ""

even when this is suppose to be a simple minus (-)

A: I converted the RegEx from the RUBY project above to a JavaScript friendly RegEx:
    /// <summary>
    /// Emoji symbols character sets (added \s and +)
    /// Unicode with עברית Delete the emoji to match
    /// https://regex101.com/r/jP5jC5/3
    /// https://github.com/franklsf95/ruby-emoji-regex
    /// http://stackoverflow.com/questions/24672834/how-do-i-remove-emoji-from-string
    /// </summary>
    public const string Emoji = @"^[\s\u00A9\u00AE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9-\u21AA\u231A-\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA-\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614-\u2615\u2618\u261D\u2620\u2622-\u2623\u2626\u262A\u262E-\u262F\u2638-\u263A\u2648-\u2653\u2660\u2663\u2665-\u2666\u2668\u267B\u267F\u2692-\u2694\u2696-\u2697\u2699\u269B-\u269C\u26A0-\u26A1\u26AA-\u26AB\u26B0-\u26B1\u26BD-\u26BE\u26C4-\u26C5\u26C8\u26CE-\u26CF\u26D1\u26D3-\u26D4\u26E9-\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733-\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763-\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934-\u2935\u2B05-\u2B07\u2B1B-\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u1F004\u1F0CF\u1F170-\u1F171\u1F17E-\u1F17F\u1F18E\u1F191-\u1F19A\u1F201-\u1F202\u1F21A\u1F22F\u1F232-\u1F23A\u1F250-\u1F251\u1F300-\u1F321\u1F324-\u1F393\u1F396-\u1F397\u1F399-\u1F39B\u1F39E-\u1F3F0\u1F3F3-\u1F3F5\u1F3F7-\u1F4FD\u1F4FF-\u1F53D\u1F549-\u1F54E\u1F550-\u1F567\u1F56F-\u1F570\u1F573-\u1F579\u1F587\u1F58A-\u1F58D\u1F590\u1F595-\u1F596\u1F5A5\u1F5A8\u1F5B1-\u1F5B2\u1F5BC\u1F5C2-\u1F5C4\u1F5D1-\u1F5D3\u1F5DC-\u1F5DE\u1F5E1\u1F5E3\u1F5EF\u1F5F3\u1F5FA-\u1F64F\u1F680-\u1F6C5\u1F6CB-\u1F6D0\u1F6E0-\u1F6E5\u1F6E9\u1F6EB-\u1F6EC\u1F6F0\u1F6F3\u1F910-\u1F918\u1F980-\u1F984\u1F9C0}]+$";

Usage:
if (!Regex.IsMatch(vm.NameFull, RegExKeys.Emoji)) // Match means no Emoji was found

A: In Android | Kotlin you can use this extension function to remove all emojis from String
fun String.removeEmojis(): String = Pattern.compile("[^\\p{L}\\s]+")
    .matcher(this).replaceAll("")

Sample :
val result = "Hi emojis      removed".removeEmojis()
output => "Hi emojis removed"

A:          // method to remove emoji from string
    public static String remove_emoji(String text){
                    String updated_text="";
                    for (int i=0;i<text.length();i++){
                        if(text.substring(i,i+1).matches("[\\x00-\\x7F]+")){
             // regex [\\x00-\\x7F]+ will check it contains emoji symbol or not,if it matches it means its not the emoji symbol

updated_text=updated_text+text.substring(i,i+1);
                        }
                    }
                    return updated_text;
                }


text:
Q: Increase solana compute budget limit in python client I have this transactions instruction created on python similar to the one written on solana cookbook but in rust.
I'm very curious why the error it returns is not coming with compute limit extension but rather an error of 200000 on 200000 compute limit consumption.
python
transaction = Transaction()

request_units = CStruct(
"units" / U32,
"additional_fee" / U32
)

transaction.add(
    TransactionInstruction(
        [],
        compute_program_meta.pubkey,
        request_units.build({"units": 500000, "additional_fee": int(0.01*10**9)})
    )
)

transaction.add(
    TransactionInstruction(
        accounts,
        program_id,
        bytes([0, 10])
    )
)

rust
fn send_instructions_demo(
rpc_client: &RpcClient,
wallet_signer: &dyn Signer,
) -> Result<(), Box<dyn std::error::Error>> {{
let accounts = &[];
let txn = submit_transaction(
    &connection,
    &wallet_signer,
    // Array of instructions: 0: Increase Budget, 1: Do something, 2: Do something else
    [ComputeBudgetInstruction::request_units(400_000u32),
    Instruction::new_with_borsh(PROG_KEY, &0u8, accounts.to_vec()),
    Instruction::new_with_borsh(PROG_KEY, &0u8, accounts.to_vec())].to_vec(),
)?;
println!("{:?}", txn);
Ok(())}

A: The compute budget increase is not released yet on mainnet-beta or devnet. You cannot use it to request more compute until the feature is activated and either cluster releases version 1.9.X


text:
Q: Need help in correcting issues in CRC-ITU check method written in Javascript (node.js) We are trying to code GPS device listener on Javascript.
While doing this, we are unable to develop the right script for the CRC-ITU error check. The explanation for the crc code generation from protocol document is as below

A check code may be used by the terminal or the server to distinguish
  whether the received information is error or not. To prevent errors
  occur during data transmission, error check is added to against data
  misoperation, so as to increase the security and efficiency of the
  system. The check code is generated by the CRC-ITU checking method.
  The check codes of data in the structure of the protocol, from the
  Packet Length to the Information Serial Number (including "Packet
  Length" and "Information Serial Number") , are values of CRC-ITU. CRC
  error occur when the received information is calculated, the receiver
  will ignore and discard the data packet.

We referred to the C code sample given in the protocol document -
// calculate the 16-bit CRC of data with predetermined length.

U16 GetCrc16(const U8* pData, int nLength)
{
   U16 fcs = 0xffff; // initialization
   while(nLength>0)
   {
     fcs = (fcs >> 8) ^ crctab16[(fcs ^ *pData) & 0xff];
     nLength--;
     pData++;
   }
   return ~fcs; // negated
}

the array crctab16 is the array same as mentioned in our code sample
    Incoming data string comes in following format

    Example of data packet sent by the terminal 78 78 0D 01 01 23 45 67 89 01 23 45 00 01 8C DD 0D 0A

    Explanation

    Start Bit - 0x78 0x78
    Length - 0x0D
    Protocol - 0x01
    Terminal ID - 0x01 0x23 0x45 0x67 0x89 0x01 0x23 0x45
    Serial No - 0x00 0x01
    Error - 0x8C 0xDD
    Stop Bit - 0x0D 0x0A

Our Javascript code below
var net = require('net');

net.createServer(function(socket)
{

    socket.setEncoding('hex');

    // New client connection event
    socket.on('connect', function(data)

    // Incoming data event
    socket.on('data', function(data)
    {
        console.log("Client said: " + data); // server log
        data_p = data.substring(4,28);
        err_code = crc16(data_p);
        console.log("error: " + err_code);
    });

    // Disconnect event
    socket.on('end', function()
    {
        //Log it to the server output
        console.log("someone left us." + socket.remoteAddress);
    });

}).listen(3006);

console.log("TCP ECHO SERVER STARTED ON 3006");

function crc16(buf)
{

    var crcTable =
    [
        0X0000, 0X1189, 0X2312, 0X329B, 0X4624, 0X57AD, 0X6536, 0X74BF, 0X8C48, 0X9DC1, 0XAF5A,
        0XBED3, 0XCA6C, 0XDBE5, 0XE97E, 0XF8F7, 0X1081, 0X0108, 0X3393, 0X221A, 0X56A5, 0X472C,
        0X75B7, 0X643E, 0X9CC9, 0X8D40, 0XBFDB, 0XAE52, 0XDAED, 0XCB64, 0XF9FF, 0XE876, 0X2102,
        0X308B, 0X0210, 0X1399, 0X6726, 0X76AF, 0X4434, 0X55BD, 0XAD4A, 0XBCC3, 0X8E58, 0X9FD1,
        0XEB6E, 0XFAE7, 0XC87C, 0XD9F5, 0X3183, 0X200A, 0X1291, 0X0318, 0X77A7, 0X662E, 0X54B5,
        0X453C, 0XBDCB, 0XAC42, 0X9ED9, 0X8F50, 0XFBEF, 0XEA66, 0XD8FD, 0XC974, 0X4204, 0X538D,
        0X6116, 0X709F, 0X0420, 0X15A9, 0X2732, 0X36BB, 0XCE4C, 0XDFC5, 0XED5E, 0XFCD7, 0X8868,
        0X99E1, 0XAB7A, 0XBAF3, 0X5285, 0X430C, 0X7197, 0X601E, 0X14A1, 0X0528, 0X37B3, 0X263A,
        0XDECD, 0XCF44, 0XFDDF, 0XEC56, 0X98E9, 0X8960, 0XBBFB, 0XAA72, 0X6306, 0X728F, 0X4014,
        0X519D, 0X2522, 0X34AB, 0X0630, 0X17B9, 0XEF4E, 0XFEC7, 0XCC5C, 0XDDD5, 0XA96A, 0XB8E3,
        0X8A78, 0X9BF1, 0X7387, 0X620E, 0X5095, 0X411C, 0X35A3, 0X242A, 0X16B1, 0X0738, 0XFFCF,
        0XEE46, 0XDCDD, 0XCD54, 0XB9EB, 0XA862, 0X9AF9, 0X8B70, 0X8408, 0X9581, 0XA71A, 0XB693,
        0XC22C, 0XD3A5, 0XE13E, 0XF0B7, 0X0840, 0X19C9, 0X2B52, 0X3ADB, 0X4E64, 0X5FED, 0X6D76,
        0X7CFF, 0X9489, 0X8500, 0XB79B, 0XA612, 0XD2AD, 0XC324, 0XF1BF, 0XE036, 0X18C1, 0X0948,
        0X3BD3, 0X2A5A, 0X5EE5, 0X4F6C, 0X7DF7, 0X6C7E, 0XA50A, 0XB483, 0X8618, 0X9791, 0XE32E,
        0XF2A7, 0XC03C, 0XD1B5, 0X2942, 0X38CB, 0X0A50, 0X1BD9, 0X6F66, 0X7EEF, 0X4C74, 0X5DFD,
        0XB58B, 0XA402, 0X9699, 0X8710, 0XF3AF, 0XE226, 0XD0BD, 0XC134, 0X39C3, 0X284A, 0X1AD1,
        0X0B58, 0X7FE7, 0X6E6E, 0X5CF5, 0X4D7C, 0XC60C, 0XD785, 0XE51E, 0XF497, 0X8028, 0X91A1,
        0XA33A, 0XB2B3, 0X4A44, 0X5BCD, 0X6956, 0X78DF, 0X0C60, 0X1DE9, 0X2F72, 0X3EFB, 0XD68D,
        0XC704, 0XF59F, 0XE416, 0X90A9, 0X8120, 0XB3BB, 0XA232, 0X5AC5, 0X4B4C, 0X79D7, 0X685E,
        0X1CE1, 0X0D68, 0X3FF3, 0X2E7A, 0XE70E, 0XF687, 0XC41C, 0XD595, 0XA12A, 0XB0A3, 0X8238,
        0X93B1, 0X6B46, 0X7ACF, 0X4854, 0X59DD, 0X2D62, 0X3CEB, 0X0E70, 0X1FF9, 0XF78F, 0XE606,
        0XD49D, 0XC514, 0XB1AB, 0XA022, 0X92B9, 0X8330, 0X7BC7, 0X6A4E, 0X58D5, 0X495C, 0X3DE3,
        0X2C6A, 0X1EF1, 0X0F78
    ];

    crcX = parseInt("FFFF",16);
    cr1 = parseInt("FF",16);
    cr2 = parseInt("FFFF",16);
    i = 0;

    while(i < buf.length)
    {
        str = buf.substring(i,i+4);
        console.log("str "+str);
        str_hex = parseInt(str,16);

        j = (crcX ^ str_hex) & cr1;
        crcX = (crcX >> 8) ^ crcTable[j] ;

        i = i + 4;
    }

    crcX = ~crcX;

    console.log("crcX - " + crcX.toString(16));
    return crcX;
}

Please find below pairs of inputs strings and the corresponding code that should be generated by the function crc16
    78780d01035889905017664600267bf90d0a - 7bf9
    78780d010358899050176646002ab1950d0a - b195
    78780d010358899050176646002ba01c0d0a - a01c

Please help us find the errors in our code.
Much thanks.

A: The ~ in the original code only worked because it was a 16-bit type.  You should use crcX = crcX ^ 0xffff instead of crcX = ~crcX.
Also your buf.substring(i,i+4) and i = i + 4 is wrong.  You need to process one byte at a time, which is two hexadecimal digits.  Those should both be i+2.

A: There are some crc packages on npm, but they may not work for you, I create a new one that is just a copy of c code from your link to document.
Install crc-itu from terminal:
npm install crc-itu

app.js
var crc16 = require('crc-itu').crc16;

var crcInHex = crc16('0d0103588990501766460026', 'hex').toString(16);
console.log(crcInHex); // will print 7bf9

you can also try with these values, note: crc16(data).toString(16) => crc
start          data              crc   end
-------------------------------------------
7878   0d0103588990501766460026  7bf9  0d0a
7878   0d010358899050176646002a  b195  0d0a
7878   0d010358899050176646002b  a01c  0d0a

A: This is my code
var net = require('net');

var HOST = '192.168.1.151';
var PORT = 5023;

function protocall_decorder(data,sbit,plength,protono,ebit){

// Login data
if(plength.toString('hex') == '0d') {
    var ret = crc16Ccitt(data.slice(2,14));
    var err_code = ret;
    console.log(err_code.toString(16));
    plength = new Buffer('05','hex');
    var res = sbit + plength + protono + data.slice(12,14) + err_code.toString(16) + ebit;

    data = "device_imei: " + parseInt(data.slice(4,12).toString('hex'));
    console.log(data);

    res = new Buffer(res)
    var dataArr = {response:res, type:"login", data:data};
}
/*
// Location data
else if(plength == '1F') {
    var res = '787805' + ***** +  data.slice(60,64) + data.slice(24,28) +'D9DC' + '0D0A';
    dataArr = data.substring(2);
}

// Alarm data
else if(plength == '25') {
    dataArr = data.substring(2);
}
// Heart Beat
else if(plength == '08') {
    dataArr = data.substring(2);
}
// Undefined data length
*/
else {
    var dataArr = {response:"error", data:plength};
}

return dataArr;

}

// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {

// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {

    console.log('DATA ' + sock.remoteAddress + ': ' + data);
    // Write the data back to the socket, the client will receive it as data from the server

//////////////// MySQL | Begin ////////////////////
var mysql      = require('mysql');
var con = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'lahirutm',
    database : 'gt06n'
});
con.connect();

var sbit = data.slice(0,2);
var plength = data.slice(2,3);
var protono = data.slice(3,4);
var ebit = data.slice(-2)

if(sbit.toString('hex') == '7878') {
    var res = protocall_decorder(data,sbit,plength,protono,ebit);
    if(res['response'] != 'error') {
        sock.write(res['response']);
        var response = res['response'];
    }
}
else {
    console.log('Undefined protocol data');
}

console.log(response); // Write data to socket

var message  = {start_bit: sbit, packet_length: plength, proto_no: protono, serial:'*', end_bit: ebit};
var query = con.query('INSERT INTO incoming_data SET ?', message,
//var message = {data: data}
//var query = con.query('INSERT INTO row_data SET ?', message,
function(err, result) {
        // Neat!
});
console.log(query.sql);

var message = {data: data}
var query = con.query('INSERT INTO row_data SET ?', message,
function(err, result) {
        // Neat!
});
console.log(query.sql);
con.end();
///////////////  MySQL | Begin ////////////////

});

// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
    console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

/**
* CRC functions
*/

var crc16CcittTableReverse = [
    0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
    0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
    0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
    0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
    0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
    0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
    0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
    0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
    0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
    0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
    0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
    0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,
    0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9,
    0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1,
    0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738,
    0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70,
    0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7,
    0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF,
    0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036,
    0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E,
    0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5,
    0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD,
    0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134,
    0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C,
    0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3,
    0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB,
    0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232,
    0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A,
    0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1,
    0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9,
    0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330,
    0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78
];

var crc16CcittStart = 0xFFFF;
var crc16CcittXorout = 0xFFFF;

function crc16Reflected(buf, crc_in, table) {
    var crc16 = crc_in;

    for (i = 0; i < buf.length; i++) {
        crc16 = table[(crc16 ^ buf[i]) & 0xff] ^ (crc16 >> 8);
    }

    return crc16 & 0xFFFF;
}

function crc16Ccitt(buf) {
    return crc16Reflected(buf, crc16CcittStart, crc16CcittTableReverse) ^ crc16CcittXorout;
}

A: Found very few links on CRC 16 calculation but found the current answer in javascript helpful.
In case anyone is looking for the same CRC 16 calculation using python, have created the public gist along with working python fiddle example:
https://gist.github.com/mrudang-vora/6a0767be085a275c0df3
Hope it helps someone.

A: In case of using java
  public static void main(String[] args) {
  String sample_string ="78 78 0D 01 01 23 45 67 89 01 23 45 00 01 8C DD 0D
  0A";
  String[] data_packet = packet.split(" ");
  String[] pdata = Arrays.copyOfRange(data_packet, 2, data_packet.length - 4);
  //pdata will be from "packet-length" to "Information Serial Nummber"
  //discarding "start-bit" from start and "Error-check" and "Stop Bit" from end
  //actual pdata[]={0D,01,01,23,45,67,89,01,23,45,00,01};
  String error_code = crc16(pdata);
  System.out.println("================>Error_code:" + error_code);

  }
  public String crc16(String[] pdata) {

    int[] crcTable
            = {
                0X0000, 0X1189, 0X2312, 0X329B, 0X4624, 0X57AD, 0X6536, 0X74BF, 0X8C48, 0X9DC1, 0XAF5A,
                0XBED3, 0XCA6C, 0XDBE5, 0XE97E, 0XF8F7, 0X1081, 0X0108, 0X3393, 0X221A, 0X56A5, 0X472C,
                0X75B7, 0X643E, 0X9CC9, 0X8D40, 0XBFDB, 0XAE52, 0XDAED, 0XCB64, 0XF9FF, 0XE876, 0X2102,
                0X308B, 0X0210, 0X1399, 0X6726, 0X76AF, 0X4434, 0X55BD, 0XAD4A, 0XBCC3, 0X8E58, 0X9FD1,
                0XEB6E, 0XFAE7, 0XC87C, 0XD9F5, 0X3183, 0X200A, 0X1291, 0X0318, 0X77A7, 0X662E, 0X54B5,
                0X453C, 0XBDCB, 0XAC42, 0X9ED9, 0X8F50, 0XFBEF, 0XEA66, 0XD8FD, 0XC974, 0X4204, 0X538D,
                0X6116, 0X709F, 0X0420, 0X15A9, 0X2732, 0X36BB, 0XCE4C, 0XDFC5, 0XED5E, 0XFCD7, 0X8868,
                0X99E1, 0XAB7A, 0XBAF3, 0X5285, 0X430C, 0X7197, 0X601E, 0X14A1, 0X0528, 0X37B3, 0X263A,
                0XDECD, 0XCF44, 0XFDDF, 0XEC56, 0X98E9, 0X8960, 0XBBFB, 0XAA72, 0X6306, 0X728F, 0X4014,
                0X519D, 0X2522, 0X34AB, 0X0630, 0X17B9, 0XEF4E, 0XFEC7, 0XCC5C, 0XDDD5, 0XA96A, 0XB8E3,
                0X8A78, 0X9BF1, 0X7387, 0X620E, 0X5095, 0X411C, 0X35A3, 0X242A, 0X16B1, 0X0738, 0XFFCF,
                0XEE46, 0XDCDD, 0XCD54, 0XB9EB, 0XA862, 0X9AF9, 0X8B70, 0X8408, 0X9581, 0XA71A, 0XB693,
                0XC22C, 0XD3A5, 0XE13E, 0XF0B7, 0X0840, 0X19C9, 0X2B52, 0X3ADB, 0X4E64, 0X5FED, 0X6D76,
                0X7CFF, 0X9489, 0X8500, 0XB79B, 0XA612, 0XD2AD, 0XC324, 0XF1BF, 0XE036, 0X18C1, 0X0948,
                0X3BD3, 0X2A5A, 0X5EE5, 0X4F6C, 0X7DF7, 0X6C7E, 0XA50A, 0XB483, 0X8618, 0X9791, 0XE32E,
                0XF2A7, 0XC03C, 0XD1B5, 0X2942, 0X38CB, 0X0A50, 0X1BD9, 0X6F66, 0X7EEF, 0X4C74, 0X5DFD,
                0XB58B, 0XA402, 0X9699, 0X8710, 0XF3AF, 0XE226, 0XD0BD, 0XC134, 0X39C3, 0X284A, 0X1AD1,
                0X0B58, 0X7FE7, 0X6E6E, 0X5CF5, 0X4D7C, 0XC60C, 0XD785, 0XE51E, 0XF497, 0X8028, 0X91A1,
                0XA33A, 0XB2B3, 0X4A44, 0X5BCD, 0X6956, 0X78DF, 0X0C60, 0X1DE9, 0X2F72, 0X3EFB, 0XD68D,
                0XC704, 0XF59F, 0XE416, 0X90A9, 0X8120, 0XB3BB, 0XA232, 0X5AC5, 0X4B4C, 0X79D7, 0X685E,
                0X1CE1, 0X0D68, 0X3FF3, 0X2E7A, 0XE70E, 0XF687, 0XC41C, 0XD595, 0XA12A, 0XB0A3, 0X8238,
                0X93B1, 0X6B46, 0X7ACF, 0X4854, 0X59DD, 0X2D62, 0X3CEB, 0X0E70, 0X1FF9, 0XF78F, 0XE606,
                0XD49D, 0XC514, 0XB1AB, 0XA022, 0X92B9, 0X8330, 0X7BC7, 0X6A4E, 0X58D5, 0X495C, 0X3DE3,
                0X2C6A, 0X1EF1, 0X0F78
            };

    int crcX = 0xFFFF;
    int cr1 = 0xFF;
    int cr2 = 0xFFFF;
    int i = 0;
    int j;

    while (i < pdata.length) {
        String str = pdata[i];

        int str_hex = Integer.parseInt(str, 16);

        j = (crcX ^ str_hex) & cr1;
        crcX = (crcX >> 8) ^ crcTable[j];

        i++;
    }


text:
Q: Build fails due to architecture deprecation armv7 in Xcode 14 I am trying to build and run my unity application in my iOS device for debugging purpose. I get a build file from Unity. Then I open .xcodeproj file in my xcode 14. When I run the app, it gives this error:

When I google it, I find out that Xcode 14 does not support this architecture anymore:

So I cannot debug my unity app in my iOS device. You may say that okay use older version of Xcode like 13, however xcode 13 does not support iOS 16 or later (my device has iOS 16). I am little bit stuck in there.  How can I get rid of this situation? Is there any way to change the armv7 architecture that is created by unity build file?
I tried to solve armv7 error but I could not. Is there any way to handle this problem with unity and Xcode 14 environments?

A: I ran into this as well and don't see a solution with Xcode 14.  I may have to investigate how to revert to Xcode 13 as I don't think I use any advanced iOS features and have older devices to test on.


text:
Q: Flying Saucer in Lotus Notes I was trying to convert simple XHTML-files to PDF, and used Flying Saucer and iText to do so. It worked without problems in Java, however, when I tried to make a Lotus Notes agent with the same code, I got an exception I am unsure how to deal with.
The code:
import lotus.domino.*;
import java.io.*;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.util.XRLog;
import java.util.*;

public class JavaAgent extends AgentBase {

    public void NotesMain() {

      try {
        Session session = getSession();
        AgentContext agentContext = session.getAgentContext();
        String received = agentContext.getDocumentContext().
             getItemValueString("Query_String");
        String[] split;
        split = received.split("&");
        String url = split[1];
        split = url.split("/");
        String outputFile = split[split.length-1];
        String direc = session.getEnvironmentString("Directory", true);
        outputFile = direc + "\\" + outputFile + ".pdf";
        OutputStream os = new FileOutputStream(outputFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        renderer.layout();
        renderer.createPDF(os);
        os.close();
        System.exit(0);

      } catch(Exception e) {
        e.printStackTrace();
      }
   }
}

This yields the following:

09-05-2011 13:33:29   HTTP JVM: Could not initialize configuration for Flying Saucer library. Message is: Can't find resource for bundle java.util.PropertyResourceBundle, key access_properties_not_allowed
09-05-2011 13:33:29   HTTP JVM: java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key access_properties_not_allowed
09-05-2011 13:33:29   HTTP JVM:    at java.util.MissingResourceException.(MissingResourceException.java:50)
09-05-2011 13:33:29   HTTP JVM:    at java.util.ResourceBundle.getObject(ResourceBundle.java:400)
09-05-2011 13:33:29   HTTP JVM:    at java.util.ResourceBundle.getString(ResourceBundle.java:421)
09-05-2011 13:33:29   HTTP JVM:    at lotus.notes.JavaString.getString(Unknown Source)
09-05-2011 13:33:29   HTTP JVM:    at lotus.notes.AgentSecurityManager.checkPropertiesAccess(Unknown Source)
09-05-2011 13:33:30   HTTP JVM:    at java.lang.System.getProperties(System.java:323)
09-05-2011 13:33:30   HTTP JVM:    at org.xhtmlrenderer.util.Configuration.loadSystemProperties(Configuration.java:419)
09-05-2011 13:33:30   HTTP JVM:    at org.xhtmlrenderer.util.Configuration.(Configuration.java:147)
09-05-2011 13:33:30   HTTP JVM:    at org.xhtmlrenderer.util.Configuration.instance(Configuration.java:742)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.util.Configuration.valueFor(Configuration.java:463)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.util.Configuration.isTrue(Configuration.java:709)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.util.XRLog.init(XRLog.java:250)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.util.XRLog.log(XRLog.java:203)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.util.XRLog.render(XRLog.java:194)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.util.XRLog.render(XRLog.java:190)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.layout.SharedContext.(SharedContext.java:107)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.pdf.ITextRenderer.(ITextRenderer.java:111)
09-05-2011 13:33:31   HTTP JVM:    at org.xhtmlrenderer.pdf.ITextRenderer.(ITextRenderer.java:102)
09-05-2011 13:33:31   HTTP JVM:    at JavaAgent.NotesMain(Unknown Source)
09-05-2011 13:33:31   HTTP JVM:    at lotus.domino.AgentBase.runNotes(Unknown Source)
09-05-2011 13:33:31   HTTP JVM:    at lotus.domino.NotesThread.run(Unknown Source)

The offending line is
ITextRenderer renderer = new ITextRenderer();

Googling "access_properties_not_allowed" gives literally nothing.

A: 1) Agents in Notes/Domino have an additional security feature in the Agent properties that sets the security level of the agent.  By default, this setting is set to not allow restricted operations (the default setting is "Do not allow restricted operations").
In order for the agent to run the property it must be set to one of the following options:
"Allow restricted operations"
"Allow restricted operations with full administration rights"
The property is found on the second tab, the key tab, of the Agent Properties dialog box.
2) As "road to yamburg" already explained, the JVM's Security Manager is not allowing access to the system's properties because the security policy does not specify to allow this action.
You must change the security policy of the Java Virtual Machine (JVM) in order to allow access to the system properties.  To do this, you can add the line "permission java.security.AllPermission;" to the "/jvm/lib/security/java.policy" file in the Notes/Domino directory.
The java.policy file will look similar to this after making the change:
grant {
    permission java.security.AllPermission;
    permission java.util.PropertyPermission "java.version", "read";
    permission java.util.PropertyPermission "java.vendor", "read";
    permission java.util.PropertyPermission "java.vendor.url", "read";
    permission java.util.PropertyPermission "java.class.version", "read";
    permission java.util.PropertyPermission "os.name", "read";
        // ... and so on ...
}

Once the client/server is restarted, any Java program requiring access to System.getProperties() will now be granted access.

A: This is likely the security configuration:
XhtmlRenderer tries to read its configuration from System properties:
09-05-2011 13:33:30 HTTP JVM: at java.lang.System.getProperties(System.java:323)
09-05-2011 13:33:30 HTTP JVM: at org.xhtmlrenderer.util.Configuration.loadSystemProperties(Configuration.java:419)

But it is not allowed (SecurityManager),
09-05-2011 13:33:29 HTTP JVM: at lotus.notes.AgentSecurityManager.checkPropertiesAccess(Unknown Source)

There must be an exception thrown, caught and an error message needs to be produced. That error message have to be loaded from a resource bundle, but the bundle is not found.
09-05-2011 13:33:29 HTTP JVM: Could not initialize configuration for Flying Saucer library. Message is: Can't find resource for bundle java.util.PropertyResourceBundle, key access_properties_not_allowed

Solution:

*

*Try to find security properties for Lotus Domino JVM (don't know where they may be or should be), and let the code to read system properties

Or

*

*Make a patch to org.xhtmlrenderer package to catch security exceptions and handle them on their own.


text:
Q: Formula for angle bisector I want to get from his formula:
$$L^2_c = ab - mn$$ to this $$L^2_c = ab - \dfrac{abc^2}{(a+b)^2}$$

The author has given this hint:
Use that $\dfrac{m}{n} = \dfrac{a}{b}$ and $m+n = c$

A: Sufficient to prove that
$$mn=\frac{abc^2}{(a+b)^2}$$
$\frac mn =\frac ab \Rightarrow m=\frac ab n$
$m+n=c \Rightarrow \frac ab n+n=c \Rightarrow n=\frac {c}{(\frac ab+1)}=\frac{bc}{a+b}$ and $m=\frac ab \cdot \frac{bc}{a+b}=\frac {ac}{(a+b)}$
Then $$mn= \frac {ac}{(a+b)} \cdot \frac{bc}{(a+b)}=\frac {abc^2}{(a+b)^2}$$


text:
Q: Is $f(x)=\sin(x^2)$ periodic?
Is the function $f:\Bbb R \rightarrow \Bbb R$ defined as $f(x)=\sin(x^2)$, for all $x\in\Bbb R$, periodic?

Here's my attempt to solve this:

Let's assume that it is periodic. For a function to be periodic, it must satisfy $f(x)=f(T+x)$ for all $x\in\Bbb R$, so it must satisfy the relation for $x=0$ as well. So we get that $T^2=k\pi \iff T=\sqrt{k\pi}$, $k\in\Bbb N$ (since $T$ must be positive, we remove the $-\sqrt{k\pi}$ solution).

So what now? I tried taking $x=\sqrt\pi$ and using the $T$ I found, and I get this: $$ \sin\pi=\sin(T+\sqrt\pi)\iff-1=\sin(\pi(\sqrt k+1)^2)\iff k+2\sqrt k+1=3/2+l  $$
Is this enough for contradiction? The left side of equation is sometimes irrational and gets rational only when $k$ is perfect square, which doesn't happen periodic, while the right hand side is always rational. Or I'm still missing some steps?
Thanks.

A: Your approach simply forces $k$ to be a square. Observing that the LHS will be irrational sometimes is a crucial idea but it cannot apply when you are using only two intervals $[0, T]$ and $[\sqrt{\pi}, \sqrt\pi + T]$ to form equations. Here is an approach that uses more.
Assume that $f$ is periodic with period $T$. Note that the solution set for $f(x) = 0$ is $\{\pm\sqrt{n\pi}\ |\ n = 0, 1, 2, \dotsc\}$. For any nonnegative integer $m$, $f(\sqrt{m\pi}) = 0$ thus $f(\sqrt{m\pi} + T) = 0$. Hence, there exists some integer $k_m$ such that $\sqrt{m\pi} + T = \sqrt{k_m\pi}$. Note that $T = \sqrt{k_0\pi}$, which gives us
$$\begin{align}
\sqrt m + \sqrt k_0 &= \sqrt k_m\\
m + k_0 + 2\sqrt{mk_0} &= k_m.
\end{align}$$
And now we have a number-theoretic question. Let $k_0 = a^2b$, where $a^2$ is the greatest square that divides $k_0$.

*

*If $b = 1$, choose $m = 2$ to have an irrational LHS and an integer RHS.

*If $b \neq 1$, choose $m = 1$ to have an irrational LHS and an integer RHS.

Contradiction!

A: Let $f : \mathbb{R} \to \mathbb{R}$ be periodic with period $T$.

*

*The range of $f$ is precisely $f([0, T])$; in particular, if $f$ is continuous, the range of $f$ is bounded.

*If $f$ is differentiable, then $f'$ is periodic with period $T$.

Note that $f(x) = \sin(x^2)$ is differentiable and $f'(x) = 2x\cos(x^2)$ which is unbounded. Therefore, $f'$ cannot be periodic by the first point, and hence $f$ cannot be periodic by the second point.


text:
Q: How to merge cells in an extjs grid panel? I have extjs grid.Panel and I am trying to mimic cell merging in the rows when there is duplicate data in the first column of consecutive rows. Using a column renderer, I clear a row's first column value if it is a duplicate of a previous row's value. I would like to modify the previous row's first cell's tdAttr to row span the appropriate number of rows. I cannot figure out how to get to a previous row's metaData. Below is my current renderer code.
                  renderer: function(value, metaData, record, row, col, store, gridView){

                     var dataIndex = metaData.column.dataIndex;
                     var overrideValue = value;

                     // check previous rows and determine whether this row's first column has the same
                     // value as a previous row's first column
                     if (col == 0){
                        var i = row-1;
                        while (i >= 0 && overrideValue != ""){
                           if (store.data.items[i].get(dataIndex) == value){
                              overrideValue = "";
                              // ----- here i want to update record i's metaData...
                              // metaData.tdAttr = 'rowspan=' + row-i+1
                           }
                           i--;
                        }
                     }

                     return overrideValue;
                  }

I've tried a number of ways to get at the metaData associated with a record but have been unsuccessful. The getnodes and getnode methods of the gridView object return undefined.

A: I created the following solution. I used a combination of a column renderer and a view listener, specifically "viewready". The grid's row line is set to "false" and I use the column renderer to apply a custom style to replace the row line as appropriate and clear the appropriate cells values. I modify the background color of "merged" cells in the "viewready" listener.
<style>
.mywrapcell .x-grid-cell-inner {
   white-space: normal;
   border-top-color: #c6c6c6;
   border-top-width: 1px;
   border-top-style: solid;
}
</style>

_addGrid: function() {

      var myModel = Ext.define('User', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'col1', type: 'string'},
            {name: 'col2',  type: 'string'},
        ]
       });

      var myData = [{col1: 'U2', col2: 'Jan 5'},
                    {col1: 'U2', col2: 'Jan 6'},
                    {col1: 'Crowded House', col2: 'Feb 19'},
                    {col1: 'Jack Johnson', col2: 'Apr 4'},
                    {col1: 'Jack Johnson', col2: 'Apr 5'},
                    {col1: 'Cage the Elephant', col2: 'May 10'},
                    {col1: 'Cage the Elephant', col2: 'May 11'},
                    {col1: 'Blondie', col2: 'Jun 6'},
                    {col1: 'Gorillaz', col2: 'Jun 19'},
                    {col1: 'Gorillaz', col2: 'Jun 20'}];

      var mystore = Ext.create('Ext.data.Store', {
         model: myModel,
         data: myData,
         proxy: {
            type: 'memory',
            enablePaging: false
         }
      });

      var mygrid = Ext.create('Ext.grid.Panel', {
         store: mystore,
         itemId: 'grid',
         viewConfig:{
            listeners: {
               viewready: function(view){

                  var dataIndex = 'col1';

                  // find the index of the column for row spanning
                  var colindex = view.ownerCt.columns.findIndex((x) => x.dataIndex == dataIndex);

                  if (colindex != -1){
                     var viewrows = view.getNodes();
                     var bgcolor = '#fff';

                     // set all the cells to the
                     // same background color
                     for(i=0;i<viewrows.length;i++){
                    viewrows[i].cells[colindex].style.backgroundColor = bgcolor;
                     }
                  }
            }
         },
         enableEditing: false,
         enableBulkEdit: false,
         showRowActionsColumn: false,
         enableRanking: false,
         sortableColumns: false,
         columnLines: true,
         rowLines: false, //row lines handled in renderer
         width: 225,
         columns: [
               {text: 'Artist',
                dataIndex: 'col1',
                flex: 1,
                renderer: function(value, metaData, record, row, col, store, view){

                      var overrideValue = value;

                      // check previous rows and determine whether this row's first column has the same
                      // value as a previous row's first column
                      var i = row-1;

                      while (i >= 0 && overrideValue != ""){
                         if (store.data.items[i].get(metaData.column.dataIndex) == value){
                            overrideValue = '';
                         }
                         i--;
                      }

                      if (overrideValue != ""){
                         metaData.tdCls = 'mywrapcell';
                      }
                      return overrideValue;
                }
               },
               {
                  text: 'Show Date',
                  dataIndex: 'col2',
                  tdCls: 'mywrapcell'
               }
         ],
      });

      this.add(mygrid);

 }

and the result...


text:
Q: How to create and implement interfaces for operations that are only sometimes async Let's say I have 100s of classes that implement a common interface with a method "calculate". Some of the classes will execute async (e.g. read a file), and other classes implementing the same interface will execute code that is sync (e.g. adding two numbers). What is a good way to code this, for maintenance and for performance?
The posts I read so far, always recommend to make async/await methods bubble up to the callers. So if you have one operation that is async, make the caller async, then its caller async, and so on. So this makes me think that the interface should be an async interface. However, this creates a problem when implementing the interface with code that is synchronous.
One idea I thought of is to expose in the interface 2 methods, one async and one sync, and one boolean property to tell the caller which method to call. This would look really ugly though.
The code I currently have is only one interface method that is async. Then for implementations that are synchronous, they wrap the code inside a Task object:
using System.IO;
using System.Threading.Tasks;

namespace TestApp
{
    interface IBlackBox
    {
        Task<string> PullText();
    }

    sealed class MyAsyncBlackBox : IBlackBox
    {
        public async Task<string> PullText()
        {
            using (var reader = File.OpenText("Words.txt"))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }

    sealed class MyCachedBlackBox : IBlackBox
    {
        public Task<string> PullText()
        {
            return Task.Run(() => "hello world");
        }
    }
}

Is this the right approach to create and implement an interface that is only sometimes async? I have a lot of classes that implement short synchronous operations, and worry that this could add a lot of overhead. Is there some other way to do this that I am missing?

A: This is a common situation with interfaces. If you have a contract that needs to specify a task for the Async Await Pattern and we have to implement that Task in the interface.
Assuming the caller is going to use await you can just drop the async and return a Task.
However, you need to be-careful with your exceptions. It's assumed that exceptions are placed on the task. So to keep this plumbing the caller will expect you have to handle them slightly differently.
Common usages
Standard async
public async Task<string> PullText()
{
   using (var reader = File.OpenText("Words.txt"))
   {
      return await reader.ReadToEndAsync();
   }
}

Returning a Task for CPU bound work (capturing the exception and placing it on the Task)
public Task<string> PullText()
{
   try
   {
      return Task.Run(() => DoCpuWork());
   }
   catch (Exception e)
   {
      return Task.FromException<string>(e);
   }
}

Slightly less efficient as we are plumbing an IAsyncStateMachine
public async Task<string> PullText()
{
    return await Task.Run(() => DoCpuWork());
}

Returning a completed Task with a simple results (capturing the exception and placing it on the Task)
public Task<string> PullText()
{
   try
   {
      // simplified example
      return Task.FromResult("someString");
   }
   catch (Exception e)
   {
      return Task.FromException<string>(e);
   }
}

There is also a 3rd approach, you can use the async keyword, and pragma out the warnings, this takes care of the error semantics for you. This feels a little dirty to me, just because it looks messy and the need to pragma out the warning, though I have now seen this used in bespoke production libraries
#pragma warning disable 1998
public async Task<string> PullText()()
#pragma warning restore 1998
{
    return Task.Run(() => "hello world");
}

and
#pragma warning disable 1998
public async Task<string> PullText()()
#pragma warning restore 1998
{
    return Task.FromResult("someString");
}

Note all the above deal with returning a Task<T> from the method. If one was just wanting to return the Task you can take advantage of Task.CompletedTask; with the same error semantics as above.

A: Usually in these cases, You have something in front of the call that is handling the request and passing it off to the "worker" classes (e.g. TestApp).   If this is the case, I don't see why having an "IAsyncable" interface where you could test if the class was async capable would not work.
if(thisObject is IAscyncAble) {
  ... call the ansync request.
}

A: I ended up using the following code:
using System.IO;
using System.Threading.Tasks;

namespace TestApp
{
    interface IBlackBox // interface for both sync and async execution
    {
        Task<string> PullText();
    }

    sealed class MyAsyncBlackBox : IBlackBox
    {
        public async Task<string> PullText()
        {
            using (var reader = File.OpenText("Words.txt"))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }

    sealed class MyCachedBlackBox : IBlackBox
    {
        public Task<string> PullText() // notice no 'async' keyword
        {
            return Task.FromResult("hello world");
        }
    }
}


text:
Q: How to include HTML inside of .ts file I'm pretty new to Angular but have been asigned a project which is written in Angular.
Looking at the .ts file which contains the list of property types I need to include a span around the label text. Is this possible?
Current list inside .ts file
export const extraQuestionsList = [
  {
    name: 'propertyType',
    type: 'radio',
    label: 'Purchase Type',
    value: 'residential',
    validators: [],
    options: [
      { id: 'residential', value: 'residential', label: 'Purchase for you (Residential)', class: 'btn-choice--left' },
      { id: 'bytolet', value: 'bytolet', label: 'Purchase to rent (Buy-to-Let)', class: 'btn-choice--right' },
    ],
    tooltip: '',
  },
];

Desired result
export const extraQuestionsList = [
  {
    name: 'propertyType',
    type: 'radio',
    label: 'Purchase Type',
    value: 'residential',
    validators: [],
    options: [
      { id: 'residential', value: 'residential', label: 'Purchase for you (Residential)', class: 'btn-choice--left' },
      { id: 'bytolet', value: 'bytolet', label: 'Purchase to rent (Buy-to-Let)', class: 'btn-choice--right' },
    ],
    tooltip: '',
  },
];

any help would be much appreciated.
Thanks in advance

A:

  {{opt.id}} {{opt.label}}

A: You can create dynamic form as per your array and it should be in your HTML file as below.

  {{extraQuestionsList[0].label}}

    <input type="radio" name="extraQuestionsList[0].propertyType" [value]="item.residential" [ngClass]="item.class">
  {{item.label}}

Also, remove const export in ts file so it can be treated as an array and you can use it to HTML template.


text:
Q: Link renders as raw html text I have a main page like this:
== Current Links ==
* [http://173.22.73.107/mediawiki/index.php?title=Tiremwiki:Changelog TIREM Changelog]
* [http://173.22.73.107/bugzilla3/ Bugzilla]
* [http://tempser.alionatigerabear.com/svn/Repository/ SubVersion]
* [http://173.22.73.107/bugzilla3/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__open__ All open TIREM bugs]
* [http://tempser.alionatigerabear.com/svn/Repository/TIREM-3/trunk/html/index.html TIREM-3 API Documentation]
* [http://tempser.alionatigerabear.com/svn/Repository/TIREM-4/trunk/html/index.html TIREM-4 API Documentation]

When I click one of the bottom two links I get raw html source rather than a web page.
What am I doing wrong?
The other links work including the third one to the same server as the last.

A: Probably you have to set svn:mime-type property on the files of interest as described in the book and suggested by svick.


text:
Q: Efficient way to group this ruby array of objects I have an array of instances of model Foo. Foo is an Ohm based data store. Each instance of Foo has an_id and integer attributes such as follows, likes. If there are two instances of Foo with the same an_id, I'd love to add the follows and likes attributes together. The solution I had was to create a hash where each key is an an_id of the array, and keep the state there. If the array is large enough, this is not efficient as I need each object back into an array. I'd love to group the array by Foo#an_id and merge/add the counter attributes together and pop that back into the array. Is something like this currently supported?

A: group_by, sum
As a start, something like this:
grouped_hash = your_array.group_by(&:an_id)
sums_by_id = {}
grouped_hash.each do |id,values|
  sums_by_id[id] = {}
  # you could also just iterate over values once and += :follows and :likes
  sums_by_id[id][:follows] = values.sum(&:follows)
  sums_by_id[id][:likes]   = values.sum(&:likes)
end

Example output:
    sums_by_id => {1 => {:follows => 2, :likes => 4}, 2 => ...
Additionally, take a look at:
inject
(5..10).inject {|sum, n| sum + n }  # 45

A: You can use inject to get a sum of values:
array = *array of Foo*
total = array.inject { |sum, x| sum + x.likes }


text:
Q: Why recipients in Laravel Mail queue are stacking up? I am trying to send emails to users in bulk. I set up queue and supervisor according to laravel documentation but recipients in Mail are stacking up and I really don't know what's wrong because everything looks fine in the code. Here is how I am queuing Mails.
$message = (new \App\Mail\EmailUpdate(request('subject'),request('message')))->onQueue('emailsDefault');
foreach($users as $user){
    \Mail::to($user)->queue($message);
}

I thought there must be some issue selecting segment of users from database. But I tried with php artisan tinker and it shows perfect results. Here is how I am getting collection of users from the database.
$users = User::join('user_metas','users.id','=','user_metas.user_id')
             ->where('meta_key','plan')
             ->where('meta_value','free')
             ->select('users.id')
             ->get();

In recipients part of the Emails, I can see an increment in the number of recipients. Here is how it looks like in mailtrap.io.

Any help would be appreciated. I don't know what I am missing here. Here is my EmailUpdate Mailable.
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class EmailUpdate extends Mailable
{
    use Queueable, SerializesModels;

    public $subject;
    public $update;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($subject,$update)
    {
        $this->subject = $subject;
        $this->update = $update;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.emailUpdate')
                    ->subject($this->subject);
    }
}

A: I updated the following code:
$message = (new \App\Mail\EmailUpdate(request('subject'),request('message')))->onQueue('emailsDefault');
foreach($users as $user){
    \Mail::to($user)->queue($message);
}

to the following code:
foreach($users as $user){
    $message = (new \App\Mail\EmailUpdate(request('subject'),request('message')))->onQueue('emailsDefault');
    \Mail::to($user)->queue($message);
}

And it is working! I don't know why this is happening because we are not defining users in the $message instance. If anyone knows the reason behind why this happens the way this happens, I am very curious to know.

A: Let's try a small refactor of the code.
$users = User::join('user_metas','users.id','=','user_metas.user_id')
             ->where('meta_key','plan')
             ->where('meta_value','free')
             ->select('users.id')
             ->get();

$email = new \App\Mail\EmailUpdate(request('subject'),request('message')));
    foreach ($users as $user) {
        Mail::queue(email);
    }

It's because I'm not sure about your:
Mail::to()->queue();
Anyway last check, is there any job failing in the failed_jobs table?

A: You could set empty the "to" property of the mailable object
$message = (new \App\Mail\EmailUpdate(request('subject'),request('message')))->onQueue('emailsDefault');
foreach($users as $user){
    $message->to = [];
    \Mail::to($user)->queue($message);
}

Or Just make a new instance for each iteration as you answered yourself
foreach($users as $user){
    $message = (new \App\Mail\EmailUpdate(request('subject'),request('message')))->onQueue('emailsDefault');
    \Mail::to($user)->queue($message);
}

Why? Idk, apparently each Mail::to() iteration are stacking up the addresses in the to property instead of set a new one.
Enjoy :)


text:
Q: VC# 2010Express print open file I'm new here and my english isn't the best but I have a question.
Is there any possibility in VC# 2010 Express to print the file I opened via openFileDialog?
The opened file is visible in a webBrowser element and can also be edited but now, every time I try to "start"/debugg my application, an error message appears.
Error message:
"System.IO.StreamReader" does not contain a constructor that takes 0 arguments.

This is the line where I need to specify the file path for the file that I want to print.
What entry should I make in the brackets to classify the file in the webBrowser element?

A: System.IO.StreamReader fileToPrint;
System.Drawing.Font printFont;
private void printButton_Click(object sender, EventArgs e)
{
  string printPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  fileToPrint = new System.IO.StreamReader(printPath + @"\myFile.txt");
  printFont = new System.Drawing.Font("Arial", 10);
  printDocument1.Print();
  fileToPrint.Close();
}


text:
Q: Enlarge Image View When Clicked in Android I am using Picasso for a while now and I'm very satisfied with it. However I'm in need of enlarging an imageview's image which is loaded by Picasso from firebase. The codes below is in an adapter.java which is called inside the MainActivity.java
UserRef = FirebaseDatabase.getInstance().getReference().child("user").child(fromUserID);
        UserRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String senderName = snapshot.child("name").getValue().toString();
                String userid = fromUserID;
                if (snapshot.hasChild("avata")){
                 final String receiverImage = snapshot.child("avata").getValue().toString();

                        if (fromUserID.equals(messageSenderId)) {
                            messageViewholder.senderMessageName.setVisibility(View.VISIBLE);
                            messageViewholder.senderImageView.setVisibility(View.VISIBLE);

                            if (fromMessageType.equals("text")) {
                                messageViewholder.senderMessageText.setVisibility(View.VISIBLE);
                                messageViewholder.senderMessageText.setText(messages.getMessage());
                            }else if (fromMessageType.equals("image")) {
                                messageViewholder.senderMessageImage.setVisibility(View.VISIBLE);
                                Picasso.get().load(messages.getMessage()).into(messageViewholder.senderMessageImage);

                            }

Here is the xml
   <ImageView
        android:id="@+id/receiver_message_image"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/receiver_image"
        android:layout_below="@id/receiver_message_name"
        android:layout_marginStart="5dp"
        android:visibility="gone"
        android:adjustViewBounds="true"
        android:layout_marginEnd="20dp" />

A: You can make use of the ScaleGestureDetector that will allow you to detect a particular gesture event that has occurred. It can also allow you to Zoom in and Zoom out depending on the gesture. In this example, I am using viewBinding to map the XML layout to the Java.
XML Layout
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/symatech_logo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

Java Code
   public class EnlargeImageViewWhenClicked extends AppCompatActivity {

    EnlargeImageViewBinding enlargeImageViewBinding;
    ScaleGestureDetector scaleGestureDetector;
    float factor = 1.5f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        enlargeImageViewBinding = EnlargeImageViewBinding.inflate(getLayoutInflater());
        setContentView(enlargeImageViewBinding.getRoot()); // Setting up the view

        scaleGestureDetector = new ScaleGestureDetector(this, new Listerner()); // Creating the ScaleGestureDetector object.
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        scaleGestureDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    private class Listerner extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
            factor *= scaleGestureDetector.getScaleFactor(); // The scaling factor from the previous scale event being applied to the current event.
            factor = Math.max(0.5f, Math.min(factor, 5.0f));
            enlargeImageViewBinding.imageView.setScaleY(factor);
            enlargeImageViewBinding.imageView.setScaleX(factor);
            return true;
        }
    }
}

Before I Zoom In

After I Zoom In

I sure hope this helps!

A: Consider subjecting your ImageView(messageViewholder.senderMessageImage) to the onScale function in the ScaleGestureDetector.SimpleOnScaleGestureListener  as on the example I gave. Something like this (you might need to edit the code to fit your case. Also don't forget to get the rest of the code i.e initializing the ScaleGestureDetector and overriding the onTouchEvent function)
 private class Listerner extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
            factor *= scaleGestureDetector.getScaleFactor(); // The scaling factor from the previous scale event being applied to the current event.
            factor = Math.max(0.5f, Math.min(factor, 5.0f));
            **messageViewholder.senderMessageImage**.setScaleY(factor);
            **messageViewholder.senderMessageImage**.setScaleX(factor);
            return true;
        }
    }


text:
Q: Polynomial Ring Quotient of $\mathbb{R}[x,y]$ by $x^2 + y^2 -1$ I want to find a simpler ring that is isomorphic to this polynomial ring quotient: $\mathbb{R}[x,y]/(x^2 + y^2 -1)$.
I've tried to use the isomorphism theorem by defining $\phi$ a ring homomorphism so that I can show the quotient ring is isomorphic to $Im(\phi)/\ker(\phi)$. But I'm stuck and not sure if this is the right approach.
$\phi: \mathbb{R}[x,y] \longrightarrow \mathbb{R}[x]\diagup(x^2-1) \,\times\,\mathbb{R}[y]\diagup(y^2 -1) \,\,\,\,$ the ring homomorphism
$\phi\big(p(x,y)\big) := \big(p(x,0),p(0,y)\big) \in  \mathbb{R}[x]\times\mathbb{R}[y]\,\,\,\,$ with each entry mod its respective equation
where

*

*$\phi(0)=(0,0)$

*$\phi(1)=(1,1)$

*$\phi\big(p(x,y)q(x,y)\big)=\big(p(x,0)q(x,0),p(0,y)q(0,y)\big)=\big(p(x,0),p(0,y)\big)\big(q(x,0),q(0,y)\big)=\phi\big(p(x,y)\big)\phi\big(q(x,y)\big)$

*$\phi\big(p(x,y)+q(x,y)\big)=\big(p(x,0)+q(x,0),p(0,y)+q(0,y)\big)=\big(p(x,0),p(0,y)\big)+\big(q(x,0),q(0,y)\big)=\phi\big(p(x,y)\big)+\phi\big(q(x,y)\big)$
Now if $p(x,y)\in \ker\phi$ then

*

*$p(x,0) \mod (x^2 -1) = 0 \,\,\,\Longrightarrow \,\,\,p(\pm1,0)=0$

*$p(0,y) \mod (y^2 -1) = 0 \,\,\,\Longrightarrow \,\,\,p(0,\pm1)=0$
Would we then have:
$\mathbb{R}[x,y]\diagup\ker(\phi) \cong \mathbb{R}\times\mathbb{R}\times\mathbb{R}\times\mathbb{R}$


text:
Q: What's wrong with the code? No matter the user input, team 1 will win the game import java.util.*;
import java.util.Random;

public class Playoffs
{
  public static Scanner scan = new Scanner(System.in);

  public static void main(String [] args)
  {
    boolean validNumber;
    int game1;

    System.out.print("What is the % chance that team 1 will win the game?");

    do{
      game1 = scan.nextInt();
      validNumber = game1 >= 0 && game1 <=100;

      if(!validNumber){
        System.out.println("INVALID NUMBER ENTERED: NOT BETWEEN 0 AND 100");
        System.out.print("Enter a valid number between 0 and 100: ");
      }
    }while(!validNumber);
    System.out.println("Team 1 has a " + game1 + "% chance of winning.");

The code below should generate a random number between 0 (inclusive) and 100 (exclusive), stating that if the random number is less than the percentage the user input, team 1 will win, and team 2 should win if the random number is greater than the percentage entered, but it always comes out that team 1 wins
    Random rand = new Random(100);
    int randomNumber = rand.nextInt();
    int oneGame = simulateOneGame(game1, randomNumber);

    if(oneGame == 1){
      System.out.println("\nTeam 1 has won the game");
    }else if(oneGame == 0){
      System.out.println("\nTeam 2 has won the game");
    }
  }

  public static int simulateOneGame(int game1, int randomNumber)
  {
    int result=0;
    if (randomNumber < game1) {
      result += 1;
    } else if(randomNumber > game1){
      result += 0;
    }
    return result;
  }
}

A: This code doesn't generate a number between 0 and 100:
Random rand = new Random(100);
int randomNumber = rand.nextInt();

rand.nextInt() can return any number between Integer.MIN_VALUE and Integer.MAX_VALUE, but since you are using a constant seed (100), you get the same "random" number every time - -1193959466 in your case.
This code does what you want:
Random rand = new Random();
int randomNumber = rand.nextInt(100);

Also note that you don't have to create a new Random instance in each iteration. It's enough to create one instance.


text:
Q: Regular Expression vs KMP Hi can any one tell me why there we are not using Knuth Morris Pratt algorithms in modern programming practices and prefer regular expression more ?

A: Is there more than one KMP algorithm?  My understanding is that there is one algorithm for performing a search for a string within another string.  Regex is much more flexible - and there's no reason why a very simple regex expression couldn't use KMP - it's up to the implementor.


text:
Q: UiAutomator 2.0 and Eclipse Is there any way to compile UiAutomator 2.0 with Eclipse and Ant?
I have added the android.jar and uitautomator.jar files from Android-23 but to no avail. Eclipse still does not see UiAutomator 2.0 specific methods like UiObject2.
I have also attempted to build a .jar file with Ant in Gradle which generates the required .jar file but only works for UiAutomator 1.0. I used the method detailed here.
I know Android now officially only supports Android Studio+Gradle now but my setup requires the usage of a standalone uiautomator.jar file that Ant builds, which is not supported (at least as far as I know) with Android Studio and Gradle.
Will appreciate any push in the right direction.


text:
Q: How should I spawn dialog boxes from my ViewModels? Is there any kind of consensus about best practices for dialog windows in MVVM (for WPF)? I've seen it approached via two ways:

*

*A mediator (EventAggregator, EventBus, or whatever you like to call it) that sends a "RequestsDialog" message and waits for a "DialogProcessed" message.

*A dialog declared in the view xaml itself which is bound to the caller's view model and shown via a Command or EventTrigger or something like that.
I'm trying to figure out which is a better way to go, and I need some help.
My concern with #1 is (and always has been), what's the best way of controlling the scope of the request and reply messages? I mean, let's say I have both "local" messages and "global" application messages being processed by my mediator....how do I make sure my ViewModel can still receive global messages...but at the same time that another ViewModel on the current window doesn't accidentally receive the DialogProcessed message intended for the active ViewModel.
Take the following scenario:

*

*1 Window

*2 UserControls, each bound to independent ViewModels

*ViewModel1 sends a RequestConfirmation  message and waits for a ConfirmationResponse message

*I also have global messages to receive in ViewModel1 (like a RequestCloseWindow message).

How do I prevent ViewModel2 from getting the ConfirmationResponse message for the RequestConfirmation message initiated by ViewModel1?

A: You can either pass a parameter along with the message which identifies who it is for, or have the Message include a delegate of some method to execute once its finished.
Usually I prefer to use an identifier because it's simpler. Sometimes it's an Id or GUID, but usually it's just this. That way in the method that handles the Processed messages I can just say
if (evt.Source != this) return;

A: Did you try using something similar to InteractionRequests from Prism ?
They are exactly covering scenario you've described. Take a look at this article.


text:
Q: how to setup a validation in custom valid using useForm how to setup a validation in custom valid using useForm
Confirm Password
    <input
        type="password"
        name="confirmPassword"
        className="form-control"
        {...register('confirmPassword',
        {
            required: "Confirm password is required",
            minLength: { value: 6, message: 'Minimum 6 characters required', },
            maxLength: { value: 32, message: 'Maximum 32 length exceeded' },
            validate: { SameAsPassword: SameAsPassword('password', getValues) }
        })}
        id="passwordConfirmation" />

    <ErrorMessage
        errors={errors}
        name="confirmPassword"
        render={({ message }) =>
{message}
}
    />

how to display error message using custom validate using UseForm hooks
SameAsPassword how to display this message using ErrorMessage component provided by useForm. Please guide on this thank you


text:
Q: I get an error when I try to use the image network in Flutter instead of the image entity image What is the solution? I get an error when I want to use image network instead of asset image. Can you find a solution?I get an error when I try to use the image network in Flutter instead of the image entity image What is the solution?
       new GestureDetector(
                    onTap: () {
                         _fraURL();
                    },
                    child: Container(
                      decoration: new BoxDecoration(
                        color: Colors.transparent,
                        image: new DecorationImage(
                     -----> image: AssetImage(
                              "res/c3.jpg"),<----
                          fit: BoxFit.scaleDown,
                        ),
                      ),
                    ),
                  ),

    new GestureDetector(
                onTap: () {
                     _fraURL();
                },
                child: Container(
                  decoration: new BoxDecoration(
                    color: Colors.transparent,
                    image: new DecorationImage(
                      image: new Image.network(
            'https://firebasestorage.googleapis.com/v0/b/book-7a285.appspot.com/o/ic_launcher.png?alt=media&token=605f6d54-7098-487c-ae4c-f70ae4476670'),
                      fit: BoxFit.scaleDown,
                    ),
                  ),
                ),
              ),

     image: new Image.network(
                'https://firebasestorage.googleapis.com/v0/b/book-7a285.appspot.com/o/ic_launcher.png?alt=media&token=605f6d54-7098-487c-ae4c-f70ae4476670')

 <-----i can't run it


text:
Q: Is it possible to have a root path containing spaces in my nginx.conf I have tried escaping (and not escaping), with (and without) single quotes double qoutes but i always end up on the 404 page.
is it even possible? i tried searching for it, but landed of https://serverfault.com/questions/361915/how-can-i-make-nginx-recognise-directories-with-spaces-in-its-name but i already tried that, and it didnt work.
if this i just me, then please prove it to me :)

A: I just ran into this issue, too. As long as I did not escape the spaces and used single or double quotes, I was able to use a root path with spaces.
the following works
root "/directory/with spaces not escaped/will work"

this does not work
root "/directory/with\ escaped\ spaces/will\ not\ work"


text:
Q: Change lighting in ChromaticityPlot3D It looks to me like ChromaticityPlot3D has some default lighting, but unlike most Graphics3D functions the Lighting option doesn't seem to have any effect.
However, the documentation states "ChromaticityPlot3D accepts all Graphics3D options with the following additions and changes: ...".
Any ideas how to affect the lighting?  Is it possible to produce a Graphics3D object from the chromaticity plot?  I am trying to achieve unshaded lighting like Lighting -> {{"Ambient", White}}.

A: If you look at the InputForm of ChromaticityPlot3D[{"WideGamutRGB", "sRGB"}] you'll find several spots where it says Lighting -> "Neutral"
So if you want to change that, you'll have to modify the output of ChromaticityPlot3D using a replacement rule.  Here is an extreme example, one that totally ruins the plot but shows how to change the lighting,
ChromaticityPlot3D["WideGamutRGB"] /.
   Rule[Lighting, "Neutral"] :> Rule[Lighting, #] & /@ {"Neutral",
  None, {{"Ambient", White}}}

A: One could override the setting for each polygon group (or GraphicsGroup[]):
cp /. p_Polygon :> {Lighting -> {{"Ambient", White}}, p}
cp /. gg_GraphicsGroup :> {Lighting -> {{"Ambient", White}}, gg}

Update: Addendum.
While Lighting shows up in Options@ChromaticityPlot3D, it is not listed among the options in the docs for ChromaticityPlot3D.
However, it inherits the setting for Lighting from ParametricPlot3D before it is embedded as styling in the graphics primitives: If the setting is not Automatic, then ChromaticityPlot3D won't override it.
With[{opts = Options[ParametricPlot3D]},
 Internal`WithLocalSettings[
  SetOptions[ParametricPlot3D, Lighting -> {{"Ambient", White}}],
  ChromaticityPlot3D[{"WideGamutRGB", "sRGB"}],
  SetOptions[ParametricPlot3D, opts]
  ]
 ]
(* same plot as above *)

See this answer or this one for more on Internal`WithLocalSettings.  In this case one might simply handle things oneself as follows:
  SetOptions[ParametricPlot3D, Lighting -> {{"Ambient", White}}];
  ChromaticityPlot3D[{"WideGamutRGB", "sRGB"}]
  SetOptions[ParametricPlot3D, Lighting -> Automatic];


text:
Q: Can you specify the order of wrapped elements in CSS flex? I have a
 that uses CSS flex to keep it responsive.
I am looking for a way to specify the order that elements are wrapped in.
For example, I need
1 - 2 - 3
To become
1
3
2

When fully wrapped.
Current code: https://jsfiddle.net/g0L44e5b/
Is this possible?

A: yes you can , use order property:

body {
  display:flex;
  flex-flow:column;
  }
p:last-child{
  order:1;
  }
p:nth-child(2) {
  order:2;
    }

1

2

3

here is an handy ressource https://css-tricks.com/snippets/css/a-guide-to-flexbox/

edit after your edit
wrap and mediaquerie can be used :

body {
  display:flex;flex-wrap:wrap;
  }
p {
  flex:1;
  min-width:380px;
  margin:10px;
  border:solid;
}
@media screen and (max-width : 800px) {
p:last-child{
  order:1;
  }
p:nth-child(2) {
  order:2;
    }
}

1

2

3

A: Check this pen out:
http://codepen.io/chriscoyier/pen/YPzyYa
What the pen does --
First gives each element a default class with an order attribute:
.icon {
  order: 0 !important;
 }
.username {
  order: 1 !important;
  width: 100%;
  margin: 15px;
}
.search {
  order: 2 !important;
  width: 100%;
}

Then it gives a class to each each flexbox a specific ordering attribute:
.bar-2 {
  .username {
    order: 2;
  }
}
.icon-3 {
  order: 3;
}

Apply the sorting classes to your case and you should be good to go.

A: if you use media queries, you can use flex-direction: column on the parent element and order: 1; , order: 2; etc. on the child elements to put them in any order you need.


text:
Q: Need help authorizing index action with Pundit I'm using Pundit and Devise on my app. My index action looks like this in my wikis_controller:
  def index
    @wikis = current_user.wikis
    authorize @wikis
  end

I'm trying to prevent un-signed-in users to access this index action but @wikis is getting set to undefined since there is no user logged in. In return, it's not authorizing.
How can I fix this?

A: You can authorize against the model instead of an object.
The code
authorize Wiki

will trigger the index? action in your pundit policy without the user object. In addition, you can use a scope to filter the data on a another level https://github.com/varvet/pundit#scopes.


text:
Q: HTML code to take user form data save in Excel file on common dropbox account What I am trying to do is take data from a user form from a website and save an Excel file in a specific dropbox account upon the end user clicking the submit button.  If this can be done safely and without to much taxation I would prefer that as to opposed to receiving multiple emails each time the form is completed.  Does any one have examples of this, bits and pieces that I have learn from would be greatly appreciated.  My programming experience is in C# and I have not attempted much html or javascript. Thank you for your time and efforts!!

A: Google forms can do most of the work for you. having user form data stored as records in a google sheet which is stored on your google drive. here's a link to create a form on google forms.