text:
Q: How to include images in LaTeX large document, while collaborating on Git I am currently working with a team to create a large latex report document (over 200 pages) where we need to include many images. We are supposed to use Git as version control to collaborate better. (Bitbuckets as remote repo). My question is how we can share images through Git, should I create a separate folder on the remote repo and ask the team members to manually insert the images there... or should we push the images every time we push code?
technical details: I have installed TeXstudio, on Windows.


text:
Q: Styling and Formatting the ComboBox selected item to match the ItemTemplate I have bound a ComboBox to a list of DateTime values to select a start time for an event.  I am using an ItemTemplate to specify the formatting of the DateTime in the list.  I also want the user to be able to manually specify a start time not in the list, like 8:27 AM or 9:30 PM.
Wiring that up is not the issue; rather, I want the user to be presented with the same formatted DateTime as the list.
<ComboBox x:Name="StartTimeButton"
          ItemsSource="{Binding DataContext.StartTimes,
                                RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
          SelectedItem="{Binding DefaultStartTime}"
          IsEditable="True">
   <ComboBox.ItemTemplate>
      <DataTemplate>
         <Label>
            <TextBlock Text="{Binding StringFormat='{}{0:hh:mm tt}'}" />
         </Label>
      </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>

This results in:

I have been unable to determine how to format the top TextBlock used by the ComboBox (when editing is enabled) to match the formatting of the dropdown area.

A: The ultra shorthand that gets you halfway there (you can drop the DataTemplate):
<ComboBox ItemsSource="{Binding Times}"
          IsEditable="True" ItemStringFormat="hh:mm tt"
          TextSearch.TextPath="Hour"/>

The problem is, that DateTime has no property that outputs the time in that format. Personally, i would write a wrapper that has an internal DateTime and a property that facilitates formatting to string and parsing from it.
There does not appear to be a standard way of creating a new item form the entered text, so you might need to parse the ComboBox.Text manually in case a value is entered that is not in the list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting Linux to 5G WiFi, whereas on 2.4G works just fine I have an quirky issue connecting my Linux machine to WiFi router only on 5Ghz band, whereas on 2.4Ghz everything works fine(, but limiting the internet bandwidth severly).
I suppose that's not router fault, because I'm able to connect my Galaxy Note 10 using 5Ghz band with full speed. I suspect that is simply a Linux configuration problem.
I'm using Ubuntu 20.10 with 5.8.0-41-generic kernel and Broadcom BCM4360 802.11ac Wireless Network Adapter.
But let's start at the very beginning. I could suspect that the problem may have someting with switching to Ubuntu 20.10, but I'm not in 100% certain. I've discovered that iw reg setting was erased after some system updates:
# iw reg get
global
country 00: DFS-UNSET
    (2402 - 2472 @ 40), (6, 20), (N/A)
    (2457 - 2482 @ 20), (6, 20), (N/A), AUTO-BW, PASSIVE-SCAN
    (2474 - 2494 @ 20), (6, 20), (N/A), NO-OFDM, PASSIVE-SCAN
    (5170 - 5250 @ 80), (6, 20), (N/A), AUTO-BW, PASSIVE-SCAN
    (5250 - 5330 @ 80), (6, 20), (0 ms), DFS, AUTO-BW, PASSIVE-SCAN
    (5490 - 5730 @ 160), (6, 20), (0 ms), DFS, PASSIVE-SCAN
    (5735 - 5835 @ 80), (6, 20), (N/A), PASSIVE-SCAN
    (57240 - 63720 @ 2160), (N/A, 0), (N/A)

# iw reg set PL
# iw reg get
global
country PL: DFS-ETSI
    (2400 - 2483 @ 40), (N/A, 20), (N/A)
    (5150 - 5250 @ 80), (N/A, 23), (N/A), NO-OUTDOOR, AUTO-BW
    (5250 - 5350 @ 80), (N/A, 20), (0 ms), NO-OUTDOOR, DFS, AUTO-BW
    (5470 - 5725 @ 160), (N/A, 26), (0 ms), DFS
    (5725 - 5875 @ 80), (N/A, 13), (N/A)
    (57000 - 66000 @ 2160), (N/A, 40), (N/A)

The current settings of my WiFi router are:
2.4Ghz
802.11 Mode: Mixed (802.11b, 802.11g and 802.11n)
Channel: Auto (Current Ch. 1)
Bandwidth: Auto
Power: 100

5Ghz
802.11 Mode: Mixed (802.11a and 802.11n/ac)
Channel: Auto (Current Ch. 100/80)
Bandwidth: Auto
Power: 100

I think that listing below could be helpful:
# iw list
Wiphy phy0
    wiphy index: 0
    max # scan SSIDs: 1
    max scan IEs length: 0 bytes
    max # sched scan SSIDs: 0
    max # match sets: 0
    max # scan plans: 1
    max scan plan interval: -1
    max scan plan iterations: 0
    Retry short limit: 7
    Retry long limit: 4
    Coverage class: 0 (up to 0m)
    Supported Ciphers:
        * WEP40 (00-0f-ac:1)
        * WEP104 (00-0f-ac:5)
        * TKIP (00-0f-ac:2)
        * CCMP-128 (00-0f-ac:4)
        * CMAC (00-0f-ac:6)
    Available Antennas: TX 0 RX 0
    Supported interface modes:
         * IBSS
         * managed
    Band 1:
        Bitrates (non-HT):
            * 1.0 Mbps
            * 2.0 Mbps (short preamble supported)
            * 5.5 Mbps (short preamble supported)
            * 11.0 Mbps (short preamble supported)
            * 6.0 Mbps
            * 9.0 Mbps
            * 12.0 Mbps
            * 18.0 Mbps
            * 24.0 Mbps
            * 36.0 Mbps
            * 48.0 Mbps
            * 54.0 Mbps
        Frequencies:
            * 2412 MHz [1] (20.0 dBm)
            * 2417 MHz [2] (20.0 dBm)
            * 2422 MHz [3] (20.0 dBm)
            * 2427 MHz [4] (20.0 dBm)
            * 2432 MHz [5] (20.0 dBm)
            * 2437 MHz [6] (20.0 dBm)
            * 2442 MHz [7] (20.0 dBm)
            * 2447 MHz [8] (20.0 dBm)
            * 2452 MHz [9] (20.0 dBm)
            * 2457 MHz [10] (20.0 dBm)
            * 2462 MHz [11] (20.0 dBm)
            * 2467 MHz [12] (20.0 dBm)
            * 2472 MHz [13] (20.0 dBm)
            * 2484 MHz [14] (disabled)
    Band 2:
        Bitrates (non-HT):
            * 6.0 Mbps
            * 9.0 Mbps
            * 12.0 Mbps
            * 18.0 Mbps
            * 24.0 Mbps
            * 36.0 Mbps
            * 48.0 Mbps
            * 54.0 Mbps
        Frequencies:
            * 5160 MHz [32] (23.0 dBm)
            * 5170 MHz [34] (23.0 dBm)
            * 5180 MHz [36] (23.0 dBm)
            * 5190 MHz [38] (23.0 dBm)
            * 5200 MHz [40] (23.0 dBm)
            * 5210 MHz [42] (23.0 dBm)
            * 5220 MHz [44] (23.0 dBm)
            * 5230 MHz [46] (23.0 dBm)
            * 5240 MHz [48] (23.0 dBm)
            * 5250 MHz [50] (disabled)
            * 5260 MHz [52] (20.0 dBm) (radar detection)
            * 5270 MHz [54] (20.0 dBm) (radar detection)
            * 5280 MHz [56] (20.0 dBm) (radar detection)
            * 5290 MHz [58] (20.0 dBm) (radar detection)
            * 5300 MHz [60] (20.0 dBm) (radar detection)
            * 5310 MHz [62] (20.0 dBm) (radar detection)
            * 5320 MHz [64] (20.0 dBm) (radar detection)
            * 5330 MHz [66] (20.0 dBm) (radar detection)
            * 5340 MHz [68] (20.0 dBm) (radar detection)
            * 5350 MHz [70] (disabled)
            * 5360 MHz [72] (disabled)
            * 5370 MHz [74] (disabled)
            * 5380 MHz [76] (disabled)
            * 5390 MHz [78] (disabled)
            * 5400 MHz [80] (disabled)
            * 5410 MHz [82] (disabled)
            * 5420 MHz [84] (disabled)
            * 5430 MHz [86] (disabled)
            * 5440 MHz [88] (disabled)
            * 5450 MHz [90] (disabled)
            * 5460 MHz [92] (disabled)
            * 5470 MHz [94] (disabled)
            * 5480 MHz [96] (26.0 dBm) (radar detection)
            * 5490 MHz [98] (26.0 dBm) (radar detection)
            * 5500 MHz [100] (26.0 dBm) (radar detection)
            * 5510 MHz [102] (26.0 dBm) (radar detection)
            * 5520 MHz [104] (26.0 dBm) (radar detection)
            * 5530 MHz [106] (26.0 dBm) (radar detection)
            * 5540 MHz [108] (26.0 dBm) (radar detection)
            * 5550 MHz [110] (26.0 dBm) (radar detection)
            * 5560 MHz [112] (26.0 dBm) (radar detection)
            * 5570 MHz [114] (26.0 dBm) (radar detection)
            * 5580 MHz [116] (26.0 dBm) (radar detection)
            * 5590 MHz [118] (26.0 dBm) (radar detection)
            * 5600 MHz [120] (26.0 dBm) (radar detection)
            * 5610 MHz [122] (26.0 dBm) (radar detection)
            * 5620 MHz [124] (26.0 dBm) (radar detection)
            * 5630 MHz [126] (26.0 dBm) (radar detection)
            * 5640 MHz [128] (26.0 dBm) (radar detection)
            * 5650 MHz [130] (26.0 dBm) (radar detection)
            * 5660 MHz [132] (26.0 dBm) (radar detection)
            * 5670 MHz [134] (26.0 dBm) (radar detection)
            * 5680 MHz [136] (26.0 dBm) (radar detection)
            * 5690 MHz [138] (26.0 dBm) (radar detection)
            * 5700 MHz [140] (26.0 dBm) (radar detection)
            * 5710 MHz [142] (26.0 dBm) (radar detection)
            * 5720 MHz [144] (disabled)
            * 5725 MHz [145] (disabled)
            * 5730 MHz [146] (disabled)
            * 5735 MHz [147] (13.0 dBm)
            * 5740 MHz [148] (13.0 dBm)
            * 5745 MHz [149] (13.0 dBm)
            * 5750 MHz [150] (13.0 dBm)
            * 5755 MHz [151] (13.0 dBm)
            * 5760 MHz [152] (13.0 dBm)
            * 5765 MHz [153] (13.0 dBm)
            * 5770 MHz [154] (13.0 dBm)
            * 5775 MHz [155] (13.0 dBm)
            * 5780 MHz [156] (13.0 dBm)
            * 5785 MHz [157] (13.0 dBm)
            * 5790 MHz [158] (13.0 dBm)
            * 5795 MHz [159] (13.0 dBm)
            * 5800 MHz [160] (13.0 dBm)
            * 5805 MHz [161] (13.0 dBm)
            * 5810 MHz [162] (13.0 dBm)
            * 5815 MHz [163] (13.0 dBm)
            * 5820 MHz [164] (13.0 dBm)
            * 5825 MHz [165] (13.0 dBm)
            * 5830 MHz [166] (13.0 dBm)
            * 5840 MHz [168] (13.0 dBm)
            * 5850 MHz [170] (13.0 dBm)
            * 5860 MHz [172] (13.0 dBm)
            * 5870 MHz [174] (disabled)
            * 5880 MHz [176] (disabled)
            * 5890 MHz [178] (disabled)
            * 5900 MHz [180] (disabled)
            * 5910 MHz [182] (disabled)
            * 5920 MHz [184] (disabled)
            * 5930 MHz [186] (disabled)
            * 5940 MHz [188] (disabled)
            * 5950 MHz [0] (disabled)
            * 5960 MHz [2] (disabled)
            * 5970 MHz [4] (disabled)
            * 5980 MHz [6] (disabled)
            * 5990 MHz [8] (disabled)
            * 6000 MHz [10] (disabled)
            * 6010 MHz [12] (disabled)
            * 6020 MHz [14] (disabled)
            * 6030 MHz [16] (disabled)
            * 6040 MHz [18] (disabled)
            * 6050 MHz [20] (disabled)
            * 6060 MHz [22] (disabled)
            * 6070 MHz [24] (disabled)
            * 6080 MHz [26] (disabled)
            * 6090 MHz [28] (disabled)
            * 6100 MHz [30] (disabled)
            * 6110 MHz [32] (disabled)
            * 6120 MHz [34] (disabled)
            * 6130 MHz [36] (disabled)
            * 6140 MHz [38] (disabled)
    Supported commands:
         * set_interface
         * new_key
         * join_ibss
         * set_pmksa
         * del_pmksa
         * flush_pmksa
         * connect
         * disconnect
    WoWLAN support:
         * wake up on disconnect
         * wake up on magic packet
         * can do GTK rekeying
         * wake up on GTK rekey failure
         * wake up on EAP identity request
    software interface modes (can always be added):
    interface combinations are not supported
    Device supports scan flush.
    Supported extended features:

I would appreciate any clues what is happening and how to utilize 5Ghz band.


text:
Q: Email notifications to AD group members - no access to Exchange Using SharePoint Designer 2010, I created a group and had AD group as a member. I tried to send email notification to the individuals in that AD group but the email only received by the group email address. I'm trying to make it distributed to the individuals email addresses within the group with no luck. I looked up and found several solutions require changes in Exchange which I don't have access to. Is there any other solution?

A: You can create the group in SharePoint and send de email to the SharePoint Group.
Let me explain. Understanding that you can not configure Exchange, I think there is no solution using AD groups. The alternative I propose is: create native sharepoint groups and associate users directly to SharePoint groups.
I know that probably you prefer to manage AD groups but not think you can solve it if you do not have access to Exchange.

A: There is a known limitation related to send SPD workflow e-mails to AD groups.
Basically AD groups are seen by SPD as a regular user... let's remember that AD groups have properties like e-mail, name, login and everything else.
So, the SPD can't understand that you are trying to send e-mails to everyone inside that group. What you can do is create something that iterates through every user inside that AD group... but this solution goes to the custom .NET way of living.
By the other hand, SPD knows that a SharePoint group is A GROUP. And when you send e-mail to the group, the SPD will send it to everyone inside it.


text:
Q: Word2vec is a Generalization or memorization algorithm? I need to know that word2vec is a Generalization algorithm like all ML algorithms or its Memorization algorithm like KNN ?
Because we have 2 types of algorithms model based and memory based , word2vec is coming in which category when it's using for most_similar_items

A: Let me define generalization as the ability of a model which has completed training to be effective in prediction across a whole range of inputs, including include inputs that is not part of training. From that perspective, Word2Vec cannot predict words that are not part of the training dataset because it simply would not have trained on the context of it to create an embedding. To qualify as a generalization method, it needs to be able to predict on an input which was not part of the training dataset.
Word2Vec model maintains a dictionary of words to the corresponding embedding/vector. In summary, cannot predict on unknown words. This was one of the important differences between fastText model and Word2Vec.


text:
Q: How to increase or decrease the number of columns according to data in table? this is the code that prints the data in a table and each column contains multiple numbers of data. In this way, it is difficult for each column to print the exact number of data.
That's why if the number of data is three and the loop has the limit of 2 then it will not print the last data column and the loop will stop at 2.
How to adjust the columns according to data?
Required Result
╔═══╤════════════════╤═════════════════════╗
║ # │    Projects    │ Project Priorities  ║
╟━━━┼━━━━━━━━━━━━━━━━┼━━━━━━━━━━━━━━━━━━━━━╢
║ 1 │ first project  │       None          ║
║ 2 │ second project │       Low           ║
║ 3 │                │      Medium         ║
║ 4 │                │       High          ║
╚═══╧════════════════╧═════════════════════╝

Code
package main

import (
    "fmt"

    "github.com/alexeyco/simpletable"
)

func InfoTable(allData [][]string) {
    table := simpletable.New()
    table.Header = &simpletable.Header{
        Cells: []*simpletable.Cell{
            {Align: simpletable.AlignCenter, Text: "#"},
            {Align: simpletable.AlignCenter, Text: "Projects"},
            {Align: simpletable.AlignCenter, Text: "Project Priorities"},
        },
    }

    var cells [][]*simpletable.Cell

    for i := 0; i < 2; i++ {
        cells = append(cells, *&[]*simpletable.Cell{
            {Align: simpletable.AlignCenter, Text: fmt.Sprintf("%d", i+1)},
            {Align: simpletable.AlignCenter, Text: allData[0][i]},
            {Align: simpletable.AlignCenter, Text: allData[1][i]},
        })
    }

    table.Body = &simpletable.Body{Cells: cells}

    table.SetStyle(simpletable.StyleUnicode)
    table.Println()
}

func main() {
    data := [][]string{
        {"first project", "second project"},
        {"None", "Low", "Medium", "High"},
    }
    InfoTable(data)
}

A: There are a range of possible approaches; here is one option that removes the need to make assumptions about the number of rows/columns (playground):
func InfoTable(headings []string, allData [][]string) {
    if len(headings) != len(allData) {
        panic("Must have a heading per column")
    }
    table := simpletable.New()

    // Populate headings (adding one for the row number)
    headerCells := make([]*simpletable.Cell, len(headings)+1)
    headerCells[0] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: "#"}
    for i := range headings {
        headerCells[i+1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: headings[i]}
    }

    table.Header = &simpletable.Header{
        Cells: headerCells,
    }

    // Work out number of rows needed
    noOfCols := len(allData)
    noOfRows := 0
    for _, col := range allData {
        if len(col) > noOfRows {
            noOfRows = len(col)
        }
    }

    // Populate cells (adding row number)
    cells := make([][]*simpletable.Cell, noOfRows)
    for rowNo := range cells {
        row := make([]*simpletable.Cell, noOfCols+1) // add column for row number
        row[0] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: fmt.Sprintf("%d", rowNo+1)}

        for col := 0; col < noOfCols; col++ {
            if len(allData[col]) > rowNo {
                row[col+1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: allData[col][rowNo]}
            } else {
                row[col+1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: ""} // Blank cell
            }
            cells[rowNo] = row
        }
    }
    table.Body = &simpletable.Body{Cells: cells}

    table.SetStyle(simpletable.StyleUnicode)
    table.Println()
}


text:
Q: Parsing feed with SimpleRSS in Rails, numeric codes appear, can't encode them properly I am using the SimpleRSS gem to parse a WordPress RSS feed. The only problem is that many characters in that feed are encoded using numeric codes, e.g.
'

instead of
'

Files
*rss_helper.rb*
module RssHelper
  require 'rubygems'
  require 'simple-rss'
  require 'open-uri'

  def rss
    rss = SimpleRSS.parse open('http://example.com/feed/')
  end
end

show.html.slim
...
-rss.entries.each do |entry|
  =entry.title

With the entry.title, I have tried:
=entry.title.encode("UTF-8")

=entry.title.encode(Encoding::UTF_8, :invalid => :replace, :undef => :replace, :replace => '')

Neither has worked. I found a lot of resources regarding the iconv gem, but from what I understand it is deprecated now.
I also attempted using the .force_encoding method instead of .encoding, but no matter what I choose it always displays that numeric code directly from the feed.
How do I force it to render the proper character?
EDIT: Here is my final helper using the gem suggested by the selected answer, included here so anyone who views this can see what I did.
*rss_helper.rb*
def decode(string)
  coder = HTMLEntities.new
  return coder.decode(string)
end

show.html.slim
...
decode(entry.title)
...

A: Run it through HTMLEntities.
HTMLEntities.new.decode(rss_feed_content)

This'll translate the entity-encoded characters into their literal equivalents.


text:
Q: Sorting on a rank field Why doesn't the following sort on a rank work? The actual ranking seems to be correct but for the life of me I cannot figure out why MDX doesn't sort it by the rank:
WITH
  MEMBER [Measures].[Division Rank] AS
    Rank
    (
      [Team].[Hierarchy].CurrentMember
     ,Order
      (
        Exists
        (
          [Team].[Hierarchy].[Code].MEMBERS
         ,Descendants
          (
            [Team].[Hierarchy].CurrentMember.Parent
           ,1
          )
        )
       ,[Measures].[Wins]
       ,bdesc
      )
    )
SELECT
  {
    (
      [Season].[Season].[Season].[2019]
     ,{
        [Measures].[Wins]
       ,[Measures].[Division Rank]
      }
    )
  } ON COLUMNS
 ,{
    Order
    (
      [Team].[Hierarchy].[Code].MEMBERS
     ,[Measures].[Division Rank]
     ,basc
    )
  } ON ROWS
FROM [Nfl2];

For example, why does the 2 occur before a 1 below?

UPDATE -- it should sort on ([Measures].[Wins], [Season].[Season].&[2019]) instead of just [Measures].[Wins].

A: Does adding the year into the order logic help?
WITH
  MEMBER [Measures].[Division Rank] AS
    Rank
    (
      [Team].[Hierarchy].CurrentMember
     ,Order
      (
        Exists
        (
          [Team].[Hierarchy].[Code].MEMBERS
         ,Descendants
          (
            [Team].[Hierarchy].CurrentMember.Parent
           ,1
          )
        )
       ,[Measures].[Wins]
       ,bdesc
      )
    )
  SET [x] AS
    Order
    (
      [Team].[Hierarchy].[Code].MEMBERS
     ,(
        [Measures].[Division Rank]
       ,[Season].[Season].[Season].[2019]
      )
     ,basc
    )
SELECT
  {
    (
      [Season].[Season].[Season].[2019]
     ,{
        [Measures].[Wins]
       ,[Measures].[Division Rank]
      }
    )
  } ON COLUMNS
 ,[x] ON ROWS
FROM [Nfl2];


text:
Q: Why is this query taking a long time to finish? I have a function. When I use this function in my query it is always taking a long time like 1 to 2hrs to finish. Here's my first query ...
SELECT GET_DAYSNS_SF(CONTRACT_ID)
FROM   CONTRACT_TEMP;

and function...
CREATE OR REPLACE FUNCTION GET_DAYSNS_SF
    (CONTRACT_ID IN NUMBER)
    RETURN DATE
AS
    CONTRACT_ID1 NUMBER(16) := CONTRACT_ID;
    DAYSNS DATE;

BEGIN
  BEGIN
    SELECT MIN(EXPECTED_DT)
    INTO DAYSNS
    FROM FLOW
    WHERE REVERSAL_STATUS = 4200
    AND FLOW_TYPE IN(1003,1006,1027)
    AND IS_CASH = 1
    AND AMOUNT > 0
    AND AMOUNT > NVL(AMT_MATCHED,0)
    AND CONTRACT_ID = CONTRACT_ID1;
 EXCEPTION
    WHEN NO_DATA_FOUND THEN
       DAYSNS := NULL;
  END;
  RETURN DAYSNS;
END;

