问:
Is there a way to get an ArrayList from a String obtained by ArrayList.toString()?
I have this code:

```<code>ArrayList<String> list = new ArrayList<>();
String str = list.toString(); // Stored in a database
</code>```

Is there a quick way to recover the ArrayList from the string ?

答:
There is no one-size-fits-all solution because ArrayList.toString() method will print all the elements separated by comma. But there is absolutely no way to find out whether the comma in your outputted string is because of separation of elements or was it literally included in the string (or object).

Consider these two code snippets:

```<code>List<String> list = new ArrayList<>();
list.add("one");
list.add("two, three");
System.out.println(list);  // [one, two, three]
</code>```

and

```<code>List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list);  // [one, two, three]
</code>```

As you can see, both of these examples are giving exactly the same output.

However, if the elements in your list are some other type, (let's say Integer, Double etc... or even String without a comma), Then you can simply get your list back using

```<code> Arrays.asList(outString.split(",\\s"));
</code>```

Body:
I have this code:

ArrayList<String> list = new ArrayList<>();
String str = list.toString(); // Stored in a database

Is there a quick way to recover the ArrayList from the string ?

Body:
There is no one-size-fits-all solution because ArrayList.toString() method will print all the elements separated by comma. But there is absolutely no way to find out whether the comma in your outputted string is because of separation of elements or was it literally included in the string (or object).

Consider these two code snippets:

List<String> list = new ArrayList<>();
list.add("one");
list.add("two, three");
System.out.println(list);  // [one, two, three]

and

List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list);  // [one, two, three]

As you can see, both of these examples are giving exactly the same output.

However, if the elements in your list are some other type, (let's say Integer, Double etc... or even String without a comma), Then you can simply get your list back using

 Arrays.asList(outString.split(",\\s"));


来源: stackexchange

答:
Sure, you can do it.

```<code> ArrayList<String> list = new ArrayList<>();
 String str = list.toString();

 int len = str.length();
 str = str.substring(1, len-1);
 String[] parts = str.split(",");
 List<String> list2 = Arrays.asList(parts);
</code>```

But this has one limitation. If any value of list contaion comma(,) then it will give you wrong output. In that case you should escape comma before convert it to String. Or you can use any serialization mechanism like JSON

Another approach is, do not call toString() directly. Instead you can use String Joiner (Example can be found here). Use any safe character. Then split your string to get the list back.

ContentLicense: CC BY-SA 3.0

Title: Is there a way to get an ArrayList from a String obtained by ArrayList.toString()?

Body:
Sure, you can do it.

 ArrayList<String> list = new ArrayList<>();
 String str = list.toString();

 int len = str.length();
 str = str.substring(1, len-1);
 String[] parts = str.split(",");
 List<String> list2 = Arrays.asList(parts);

But this has one limitation. If any value of list contaion comma(,) then it will give you wrong output. In that case you should escape comma before convert it to String. Or you can use any serialization mechanism like JSON

Another approach is, do not call toString() directly. Instead you can use String Joiner (Example can be found here). Use any safe character. Then split your string to get the list back.


问:
nxlog.conf filtering windows event log issues
I'm trying to pull specific windows event logs using nxlog and displaying them in graylog. It is retrieving the logs just fine, however, my problem is that:
Even with a query, it still seems to pull a lot of data that is not specified in the query (e.g. here I specify Application with specific eventID's that I have been testing by creating dummy logs in cmd).

For example, I am still getting System, Security and various other logs appearing in graylog.

I'm very new to this so I'm probably missing something stupid. Here's a snip from my .conf:

nxlog.conf

答:
You should be able to test the XML query in event viewer. It's exactly the same there which you can copy-paste into your nxlog.conf.

If you are not getting filtered events it's either because you did not restart NXLog or still old events are showing up in Graylog.


问:
move instruction from eax to es register gives error
i cant figure out a way to move code from one location to other in memory

so i put in a way some thing like this but it doesn't work

```<code>extern _transfer_code_segment

 extern _kernel_segment

  extern _kernel_reloc

 extern _kernel_reloc_segment

  extern _kernel_para_size

    section .text16

    global transfer_to_kernel

transfer_to_kernel:

    ;cld

    ;
    ; Turn off interrupts -- the stack gets destroyed during this routine.
    ; kernel must set up its own stack.
    ;
    ;cli
    ; stack for only for this function

    push ebp
    mov ebp, esp

    mov eax, _kernel_segment             ; source segment
    mov ebx, _kernel_reloc_segment       ; dest segment
    mov ecx, _kernel_para_size

.loop:

    ; XXX: Will changing the segment registers this many times have
    ; acceptable performance?

    mov ds, eax  ;this the place where the error
    mov es, ebx  ; this to
    xor esi, esi
    xor edi, edi
    movsd
    movsd
    movsd
    movsd
    inc eax
    inc ebx
    dec ecx
    jnz .loop

    leave
    ret
</code>```

do have any other way to do it or how can i solve this problem

答:
That will have horrible performance.  Agner Fog says mov sr, r has one per 13 cycle throughput on Nehalem, and I'd guess that if anything it's worse on more recent CPUs since segmentation is obsolete.  Agner stopped testing mov to/from segment register performance after Nehalem.

Are you doing this to let you copy more than 64kiB total?  If so, at least copy a full 64kiB before changing a segment register.

I think you can use 32-bit addressing modes to avoid messing with segments, but segments that you set in 16-bit mode implicitly have a "limit" of 64k.  (i.e. mov eax, [esi] is encodable in 16-bit mode, with an operand-size and address-size prefix.  But with a value in esi of more than 0xFFFF, I think it would fault for violating the ds segment limit.)  The the osdev link below for more.

As Cody says, use rep movsd to let the CPU use an optimized microcoded memcpy.  (or rep movsb, but only on CPUs with the ERMSB feature.
In practice, most CPUs that support ERMSB give the same performance benefit for rep movsd too, so it's probably easiest to just always use rep movsd.  But IvyBridge might not.)  It's much faster than separate movsd instructions (which are slower than separate mov loads/stores).  A loop with SSE 16B vector loads/stores might go almost as fast as rep movsd on some CPUs, but you can't use AVX for 32B vectors in 16-bit mode.

Another option for big copies: huge unreal mode

In 32-bit protected mode, the values you put in segments are descriptors, not the actual segment base itself. mov es, ax triggers the CPU to use the value as an index into the GDT or LDT and get the segment base / limit from there.

If you do this in 32-bit mode and then switch back to 16-bit mode, you're in huge unreal mode with segments that can be larger than 64k.  The segment base/limit/permissions stay cached until something writes a segment register in 16-bit mode and puts it back to the usual 16*seg with a 64k limit.  (If I'm describing this correctly).  See http://wiki.osdev.org/Unreal_Mode for more.

Then you may be able to use rep movsd in 16-bit mode with operand-size and address-size prefixes so you can copy more than 64kiB in one go.

This works well for ds and es, but interrupts will set cs:ip, so this isn't convenient for big flat code address space, just data.

Body:
i cant figure out a way to move code from one location to other in memory

so i put in a way some thing like this but it doesn't work

extern _transfer_code_segment

 extern _kernel_segment

  extern _kernel_reloc

 extern _kernel_reloc_segment

  extern _kernel_para_size

    section .text16

    global transfer_to_kernel

transfer_to_kernel:

    ;cld

    ;
    ; Turn off interrupts -- the stack gets destroyed during this routine.
    ; kernel must set up its own stack.
    ;
    ;cli
    ; stack for only for this function

    push ebp
    mov ebp, esp

    mov eax, _kernel_segment             ; source segment
    mov ebx, _kernel_reloc_segment       ; dest segment
    mov ecx, _kernel_para_size

.loop:

    ; XXX: Will changing the segment registers this many times have
    ; acceptable performance?

    mov ds, eax  ;this the place where the error
    mov es, ebx  ; this to
    xor esi, esi
    xor edi, edi
    movsd
    movsd
    movsd
    movsd
    inc eax
    inc ebx
    dec ecx
    jnz .loop

    leave
    ret

do have any other way to do it or how can i solve this problem


问:
splitting a drill file using regex
i have a file here is it's dump

```<code>T01
X064900Y049200
X065900
X066900
X067900
X068900
X069900
T02
X062900Y048200
Y049200
Y050200
Y053700
X063900
X064900
X065900
X046350
</code>```

I wan to split it's contents   by T*   "T* must be included" by using
Java regex
   here what i did i read file contents into string parts
then String [] tools = parts.split("T\\d+");

but it didn't work, what is the best regex to use .

答:
Split at the letter "T".  The newline keeps the first line from being split.</p>

```<code>String[] tools=parts.split("\n(?=T)");
</code>```

Title: splitting a drill file using regex

Body:
i have a file here is it's dump

T01
X064900Y049200
X065900
X066900
X067900
X068900
X069900
T02
X062900Y048200
Y049200
Y050200
Y053700
X063900
X064900
X065900
X046350

I wan to split it's contents   by T*   "T* must be included" by using
Java regex
   here what i did i read file contents into string parts
then String [] tools = parts.split("T\\d+");

but it didn't work, what is the best regex to use .

Body:
Split at the letter "T".  The newline keeps the first line from being split.

String[] tools=parts.split("\n(?=T)");


问:
How does a `select (. == ["a","b"][])` predicate work in JQ?
I'm looking for ways to select JSON entries based on an array that I provide as a literal:

```<code>$ echo '["a","b","c","d"]' | jq '.[] | select (. == ["a","b"][] )'
"a"
"b"
</code>```

In the code above, all entries are selected that are in the ["a","b"] array. However, I don't understand how the . == ["a","b"][] predicate works in detail and would be grateful for an explanation. The tricky part is the right-hand side of ==.

Related:

jq - How to select objects based on a 'whitelist' of property values

答:
The key to understanding here is that jq is stream-oriented.  ["a","b"][] produces a stream, ergo . == ["a","b"][] produces a stream.  select selects the items that produce truthy values in that stream.

To gain an understanding of how jq works, it often helps to pull things apart.  In the present case, you could begin by trying:

```<code>echo '["a","b","c","d"]' | jq '.[] | (. == ["a","b"][])'
</code>```

debug is also helpful, e.g.

```<code>echo '["a","b","c","d"]' | jq '.[] | select(debug == ["a","b"][])'
</code>```

Body:
I'm looking for ways to select JSON entries based on an array that I provide as a literal:

$ echo '["a","b","c","d"]' | jq '.[] | select (. == ["a","b"][] )'
"a"
"b"

In the code above, all entries are selected that are in the ["a","b"] array. However, I don't understand how the . == ["a","b"][] predicate works in detail and would be grateful for an explanation. The tricky part is the right-hand side of ==.

Related:

jq - How to select objects based on a 'whitelist' of property values

Body:
The key to understanding here is that jq is stream-oriented.  ["a","b"][] produces a stream, ergo . == ["a","b"][] produces a stream.  select selects the items that produce truthy values in that stream.

To gain an understanding of how jq works, it often helps to pull things apart.  In the present case, you could begin by trying:

echo '["a","b","c","d"]' | jq '.[] | (. == ["a","b"][])'

debug is also helpful, e.g.

echo '["a","b","c","d"]' | jq '.[] | select(debug == ["a","b"][])'


问:
No plugin found for prefix 'jetty' in the current project
I have added jetty mvn plugin code in my project pom.xml.

<plugin>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>maven-jetty-plugin</artifactId>
  <version>6.1.26</version>
  <configuration>
    <contextPath>/redkites</contextPath>
  </configuration>
  <executions>
    <execution>
      <id>start-jetty</id>
      <phase>deploy</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
        <scanIntervalSeconds>10</scanIntervalSeconds>
        <daemon>true</daemon>
      </configuration>
    </execution>
  </executions>
</plugin>
```

<p>When I use commands <code>sudo mvn compile</code> and <code>sudo mvn clean install</code>, I didn't find any errors & build successfully, but when I type the command <code>sudo mvn jetty:run</code>, I'm getting an error:</p>

```[ERROR] No plugin found for prefix 'jetty' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/root/.m2/repository), central (http://repo.maven.apache.org/maven2)] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException
```

Please suggest a way to solve it. Thank you

答: I was running the command in the directory in which the project was present but the command worked fine after switching to the one directory up i.e in one in which all the files of the project were present.</p>

Body:
I have added jetty mvn plugin code in my project pom.xml.

<plugin>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>maven-jetty-plugin</artifactId>
  <version>6.1.26</version>
  <configuration>
    <contextPath>/redkites</contextPath>
  </configuration>
  <executions>
    <execution>
      <id>start-jetty</id>
      <phase>deploy</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
        <scanIntervalSeconds>10</scanIntervalSeconds>
        <daemon>true</daemon>
      </configuration>
    </execution>
  </executions>
</plugin>

When I use commands sudo mvn compile and sudo mvn clean install, I didn't find any errors & build successfully, but when I type the command sudo mvn jetty:run, I'm getting an error:

[ERROR] No plugin found for prefix 'jetty' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/root/.m2/repository), central (http://repo.maven.apache.org/maven2)] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException

Please suggest a way to solve it. Thank you


问:
Drawing tables in terminal using ANSI box characters
I'm trying to print a table that's more pleasant to the eye than the pure text representation of it. basically I want to convert something like this:

```<code>+-----+--------+
| age | weight |
+-----+--------+
| 10  | 100    |
| 80  | 500    |
+-----+--------+
</code>```

to something like this:

```<code>┌─────┬────────┐
| age | weight |
├─────┼────────┤
│ 10  │   100  │
│ 80  │  500   │
└─────┴────────┘
</code>```

here is the screenshot of what I see in terminal:

Notice the gaps between the rows. My problem is that they are not connecting properly while other Unix tools that use ANSI printing look fine in terminal. For example, tree, if I run tree -A in my terminal `I get this:

notice how vertical lines are connected together. it's funny because when I copy and paste the output of tree into my text editor and run my script I get something like this:

Obviously I'm missing something about printing ANSI chars in terminal and couldn't find anything about it by googling it. can anyone shed some light on this topic?

答:
I guess I should answer my own question. After a little research and the help of friend and boss ,Linus, I found that I need to force the terminal to go to graphical mode first, then print the special characters and then return back to text mode. the ascii code for switching to graphical mode is 14 and 15 will return back to text mode. so here is the code in ruby: </p>

```<code>printf("%c\n", 14)
printf("%c ", 0x6A) # ┘
printf("%c ", 0x6B) # ┐
printf("%c ", 0x6C) # ┌
printf("%c ", 0x6D) # └
printf("%c ", 0x6E) # ┼
printf("%c ", 0x71) # ─
printf("%c ", 0x74) # ├
printf("%c ", 0x75) # ┤
printf("%c ", 0x76) # ┴
printf("%c ", 0x77) # ┬
printf("%c\n", 0x78) # │

a = sprintf("%c", 0x6C) + # ┌
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c\n", 0x6B) +  # ┐
sprintf("%c", 0x78) + # │
#print("      ")
"      " +
sprintf("%c\n", 0x78) + # │
sprintf("%c", 0x6D) + # └
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x6A)  # ┘

puts a

printf("%c\n", 15)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to print a table that's more pleasant to the eye than the pure text representation of it. basically I want to convert something like this:

+-----+--------+
| age | weight |
+-----+--------+
| 10  | 100    |
| 80  | 500    |
+-----+--------+

to something like this:

┌─────┬────────┐
| age | weight |
├─────┼────────┤
│ 10  │   100  │
│ 80  │  500   │
└─────┴────────┘

here is the screenshot of what I see in terminal:

Notice the gaps between the rows. My problem is that they are not connecting properly while other Unix tools that use ANSI printing look fine in terminal. For example, tree, if I run tree -A in my terminal `I get this:

notice how vertical lines are connected together. it's funny because when I copy and paste the output of tree into my text editor and run my script I get something like this:

Obviously I'm missing something about printing ANSI chars in terminal and couldn't find anything about it by googling it. can anyone shed some light on this topic?

Body:
I guess I should answer my own question. After a little research and the help of friend and boss ,Linus, I found that I need to force the terminal to go to graphical mode first, then print the special characters and then return back to text mode. the ascii code for switching to graphical mode is 14 and 15 will return back to text mode. so here is the code in ruby:

printf("%c\n", 14)
printf("%c ", 0x6A) # ┘
printf("%c ", 0x6B) # ┐
printf("%c ", 0x6C) # ┌
printf("%c ", 0x6D) # └
printf("%c ", 0x6E) # ┼
printf("%c ", 0x71) # ─
printf("%c ", 0x74) # ├
printf("%c ", 0x75) # ┤
printf("%c ", 0x76) # ┴
printf("%c ", 0x77) # ┬
printf("%c\n", 0x78) # │

a = sprintf("%c", 0x6C) + # ┌
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c\n", 0x6B) +  # ┐
sprintf("%c", 0x78) + # │
#print("      ")
"      " +
sprintf("%c\n", 0x78) + # │
sprintf("%c", 0x6D) + # └
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x6A)  # ┘

puts a

printf("%c\n", 15)


问:
How do I Create a CloudWatch Email Alert With Custom Content?
I am trying to edit an AWS CloudWatch alert that sends an email to my team such that custom content is sent in the email. Currently, all email alerts contain only auto-generated content. The email content contains the reason for the alert, a link to the alarm in the AWS console, and sections for Alarm Details, Threshold, and Monitored Metric. However, I want to add custom content listing likely causes of the alert and procedures to execute when receiving the alert. Does anybody know how custom content can be added to a CloudWatch alert email?

I have read existing AWS CloudWatch Alarm documentation such as How to Create/Edit a CloudWatch Alarm, and How to create a CPU Usage Alarm that Sends an Email. I have also tried various Google searches and searches for existing questions here on SO but to no avail. Any help/advice would be greatly appreciated.

答: You can setup a Lambda trigger to the alarm and send an email using AWS SES SMTP credentials, creating a formatted email content with alarm trigger event data.</p>


问:
VBA to flatten a file
I'm looking for vba code to clean up excel files with grouped data.

With many clients, many different accounts, many different details.

100's of files, needs to be done as needed for creating reporting.

I have data that looks like this:

```<code>#client A#
##Account number | Account Type#
##many rows of details##
###Ticker | Quantity | Value#
###many rows of details###
</code>```

I need this:

client | account number | Account Type | Ticker | Quantity | Value

I have some code that almost works but have read that it's not best practice, so rather than try to figure out how to make it work thought I'd ask for help.

Here's what I have:

```<code>Sub crk()

Dim inv As Long, name As Long, tipe As Long
Dim assname As Long, ticker As Long, broad As Long
Dim assid As Long, value As Long
Dim i As Long, j As Long, clname As Long

inv = 2
name = 2
acno = 2
tipe = 2
assname = 2
ticker = 2
broad = 2
assid = 2
value = 2
clname = 2

For i = 1 To 50

    For j = 1 To 9
        Sheets("by-investor-raw").Select
        x = Cells(i, j).value
        If x = "Acct Name" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(name, 2).Select
            ActiveSheet.Paste
            name = name + 1

        ElseIf x = "Acct No" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(acno, 3).Select
            ActiveSheet.Paste
            acno = acno + 1

        ElseIf x = "Acct Type" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(tipe, 4).Select
            ActiveSheet.Paste
            tipe = tipe + 1

        ElseIf x = "Asset Name" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(assname, 5).Select
            ActiveSheet.Paste
            assname = assname + 1

        ElseIf x = "Ticker" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(ticker, 6).Select
            ActiveSheet.Paste
            ticker = ticker + 1

        ElseIf x = "Broad" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(broad, 7).Select
            ActiveSheet.Paste
            broad = broad + 1

        ElseIf x = "Asset ID" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(assid, 8).Select
            ActiveSheet.Paste
            assid = assid + 1

        ElseIf x = "Value" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(value, 9).Select
            ActiveSheet.Paste
            value = value + 1

        ElseIf x = "Investor" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(assid, 1).Select
            ActiveSheet.Paste

        ElseIf x = "Investor's Name" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(clname, 10).Select
            TargetSheet.Paste
            ActiveSheet.Paste
            clname = clname + 1

        End If
Next j
Next i
Sheets("portfolio-clean").Select
End Sub
</code>```

This code is throwing a Runtime 1004 error at Cells(clname, 10).Select

Thanks for any help

答:
Try this, also the variable acno was not defined, as well as x.     </p>

```<code>Option Explicit

Sub crk()

Dim inv As Long, name As Long, tipe As Long
Dim assname As Long, ticker As Long, broad As Long
Dim assid As Long, value As Long
Dim i As Long, j As Long, clname As Long
Dim acno, x

inv = 2
name = 2
acno = 2
tipe = 2
assname = 2
ticker = 2
broad = 2
assid = 2
value = 2
clname = 2

For i = 1 To 50

    For j = 1 To 9
        x = Cells(i, j).value
        If x = "Acct Name" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(name, 2)
            name = name + 1
        ElseIf x = "Acct No" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(acno, 3)
            acno = acno + 1

        ElseIf x = "Acct Type" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(tipe, 4)
            tipe = tipe + 1

        ElseIf x = "Asset Name" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(assname, 5)
            assname = assname + 1

        ElseIf x = "Ticker" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(ticker, 6)
            ticker = ticker + 1

        ElseIf x = "Broad" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(broad, 7)
            broad = broad + 1

        ElseIf x = "Asset ID" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(assid, 8)
            assid = assid + 1

        ElseIf x = "Value" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(value, 9)
            value = value + 1

        ElseIf x = "Investor" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(assid, 1)

        ElseIf x = "Investor's Name" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(clname, 10)
            clname = clname + 1

        End If
Next j
Next i
Sheets("portfolio-clean").Select
End Sub
</code>```

Title: VBA to flatten a file

Body:
I'm looking for vba code to clean up excel files with grouped data.

With many clients, many different accounts, many different details.

100's of files, needs to be done as needed for creating reporting.

I have data that looks like this:

#client A#
##Account number | Account Type#
##many rows of details##
###Ticker | Quantity | Value#
###many rows of details###

I need this:

client | account number | Account Type | Ticker | Quantity | Value

I have some code that almost works but have read that it's not best practice, so rather than try to figure out how to make it work thought I'd ask for help.

Here's what I have:

Sub crk()

Dim inv As Long, name As Long, tipe As Long
Dim assname As Long, ticker As Long, broad As Long
Dim assid As Long, value As Long
Dim i As Long, j As Long, clname As Long

inv = 2
name = 2
acno = 2
tipe = 2
assname = 2
ticker = 2
broad = 2
assid = 2
value = 2
clname = 2

For i = 1 To 50

    For j = 1 To 9
        Sheets("by-investor-raw").Select
        x = Cells(i, j).value
        If x = "Acct Name" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(name, 2).Select
            ActiveSheet.Paste
            name = name + 1

        ElseIf x = "Acct No" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(acno, 3).Select
            ActiveSheet.Paste
            acno = acno + 1

        ElseIf x = "Acct Type" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(tipe, 4).Select
            ActiveSheet.Paste
            tipe = tipe + 1

        ElseIf x = "Asset Name" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(assname, 5).Select
            ActiveSheet.Paste
            assname = assname + 1

        ElseIf x = "Ticker" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(ticker, 6).Select
            ActiveSheet.Paste
            ticker = ticker + 1

        ElseIf x = "Broad" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(broad, 7).Select
            ActiveSheet.Paste
            broad = broad + 1

        ElseIf x = "Asset ID" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(assid, 8).Select
            ActiveSheet.Paste
            assid = assid + 1

        ElseIf x = "Value" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(value, 9).Select
            ActiveSheet.Paste
            value = value + 1

        ElseIf x = "Investor" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(assid, 1).Select
            ActiveSheet.Paste

        ElseIf x = "Investor's Name" Then
            Cells(i + 1, j).Select
            Selection.Copy
            Sheets("portfolio-clean").Select
            Cells(clname, 10).Select
            TargetSheet.Paste
            ActiveSheet.Paste
            clname = clname + 1

        End If
Next j
Next i
Sheets("portfolio-clean").Select
End Sub

This code is throwing a Runtime 1004 error at Cells(clname, 10).Select

Thanks for any help

Body:
Try this, also the variable acno was not defined, as well as x.

Option Explicit

Sub crk()

Dim inv As Long, name As Long, tipe As Long
Dim assname As Long, ticker As Long, broad As Long
Dim assid As Long, value As Long
Dim i As Long, j As Long, clname As Long
Dim acno, x

inv = 2
name = 2
acno = 2
tipe = 2
assname = 2
ticker = 2
broad = 2
assid = 2
value = 2
clname = 2

For i = 1 To 50

    For j = 1 To 9
        x = Cells(i, j).value
        If x = "Acct Name" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(name, 2)
            name = name + 1
        ElseIf x = "Acct No" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(acno, 3)
            acno = acno + 1

        ElseIf x = "Acct Type" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(tipe, 4)
            tipe = tipe + 1

        ElseIf x = "Asset Name" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(assname, 5)
            assname = assname + 1

        ElseIf x = "Ticker" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(ticker, 6)
            ticker = ticker + 1

        ElseIf x = "Broad" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(broad, 7)
            broad = broad + 1

        ElseIf x = "Asset ID" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(assid, 8)
            assid = assid + 1

        ElseIf x = "Value" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(value, 9)
            value = value + 1

        ElseIf x = "Investor" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(assid, 1)

        ElseIf x = "Investor's Name" Then
            Sheets("by-investor-raw").Cells(i + 1, j).Copy Destination:=Sheets("portfolio-clean").Cells(clname, 10)
            clname = clname + 1

        End If
Next j
Next i
Sheets("portfolio-clean").Select
End Sub


问:
Export to *.txt with specific Font
I need to export from sql server to *.txt. But i want my export to be with specific Font.Example I need my txt file to have Terminal Font.

Here is my code:

```<code>SqlCommand cmd = new SqlCommand("Select Code,Name,Price", con);
SqlDataReader read = cmd.ExecuteReader();
using (StreamWriter sw = new StreamWriter("C://test.txt")) {

while (read.Read())
{
    //Code
    string CodeString = (read["Code"].ToString());
    sw.Write(CodeString);

    //Name
    string NameString = (read["Name"].ToString());
    sw.Write(NameString);

    //Price
    string PriceString = (read["Price"].ToString());
    sw.Write(PriceString);
}

sw.Close();
read.Close();
</code>```

答: .txt does not contain any formatting. If you want to format your documents, you'll have to use another file format. </p>

Title: Export to *.txt with specific Font

Body:
I need to export from sql server to *.txt. But i want my export to be with specific Font.Example I need my txt file to have Terminal Font.

Here is my code:

SqlCommand cmd = new SqlCommand("Select Code,Name,Price", con);
SqlDataReader read = cmd.ExecuteReader();
using (StreamWriter sw = new StreamWriter("C://test.txt")) {

while (read.Read())
{
    //Code
    string CodeString = (read["Code"].ToString());
    sw.Write(CodeString);

    //Name
    string NameString = (read["Name"].ToString());
    sw.Write(NameString);

    //Price
    string PriceString = (read["Price"].ToString());
    sw.Write(PriceString);
}

sw.Close();
read.Close();


问:
How can I limit a TextView's size without using 'maxwidth'?
I've been trying to create a layout for a RecyclerView item, but I'm, having trouble getting there. I'll try my best to explain what I want and what I've gotten so far.
My design has a Button, a TextView, a couple of ImageViews and a LinearLayout with some ImageViews inside it. The image below explains it well.

The gray elements have fixed width and position (the button to the left and the LL with ivs to the right).

The green and red ivs have fixed width but should be positioned to the right of the blue tv, UNLESS the blue tv is too big and tries to push them on top of the gray LL to the right. In that case, the text is cut short and an ellipsis is added at the end.

The green and red ivs may or may not be visible (visibility="true" or "gone"). The blue tv should occupy their spaces if they're "gone" (and if there's enough text content in it to do so).

I've gotten sort of close to what I want: the blue tv and the red and green ivs are inside a LinearLayout with a gravity=left attribute. The blue tv has the ellipsis=end attribute. The one thing that's still wrong is the blue tv has to have a maxwidth attribute so it does not push the green/red ivs over the gray LinearLayout to the right. So, when the red or green ivs are "gone", there's an empty space to the right (before the gray LinearLayout) since the blue tv's maxwidth limits it.

Is there a way to achieve this? How can I eliminate the maxwidth attribute and still prevent the textview content from pushing the green and red ivs too far to the right and overruning the gray LinearLayout?

I don't have any experience with ConstraintLayout (and am a beginner in android development). Is there a way to achieve this using it?

Here's the code I have so far.

```<code><LinearLayout
    android:id="@+id/leiaute"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <Button
        android:id="@+id/quad_done_undone"
        android:layout_width="17.6dp"
        android:layout_height="16dp"
        android:layout_marginLeft="14dp"
        android:src="@drawable/circulo_unchecked"/>

    <LinearLayout
        android:id="@+id/itemClickableArea"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:gravity="left|center_vertical"
        android:orientation="horizontal"
        android:background="?attr/selectableItemBackground">

        <TextView
            android:id="@+id/titulo"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:ellipsize="end"
            android:fontFamily="sans-serif"
            android:gravity="left|center_vertical"
            android:maxLines="1"
            android:maxWidth="210dp"
            android:text="Lorem Ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
            android:textColor="@color/preto"
            android:textSize="13sp"
            android:visibility="visible"/>

        <ImageButton
            android:id="@+id/descricao"
            android:layout_width="16dp"
            android:layout_height="13.5dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="1dp"
            android:background="@drawable/description_icon"/>

        <ImageView
            android:id="@+id/play"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:src="@drawable/play"
            android:tint="@color/cinza3"
            android:visibility="visible"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="36dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dp"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/data_hora"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:fontFamily="sans-serif"
            android:gravity="center"
            android:maxLines="2"
            android:textColor="@color/textList"
            android:textSize="12sp"
            tools:text="31 mar\n9:42"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/repeat"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginRight="2dp"
                android:src="@drawable/repeat"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/locale"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:src="@drawable/locale"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/alarm"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginLeft="2dp"
                android:src="@drawable/alarm"
                android:tint="@color/iconesList"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</code>```

答:
What you want to do can be handled easily by TableLayout and TableRow. See the following XML for a sample layout. The key to the layout is to set the TextView that holds the long text to shrink as needed android:shrinkColumns="1" and to add a Space view that will grow to fill up extra space so the LinearLayout on the right doesn't shift to the left when the TextView shrinks.

This video shows what happens as the content of the TextView changes and the other views are set to gone.

```<code><?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <!-- TableLayout is needed to specify shrinkColumns. Ignore "Useless parent" error. -->
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="UselessParent">

        <Button
            android:layout_width="80dp"
            android:layout_height="45dp"
            android:text="Button"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:background="@android:color/holo_blue_dark"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:maxLines="1"
            android:paddingEnd="8dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingStart="8dp"
            android:scrollHorizontally="true"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, etc."
            android:textSize="20sp"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/imageView1"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:background="@android:color/holo_green_light"
            android:gravity="center"
            android:text="iv"
            android:textSize="20sp"
            android:visibility="visible"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/imageView2"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:background="@android:color/holo_red_dark"
            android:gravity="center"
            android:textSize="20sp"
            android:visibility="visible"
            tools:text="iv" />
<!-- Space to expand/shrink so TableRow is always width of the screen. -->
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/transparent" />

        <LinearLayout
            android:layout_width="60dp"
            android:layout_height="45dp"
            android:background="@android:color/darker_gray"
            android:orientation="horizontal" />
    </TableRow>
</TableLayout>
</code>```

Body:
I've been trying to create a layout for a RecyclerView item, but I'm, having trouble getting there. I'll try my best to explain what I want and what I've gotten so far.
My design has a Button, a TextView, a couple of ImageViews and a LinearLayout with some ImageViews inside it. The image below explains it well.

The gray elements have fixed width and position (the button to the left and the LL with ivs to the right).

The green and red ivs have fixed width but should be positioned to the right of the blue tv, UNLESS the blue tv is too big and tries to push them on top of the gray LL to the right. In that case, the text is cut short and an ellipsis is added at the end.

The green and red ivs may or may not be visible (visibility="true" or "gone"). The blue tv should occupy their spaces if they're "gone" (and if there's enough text content in it to do so).