A: The trivial answer (very probably valid guess) is a missing index on  FLOW(CONTRACT_ID).
This leads to a FULL TABLE SCAN in each function call.
Note, that in case the column CONTRACT_ID is not very selective, you may need to add some other column from the predicated used in the query in the function (e.g. REVERSAL_STATUS).
But you may do even better - you need only to left behind the PL/SQL cursor row by row logik and enter the SQL approach.
This will solve the two additional problems that remains after adding the index:

*

*PL/SQL context swich is costly in case of large number of function calls

*You implemented an OUTER JOIN with DIY matter, which is far slower that done by Oracle.
What you need id to get for each contract_id from CONTRACT_TEMP the minimum EXPECTED_DT from FLOW if exists, filtered with the WHERE predicate in the function.
This can be done in two steps:
1) Precalculate for each CONTRACT_ID the minimum EXPECTED_DT - see subquery below. Note, that using GROUP BY you calculates the result for each contract in one step.
2) LEFT OUTER JOIN the table CONTRACT_TEMP to the result of 1)
The query - that is equivalent to yours initial query:
SELECT   f.EXPECTED_DT
FROM   CONTRACT_TEMP c
LEFT OUTER JOIN
   (SELECT CONTRACT_ID, MIN(EXPECTED_DT) EXPECTED_DT
    FROM FLOW
    WHERE REVERSAL_STATUS = 4200
    AND FLOW_TYPE IN(1003,1006,1027)
    AND IS_CASH = 1
    AND AMOUNT > 0
    AND AMOUNT > NVL(AMT_MATCHED,0)
    GROUP BY CONTRACT_ID) f
on c.CONTRACT_ID = f.CONTRACT_ID

A: You can remove the condition AND AMOUNT > 0  as the query already has one more similar condition  AMOUNT > NVL(AMT_MATCHED,0)