I've gotten sort of close to what I want: the blue tv and the red and green ivs are inside a LinearLayout with a gravity=left attribute. The blue tv has the ellipsis=end attribute. The one thing that's still wrong is the blue tv has to have a maxwidth attribute so it does not push the green/red ivs over the gray LinearLayout to the right. So, when the red or green ivs are "gone", there's an empty space to the right (before the gray LinearLayout) since the blue tv's maxwidth limits it.

Is there a way to achieve this? How can I eliminate the maxwidth attribute and still prevent the textview content from pushing the green and red ivs too far to the right and overruning the gray LinearLayout?

I don't have any experience with ConstraintLayout (and am a beginner in android development). Is there a way to achieve this using it?

Here's the code I have so far.

<LinearLayout
    android:id="@+id/leiaute"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <Button
        android:id="@+id/quad_done_undone"
        android:layout_width="17.6dp"
        android:layout_height="16dp"
        android:layout_marginLeft="14dp"
        android:src="@drawable/circulo_unchecked"/>

    <LinearLayout
        android:id="@+id/itemClickableArea"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:gravity="left|center_vertical"
        android:orientation="horizontal"
        android:background="?attr/selectableItemBackground">

        <TextView
            android:id="@+id/titulo"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:ellipsize="end"
            android:fontFamily="sans-serif"
            android:gravity="left|center_vertical"
            android:maxLines="1"
            android:maxWidth="210dp"
            android:text="Lorem Ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
            android:textColor="@color/preto"
            android:textSize="13sp"
            android:visibility="visible"/>

        <ImageButton
            android:id="@+id/descricao"
            android:layout_width="16dp"
            android:layout_height="13.5dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="1dp"
            android:background="@drawable/description_icon"/>

        <ImageView
            android:id="@+id/play"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:src="@drawable/play"
            android:tint="@color/cinza3"
            android:visibility="visible"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="36dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dp"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/data_hora"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:fontFamily="sans-serif"
            android:gravity="center"
            android:maxLines="2"
            android:textColor="@color/textList"
            android:textSize="12sp"
            tools:text="31 mar\n9:42"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/repeat"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginRight="2dp"
                android:src="@drawable/repeat"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/locale"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:src="@drawable/locale"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/alarm"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginLeft="2dp"
                android:src="@drawable/alarm"
                android:tint="@color/iconesList"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Body:
What you want to do can be handled easily by TableLayout and TableRow. See the following XML for a sample layout. The key to the layout is to set the TextView that holds the long text to shrink as needed android:shrinkColumns="1" and to add a Space view that will grow to fill up extra space so the LinearLayout on the right doesn't shift to the left when the TextView shrinks.

This video shows what happens as the content of the TextView changes and the other views are set to gone.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <!-- TableLayout is needed to specify shrinkColumns. Ignore "Useless parent" error. -->
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="UselessParent">

        <Button
            android:layout_width="80dp"
            android:layout_height="45dp"
            android:text="Button"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:background="@android:color/holo_blue_dark"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:maxLines="1"
            android:paddingEnd="8dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingStart="8dp"
            android:scrollHorizontally="true"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, etc."
            android:textSize="20sp"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/imageView1"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:background="@android:color/holo_green_light"
            android:gravity="center"
            android:text="iv"
            android:textSize="20sp"
            android:visibility="visible"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/imageView2"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:background="@android:color/holo_red_dark"
            android:gravity="center"
            android:textSize="20sp"
            android:visibility="visible"
            tools:text="iv" />
<!-- Space to expand/shrink so TableRow is always width of the screen. -->
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/transparent" />

        <LinearLayout
            android:layout_width="60dp"
            android:layout_height="45dp"
            android:background="@android:color/darker_gray"
            android:orientation="horizontal" />
    </TableRow>
</TableLayout>


问:
jQuery beginner - need assistance with .each() in terms of looping through *selective* input fields
My experience lies mostly with backend coding, PHP mostly. I am having some trouble understanding how to properly loop through an array of input fields ids using jQuery. I have seen Previous Posts on Stackoverflow very similar to my own, but just different enough to cause myself some head ache. I am sure this will be a whiz for a seasoned jQuery coder.

Keep in mind that I am a relative beginner in terms of jQuery and JS.
* I am familiar with validated.js and jquery.validate.js, I am trying to learn more about jQuery and not interested in additional plugins at this time.

What I am trying to do:
I am trying to take input fields from a sign up form and assign varying degrees of thresholds in terms of character length, as well as some other switch style tricks within the form fields. I am able to accomplish what I want with one field, however, I want to loop through these fields and dynamically grab ID's due to their placements within arrays.