text:
Q: Running a for loop on data from Facebook Graph Api I am trying to dynamically show photos on my moms wedding website that she adds to her photos albums on Facebook but I am having trouble getting the images to render and loop. My get request is working and currently pulling in the image link and the id of each photo in the album. This is an example of the json that is returned.
{
 "photos": {
  "data": [
     {
        "picture": "https://scontent.xx.fbcdn.net/v/t1.0-0/s130x130/13879222_1235179076493734_1631898598554522774_n.jpg?oh=e6d74e7731f374be63a378e99ef3a88e&oe=58111449",
        "id": "1235179076493734"
     }

Here's my code so far
$.getJSON('https://graph.facebook.com/102060453138941?fields=photos{picture}&access_token=xxx',
function(fbResults) {

        for(var i =0; i < fbResults; i++) {

            $('.gallery').append(

            ''

            );

        }

    });

A: Try this:
for(var i = 0; i < fbResults.photos.data.length; i++) {
    $('.gallery').append(
        ''
    );
}

Btw, you will only get 25 entries with the API. You can set a limit with the limit parameter or you can use paging: https://developers.facebook.com/docs/graph-api/using-graph-api/#paging
If you need to get all entries at once, i suggest using paging with a recursive function.
Btw, you would need to add the User Token to each line, which is a very bad idea. The whole code should better go to the server and you should actually download the photos and cache them. Just saying.


text:
Q: Trying to Get the name of an uploaded Image I am trying to get the name of an image and save it instead of saving it as laravel default hashing.
i.e if an image name is go.jpg it should save as go.jpg instead of randomly generated numbers
Here is my controller
private function storeImage($news)
{
    if (request()->has('image')){
        $news->update([
            'image' => request()->image->store('uploads', 'public'),
        ]);

        $image = Image::make(public_path('storage/'. $news->image))->resize(600, 600);
        $image->save();
    }
}

A: getClientOriginalName use this method.
use Illuminate\Support\Facades\Input;

private function storeImage($news)
{
    if (request()->has('image')){
        $file = Input::file('image');
        $img= $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
        $news->update([
            'image' => $img,
        ]);

        $image = Image::make(public_path('storage/'. $news->image))-
      >resize(600, 600);
      $image->save();
    }
}

A: You can use this method: getClientOriginalName()
if ($request->hasFile('image')) {
    return $request->file('image')->getClientOriginalName();
} else {
    return 'no file!'
}

http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_getClientOriginalName


text:
Q: InputMismatchError while scanning number While trying to read a number using below code InputMismatchError is generated:
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {

    long number = sc.nextLong(); // Error here

    if (number % 2 == 0 && number != 0) {
        System.out.println("even");
    } else if (number % 2 != 0 && number != 0) {
        System.out.println("odd");
    } else if (number == 0) {
        System.out.println("");
    }
}

I don't understand where a mistake. Eclipse compiled program without errors.
Following is the input from console used
1234.5

A: If the input might have some non-integers with the values, you should check if the next value is a long. If not, ignore it:
while (sc.hasNext()) {
    // Check if next is a long
    if (sc.hasNextLong()) {
        long number = sc.nextLong();

        if (number == 0) {
            System.out.println("");
        }
        else if (number % 2 == 0) {
            System.out.println("even");
        }
        else {
            System.out.println("odd");
        }
    }
    else {
        // Not a long, consume rest of line.
        // You might need to change this to sc.next() depending on requirements
        sc.nextLine();
    }
}

A: You could do this way
Scanner scan = new Scanner(System.in);
long val = scan.nextLong();
System.out.printf(String.valueOf(val));

while you are expecting long you should pass non-decimal numeric value from command line.


text:
Q: Wamp does not show any thing on http://localhost I have installed wamp server on windows 7. Its saying You don't have permission to access the page when i type http://localhost/phpmyadmin but doing well when i type 127.0.0.1/phpmyadmin.
I am ok with it but just want to know is this some window restriction??

A: You need to stop IIS Services
If you wish to keep both running - http://www.programmerfish.com/how-to-run-wamp-server-parallel-with-iis-7-on-windows/


text:
Q: Session across domains in Rails 4 I have an issue with wanting to use session across domains (not subdomain).  Eg, I have .co.uk, .com.au, and .com all for the same address.
I know for subdomains I can use something like:
SomeApp::Application.config.session_store :cookie_store, key: '_some_app_session', domain => :all, :tld_length => 2

But I would like my solution to work between actually domains to have one set of sessions/cookies.

A: As your default session store is 'cookie_store'
You could just do it the same way as when you might send an email link with an authentication token. Check to verify that the cookie is correct on example.org and, if it is, redirect them to:
http://example.com?token=
and then check to make sure the token matches the one you have in the DB when they arrive. If the token does match, create the session cookie for the example.com domain and then change the token in the database.
This will successfully transfer from one domain to another while providing persistent login on the new domain (via cookie) and shutting the door behind them by changing the authentication token in the DB.
EDIT
To answer your question below, I don't think you need middleware or anything fancy. You could do a simple before filter in the application controller of example.org, something like:
before_filter :redirect_to_dot_com
...
def redirect_to_dot_com
  url = "http://example.com" + request.fullpath
  url= destination + (url.include?('?') ? '&' : '?') + "token=#{current_user.token}" if signed_in?
  redirect_to url, status: 301
end

That will redirect the user either way, and append the token to the query if the user is signed in on the .org site.
Go to more details on Persisting user sessions when switching to a new domain name (Ruby on Rails)

A: I wouldn't use the PHP style routings which pass ?php=bad style variables via :get especially if you're already using sessions.  And also since then you'd have to parse the original URL and a bunch of other work.
Instead of using session[:edition_id] = 'UK' you can use:
cookies[:edition_id] = { value: 'UK', domain: 'some-app.com', expires: 1.year.from_now }

# or if you want to be google 10.years.from_now

When you use session[:edition_id] = 'UK' the value will be encrypted by rails and stored in the _myapp_session cookie. But in your case that probably doesn't matter much.
If you set the cookie explicitly on the domain you want to read it from, it will work without having to set odd ball variables via get and then trying to interpret them again on redirect.


text:
Q: Django is asking to delete column, which does not even exists I tried applying migrations, but Django asks me to delete a column that does not exist.
The error I get is:
OperationalError at /admin/location/location/
(1054, "Unknown column 'location_location.id' in 'field list'")

models.py
class Location(models.Model):
    city = models.CharField(max_length=255)
    state = models.CharField(max_length=255)
    country = models.CharField(max_length=255)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)

views.py
def add_location(request):
    if request.method == 'POST':
        form = LocationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = LocationForm()
    return render(request, 'add_location.html', {'form': form})

admin.py
from django.contrib import admin
from .models import Location

# Register your models here.
admin.site.register(Location)

I tried using the --fake option but it made it even worse.
Traceback
Traceback (most recent call last):

    File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute
    return self.cursor.execute(query, args)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\MySQLdb\cursors.py", line 206, in execute
    res = self._query(query)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\MySQLdb\cursors.py", line 319, in _query
    db.query(q)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\MySQLdb\connections.py", line 254, in query
    _mysql.connection.query(self, query)

The above exception ((1054, "Unknown column 'location_location.id' in 'field list'")) was the direct cause of the following exception:   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\options.py", line 686, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view
    response = view_func(request, *args, **kwargs)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\sites.py", line 242, in inner
    return view(request, *args, **kwargs)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view
    response = view_func(request, *args, **kwargs)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\options.py", line 2068, in changelist_view
    "selection_note": _("0 of %(cnt)s selected") % {"cnt": len(cl.result_list)},   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 376, in __len__
    self._fetch_all()   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1867, in _fetch_all
    self._result_cache = list(self._iterable_class(self))   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 87, in __iter__
    results = compiler.execute_sql(   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\compiler.py", line 1398, in execute_sql
    cursor.execute(sql, params)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 103, in execute
    return super().execute(sql, params)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    with self.db.wrap_database_errors:   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute
    return self.cursor.execute(query, args)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\MySQLdb\cursors.py", line 206, in execute
    res = self._query(query)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\MySQLdb\cursors.py", line 319, in _query
    db.query(q)   File "C:\Users\sarthak.lamba\AppData\Local\Programs\Python\Python311\Lib\site-packages\MySQLdb\connections.py", line 254, in query
    _mysql.connection.query(self, query)

Exception Type: OperationalError at /admin/location/location/ Exception Value: (1054, "Unknown column 'location_location.id' in 'field list'")

A: Simply try this:
first, delete migration file related to that Location models and re-migrate manually using below commands:
python manage.py makemigrations appname

python manage.py sqlmigrate appname 0001 # this value will generate after makemigration. It can be either 0001 or 0002 and so on.

python manage.py migrate


text:
Q: Excel/VBA: Open New Workbook In New Window I am using Excel 2010, and am looking for a VBA script that will open a new workbook in a new window (such that I could, for example, place one workbook on each of 2 monitors).
I'd then place this VBA/macro on the ribbon and assign it a shortcut key. Thus, it'd work like CTRL+N, but the new workbook would open in a separate window/instance of Excel, instead of the same.
I've tried just using Shell ("excel.exe"), but I suppose since it is running from my PERSONAL.XLSB workbook, it then asks if I want to Read Only or Notify.
I just want CTRL+N functionality, but with the new window addition.
Thank you!

A: You can use this:
Sub NewApp()
    With CreateObject("Excel.Application")
        .Workbooks.Add
        .Visible = True
    End With
End Sub

but be aware that any automation of this sort won't load startup workbooks and add-ins by default.

A: Alternate way to do the same thing, includes selecting the file you want to open:
Sub tgr()

    Dim strFilePath As String
    Dim xlApp As Object

    strFilePath = Application.GetOpenFilename("Excel Files, *.xls*")
    If strFilePath = "False" Then Exit Sub  'Pressed cancel

    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = True
    xlApp.Workbooks.Open strFilePath

End Sub


text:
Q: JAXB-XJC compilation difference about compiling schema having  with name and without name i am having the application which compiles the schema using JAXB /XJC. i would like to identify the real problem when we are about to deploying web service code in application server . here we are having the schema contains element which does have type causing issues. i want to check are we giving the right schema to the compiler. assume the xsd definition we given below. This cause problem. The real difference is the standard definition generated class files web service not get deployed. but if we remove the element entirely, the web service get deployed successfully. can any one please Guide me?
Problematic schema (According to w3schools )
<xsd:complexType name="PersonType">
     <xsd:sequence>
          <xsd:element name="nom" type="xsd:string" />
          <xsd:element name="prenom" type="xsd:string" />
          <xsd:element name="date_naissance" type="xsd:date" />
          <xsd:element name="etablissement" type="xsd:string" />
          <xsd:element name="num_tel" type="xsd:string" />
     </xsd:sequence>
</xsd:complexType>

<xsd:element name="row" type="PersonType"/>

Working schema, (Webservice get deploying)
<xsd:complexType name="PersonType">
     <xsd:sequence>
          <xsd:element name="nom" type="xsd:string" />
          <xsd:element name="prenom" type="xsd:string" />
          <xsd:element name="date_naissance" type="xsd:date" />
          <xsd:element name="etablissement" type="xsd:string" />
          <xsd:element name="num_tel" type="xsd:string" />
     </xsd:sequence>
</xsd:complexType>

A: You should define a namespace for your xsd and a prefix to use each complex type.
The XSD should be
<?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema elementFormDefault="qualified"
    targetNamespace="http://yournamespace"
    xmlns:your_prefix="http://yournamespace"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <xsd:complexType name="PersonType">
        <xsd:sequence>
            <xsd:element name="nom" type="xsd:string" />
            <xsd:element name="prenom" type="xsd:string" />
            <xsd:element name="date_naissance" type="xsd:date" />
            <xsd:element name="etablissement" type="xsd:string" />
            <xsd:element name="num_tel" type="xsd:string" />
        </xsd:sequence>
    </xsd:complexType>

    <xsd:element name="row" type="your_prefix:PersonType"/>

</xsd:schema>


text:
Q: I want to change using C# the style of a set of shapefiles once I have uploaded them or while I am uploading them I am using C# and the WebRequest class to create a worksapce and then another WebRequest to create a datastore and upload a folder full of shapefiles to a geoserver. However, I would also like to change the style of the uploaded shapefiles to another style that has already been installed on the geoserver. Any ideas?
Lazaros.

A: Ok, this is what I did....
Assumptions: I have a List<string> named layers that contains my layer names, I have a string called style that contains the style name, I have a class SessionConfig defined as follows and being populated with appropriate values (url, username, password etc):
static class SessionConfig
{
    public static string url = null;
    public static string username = null;
    public static string password = null;
    // public static string locationOfCurl = null;
    public static string workspaceName = null;
    public static string storeName = null;
    public static string locationOfShapeFiles = null;
};

Then the code to change the style of each layer in my workspace/datastore is as follows:
    string responseFromServer = null;

            for (int i = 0; i < layers.Count; i++)
            {
    WebRequest request = WebRequest.Create(SessionConfig.url + "/rest/layers/" +
                                               SessionConfig.workspaceName + ":" + layers[i]);
                    request.ContentType = "text/xml";
                    request.Method = "PUT";
                    request.Credentials = new NetworkCredential(SessionConfig.username, SessionConfig.password);

                    byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<layer><defaultStyle><name>"+style+"</name></defaultStyle><enabled>true</enabled></layer>");
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(buffer, 0, buffer.Length);
                    requestStream.Close();
                    WebResponse response = null;

                    bool done = false;

                    try
                    {
                        while (!done)
                        {
                            response = request.GetResponse();
                            response.Close();
                            done = true;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
}

I'm not sure if this is 100% good code but it works for me.


text:
Q: Sync function wraps Async operations Say we have the following if statement
.
.
if (!user.comparePassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
    }
.
.

where comparePassword(password) is a function to check if the user input password is identical to the one in the database.., and it's in another module being defined as follows:
userSchema.methods.comparePassword = function (password) {
let match = false;

bcrypt.compare(password, this.password)
.then(function (isMatch) {
  if(isMatch){
    match = true;
  }
})
.catch(function (err) {
  // handle error
});
return match;
};

The problem is in I/O.., where one could easily see the if statement depends on a function comparePassword(password) that could finish execution before the promises inside it bcrypt.compare() finishes execution.., which means I get match most of the time false even if it should technically be true. the compare function of bcrypt runs an expensive operation, so how do I get the result of comparison in time without blocking code-execution ?


text:
Q: Is Hausdorff maximal principle and Kuratowski lemma same things? In the John's Kelley "General Topology" (pages 32-34) there is definition of both of them and its look like its just different ways of notation of one proposition. But also there is something strange on page 34 that is called "proof" and perhaps is just a sequence of random words.

A: It's perfectly straightforward: the Hausdorff maximal principle is the special case of the Kuratowski lemma in which the partial order is some family of sets ordered by $\subseteq$. It just happens that the more general result follows from the special case — as is shown on page $34$. This should not be an unfamiliar phenomenon: in elementary calculus one learns that the Mean Value Theorem is easily proved from Rolle's Theorem, which is clearly just a special case of it.


text:
Q: Determinant of a 3x3 matrix by permutation of rows in sagemaths (with CoCalc) In order to solve a mathematical problem, I would have liked to know how to calculate the determinant of a 3x3 matrix with permutation of rows in sagemaths on Co Calc. Here is a type of statement, the values change each time the page is reloaded, hence the interest of programming an algorithm to find the result of the exercise by changing the values of the corresponding matrix.

Thanking you in advance

A: Use this code to show $\det A=\det B$
R.<a,b,c> = QQ[]
A = matrix(R, [[a,b,c],[-8,-62,-38],[15,2,55]])
B = matrix(R, [[15,2,55],[a,b,c],[-8,-62,-38]])
det(A)
det(B)


text:
Q: What does the '@' operator do in Scala? I'm looking at some Scala code in the Akka codebase, and this code snippet below is responsible for handling an Exception.
override val supervisorStrategy =
OneForOneStrategy(loggingEnabled = false) {
  case e @ InvalidAssociation(localAddress, remoteAddress, reason) ⇒
    log.warning("Tried to associate with unreachable remote address [{}]. " +
      "Address is now gated for {} ms, all messages to this address will be delivered to dead letters. Reason: {}",
      remoteAddress, settings.RetryGateClosedFor.toMillis, reason.getMessage)
    endpoints.markAsFailed(sender(), Deadline.now + settings.RetryGateClosedFor)
    AddressTerminatedTopic(context.system).publish(AddressTerminated(remoteAddress))
    Stop

  case ShutDownAssociation(localAddress, remoteAddress, _) ⇒
    log.debug("Remote system with address [{}] has shut down. " +
      "Address is now gated for {} ms, all messages to this address will be delivered to dead letters.",
      remoteAddress, settings.RetryGateClosedFor.toMillis)
    endpoints.markAsFailed(sender(), Deadline.now + settings.RetryGateClosedFor)
    AddressTerminatedTopic(context.system).publish(AddressTerminated(remoteAddress))
    Stop

The code on line 3, case e @ InvalidAssociation - InvalidAssociation is indeed an exception type, but why is the e @ necessary and what does it do?

A: It's a bind operator. It allows you to assign an identifier to some complex pattern-matched value, so - for example - when pattern matching against case class, you can refer to both the fields of that case class as well as to the case class instance itself:
case class Record(intField: Int, stringField: String)

val something: Any = ...
something match {
   case entireInstance @ Record(intField, stringField) =>
       println(s"$entireInstance has fields $intField and $stringField")
}


text:
Q: Can someone help me with this algebraic inequality? I found this inequality on twitter and I can't seem to prove the statement.
Prove that for $a,b,c > 0$ that
$$
\frac{a+b+c}{2} \geq \frac{ab}{a+b} + \frac{ac}{a+c} + \frac{bc}{b+c}
$$
After an hour (and a crick in my neck) I've only been able to turn it into
$$
a^3(b+c)+b^3(a+c)+c^3(a+b)-2abc(a+b+c) \geq 0
$$
and I'm not even sure if that's much better.

A: We have that by HM-AM inequality
$$\frac{ab}{a+b} + \frac{ac}{a+c} + \frac{bc}{b+c}=\frac{1}{\frac1a+\frac1b} + \frac{1}{\frac1a+\frac1c}+ \frac{1}{\frac1b+\frac1c} \le$$ $$\le\frac{a+b}4+\frac{a+c}4+\frac{b+c}4=\frac{a+b+c}2$$

A: Since $(3,1,0)\succ(2,1,1),$ your inequality is true by Muirhead.


text:
Q: How do I get the text value of the active tab using JavaScript? How do I get the text value of the active tab using JavaScript? I can't modify the code on the page as it is a 3rd party web app. In the example, I would want the value "BASIC INFORMATION" returned. I'm assuming there is some type of way to leverage the tabindex=0 etc. but I don't know how?

Thanks!

A: applyNow-active looks like a good class to use. The challenge here is ignoring the child node.
let element = document.querySelector('.applyNow-active label');

let child = element.firstChild;
let texts = [];

while (child) {
    if (child.nodeType == 3) {
        texts.push(child.data);
    }
    child = child.nextSibling;
}

texts.join(""); // this is the text!

example: https://jsfiddle.net/vo0hperz/

A: Here's a way:
var textYouWant = document.querySelector('.applyNow-active>label').firstChild.textContent.trim();

A: Get the first child (textNode) of the .applyNow-active label:

let activeElement = document.querySelector('.applyNow-active label')
console.log(activeElement.firstChild.textContent.trim())

          "BASIC INFORMATION"
          APPLICATION STEP

          "BUSINESS INFORMATION"
          APPLICATION STEP

          "PERSONAL INFORMATION"
          APPLICATION STEP


text:
Q: What is the name and meaning of the second number at the end of a line in a Error Callstack? I've thrown an Error and I know the one number is the line in the file but what is the second number?
somefile.js:43644:11
^file            ^line    ^?
Example Callstack:
Error:  Error: p1 was rejected
    at Timeout.setTimeout [as _onTimeout] (/home/user/Node/async-demo/promise.js:6:16)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)

I'm sure this is the easiest question but I don't know how to ask to search SO or Google.

A: Usually it's [Class]:[Line Number]:[Character Position]


text:
Q: Sort vector of vectors I have
    vector<vector<int>> vec

in my c++ app.
Every vector of integers as an element of "big" vector has 4 INT values.
I want to sort vec basing on third value of it's content vectors of ints (I mean every "inside" vector third element) - is it possible?
EDIT
Let's say I've got a function
COST(vector<int>)

which calculates me some value based on my vector values - can I use it in comparation parameter too? It'd help me a lot more.

A: Sure it is. std::sort can take a third parameter which is the comparison function to use when sorting. For example, you could use a lambda function:
std::vector<std::vector<int>> vec;
// Fill it

std::sort(vec.begin(), vec.end(),
          [](const std::vector<int>& a, const std::vector<int>& b) {
  return a[2] < b[2];
});

Alternatively, you can pass anything else callable with signature bool(const std::vector<int>&, const std::vector<int>&), such as a functor or function pointer.

Response to edit: Simply apply your COST function to a and b:
std::sort(vec.begin(), vec.end(),
          [](const std::vector<int>& a, const std::vector<int>& b) {
  return COST(a) < COST(b);
});

A: If you want to compare the two vectors by cost, try this:
bool predicate(const std::vector<int>& a, const std::vector<int>& b)
{
    return COST(a) < COST(b);
}

Notes:

*

*The above works with C++98, too, I'm not sure about how widespread the use of C++11 is and whether you have a compliant compiler. Otherwise, you can of course use a lambda expression, too, as sftrabbit suggested.

*You don't say what COST returns, I simply assumed some sortable value like float or long.

*I hope you don't copy the vector when passing it to COST(), that would be horribly inefficient.

*COST suggests a macro, like all UPPERCASE_NAMES. Don't use macros. Don't use macro names for functions.

A: sort(vec.begin(), vec.end(), comp);
where comp is:
static bool comp(const vector<int>& vec1, const vector<int>& vec2){
    return vec1[2] < vec2[2];
}

A: #include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

// This makes the sort be according to column 2 and ascending
bool sortFunc( const vector<int>& p1,
           const vector<int>& p2 ) {
 return p1[1] < p2[1];
 }

int main() {

  srand(time(NULL));

  // Creates and initializes 10 x 4 vector
  vector< vector<int> > vec;
  for( int i=0; i<10; i++ ) {
   vector<int> tmpVec;
   for( int j=0; j<2; j++ ) {
  tmpVec.push_back( rand()%10 );
   }
   vec.push_back( tmpVec );
  }

  // Print out the pre-sorted vector
 cout << "Pre-sorting state:" << endl;
  for( int i=0; i<vec.size(); i++ ) {
   for( int j=0; j<vec[i].size(); j++ ) {
  cout << vec[i][j] << " ";
  }
cout << endl;
}
  cout << endl;

  // Do the sorting according to column 2
  sort(vec.begin(), vec.end(), sortFunc);

  // Print out the post-sorted vector
   cout << "Post-sorting state:" << endl;
   for( int i=0; i<vec.size(); i++ ) {
    for( int j=0; j<vec[i].size(); j++ ) {
  cout << vec[i][j] << " ";
    }
   cout << endl;
   }

  return 0;
  }

source: https://shihho.wordpress.com/2012/11/28/sort_with_vectors/


text:
Q: How to set Lock screen message programmatically In Setting we can set lock screen manually but I want to set lock screen message through programming

I have tried below approaches:

*

*1.have tried DevicePolicyManager.getDeviceOwnerLockScreenInfo, but it reterning null.

*I tried to get it using ContactsContract.Profile.CONTENT_URI, in this there is no field regarding this. I extracted the values of existing fields in this URI but there is no value as we have set for lock screen message.

*I tried to use LOCK_PATTERN_ENABLED & NEXT_ALARM_FORMATTED, these are also not useful.

I have tried all above approached but not able to set and get message if some one has knowledge let me update.

A: After a lot of research i got the proper solution by using reflection we can achieve it. There is a LockPatternUtils class by which we can get device information, Below is the code.
  ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);

    //String a = Settings.Secure.getString(getContentResolver(),"lock_screen_owner_info");
    //printLog("a : "+a);

    Class<?> cl = null;
    try {
        cl = Class.forName("com.android.internal.widget.LockPatternUtils");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    try {
        Constructor<?> cons = cl.getConstructor(Context.class);
        Object obj = cons.newInstance(this);
        Class[] paramInt = new Class[1];
        paramInt[0] = Integer.TYPE;
        Method method = cl.getDeclaredMethod("getOwnerInfo", paramInt);
        Log.d("b : " ,""+ method.invoke(obj, 0));
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }


text:
Q: Using more than nine back references in an R regex The code below does not work, because the replacement string for \10, \11, and so on,     cannot be read properly. It reads \10 as \1 and print 0 instead, can you help me fix it?
There is an answer in one of the threads, saying that I am supposed to use capturing or    naming groups, but I don't really understand how to use them.
headline <- gsub("regexp with 10 () brackets",
"\\1 ### \\2 ### \\3 ### \\4 ### \\5 ### \\6 ### \\7 ### \\8 ### \\9 ###
\\10### \\11### \\12### \\13### \\14### \\15### \\16",
page[headline.index])

A: According to ?regexp, named capture has been available in regexpr() and gregexpr() since R-2.14.0. Unfortunately, it is not yet available for sub() or, it turns out, gsub(). So, it may still be useful to you, but will probably require a bit more legwork than you might have hoped.
(For a few examples of naming groups in action, see the examples section of ?regexpr.)
ADDED LATER, FOLLOWING GREG SNOW'S ANSWER
Greg Snow alluded to the possibility of doing this with the gsubfn package.  Here's an example that shows that gsubfn() can indeed handle more than nine backreferences:
require(gsubfn)
string <- "1:2:3:4:5:6:7:8:9:10:11"
pat <- "^(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+"
gsubfn(pat, ~ paste(a,b,c,d,e,f,g,h,i,j,k,j,i,h,g,f,e,d,c,e,a), string)
# [1] "1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 5 1"

A: You might consider using gsubfn from the gsubfn package instead of gsub, it gives more options on how to create your replacement.


text:
Q: Condition on sigma algebra Say I toss two distinct coins.
Let A be event: there are two heads, $\{HH\}$
Let $\sigma$ be a sigma algebra $\big\{\emptyset,\Omega,\{HH,HT\},\{TT,TH\}\big\}$
How does one understand $P(A|\sigma)$, $E(A|\sigma)$?
How does the meaning differ if sigma algebra is chosen differently, say trivial, or full algebra?

A: The following are the definitions of conditional expectation and conditional probability, could you fit your case in?

Definition 1: If $\mathcal F \subseteq \mathcal G$ are two $\sigma$-fields, and $X$ a $\mathcal G$-measurable integrable random variable, then $\mathbb E[X | \mathcal F]$ is defined as any $\mathcal F$-measurable random variable $Y$, such that $\mathbb E[Y;A]=\mathbb E[X;A]$ for every $A \in \mathcal F$. Here $\mathbb E[X;A]$ is a notation for $\int_AX\,d\mathbb P$.
Definition 2: We define conditional probability as $\mathbb P(A | \mathcal F)=
\mathbb E[1_A|\mathcal F]$.

From above definition, such r.v. of $Y$ is guaranteed to exist, and is unique up to a.s. equivalence - this is guaranteed by one version of Radon-Nikodym Theorem (i.e. for finite positive $\mathbb P$, and finite signed $\mathbb Q(A) = \mathbb E[X;A] \ll \mathbb P$, the conditional expectation as a Radon-Nikodym Derivative exits and is unique up to a.s.)


text:
Q: Install Yeoman on C9.io Has anyone tried to install Yeoman in the Cloud9 environment? If so how to do it?
I get this error on any yeoman command:
<FATAL> EACCES, permission denied '/var/lib/stickshift/' </FATAL>

A: I can install yeoman but after running install for generators, they don't work:
$ yo angular
Error angular
You don't seem to have a generator with the name angular installed.
You can see available generators with npm search yeoman-generator and then install them with npm install [name].
To see the 0 registered generators run yo with the --help option.
Tried a couple other generators, none work so not just an issue with angular.
Then found:
Why are my Yeoman generators installing in the wrong place?
Fixed it!

A: Ok, so I played a little bit with Cloud9 and yeoman ;)
Seems like your error comes mainly from the fact that yeoman is trying to goes up the tree, looking for a Gruntfile.js ... Doing so it encounters an issue as the directory it tries to read are not accessible for the current user.
The first work-around is to create an empty Gruntfile.js:
'use strict';
 module.exports = function (grunt) {
 // Project configuration.
 grunt.initConfig({});
 };

Then launching "yeoman init" will ask you the standard questions and at a given point will ask you if it can overwrite the Gruntfile, which you can answer positively ;)
Then if you launch a "yeoman server", you'll encounter another error, due to the port the server is willing to answer.
Add the following options to your Gruntfile.js:
  server: {
    port: process.env.PORT,
    host: process.env.IP
},

Note that you also need to have Compass installed (gem install compass).
Then launching "yeoman server' will launch the server and the needed task (ending with the watch task) ...
I didn't went further down the path though ;)
Hope this helps.


text:
Q: Selenium + Python + onclick + NoSuchElementException I have an "onclick" element in a webpage whose HTML reads as follows:
Text 1

I am trying to use selenium to click on this element. I tried the following code (including an implicit wait)
import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.get(webpage);

driver.implicitly_wait(5)
driver.find_element_by_xpath("//a[@onclick='blah.submit()']").click()

However, it returned a NoSuchElementException
NoSuchElementException: Message: no such element: Unable to locate element:
{"method":"xpath","selector":"//a[@onclick='blah.submit()']"}

I then tried using WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get(webpage);

button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,
"//a[@onclick='blah.submit()']")))
button.click()

However, this still didn't work and returned the following error:
TimeoutException: Message:

Does anyone know what's going wrong? Thanks in advance.


text:
Q: Point on Circle (Longitude/Latitude) in .NET/SQL I've got the following problem:
I have a table with long/lat values and another table with a project-id and long/lat/radius (circle).
Now I need to find out which project matches the long/lat values from the first table.
Is there an easy way to do that?

A: There are multiple algorithms to calculate distance on sphere, but we use following:
create function GetDistance(
    @latitudeFrom decimal(30,10),
    @longitudeFrom decimal(30,10),
    @latitudeTo decimal(30,10),
    @longitudeTo decimal(30,10)
)
RETURNS float
AS
BEGIN

DECLARE @distance float

    SET @distance = ROUND(6378.137 * ACOS(
            convert(decimal(30,10),
            (SIN(RADIANS(@latitudeFrom)) * SIN(RADIANS(@latitudeTo))) +
            (COS(RADIANS(@latitudeFrom)) * COS(RADIANS(@latitudeTo)) *
             COS(RADIANS(@longitudeTo) - RADIANS(@longitudeFrom))))), 15)

 RETURN @distance
 END
 go

(where 6378.137 - is Earth's radius)
So now when you can calculate distance between 2 points on Earth you can build query
 select *
     from Table1, Project
     where dbo.GetDistance(
           Table1.lat, Table1.lon,
           Project.lat, Project.lon) < @YouRadius

where @YouRadius - parameterized radius of your circle

A: Relatively easy: compute the great-circle distance between the point and the centre of the circle.  If the distance is less than the radius, the point is in the circle, if not not.  If it's on the circumference of the circle, you decide.  There have been several SO discussions on computation of great-circle distances, have a look at them.
To speed things up you might consider storing, with the definition of each circle, its minimum bounding box in lat/long 'squares'.  This would provide you with the info necessary to do a quick check of whether a point is possibly inside a circle, only computing distances when the point is inside the mbb.


text:
Q: How do the permissions and triggers work in Apps Script API? I have read and re-read the docs (here) and here and related. Is there some other documentation that will help me get a better understanding of what type of permissions require what type of formatting, etc?
The puzzle I'm trying to solve is this: when someone edits a cell, I'd like the cell colors to be formatted based on the user who edited it.
It's easy to write a code that works just for myself; however, I keep running into problems with permissions in getting it to work for another person.
Here's where I get confused. I'll explain my understanding, and I hope you can either correct me or point me to a document with more info. There seem to be 3 ways to make an event occur when a cell is edited: an Edit Event, a simple onEdit trigger, and an installable onEdit trigger.
To create a simple onEdit trigger, you create a new function named onEdit(). To capture an event, you put a string in the parentheses, eg onEdit(e). And then to access info stored on edit, you type something like var range = e.source.getActiveRange(). Simple event triggers have restricted security and cannot get the name of a user/activeUser, so I can't use them to solve my problem.
To create an installable onEdit trigger that captures an event, you create a new function, eg myFunction(e). Then you get into script editor, click "resources", select your function from the dropdown, hit "from spreadsheet," and then onEdit. In this case, to access information about the event, you type something like var range = e.range.
This method is supposed to give more advanced permissions so that I should be able to go "variable user = e.user" and then "ss.toast(user)" to see the name of the user. However, when anyone besides myself does this, the toast is blank. Also, with this, I know the script "runs as the user who installed the script" but does that mean I can't access the identity of the person who triggered the script?
To create an Edit Event, you... well... is this the same thing as creating a trigger? I guess I'm totally lost on this one.
So what happens if I cross my wires-- for example, I name something myFunction(e) and make an installable onEdit trigger, but then instead of typing range = e.range I type range = e.source.getActiveRange? It seems to work the same for just me, but then have I crossed up permissions so that it will act like a simple event instead of an installable one?
The docs say:

"They may not be able to determine which user triggered the event being handled. For clock tick events, this is not important, but in a Spreadsheet edit event, the user changing the Spreadsheet would not necessarily be identifiable."

So... not necessarily? When would it work and when wouldn't it? Is it possible in my case? How do I find out (besides my current, failing method of trial-and-error?).

A: The documentation around this is a little confusing, and we should work to clarify it. If you use a simple trigger and the effective user, you should be able to get what you want.
function onEdit() {
  SpreadsheetApp.getActiveRange()
      .setComment('Last Editor: ' + Session.getEffectiveUser().getEmail());
}


text:
Q: I have to write query based on cases can i write like this
    SELECT   DISTINCT  AD_MA_CODE,AD_PA_CODE,AD_EN_CODE_PSV,AD_CODE,
    CASE  WHEN AD_EN_CODE_PSV = ID_EN_CODE_PSV AND  AD_CODE = ID_AD_CODE THEN '1'
     WHEN AD_CODE_POSTAL=ZL_CODE_POSTAL AND AD_VILLE=ZL_VILLE THEN AD_ADR_DEFAUT,AD_FACTURATION_VN,AD_LIVRAISON_VN,AD_VENTE_VN,AD_PA_CODE_IMP,
    AD_LA_CODE,AD_NOM_COMMERCIAL,AD_RUE,AD_LIEU,AD_CODE_POSTAL,AD_VILLE,AD_TELEPHONE,AD_FAX,AD_EMAIL,EN_NA_CODE,EN_OE_BLOQUE,LB_VALEUR,AD_FLAG_INT,
    AD_DATE_CRE,AD_ZL_CODE_ZONE,AD_CODE_GARANTIE,ZL_LIBELLE_ZONE,LG_CODE_TR_ASSOCIE,OP_CLE_CODE,LG_ANNU_OE,LG_OE_MOD,LG_MUT_CAF,UP_ANNU_OF,
    CLIENT.ET_TE_CODE TYPE_CLIENT,CLIENT_PROTOCOLE.ET_TE_CODE TYPE_CLIENT_PROTOCOLE,LIEU_GEOGRAPHIQUE.ET_TE_CODE TYPE_LIEU_GEOGRAPHIQUE,
    PA_CODE_ISO_3C,LG_CODE_UP,UP_LIBELLE,LG_AG_CODE,LG_STOCKEUR,LG_FACT_RETEN,AD_CODE_NOTICE FROM  CVNQTAD1 LEFT JOIN CVNQTLA1 ON
    AD_LA_CODE = LA_CODE_ISO_2C LEFT OUTER JOIN  CVNQTID1 ON  AD_EN_CODE_PSV = ID_EN_CODE_PSV JOIN  CVNQTEN1 ON  AD_EN_CODE_PSV = EN_CODE_PSV JOIN
    CVNQTPA1 ON  AD_PA_CODE_IMP = PA_CODE_ISO_2C JOIN  CVNQTLB ON  PA_CLE_LIBELLE = LB_CLE LEFT OUTER JOIN  CVNQTZL1 ON  AD_ZL_CODE_ZONE = ZL_CODE_ZONE
    AND  AD_MA_CODE = ZL_MA_CODE AND  AD_PA_CODE = ZL_PA_CODE LEFT OUTER JOIN
    CVNQTET1 CLIENT ON  EN_CODE_PSV = CLIENT.ET_EN_CODE_PSV AND  CLIENT.ET_TE_CODE =  'CL'  LEFT OUTER JOIN  CVNQTET1 CLIENT_PROTOCOLE ON
    EN_CODE_PSV = CLIENT_PROTOCOLE.ET_EN_CODE_PSV AND  CLIENT_PROTOCOLE.ET_TE_CODE =  'CD'  LEFT OUTER JOIN  CVNQTET1 LIEU_GEOGRAPHIQUE ON
    EN_CODE_PSV = LIEU_GEOGRAPHIQUE.ET_EN_CODE_PSV AND  LIEU_GEOGRAPHIQUE.ET_TE_CODE =  'LG'  LEFT OUTER JOIN  CVNQTLG1 ON
    AD_EN_CODE_PSV = LG_EN_CODE_PSV AND  AD_CODE = LG_AD_CODE LEFT OUTER JOIN  CVNQTUP1 ON  LG_CODE_UP = UP_CODE LEFT OUTER JOIN
    CVNQTAG1 ON  LG_AG_CODE = AG_CODE LEFT OUTER JOIN  CVNQTOP1 ON  LG_OPERATEUR = OP_CODE  WHERE  EN_MA_CODE = 'AC' AND  AD_PA_CODE = 'NL' AND
    (AD_PA_CODE IS NOT NULL  AND  AD_MA_CODE IS NOT NULL  AND  AD_FACTURATION_VN IS NOT NULL  AND  AD_LIVRAISON_VN IS NOT NULL  AND
    AD_VENTE_VN IS NOT NULL  AND  AD_PA_CODE_IMP IS NOT NULL ) AND  LB_LC_LOCALE = 'fr_FR' ORDER BY  AD_PA_CODE,AD_MA_CODE ASC
    ELSE  DECODE (AD_ADR_DEFAUT, null, '0', AD_ADR_DEFAUT) END AS AD_ADR_DEFAUT,AD_FACTURATION_VN,AD_LIVRAISON_VN,AD_VENTE_VN,AD_PA_CODE_IMP,
    AD_LA_CODE,AD_NOM_COMMERCIAL,AD_RUE,AD_LIEU,AD_CODE_POSTAL,AD_VILLE,AD_TELEPHONE,AD_FAX,AD_EMAIL,EN_NA_CODE,EN_OE_BLOQUE,LB_VALEUR,AD_FLAG_INT,
    AD_DATE_CRE,AD_ZL_CODE_ZONE,AD_CODE_GARANTIE,ZL_LIBELLE_ZONE,LG_CODE_TR_ASSOCIE,OP_CLE_CODE,LG_ANNU_OE,LG_OE_MOD,LG_MUT_CAF,UP_ANNU_OF,
    CLIENT.ET_TE_CODE TYPE_CLIENT,CLIENT_PROTOCOLE.ET_TE_CODE TYPE_CLIENT_PROTOCOLE,LIEU_GEOGRAPHIQUE.ET_TE_CODE TYPE_LIEU_GEOGRAPHIQUE,
    PA_CODE_ISO_3C,LG_CODE_UP,UP_LIBELLE,LG_AG_CODE,LG_STOCKEUR,LG_FACT_RETEN,AD_CODE_NOTICE FROM  CVNQTAD1 LEFT JOIN CVNQTLA1 ON
    AD_LA_CODE = LA_CODE_ISO_2C LEFT OUTER JOIN  CVNQTID1 ON  AD_EN_CODE_PSV = ID_EN_CODE_PSV JOIN  CVNQTEN1 ON  AD_EN_CODE_PSV = EN_CODE_PSV JOIN
    CVNQTPA1 ON  AD_PA_CODE_IMP = PA_CODE_ISO_2C JOIN  CVNQTLB ON  PA_CLE_LIBELLE = LB_CLE LEFT OUTER JOIN  CVNQTZL1 ON  AD_ZL_CODE_ZONE = ZL_CODE_ZONE
    AND  AD_MA_CODE = ZL_MA_CODE AND  AD_PA_CODE = ZL_PA_CODE LEFT OUTER JOIN
    CVNQTET1 CLIENT ON  EN_CODE_PSV = CLIENT.ET_EN_CODE_PSV AND  CLIENT.ET_TE_CODE =  'CL'  LEFT OUTER JOIN  CVNQTET1 CLIENT_PROTOCOLE ON
    EN_CODE_PSV = CLIENT_PROTOCOLE.ET_EN_CODE_PSV AND  CLIENT_PROTOCOLE.ET_TE_CODE =  'CD'  LEFT OUTER JOIN  CVNQTET1 LIEU_GEOGRAPHIQUE ON
    EN_CODE_PSV = LIEU_GEOGRAPHIQUE.ET_EN_CODE_PSV AND  LIEU_GEOGRAPHIQUE.ET_TE_CODE =  'LG'  LEFT OUTER JOIN  CVNQTLG1 ON
    AD_EN_CODE_PSV = LG_EN_CODE_PSV AND  AD_CODE = LG_AD_CODE LEFT OUTER JOIN  CVNQTUP1 ON  LG_CODE_UP = UP_CODE LEFT OUTER JOIN
    CVNQTAG1 ON  LG_AG_CODE = AG_CODE LEFT OUTER JOIN  CVNQTOP1 ON  LG_OPERATEUR = OP_CODE  WHERE  EN_MA_CODE = 'AC' AND  AD_PA_CODE = 'NL' AND
    (AD_PA_CODE IS NOT NULL  AND  AD_MA_CODE IS NOT NULL  AND  AD_FACTURATION_VN IS NOT NULL  AND  AD_LIVRAISON_VN IS NOT NULL  AND
    AD_VENTE_VN IS NOT NULL  AND  AD_PA_CODE_IMP IS NOT NULL ) AND  LB_LC_LOCALE = 'fr_FR' ORDER BY  AD_PA_CODE,AD_MA_CODE ASC

A: The case construct has to have an "end".
CASE
WHEN condition1 THEN value1
WHEN condition2 THEN value2
END [column-alias]

So, the first few lines of your query might look more like this:
SELECT DISTINCT
  AD_MA_CODE
, AD_PA_CODE
, AD_EN_CODE_PSV
, AD_CODE
, CASE
  WHEN AD_EN_CODE_PSV = ID_EN_CODE_PSV AND AD_CODE = ID_AD_CODE
    THEN '1'
  WHEN AD_CODE_POSTAL=ZL_CODE_POSTAL AND AD_VILLE=ZL_VILLE
    THEN AD_ADR_DEFAUT
  END c1
, AD_FACTURATION_VN
. . .

I would also caution against the "blind" use of select distinct.
If you're getting "duplicate" rows in your query, then removing the cause of that duplication (often an incorrect join condition) is a better choice then trying to get the database to try and resolve them out afterwards.
This can have a huge negative performance impact, especially on resultsets with a large number of columns (distinct a, b, c can perform as poorly as group by a, b, c order by a, b, c - and you've a lot more than three columns there!).


text:
Q: Refresh a ListView implemented using Lazy Load and JSON I have implement Fedor's Lazy Load code to implement a subset of my application. I am pulling data using the facebook sdk and showing a newsfeed post with its comments, like count, etc in an activity. There is also a comment box using which, you can post a comment to the newsfeed post. This function works just fine. What I want to do however is, after a user has posted his comment to the thread, the list should refresh and also display the comment he just posted. I have tried calling the adapter.notifyDataSetChanged(); in the onClick method right after posting the comment. The listview never refreshes though.
Correct me if I am wrong here, but my best guess is, the arraylist I have used to hold the data is not refreshing. Here are the (what I think) relevant parts of the code. Please let me know if more is needed.
The onCreate method: initialize the ArrayLists and pull data using JSONObject and JSONArray
arrayUserID = new ArrayList<String>();
arrayProfilePic = new ArrayList<String>();
arrayFromName = new ArrayList<String>();
arrayMessage = new ArrayList<String>();

try {

    JOFeedDetails = new JSONObject(apiResponse);
    JAFeedDetails = JOFeedDetails.getJSONArray("data");

    for (int i = 0; i < JAFeedDetails.length(); i++) {
        json_data = JAFeedDetails.getJSONObject(i);

        // GET THE POST'S FROM USER NAME AND ID
        JSONObject joFromName = new JSONObject();
        joFromName = json_data.optJSONObject("from");

        if (joFromName.has("id"))   {
            String getCommentersID = joFromName.getString("id");
            arrayUserID.add(getCommentersID);
            String fromProfilePic = "https://graph.facebook.com/"+ getCommentersID +"/picture?type=square" + "&access_token=" + Utility.mFacebook.getAccessToken();;
            arrayProfilePic.add(fromProfilePic);
        } else {
            String getCommentersID = "";
            arrayUserID.add(getCommentersID);
        }

        if (joFromName.has("name")) {
            String getCommentersName = joFromName.getString("name");
            arrayFromName.add(getCommentersName);
        } else {
            String getCommentersName = "";
            arrayFromName.add(getCommentersName);
        }

        if (json_data.has("message"))   {
            String getMessage = json_data.getString("message");
            arrayMessage.add(getMessage);
        } else {
            String getMessage = "";
            arrayMessage.add(getMessage);
        }

        // GET THE POST'S TIME STAMP
        if(json_data.has("created_time"))   {

            String dateStr = json_data.optString("created_time");
            SimpleDateFormat formatter = getDateFormat();
            ParsePosition pos = new ParsePosition(0);
            long then = formatter.parse(dateStr, pos).getTime();
            long now = new Date().getTime();

            long seconds = (now - then)/1000;
            long minutes = seconds/60;
            long hours = minutes/60;
            long days = hours/24;

            String friendly = null;
            long num = 0;
            if (days > 0) {
                num = days;
                friendly = days + " day";
            } else if (hours > 0) {
                num = hours;
                friendly = hours + " hour";
            } else if (minutes > 0) {
                num = minutes;
                friendly = minutes + " minute";
            } else {
                num = seconds;
                friendly = seconds + " second";
            }
            if (num > 1) {
                friendly += "s";
            }
            String postTimeStamp = friendly.toUpperCase() + " AGO";
            arrayTimeStamp.add(postTimeStamp);
        } else {
            String postTimeStamp = "";
            arrayTimeStamp.add(postTimeStamp);
        }

        if (json_data.has("likes")) {
            String getCommentLikes = json_data.getString("likes");
            arrayCountLikes.add(getCommentLikes);
        } else {
            String getCommentLikes = "0";
            arrayCountLikes.add(getCommentLikes);
        }
    }

} catch (Exception e) {
}

stringUserID = new String[arrayUserID.size()];
stringUserID = arrayUserID.toArray(stringUserID);

stringProfilePics = new String[arrayProfilePic.size()];
stringProfilePics = arrayProfilePic.toArray(stringProfilePics);

stringFromName = new String[arrayFromName.size()];
stringFromName = arrayFromName.toArray(stringFromName);

stringMessage = new String[arrayMessage.size()];
stringMessage = arrayMessage.toArray(stringMessage);

stringTimeStamp = new String[arrayTimeStamp.size()];
stringTimeStamp = arrayTimeStamp.toArray(stringTimeStamp);

stringCountLikes = new String[arrayCountLikes.size()];
stringCountLikes = arrayCountLikes.toArray(stringCountLikes);

getNewsfeedDetailsHeader();

adapter = new NewsFeedDetailsAdapter(this, stringUserID, stringFromName, stringProfilePics,
        stringMessage, stringTimeStamp, stringCountLikes);

list.setAdapter(adapter);

And the onClick event from where the comment is posted:
public OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                Bundle parameters = new Bundle();
                parameters.putString("message", txtCommentBox.getText().toString());
                parameters.putString("description", getString(R.string.app_desc));
                parameters.putString("caption", getString(R.string.app_name));

                Utility.mFacebook.request(fetchedThreadID + "/comments", parameters, "POST");

                adapter.notifyDataSetChanged();

                InputMethodManager inputManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(txtCommentBox.getWindowToken(), 0);
                txtCommentBox.setText("");
            } catch (Exception e) {
            }
        }
    };