So for example. I have my input fields along with "character length" span tag to hold the .length() values of each input as well as an error div I can push err statements into using .text() or .html().

```<code><h4>First name: <span id="ufnLenDis" class="lngthDisplay"><!--displays .length()--></span></h4>
<div id="err_usr_first_name"><!--displays errMSG--></div>
<div class="input-group col-sm-12">
  <input type="text" id="usr_first_name" class="form-control" placeholder="First Name">
</div>
</code>```

(UPDATE:) Using jQuery, I want to classify certain input fields ID's as variables or object arrays. Like validation thresholds. Several input fields may have a max of 1 and a limit of 60 characters, where others have max of 8 and limits of 30 characters. Specific restrictions and/rules for different functions and variable groups that apply to certain fields but not all. So I create a variable and add these like id fields to run through a loop.

Really the rules are ancillary but I wanted to outline my objective with regard to one of these functions.

So here is my desired output in a single form entry.
*I am using bootstrap and latest jquery plugins along with animated.css/js.
*Character input threshold = 2 - 60

Length is === 0 remove all "bootstrap" alerts and any input related output statements in all relative tags.

length is === 1

add bootstrap alert alert-info and remove all other alert related classes

output character length in span tag held within header tag of input div also add class to change color to correlate with alert proper alert color

output alert message in error div in proper alert config

Length is > 1 or < 59

Add alert-success, remove all other alert classes

Add and remove relative classes to and from the other relative tags.

inform customer they are about to reach the limit of the character threshold.

Length is === 59 - reset alerts from possible over count

Add alert-success, remove all other alert classes

Add and remove relative classes to and from the other relative tags.

Length is === 60

Add alert-warning classes and remove other alert classes from the tags

Add animated shake to bring attention to the field input.

Inform customer they have reached the limit of allowable characters in err field.

Length > 60

add attr.("disabled") and place alert-danger in all relative tags classes.

Here is a working jfiddle of what I want to do:

Jfiddle of single input field working

Again, this is one single input field, I want to take some code like the following and loop it through .each() and use the key/value pairs to construct the validation of multiple form fields coming from the same form, but some fields will not be run through the function.

Here is a jfiddle of what I have tried with the .each() function.

Multiple input entries not working

I am really just looking for some assistance with getting the jQuery loop properly constructed using a variable that identifies the ID's of the input fields I want to run through a particular function that adds specific thresholds.

My code is located in each jfiddle. The first Jfiddle link is the working example of the field as I want it to perform. The second is my attempt at looping the function to apply the rules to multiple ids coming from the form.