I really appreciate your patience going through this long post. But I really think it might be helpful to understand the flow. I hope someone here can help get me through this problem.

A: I ran into a similar problem once where my ArrayLists were not updating.
try calling .clear() on your Arraylist before adapter.notifyDataSetChanged()   this worked for me.  Good luck!


text:
Q: Adding a background image to a UILabel I'm attempting to add a UIImageView to the subview of a UILabel, but for some reason, I'm unable to have it as the background as this will cover the actual label text.
I don't want to set the UILabel's background color as because it will repeat as a pattern:
[self setBackgroundColor: [UIColor colorWithPatternImage:[UIImage imageNamed:@"someBg.png"]]];

Looking at the number of subviews to a raw UILabel it seems like the text isn't a UIView so adding the subview to index 0 won't help either.
I need the text to be ON TOP of the image background.
Any ideas?

A: Your options:

*

*Wrap the label and the background image view in another container view.

*Write your own label class that supports background images.

A: Anyhow I solved this by inheriting UITextField and adding the subview to that. This works since there's actually a UILabel subview within this control and adding it behind it naturally solves the problem.
Also, I disabled user interaction so that it behaves like a label.


text:
Q: The images of disjoint regions separated by a circle or line are disjoint under a linear fractional transformation It is known that linear fractional transformations (LFTs) take lines and circles to either a line or a circle.
$$ T: \{ \text{ Line or Circle } \} \mapsto \{ \text{ Line or Circle } \}$$
I would like to know whether the two regions of $\mathbb{C}$ partitioned by a line or circle map to regions that are disjoint with respect to each other. Additionally, are the images of these regions still separated by the image of the divider (the line or the circle)?
In multivariate real analysis, it is known that given a set $S$, a diffeomorphism $f$ takes
$$int(S) \mapsto int(f(S))$$ $$bd(S) \mapsto bd(f(S))$$ $$int(S^{c}) \mapsto int(f(S)^{c})$$
Perhaps there is an analog for holomorphic functions -- in particular, for LFTs.

A: Here's an approach with a classical geometric flavour. First note the following:

Let $Q$ be a line or circle partitioning $\Bbb{C}$ into two regions and let $x,y\in\Bbb{C}-Q$. Then there exists a line or circle $Q'$ with $x,y\in Q$ and $Q'\cap Q=\varnothing$ if and only if $x$ and $y$ are in the same region.

Now let $Q$ be a line or circle and let $f$ be a linear fraction transformation. We distinguish two cases:

*

*Suppose $x$ and $y$ are in the same region with respect to $Q$. Let $Q'$ be a line or
circle with $x,y\in Q'$ and $Q'\cap Q=\varnothing$. Then $f(Q')$ is a line or circle with $f(x),f(y)\in f(Q')$ and $f(Q')\cap f(Q)=\varnothing$, so
$f(x)$ and $f(y)$ are in the same region with respect to $f(Q)$.

*Suppose $x$ and $y$ are not in the same region with respect to $Q$. If $f(x)$ and $f(y)$ are in the same region with respect to $f(Q)$, then there exists a line or circle $Q'$ such that $f(x),f(y)\in Q'$ and $Q'\cap f(Q)=\varnothing$. Then $f^{-1}(Q')$ is a line or circle with $x,y\in f^{-1}(Q')$ and $f^{-1}(Q')\cap Q=\varnothing$, contradicting the fact that $x$ and $y$ are not in the same region with respect to $Q$. So $f(x)$ and $f(y)$ are in the same region with respect to $f(Q)$.

Here's an approach with a more topological flavour. First note the following:

Let $X$ be a connected topological space and $f: X\ \longrightarrow\ Y$ a continuous map. Then $f(X)$ is a connected subspace of $Y$

Now let $Q$ be a line or circle and let $f$ be a linear fraction transformation. Then the connected components of $\Bbb{C}-Q$ are the two regions that $Q$ divides $\Bbb{C}$ into. We distinguish two cases:

*

*Suppose $x$ and $y$ are in the same region with respect to $Q$. The restriction of $f$ to this region is a continuous map from a connected space to $\Bbb{C}-f(Q)$, so its image is connected. Ihis means it is contained in a connected component of $\Bbb{C}-f(Q)$, i.e. $f(x) $ and $f(y)$ are in the same region with respect to $f(Q)$.

*Suppose $x$ and $y$ are not in the same region. If $f(x)$ and $f(y)$ are in the same region with respect to $f(Q)$...


text:
Q: Django unittest and mocking the requests module I am new to Mock and am writing a unit test for this function:
# utils.py
import requests

def some_function(user):
    payload = {'Email': user.email}
    url = 'http://api.example.com'
    response = requests.get(url, params=payload)

    if response.status_code == 200:
       return response.json()
    else:
        return None

I am using Michael Foord's Mock library as part of my unit test and am having difficulty mocking the response.json() to return a json structure. Here is my unit test:
# tests.py
from .utils import some_function

class UtilsTestCase(unittest.TestCase):
    def test_some_function(self):
        with patch('utils.requests') as mock_requests:
            mock_requests.get.return_value.status_code = 200
            mock_requests.get.return_value.content = '{"UserId":"123456"}'
            results = some_function(self.user)
            self.assertEqual(results['UserId'], '123456')

I have tried numerous combinations of different mock settings after reading the docs with no luck. If I print the results in my unit test it always displays the following instead of the json data structure I want:
<MagicMock name=u'requests.get().json().__getitem__().__getitem__()' id='30315152'>

Thoughts on what I am doing wrong?

A: Another pattern I like to use that is a little more reusable would be to start the patcher in your unit test's setUp method. It's also important to check that mock request was called  with the expected parameters:
class UtilsTestCase(TestCase):

    def setUp(self):
        self.user = Mock(id=123, email='foo@bar.com')

        patcher = patch('utils.requests.get')
        self.mock_response = Mock(status_code=200)
        self.mock_response.raise_for_status.return_value = None
        self.mock_response.json.return_value = {'UserId': self.user.id}
        self.mock_request = patcher.start()
        self.mock_request.return_value = self.mock_response

    def tearDown(self):
        self.mock_request.stop()

    def test_request(self):
        results = utils.some_function(self.user)

        self.assertEqual(results['UserId'], 123)

        self.mock_request.assert_called_once_with(
            'http://api.example.com'
            payload={'Email': self.user.email},
        )

    def test_bad_request(self):
        # override defaults and reassign
        self.mock_response.status_code = 500
        self.mock_request.return_value = self.mock_response
        results = utils.some_function(self.user)

        self.assertEqual(results, None)

        self.mock_request.assert_called_once_with(
            'http://api.example.com'
            payload={'Email': user.email},
        )

A: Patch json method instead of content. (content is not used in some_function)
Try following code.
import unittest

from mock import Mock, patch

import utils

class UtilsTestCase(unittest.TestCase):
    def test_some_function(self):
        user = self.user = Mock()
        user.email = 'user@example.com'
        with patch('utils.requests') as mock_requests:
            mock_requests.get.return_value = mock_response = Mock()
            mock_response.status_code = 200
            mock_response.json.return_value = {"UserId":"123456"}
            results = utils.some_function(self.user)
            self.assertEqual(results['UserId'], '123456')

A: Another way that I believe is more clear and straight forward:
import unittest

from mock import Mock, patch

import utils

class UtilsTestCase(unittest.TestCase):
    def test_some_function(self):
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {"UserId": "123456"}
        with patch('utils.requests.get') as mock_requests:
            results = utils.some_function(self.user)
            self.assertEqual(results['UserId'], '123456')


text:
Q: How to Install devtoolset 8 in RHEL 8 image Please help me to install dev toolset-8 in rhel 8 image.
i have pulled the base image as below . I want to install devtoolset-8. is there any other way please let me know.
sudo docker pull registry.access.redhat.com/ubi8/ubi:8.2