Here is the raw code with out CDN extensions.
The following code snipit is working for my needs with one single input field at a time.
However anytime I try to add an .each loop using examples I have seen, it breaks my code. I tried adding the following line and using the key/value pairs as substitutions for any val() call outs within the function. $.each([ "#usr_first_name", "#usr_last_name", "#usr_company_name", "usr_city_name"], function( index, value ) {, then use the index/value pairs to construct the function by replacing any call outs for the values within each() function. See my linked "non-working" jfiddle for an example.

Non working example of multiple fields

working example of single field (code below)

```<code>var input = $('#proper_config');
$('#lenDis').text(input.val().length);
input.bind('keydown, keyup', function(e) {
  var spart = input.val().split(" ");
  for (var i = 0; i < spart.length; i++) {
     var j = spart[i].charAt(0).toUpperCase();
     spart[i] = j + spart[i].substr(1);
  }
$(this).val(spart.join(" "));
$('#lenDis').html("Character count: " + input.val().length).addClass("danger").removeClass("warning success info");
if (input.val().length === 0) {
  input.removeClass("alert-info alert-success alert-warning alert-danger");
  $('#lenDis').removeClass().addClass("hidden");
  $('#err').empty();
} else if (input.val().length === 1) {
  input.addClass("alert alert-info");
  $('#lenDis').addClass("info").removeClass("danger success warning hidden");
  $('#submitBTN').removeAttr('disabled');
  $('#err').empty().html("Input field must have 2 or more characters and no more than 60 characters.");
} else if (input.val().length >= 2 && input.val().length < 59) {
  input.removeClass("alert-info").addClass("alert alert-success");
  $('#lenDis').removeClass("danger info waring").addClass("success");
  $('#err').empty();
} else if (input.val().length === 59) {
  $('#lenDis').removeClass("warning info danger").addClass("success");
  input.removeClass("alert-warning alert-info alert-danger").addClass("alert alert-success");
  $('#submitBTN').removeAttr('disabled');
  $('#err').empty();
} else if (input.val().length === 60) {
  $('#err').removeClass().html("<small>You have reached the max amount of characters allowed for this field!<small>");
  $('#lenDis').addClass("warning");
  input.removeClass("alert-info alert-success alert-danger").addClass("alert alert-warning");
  $('#submitBTN').removeAttr('disabled');
} else if (input.val().length > 60) {
  $('#err').removeClass().empty().addClass("danger").html("You have exceeded the amount of characters allowed for this field!.");
  input.removeClass("alert-info alert-success alert-warning").addClass("alert alert-danger");
</code>```

Any assistance will be greatly appreciated!

答:
As given in your code documented in jsfiddle : https://jsfiddle.net/Lb19rcxy/3/, You've called several DOM ID elements like this:

```<code>var valLenSixty = ("#usr_first_name", "#usr_last_name", "#usr_company_name", "#usr_city");
</code>```

Thus, by the time you've attached / bind these elements by a certain event listener (e.g keyup and keydown), It cannot determine which DOM elements you've place it:

You can fix this issue by wrapping them in a single / double quotations like this:

```<code>var valLenSixty = $("#usr_first_name, #usr_last_name, #usr_company_name, #usr_city");
</code>```

Now for your case in using $.each, I don't think it would be necessary to use this since you've already called them in your variable valLenSixty beforehand.

You can call each of their values by using $(this).val() inside your event handler like this:

```<code>valLenSixty.bind('keydown, keyup', function(e) {
    console.log($(this).val());
});
</code>```

Then I notice you've assigned another variables:

```<code>var lenDis = ("#ufnLenDis", "#ulnLenDis", "#ucnLenDis", "#uccLenDis");
var errDis = ("#err_usr_first_name", "#err_usr_last_name",
</code>```

You can also simplify this by placing another attribute (e.g data_len_dis_id) for your input as well:

Example:

```<code><input type="text" id="usr_company_name" class="form-control" placeholder="Company Name" data_len_dis_id="ucnLenDis">
</code>```

From which you can call them like this: $(this).attr('data_len_dis_id');

```<code>var valLenSixty = $("#usr_first_name, #usr_last_name, #usr_company_name, #usr_city");

valLenSixty.bind('keydown, keyup', function(e) {
    console.log($(this).val());
    var spart = $(this).val().split(" ");
    for (var i = 0; i < spart.length; i++) {
        var j = spart[i].charAt(0).toUpperCase();
        spart[i] = j + spart[i].substr(1);
    }

    var sDataLenDisId = $(this).attr('data_len_dis_id'); // expected output: ucnLenDis
    var oSpanDisplay = $('.form_group').find('span#' + sDataLenDisId).html("Character count: " + $(this).val().length).addClass("danger").removeClass("warning success info");

    // Rest of your code
});
</code>```

Here's a revised js code for further reference:
https://jsfiddle.net/L07mvLqz/

Hope this helps for your case.

Body:
My experience lies mostly with backend coding, PHP mostly. I am having some trouble understanding how to properly loop through an array of input fields ids using jQuery. I have seen Previous Posts on Stackoverflow very similar to my own, but just different enough to cause myself some head ache. I am sure this will be a whiz for a seasoned jQuery coder.

Keep in mind that I am a relative beginner in terms of jQuery and JS.
* I am familiar with validated.js and jquery.validate.js, I am trying to learn more about jQuery and not interested in additional plugins at this time.

What I am trying to do:
I am trying to take input fields from a sign up form and assign varying degrees of thresholds in terms of character length, as well as some other switch style tricks within the form fields. I am able to accomplish what I want with one field, however, I want to loop through these fields and dynamically grab ID's due to their placements within arrays.

So for example. I have my input fields along with "character length" span tag to hold the .length() values of each input as well as an error div I can push err statements into using .text() or .html().

First name:

  <input type="text" id="usr_first_name" class="form-control" placeholder="First Name">

(UPDATE:) Using jQuery, I want to classify certain input fields ID's as variables or object arrays. Like validation thresholds. Several input fields may have a max of 1 and a limit of 60 characters, where others have max of 8 and limits of 30 characters. Specific restrictions and/rules for different functions and variable groups that apply to certain fields but not all. So I create a variable and add these like id fields to run through a loop.

Really the rules are ancillary but I wanted to outline my objective with regard to one of these functions.

So here is my desired output in a single form entry.
*I am using bootstrap and latest jquery plugins along with animated.css/js.
*Character input threshold = 2 - 60

Length is === 0 remove all "bootstrap" alerts and any input related output statements in all relative tags.

length is === 1

add bootstrap alert alert-info and remove all other alert related classes

output character length in span tag held within header tag of input div also add class to change color to correlate with alert proper alert color

output alert message in error div in proper alert config

Length is > 1 or < 59

Add alert-success, remove all other alert classes

Add and remove relative classes to and from the other relative tags.

inform customer they are about to reach the limit of the character threshold.

Length is === 59 - reset alerts from possible over count

Add alert-success, remove all other alert classes

Add and remove relative classes to and from the other relative tags.

Length is === 60

Add alert-warning classes and remove other alert classes from the tags

Add animated shake to bring attention to the field input.

Inform customer they have reached the limit of allowable characters in err field.

Length > 60

add attr.("disabled") and place alert-danger in all relative tags classes.

Here is a working jfiddle of what I want to do:

Jfiddle of single input field working

Again, this is one single input field, I want to take some code like the following and loop it through .each() and use the key/value pairs to construct the validation of multiple form fields coming from the same form, but some fields will not be run through the function.

Here is a jfiddle of what I have tried with the .each() function.

Multiple input entries not working

I am really just looking for some assistance with getting the jQuery loop properly constructed using a variable that identifies the ID's of the input fields I want to run through a particular function that adds specific thresholds.

My code is located in each jfiddle. The first Jfiddle link is the working example of the field as I want it to perform. The second is my attempt at looping the function to apply the rules to multiple ids coming from the form.

Here is the raw code with out CDN extensions.
The following code snipit is working for my needs with one single input field at a time.
However anytime I try to add an .each loop using examples I have seen, it breaks my code. I tried adding the following line and using the key/value pairs as substitutions for any val() call outs within the function. $.each([ "#usr_first_name", "#usr_last_name", "#usr_company_name", "usr_city_name"], function( index, value ) {, then use the index/value pairs to construct the function by replacing any call outs for the values within each() function. See my linked "non-working" jfiddle for an example.

Non working example of multiple fields

working example of single field (code below)

var input = $('#proper_config');
$('#lenDis').text(input.val().length);
input.bind('keydown, keyup', function(e) {
  var spart = input.val().split(" ");
  for (var i = 0; i < spart.length; i++) {
     var j = spart[i].charAt(0).toUpperCase();
     spart[i] = j + spart[i].substr(1);
  }
$(this).val(spart.join(" "));
$('#lenDis').html("Character count: " + input.val().length).addClass("danger").removeClass("warning success info");
if (input.val().length === 0) {
  input.removeClass("alert-info alert-success alert-warning alert-danger");
  $('#lenDis').removeClass().addClass("hidden");
  $('#err').empty();
} else if (input.val().length === 1) {
  input.addClass("alert alert-info");
  $('#lenDis').addClass("info").removeClass("danger success warning hidden");
  $('#submitBTN').removeAttr('disabled');
  $('#err').empty().html("Input field must have 2 or more characters and no more than 60 characters.");
} else if (input.val().length >= 2 && input.val().length < 59) {
  input.removeClass("alert-info").addClass("alert alert-success");
  $('#lenDis').removeClass("danger info waring").addClass("success");
  $('#err').empty();
} else if (input.val().length === 59) {
  $('#lenDis').removeClass("warning info danger").addClass("success");
  input.removeClass("alert-warning alert-info alert-danger").addClass("alert alert-success");
  $('#submitBTN').removeAttr('disabled');
  $('#err').empty();
} else if (input.val().length === 60) {
  $('#err').removeClass().html("You have reached the max amount of characters allowed for this field!");
  $('#lenDis').addClass("warning");
  input.removeClass("alert-info alert-success alert-danger").addClass("alert alert-warning");
  $('#submitBTN').removeAttr('disabled');
} else if (input.val().length > 60) {
  $('#err').removeClass().empty().addClass("danger").html("You have exceeded the amount of characters allowed for this field!.");
  input.removeClass("alert-info alert-success alert-warning").addClass("alert alert-danger");

Any assistance will be greatly appreciated!

Body:
As given in your code documented in jsfiddle : https://jsfiddle.net/Lb19rcxy/3/, You've called several DOM ID elements like this:

var valLenSixty = ("#usr_first_name", "#usr_last_name", "#usr_company_name", "#usr_city");

Thus, by the time you've attached / bind these elements by a certain event listener (e.g keyup and keydown), It cannot determine which DOM elements you've place it:

You can fix this issue by wrapping them in a single / double quotations like this:

var valLenSixty = $("#usr_first_name, #usr_last_name, #usr_company_name, #usr_city");

Now for your case in using $.each, I don't think it would be necessary to use this since you've already called them in your variable valLenSixty beforehand.

You can call each of their values by using $(this).val() inside your event handler like this:

valLenSixty.bind('keydown, keyup', function(e) {
    console.log($(this).val());
});

Then I notice you've assigned another variables:

var lenDis = ("#ufnLenDis", "#ulnLenDis", "#ucnLenDis", "#uccLenDis");
var errDis = ("#err_usr_first_name", "#err_usr_last_name",

You can also simplify this by placing another attribute (e.g data_len_dis_id) for your input as well:

Example:

<input type="text" id="usr_company_name" class="form-control" placeholder="Company Name" data_len_dis_id="ucnLenDis">

From which you can call them like this: $(this).attr('data_len_dis_id');

var valLenSixty = $("#usr_first_name, #usr_last_name, #usr_company_name, #usr_city");

valLenSixty.bind('keydown, keyup', function(e) {
    console.log($(this).val());
    var spart = $(this).val().split(" ");
    for (var i = 0; i < spart.length; i++) {
        var j = spart[i].charAt(0).toUpperCase();
        spart[i] = j + spart[i].substr(1);
    }

    var sDataLenDisId = $(this).attr('data_len_dis_id'); // expected output: ucnLenDis
    var oSpanDisplay = $('.form_group').find('span#' + sDataLenDisId).html("Character count: " + $(this).val().length).addClass("danger").removeClass("warning success info");

    // Rest of your code
});

Here's a revised js code for further reference:
https://jsfiddle.net/L07mvLqz/

Hope this helps for your case.


问:
How can I get OS default apps in android
I'm developing a launcher app, I need to retrieve an Android OS default Phone app, Browser app and SMS apps', application Info (Application name, Package name, Launcher icon). Following code is used to get all launchable applications.</p>

```<code>private static List<ApplicationInfo> getInstalledApps(Context context, PackageManager pm) {
    List<ApplicationInfo> installedApps = context.getPackageManager().getInstalledApplications(0);
    List<ApplicationInfo> laughableInstalledApps = new ArrayList<>();
    for(int i =0; i<installedApps.size(); i++){
        if(pm.getLaunchIntentForPackage(installedApps.get(i).packageName) != null){
            laughableInstalledApps.add(installedApps.get(i));
        }
    }
    return laughableInstalledApps;
}
</code>```

答:
After spending some time with the code, I found a way get what I wanted.

Default Dial App

```<code>Intent mainIntent = new Intent(Intent.ACTION_DIAL, null);
mainIntent.addCategory(Intent.CATEGORY_DEFAULT);
List<ResolveInfo> pkgAppsList = getPackageManager().queryIntentActivities(mainIntent, 0);
ActivityInfo info = pkgAppsList.get(0).activityInfo;
</code>```

Default SMS App

```<code>String smsPkgName = Telephony.Sms.getDefaultSmsPackage(context);
ApplicationInfo info = getPackageManager().getApplicationInfo(smsPkgName, 0);
</code>```

Default Browser App

```<code>Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
ResolveInfo resolveInfo = getPackageManager().resolveActivity(browserIntent,
    PackageManager.MATCH_DEFAULT_ONLY);
ActivityInfo info = resolveInfo.activityInfo;
</code>```

Body:
I'm developing a launcher app, I need to retrieve an Android OS default Phone app, Browser app and SMS apps', application Info (Application name, Package name, Launcher icon). Following code is used to get all launchable applications.

private static List<ApplicationInfo> getInstalledApps(Context context, PackageManager pm) {
    List<ApplicationInfo> installedApps = context.getPackageManager().getInstalledApplications(0);
    List<ApplicationInfo> laughableInstalledApps = new ArrayList<>();
    for(int i =0; i<installedApps.size(); i++){
        if(pm.getLaunchIntentForPackage(installedApps.get(i).packageName) != null){
            laughableInstalledApps.add(installedApps.get(i));
        }
    }
    return laughableInstalledApps;
}

Body:
After spending some time with the code, I found a way get what I wanted.

Default Dial App

Intent mainIntent = new Intent(Intent.ACTION_DIAL, null);
mainIntent.addCategory(Intent.CATEGORY_DEFAULT);
List<ResolveInfo> pkgAppsList = getPackageManager().queryIntentActivities(mainIntent, 0);
ActivityInfo info = pkgAppsList.get(0).activityInfo;

Default SMS App

String smsPkgName = Telephony.Sms.getDefaultSmsPackage(context);
ApplicationInfo info = getPackageManager().getApplicationInfo(smsPkgName, 0);

Default Browser App

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
ResolveInfo resolveInfo = getPackageManager().resolveActivity(browserIntent,
    PackageManager.MATCH_DEFAULT_ONLY);
ActivityInfo info = resolveInfo.activityInfo;


问:
Compare latest record with previous record for updated columns from Audit log table
I am facing scenario where i need to get the data from audit log table and show Old and new value.

For eg. Below is audit_Log table for Person

```<code>AUDIT_ID       PERSON_ID       OPERATION       NAME       ADDRESS       AGE     DOY
    1           101             I           Prashant        Andheri     21      1991
    2           101             U           Prashant1       Santacruz   22      1990
    3           101             U           rashant2        Parle       23      1989
</code>```

I want the latest value and previous value for all the columns as below,

```<code>PERSON_ID       COLUMNS      OLD_VALUE       NEW_VALUE
101             OPERATION       U               U
101             NAME            PRASHANT1       PRASHANT2
101             ADDRESS         Santacruz       Parle
101             AGE             22              23
101             BIRTH_YEAR      1990            1989
</code>```

Can anyone please help me to get this result from above table.

Thanks,
Prashant

答:
I try to find a function/ query to do what do you want but I do not found nothing. so I develop a procedure verify if work.</p>

```<code>CREATE PROCEDURE _spManageAuditLog
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT AUDIT_ID, PERSON_ID, OPERATION, NAME, [ADDRESS], AGE, DOY, count(1)
    FROM dbo.audit_Log
    GROUP BY AUDIT_ID, PERSON_ID, OPERATION, NAME, [ADDRESS], AGE, DOY;

CREATE TABLE #row (personId Int, operation char(1), name nvarchar(250),[address] nvarchar(250), age smallint,
doy smallint);

CREATE TABLE #out (PersonID Int, [columnName] nvarchar(250), OLD_VALUE nvarchar(250),NEW_VALUE  nvarchar(250));

--cursor variable
DECLARE
@AUDIT_ID   int,
@PERSON_ID  int,
@OPERATION  char,
@NAME   nvarchar,
@ADDRESS    nvarchar,
@AGE    smallint,
@DOY    smallint;

DECLARE myCursor CURSOR FOR
    SELECT AUDIT_ID, PERSON_ID, OPERATION, NAME, [ADDRESS], AGE, DOY
    FROM dbo.audit_Log

OPEN myCursor
FETCH NEXT FROM myCursor INTO @AUDIT_ID, @PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY

WHILE @@FETCH_STATUS = 0
BEGIN
    declare @countTempData int;
    select @countTempData= count(1) from #row;

    IF @countTempData=0
     BEGIN
        Insert into #row VALUES(@PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY);
        --to debug
        --SELECT * FROM #row;
     END
    ELSE
     BEGIN
        --do comparison previus row

        INSERT INTO #out VALUES (@PERSON_ID, 'Operation', (SELECT TOP(1) OPERATION FROM #row) , @OPERATION );
        INSERT INTO #out VALUES (@PERSON_ID, 'Name',(SELECT TOP(1) NAME FROM #row), @NAME );
        INSERT INTO #out VALUES (@PERSON_ID, 'Address',(SELECT TOP(1) ADDRESS FROM #row), @ADDRESS );
        INSERT INTO #out VALUES (@PERSON_ID, 'Age',(SELECT TOP(1) AGE FROM #row), @AGE );
        INSERT INTO #out VALUES (@PERSON_ID, 'BirthYear',(SELECT TOP(1) DOY FROM #row), @DOY );

        --new item became temp item
        TRUNCATE TABLE #row
        INSERT INTO #row VALUES(@PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY);
        --to debug
        --SELECT * FROM #row;

     END

    -- Get the next.
    FETCH NEXT FROM myCursor INTO @AUDIT_ID, @PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY
END
CLOSE myCursor;
DEALLOCATE myCursor;

SELECT * FROM #out;

END
GO
</code>```

Body:
I am facing scenario where i need to get the data from audit log table and show Old and new value.

For eg. Below is audit_Log table for Person

AUDIT_ID       PERSON_ID       OPERATION       NAME       ADDRESS       AGE     DOY
    1           101             I           Prashant        Andheri     21      1991
    2           101             U           Prashant1       Santacruz   22      1990
    3           101             U           rashant2        Parle       23      1989

I want the latest value and previous value for all the columns as below,

PERSON_ID       COLUMNS      OLD_VALUE       NEW_VALUE
101             OPERATION       U               U
101             NAME            PRASHANT1       PRASHANT2
101             ADDRESS         Santacruz       Parle
101             AGE             22              23
101             BIRTH_YEAR      1990            1989

Can anyone please help me to get this result from above table.

Thanks,
Prashant

Body:
I try to find a function/ query to do what do you want but I do not found nothing. so I develop a procedure verify if work.

CREATE PROCEDURE _spManageAuditLog
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT AUDIT_ID, PERSON_ID, OPERATION, NAME, [ADDRESS], AGE, DOY, count(1)
    FROM dbo.audit_Log
    GROUP BY AUDIT_ID, PERSON_ID, OPERATION, NAME, [ADDRESS], AGE, DOY;

CREATE TABLE #row (personId Int, operation char(1), name nvarchar(250),[address] nvarchar(250), age smallint,
doy smallint);

CREATE TABLE #out (PersonID Int, [columnName] nvarchar(250), OLD_VALUE nvarchar(250),NEW_VALUE  nvarchar(250));

--cursor variable
DECLARE
@AUDIT_ID   int,
@PERSON_ID  int,
@OPERATION  char,
@NAME   nvarchar,
@ADDRESS    nvarchar,
@AGE    smallint,
@DOY    smallint;

DECLARE myCursor CURSOR FOR
    SELECT AUDIT_ID, PERSON_ID, OPERATION, NAME, [ADDRESS], AGE, DOY
    FROM dbo.audit_Log

OPEN myCursor
FETCH NEXT FROM myCursor INTO @AUDIT_ID, @PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY

WHILE @@FETCH_STATUS = 0
BEGIN
    declare @countTempData int;
    select @countTempData= count(1) from #row;

    IF @countTempData=0
     BEGIN
        Insert into #row VALUES(@PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY);
        --to debug
        --SELECT * FROM #row;
     END
    ELSE
     BEGIN
        --do comparison previus row

        INSERT INTO #out VALUES (@PERSON_ID, 'Operation', (SELECT TOP(1) OPERATION FROM #row) , @OPERATION );
        INSERT INTO #out VALUES (@PERSON_ID, 'Name',(SELECT TOP(1) NAME FROM #row), @NAME );
        INSERT INTO #out VALUES (@PERSON_ID, 'Address',(SELECT TOP(1) ADDRESS FROM #row), @ADDRESS );
        INSERT INTO #out VALUES (@PERSON_ID, 'Age',(SELECT TOP(1) AGE FROM #row), @AGE );
        INSERT INTO #out VALUES (@PERSON_ID, 'BirthYear',(SELECT TOP(1) DOY FROM #row), @DOY );

        --new item became temp item
        TRUNCATE TABLE #row
        INSERT INTO #row VALUES(@PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY);
        --to debug
        --SELECT * FROM #row;

     END

    -- Get the next.
    FETCH NEXT FROM myCursor INTO @AUDIT_ID, @PERSON_ID, @OPERATION, @NAME, @ADDRESS, @AGE, @DOY
END
CLOSE myCursor;
DEALLOCATE myCursor;

SELECT * FROM #out;

END
GO


问:
Compile-time and runtime casting c#
I was wondering why some casts in C# are checked at compile-time whereas in other cases the responsibility is dumped on CLR. Like above both are incorrect but handled in a different way.

```<code>class Base { }
class Derived : Base { }
class Other { }

static void Main(string[] args)
{
    Derived d = (Derived)new Base();     //Runtime       InvalidCastException
    Derived d = (Derived)new Other();    //Compile-time  Cannot convert type...
}
</code>```

While reading "C# in depth" I've found the information on this topic where autor says:

  "If the compiler spots that it’s actually impossible for that cast to work, it’ll trigger a compilation error—and if it’s theoretically allowed but actually incorrect at execution time, the CLR will throw an exception."

Does 'theoretically' mean connected by inheritance hierarchy (some another affinity between objects ?) or it is compiler's internal business?

答:
If your variable is of Base type, is can be theoretically constructed by Derived constructor, thus being a variable of Derived type actually. At compile time, compiler does not bother itself with trying to figure out whether in each particular case such downcast (representing a variable of Base type as an entity of Derived type) is possible.

Your sample is simple - you create a new class and cast it right away. But what if you get Base from somewhere else, e.g., some method call? Compiler just cannot "guess" what your method is going to return and therefore throw on not throw an error.

When you cast Other, compiler sees that there is no possibility that Other is actually Derived and throws an exception.

Title: Compile-time and runtime casting c#

Body:
I was wondering why some casts in C# are checked at compile-time whereas in other cases the responsibility is dumped on CLR. Like above both are incorrect but handled in a different way.

class Base { }
class Derived : Base { }
class Other { }

static void Main(string[] args)
{
    Derived d = (Derived)new Base();     //Runtime       InvalidCastException
    Derived d = (Derived)new Other();    //Compile-time  Cannot convert type...
}

While reading "C# in depth" I've found the information on this topic where autor says:

  "If the compiler spots that it’s actually impossible for that cast to work, it’ll trigger a compilation error—and if it’s theoretically allowed but actually incorrect at execution time, the CLR will throw an exception."

Does 'theoretically' mean connected by inheritance hierarchy (some another affinity between objects ?) or it is compiler's internal business?


问:
Change visibility of a view in all items of recyclerview
I have a  CheckBox  in my recyclerview items with Gone visibility . I want to make it visible for all items in recyclerview when I have a longClick on one of items .so I did this : </p>

```<code>    holder.faviorateVideoItemRelative.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View arg0) {
            holder.chk_faviorateVideo.setVisibility(View.VISIBLE);
           // holder.chk_faviorateVideo.setChecked(!holder.chk_faviorateVideo.isChecked());
            return  true ;
        }
    });
</code>```

<p>but this will make CheckBox  visible just for current item .
I even moved my code to  my ViewHolder class, but nothing changed . how can I do that without loop or redrawing of recyclerview ?
I need to do something like android's default file manager long press and selecting .
thanks in advance . </p>

答:
Your Holder holds only current item, that's why you see a result in this item only.

First option is just to make some boolean flag and call notifyDataSetChanged(), in onBindViewHolder() just use that flag to set visibility.

Also you can try to create collection of your CheckBoxes or Holders and on long click iterate them to make checkboxes visible. As for me, it's not the worst option.

If you don't want to have a loop for that, another way I see, is to implement Observer pattern - on checkbox creation you should add it as a subscriber to receive visibility notification.

Also there is a good possibility to use RX here:

- on long click you emit event

- and before you subscribe your checkboxes on that event.

It's also related to Observer pattern.

Body:
I have a  CheckBox  in my recyclerview items with Gone visibility . I want to make it visible for all items in recyclerview when I have a longClick on one of items .so I did this :

    holder.faviorateVideoItemRelative.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View arg0) {
            holder.chk_faviorateVideo.setVisibility(View.VISIBLE);
           // holder.chk_faviorateVideo.setChecked(!holder.chk_faviorateVideo.isChecked());
            return  true ;
        }
    });

but this will make CheckBox  visible just for current item .
I even moved my code to  my ViewHolder class, but nothing changed . how can I do that without loop or redrawing of recyclerview ?
I need to do something like android's default file manager long press and selecting .
thanks in advance .


答:
You could create a boolean in your adapter that stores the information if the there was a long press or not and in your onBindViewHolder you check whether this is true or false and set the visibility according to it: holder.chk_faviorateVideo.setVisibility(longPressed ? View.VISIBLE : View.GONE);
Then in your click listener you toggle this variable and call notifyDataSetChanged()

Title: Change visibility of a view in all items of recyclerview


问:
How to determine if string contains substring with awk
I have the following bash script segment that uses grep to find out whether input line contains certain pattern or not.

```<code>echo $input_line | grep -q "$pattern"
if [ $? -eq 0 ];
then
    # Input line contains pattern
    # Execute some bash commands
else
    # Input line DOES NOT contain pattern
    # Execute other bash commands
fi
</code>```

I need to rewrite it with awk without grep. I tried several variants, but none of them works, for example, both of the following always print MATCH,
no matter contains input line pattern or not.

```<code>echo $input_line | awk -v b="$pattern" '/pattern/ { print "MATCH" }'

echo $input_line | awk -v b="$pattern" '/$0 ~ pattern/ { print "MATCH" }'
</code>```

Update:

Removing / as recommended resolved the described issue. Now I have the problem with returning result of awk command for usage in if statement. I wrote the following "ugly" snippet:

```<code>pattern="abc"
input_line="xyz123 678q we uqa abc asd"
RES=$(echo $input_line | awk -v pat="$pattern" '$0 ~ pat { print "1" }')
if [ $RES -eq 1 ];
then
    echo Input line $input_line contains pattern $pattern
else
    echo Input line $input_line DOES NOT contains pattern $pattern
fi

input_line="tult uil7665 5444tu l098 7tu"
RES=$(echo $input_line | awk -v pat="$pattern" '$0 ~ pat { print "1" }')
if [ $RES -eq 1 ];
then
    echo Input line $input_line contains pattern $pattern
else
    echo Input line $input_line DOES NOT contains pattern $pattern
fi
</code>```

So I've got the following output, because in second case when input line doesn't contain pattern the variable RES is not set:

```<code>Input line xyz123 678q we uqa abc asd contains pattern abc
./test.sh: line 21: [: -eq: unary operator expected
Input line tult uil7665 5444tu l098 7tu DOES NOT contains pattern abc
</code>```

Any ideas how to improve this "ugly" script snippet with if statement?

Thanks

答:
To use awk with a referenced variable for the pattern match you would need to do:

```<code>if [[ "$(input_line | awk '/'$pattern'/ { print "MATCH" }')" == "MATCH" ]]
then
         pattern matches
else
         No pattern matches
fi
</code>```

I'm assuming here that the regular expression is a dynamic variable referenced by the variable pattern.

Place particular attention to the position of the single quotes in the awk statement.

Body:
I have the following bash script segment that uses grep to find out whether input line contains certain pattern or not.

echo $input_line | grep -q "$pattern"
if [ $? -eq 0 ];
then
    # Input line contains pattern
    # Execute some bash commands
else
    # Input line DOES NOT contain pattern
    # Execute other bash commands
fi

I need to rewrite it with awk without grep. I tried several variants, but none of them works, for example, both of the following always print MATCH,
no matter contains input line pattern or not.

echo $input_line | awk -v b="$pattern" '/pattern/ { print "MATCH" }'

echo $input_line | awk -v b="$pattern" '/$0 ~ pattern/ { print "MATCH" }'

Update:

Removing / as recommended resolved the described issue. Now I have the problem with returning result of awk command for usage in if statement. I wrote the following "ugly" snippet:

pattern="abc"
input_line="xyz123 678q we uqa abc asd"
RES=$(echo $input_line | awk -v pat="$pattern" '$0 ~ pat { print "1" }')
if [ $RES -eq 1 ];
then
    echo Input line $input_line contains pattern $pattern
else
    echo Input line $input_line DOES NOT contains pattern $pattern
fi

input_line="tult uil7665 5444tu l098 7tu"
RES=$(echo $input_line | awk -v pat="$pattern" '$0 ~ pat { print "1" }')
if [ $RES -eq 1 ];
then
    echo Input line $input_line contains pattern $pattern
else
    echo Input line $input_line DOES NOT contains pattern $pattern
fi

So I've got the following output, because in second case when input line doesn't contain pattern the variable RES is not set:

Input line xyz123 678q we uqa abc asd contains pattern abc
./test.sh: line 21: [: -eq: unary operator expected
Input line tult uil7665 5444tu l098 7tu DOES NOT contains pattern abc

Any ideas how to improve this "ugly" script snippet with if statement?

Thanks

Body:
To use awk with a referenced variable for the pattern match you would need to do:

if [[ "$(input_line | awk '/'$pattern'/ { print "MATCH" }')" == "MATCH" ]]
then
         pattern matches
else
         No pattern matches
fi

I'm assuming here that the regular expression is a dynamic variable referenced by the variable pattern.

Place particular attention to the position of the single quotes in the awk statement.


问:
find type -f also returns non-matching files in matching directory

all files/folders in current directory:

```<code>./color_a.txt
./color_b.txt
./color_c.txt
./color/color_d.txt
./color/blue.txt
./color/red.txt
./color/yellow.txt
</code>```

command used to find all files with the word color in name:

```<code>find ./*color* -type f
</code>```

result:

```<code>./color_a.txt
./color_b.txt
./color_c.txt
./color/color_d.txt
./color/blue.txt
./color/red.txt
./color/yellow.txt
</code>```

expected result:

```<code>./color_a.txt
./color_b.txt
./color_c.txt
./color/color_d.txt
</code>```

The result also includes all the non-matching file names under a matching parent directory.
How could I get ONLY files with names directly matching the color pattern?

Thanks a lot!

答:
What you probably want for filename filtering is a simple -name <glob-pattern> test:

```<code>find -name '*color*' -type f
</code>```

From man find:

```<code> -name pattern
        Base  of  file  name  (the  path with the leading directories removed) matches shell
        pattern pattern.  Because the leading directories are removed, the file names
        considered for a match with -name will never include a  slash,  so `-name a/b' will
        never match anything (you probably need to use -path instead).
</code>```

Just as a side note, when you wrote:

```<code>find ./*color* -type f
</code>```

the shell expanded the (unquoted) glob pattern ./*color*, and what was really executed (what find saw) was this:

```<code>find ./color ./color_a.txt ./color_b.txt ./color_c.txt -type f
</code>```

thus producing a list of files in all of those locations.

ContentLicense: CC BY-SA 4.0

Body:
all files/folders in current directory:

./color_a.txt
./color_b.txt
./color_c.txt
./color/color_d.txt
./color/blue.txt
./color/red.txt
./color/yellow.txt

command used to find all files with the word color in name:

find ./*color* -type f

result:

./color_a.txt
./color_b.txt
./color_c.txt
./color/color_d.txt
./color/blue.txt
./color/red.txt
./color/yellow.txt

expected result:

./color_a.txt
./color_b.txt
./color_c.txt
./color/color_d.txt

The result also includes all the non-matching file names under a matching parent directory.
How could I get ONLY files with names directly matching the color pattern?

Thanks a lot!

Body:
What you probably want for filename filtering is a simple -name <glob-pattern> test:

find -name '*color*' -type f

From man find:

 -name pattern
        Base  of  file  name  (the  path with the leading directories removed) matches shell
        pattern pattern.  Because the leading directories are removed, the file names
        considered for a match with -name will never include a  slash,  so `-name a/b' will
        never match anything (you probably need to use -path instead).

Just as a side note, when you wrote:

find ./*color* -type f

the shell expanded the (unquoted) glob pattern ./*color*, and what was really executed (what find saw) was this:

find ./color ./color_a.txt ./color_b.txt ./color_c.txt -type f

thus producing a list of files in all of those locations.