A: devtoolset is called gcc-toolset in RHEL8.
The following commands worked for me:
microdnf install -y gcc-toolset-12
scl enable gcc-toolset-12 bash
gcc --version
# gcc (GCC) 12.1.1 20220628 (Red Hat 12.1.1-3)

A: According to that article, you can check if you have access to Red Hat Software Collections (RHSCL) by running the following command by the root user:
$ su -
# subscription-manager repos --list | egrep rhscl

If you have, enable necessary software repo and then install devtoolset:
# subscription-manager repos --enable rhel-7-server-optional-rpms
# yum install devtoolset-8

A: The other answer seems to be for RHEL 7.
On the RedHat site
Chrisian Labisch answered this with:

RHEL 8 doesn't work with Software Collections, RHEL 8 uses modules instead.
sudo dnf module list
In RHEL 8 you find the developer tools in the CodeReady Builder repository. :)
sudo subscription-manager repos --enable codeready-builder-for-rhel-8-x86_64-rpms

But even that seems to be unneeded because the system compiler version for RHEL is already GCC 8, so you would normally only need devtoolset-9 or up for it, if I understood the purpose correctly.
Additionally this blog post outlines the differences between the old SCL toolsets and the new AppStreams concept.


text:
Q: Dereference operator (*) differences between char* and int* Why is the operator (*) needed to access the value of an int* variable but not for char*?
char *char_ptr;
int *int_ptr;
int mem_size = 50;

char_ptr = (char *) malloc(mem_size);
strcpy(char_ptr, "This is memory is located on the heap.");
printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);

int_ptr = (int *) malloc(12);
*int_ptr = 31337;
printf("int_ptr (%p) --> %d\n", int_ptr, *int_ptr);

Output:
char_ptr (0x8742008) --> 'This is memory is located on the heap.'
int_ptr (0x8742040) --> 31337

A: This is because of the way the printf format specifiers work: the %s format expects, for its corresponding argument, a pointer to a character (more precisely, the address of a nul-terminated string - which can be an array of char, an allocated buffer with at least one zero byte in it, or a string literal), so you can just give it the char_ptr variable as-is; on the other hand, the %d format expects an integer (not a pointer-to-integer), so you have to dereference the int_ptr variable using the * operator.
Note on Good Programming Style: As mentioned in the comments to your question, be sure to call free() at some point on every buffer allocated with malloc, or you will introduce memory leaks into your code. Also see: Do I cast the result of malloc?.

A: You also can use the expression *char_ptr. It has the type char and the expression will yield the pointed character that is 'T' - the first character of the stored string literal.
This is the same as *int_ptr that returns the first element of the allocated integer array.
As for the conversion specifier %s then it expects an argument of the type char * that points to a string. On the other hand, the conversion specifier %d expects an object of the type int
You could use the conversion specifier %c. to output just a single character of the pointed string like
printf( "%c", *char_ptr );

A: For any pointer or array p and index i, the expression p[i] is exactly equal to *(p + i). From that follows that *p is equal to p[0].
In your case *int_ptr is equal to int_ptr[0].
If you did the same with char_ptr (i.e. *char_ptr) you would have char_ptr[0] which is a single character, that could be printed with %d as well:
printf("char_ptr (%p) --> '%d'\n", char_ptr, *char_ptr);

This would print the decimal representation of the first character in the string.

A:
"Why is operator (*) needed to access the value of an int* variable and not for char* ?"

Because at the printf() function, the format specifier %s expects a matching argument of type char * - a pointer to a string, while %d expects an argument of type int.
In the latter case, the dereference operator * is required to dereference int_ptr and yield the value of the int object int_ptr points to.
As char_ptr is already of type char* as required by %s, there is no need to dereference it.

Side notes:
1.
int_ptr = (int *) malloc(12);

Note that with 12 Bytes on most modern system you be able to allocate only 1 int object as it requires 8 Byte. The remaining 4 Byte are not sufficient to hold another.
If you want to allocate space for only one int, use sizeof(*int_ptr):
int_ptr = (*int) malloc(sizeof(*int_ptr));

2.
Also don´t forget to free() the storage allocated by malloc() after its use:
free(int_ptr);
free(char_ptr);

3.
Furthermore there is no need to cast the return value of malloc(): Do I cast the result of malloc?
char_ptr = malloc(mem_size);
int_ptr = malloc(sizeof(*int_ptr));


text:
Q: Java. IO. Как из байтов собрать файл? У меня через сокет приходит поток байтов которые мне надо собрать в файл. Но как это сделать c файлом? С строкой понятно можно просто написать
InputStream input = socket.getInputStream();
DataInputStream in = new DataInputStream(input);
String s = in.readUTF()

А как с файлом аналогичную ситуацию создать?
можно читать просто in.read() и он мне вернет int. Как я из него объект File обратно могу собрать?
Могу ли я отправить файл в сокет так?:
void upload(String path) {
        try (OutputStream out = this.socket.getOutputStream()) {
            InputStream in = new FileInputStream(path);
            int i = in.read();
            while (i != -1) {
                подскажите что тут?
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

A: Попробуйте код приведенный ниже (не забудьте, про кодировку)
InputStream input = socket.getInputStream();
DataInputStream in = new DataInputStream(input);

try (OutputStream outputStream = Files.newOutputStream(Paths.get("file.txt"))) {
   byte[] buffer = new byte[1024];
   int count = 0;
   while ((count = in.read(buffer)) != -1)
      outputStream.write(buffer, 0, count);
}

A:
InputStream input = socket.getInputStream();
// Саздаём пустой массив байтов из
byte[] buffer = new byte[input.available()];
// Читаем из InputStream
initialStream.read(buffer);
// Саздаём файл  ...
File file = new File("path to your file..");
// Саздаём OutputStream из файла  ...
OutputStream outStream = new FileOutputStream(file);
// Записываем массив байтов в файл
outStream.write(buffer);


text:
Q: How to open new tab in existing window using keyboard shortcuts on Ubuntu Keyboard shortcut Ctrl+Alt+T opens a new terminal window on Linux. By default it opens 1 new terminal window.
Is there a way how to customize how many new tabs are going to be opened? E.g. by using this shortcut it will open 2 tabs by default.
What is the right keyboard shortcut to open a new tab in existing terminal ?
I want to have 2 tabs opened and switch between them with Ctrl+Page Up.

A: Looking in the menu I can see that the shortcut to open a new tab is CTRL+SHIFT+T

A: Once you have Terminal open you can use Shift+Ctrl+T, and that will open another tab.  see image below.  Once you do that you can use Ctrl+Page Up to switch.

A: If you want to open gnome-terminal with more than one tab when you open it using Ctrl+Alt+T shortcut, go to System Settings → Keyboard → Shortcuts → Custom Shortcuts and add a new Ctrl+Alt+T shortcut as follow:

Select Reassign when you are asked:

Now, to open a new tab in gnome-terminal, you can use Ctrl+Shift+T. To access/view/edit your terminal shortcuts go to Edit → Keyboard Shortcuts...:


text:
Q: goto a specific line in awk to start processing I want the awk to go to the beginning of the block of lines to start processing it again once it hit the bottom of that block and processed its last line.
Basically, if block of text is
<START of block>
Hi
How
Are
You
<END of block>

I want awk to check if "You" is last line of the block, then to print that block else not the print it. There are multiple blocks of texts with different values in my file.
If I can make awk to go to a specific line stored in 'line' variable to start processing then my purpose would be solved.

A: if I understood correctly:
  - your input has a dedicated line saying "<START of block>", and another for "<END of block>", and you want to print that block (including those 2 markers? or not?) if they end up with "You" at the line before "<END of block>" ?
then:
awk -v regstart="<START of block>" -v regend="<END of block>" -v reglast="You" '
 BEGIN { rem="we will remember a block between those regstart and regend markers, and only print it if the last line matches reglast"
         remember=0; rem="by default we are not inside a block, so we do not remember lines until we match the regstart"
 }

 ( $0 ~ regstart ) {
     remember=1; nb=0;
 }

 ( remember==1 )   {
     line[++nb]=$0 ;
 }

 ( $0 ~ regend   ) {
     remember=0; rem="we reached the end of block, we do not remember anymore the lines we see until next regstart"
     if ( line[(nb-1)] ~ reglast ) {
          ## for(i=2;i<=(nb-1);i++) { rem="this version do NOT show the 2 marker lines"
          for(i=1;i<=nb;i++) { rem="this version shows the 2 marker lines"
              print line[i]
          }
          ## print "" ; rem="uncomment this line if you want a separator lines between blocks"
     }
 }

'

Note1: I use regexps to match start, end and last line, but you could use "==" intead to compare exact strings.
Note2: the printing part: could go from 2 to nb-1 to not show the START (stored in line[1]) and END (stored in line[nb]) lines.
Note3: the script above happily processes every blocks and only prints those that finished with a line matching "reglast". Ie it doesn't only print one, but all matching blocks.

A: A shorter awk alternative for an input at below:
< infile awk -v RS='\n<END of block>' '$NF == "You" { print $0 RS }'
<START of block>
Hi
How
Are
You
<END of block>

<START of block>
thank
You
<END of block>

$NF here (according to the defined RS (Record Separator) setting to a static string that makes we separate each block based on that) indicates the value of last line, so if it's equal with Yes string then print that block and revert back RS as well.
Input file:
<START of block>
Hi
How
Are
You
<END of block>
<START of block>
Hi
How
Are
not YOU
<END of block>
<START of block>
thank
You
<END of block>
<START of block>
welcome
to
Unix
<END of block>


text:
Q: SharePoint | Change Combo Box Options Depending on Same Combo Box Status Can JavaScript manipulate the options of a combo box?
Idea is to When a status was changes to "B" after submitting the form and the other person change the status "A" should not be an option because it's a previous step.

A: Yes, You can write a javascript based on the option selected in combobox.
Let say if the status of a dropdown is "B", you can disable the dropdown, so that nobody can change the status.
<script>
$(document).ready(function()
{
  var statusValue = $('select[title=DDStatus]').val();
  if(statusVal == "B")
  {
    $("select[title$='DDStatus']").attr('disabled', 'disabled');
  }
}
);
</script>

You can also do validation on other fileds based on the status column before you click on OK button.
you can use a PreSaveAction() function to do that.
function PreSaveAction()
{
  var statusValue = $('select[title=DDStatus]').val();
  if(statusVal == "B")
  {Your code here with return false;}
  else{return true; }
}

I hope it helps you.

A: Hi Guys here's my solution to this.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>

$( document ).ready(function() {

if($("#ID option:selected").val() == "Initial"){

$("#ID option[value='Initial']").attr("disabled", "disabled");
//to disable

$("#ID option[value='Invalid']").attr("disabled", false);
//to enable

}
});
</script>


text:
Q: How to get out of input in Linux console I have written a program that asks for user input in a loop and only terminates when exit was entered. However, there seems to be a bug in my program so that I can never exit. Is there a Linux shortcut that lets me exit the program even when I am in the user input? I am running Linux in Oracle Virtualbox on a Windows 10 Laptop.
I think the reason might be fgets. Now, using fflush() "test" is printed, but after this the command line expects input again. The function "parse" is specified in the function parser.c but this should not be of relevance for this question.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "parser.c"

int main()
{
    //Ausgabe des "$"
    write(1, "$", 1);
    //Auf Eingabe des Nutzers warten:
    char *input=malloc(1024*sizeof(char));
    fgets(input, 1023, stdin);
    fflush(stdout);
    printf("%s", "test", 5);
    parse(input);
    return 0;
}

Thank you very much for your answer.