text:
Q: Create a child thread that is independent of parent in C++ I am working in a C++ DLL module where I need to perform a task for every X min independently. I tried to create a thread for the task but my main program which creates threads will also keep waiting for the child thread(s) to complete.
Could someone please help me how to create a separate process (Please provide sample code if possible) independent of main program and do the Task?
The process should take a function and run the code present in function for every X min.
EDIT:
void test(void *param)
{
    cout << "In thread function" << endl;
    Sleep(1000); // sleep for 1 second
    cout << "Thread function ends" << endl;
    _endthread();
}

int main()
{
    HANDLE hThread;
    cout << "Starting thread" << endl;
    cout << (hThread = (HANDLE)_beginthread(test,0,NULL));
    WaitForSingleObject( hThread, INFINITE );
    cout << "Main ends" << endl;
    return 0;
}

A: WaitForSingleObject() will block main until the thread completes. If you want to run some stuff periodically from the thread function test() you'll need to put a loop there. Best with some condition to trigger ending the thread function from main() when exiting. You shouldn't call WaitForSingleObject() before you want to exit the main() method. Thus you'll have the test() method running asynchonously.
bool endThread = false;
void test(void *param)
{
    cout << "In thread function" << endl;
    while(!endThread)
    {
        Sleep(1000); // sleep for 1 second
    }

    cout << "Thread function ends" << endl;
    _endthread();
}

int main()
{
    HANDLE hThread;
    cout << "Starting thread" << endl;
    cout << (hThread = (HANDLE)_beginthread(test,0,NULL));

    // Do any other stuff without waiting for the thread to end
    // ...

    endThread = true;
    WaitForSingleObject( hThread, INFINITE );
    cout << "Main ends" << endl;
    return 0;
}

Note that you might need to synchronize access to the endThread variable properly using a mutex or similar, the sample should just show the principle.
UPDATE:
In case you want to exit main() before the thread ends, you cannot use threads at all.
You'll need to create an independent child process as I had mentioned in my 1st comment. Lookup for the fork() and exec() functions to do this (there might be specific WinAPI methods for these also, I don't know about).


text:
Q: Using regex to extract a double digit number from a string I want to extract the "73" from this string:
wiring_details_1-6-73

The numbers 1, 6 and 73 are all vars so I need it to be value independant, I found this website which generated this regex:
.*?\\d+.*?\\d+.*?(\\d+)

But that seems a bit overkill and complicated, what is the cleanest method to extract the "73"?

A: var string = "wiring_details_1-6-73"
var chunks = string.split("-");
alert(chunks[chunks.length-1]) //73

demo: http://jsfiddle.net/eawBT/

A: You can use this /\d{1,2}$/
var str = "wiring_details_1-6-73";

var result = str.match(/\d{1,2}$/);

this returns an array with the matched number as string and you can access the value as result[0].

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I show non-ascii characters in MovieClip, using ExternalInterface and invoke? I have some MovieClips with TextField. I want these text fields to show non-ascii characters.
My Question: How should I escape\send the special characters, so I can see them well in the MovieClip?
When I simply enter these characters they are clipped. Only ascii characters are seen.
[see bellow, the remarks in the HTML code]
When I try to use Unicode escaping, I just see the original escaped string. Though this should do the trick according to [Creating multilanguage documents by using text variables] in
http://help.adobe.com/en_US/flash/cs/using/WSd5f4b6c52cfaa4b179ef359133a95cac4a-8000.html#WS754A19FC-48CE-49ee-8EF2-B9C927F64BEB
http://help.adobe.com/en_US/Flash/10.0_UsingFlash/WSD4DFC446-FA27-4b25-8346-C5498B5352FC.html
http://livedocs.adobe.com/flash/9.0/UsingFlash/help.html?content=WSd60f23110762d6b883b18f10cb1fe1af6-7ceb.html
I prefer to send the characters as wanted (on my side), and not change the actionScript code (I have no simple access to change this code. only if I must . . .).
Thanks,
Atara.
my HTML code:
  . . .
  <input type="text" size="45" id="txt0" value="Facoltà di Français montrés contrôleurs très María Mª ">

  <input type="text" size="45" id="txt1" value="greek small letters entities: α β π ρ">

  <input type="text" size="45" id="txt2" value="greek in unicode: \u03B1 \u03B2 \u03C0 \u03C1 ">

  <INPUT TYPE="BUTTON" style="width:250px" OnClick="fRunSetFirstScreen();" VALUE="Run SetFirstScreen()">
  . . .

my JavaScript code:
// - - - - - - - - - - - - - - -
function fRunSetFirstScreen(){
// - - - - - - - - - - - - - - -
   alert("fRunSetFirstScreen()");

   objF = mcGetObjF("mySwf1");
   obj0 = document.getElementById("txt0");
   obj1 = document.getElementById("txt1");
   obj2 = document.getElementById("txt2");

   var strRequest = "";
   strRequest = strRequest + "<invoke name='RunSetFirstScreen' returntype='void'>";
   strRequest = strRequest + "<arguments>";
   strRequest = strRequest + "<string>" + obj0.value + "</" + "string>";
   strRequest = strRequest + "<string>" + obj1.value + "</" + "string>";
   strRequest = strRequest + "<string>" + obj2.value + "</" + "string>";
   strRequest = strRequest + "</" + "arguments>";
   strRequest = strRequest + "</" + "invoke>";
    alert(strRequest);
   objF.CallFunction(strRequest);
}

The Action Script code:
// ==============================================
public class myroot extends MovieClip {
// ==============================================

  private var lines:Array=new Array("","","");

  ExternalInterface.addCallback("RunSetFirstScreen", fSetFirstScreen);

  // ==============================================
  public function fSetFirstScreen(l0, l1, l2):void {  // External Interface.
  // ==============================================
    lines[0]=l0;
    lines[1]=l1;
    lines[2]=l2;
  }

  // ==============================================
  public function setRightMenu() {
  // ==============================================
    . . .
    for (i = 0; i < lines.length; i++) {
        itemM = new itemMenu();
        itemM.ptxt = lines[i];
        itemM.psize = psize1;
        itemM.x = x1;
        itemM.y = y1+dy*i;
        addChild(itemM);
        itemM.setParam();
        arrRightMenu.push(itemM);
       }
       . . .
   }

// ================================================
public class itemMenu extends MovieClip {
// ================================================
   . . .
  public var txt1:TextField;
  public var ptxt:String = "";
  public var psize:int = 0;
  . . .

  // ==============================================
  public function setParam() {
  // ==============================================
    txt1.text = ptxt1;
    . . .


text:
Q: What to do on a protocol error? What is the proper way or technique in framing with TCP?
I have created a simple framer in my node.js server that frames each message as they come-in where the 1st byte is the packet size.
One problem though: What if a user purposely sends an invalid packet.
Something like:
0A 00 03 04 05

We can tell that this is a broken packet, 0A is the size but we can see that the actual size is only 05.
How can we prevent such attacks?

A: If you receive rubbish, just close the socket. No point in persisting. The peer doesn't speak your language, or is deliberately trying to crash you or exploit vulnerabilities. Don't let him.

A: TCP is stream based and does not work on boundaries. So recv() returning partial data can be genuine. Or there can be invalid peer who just wants to mess up the connection. TCP will not help. The onus is on application to take action.
If the data is not fully received (as many as the length bytes indicate) the application must have the logic to give up. May be a timer on whose expiry the application shall mark the connection as invalid and then do close().

A: You can't since there is nothing in your protocol that allows you to validate that the specified size is correct.
You could append a control character to every message (for instance ascii 03):
<length><body><footer char>

But then an attacker could write:
03 32 32 32 03 32 32 32

Your validation would work, but the next message would be screwed.
The only way to prevent that is make sure that the actual body contains reasonable values and disconnect the client if it doesn't.

A: Simply validate all input. If the client sends "N bytes coming" then read N bytes. If you read less (because the stream is depleted before you get N bytes) interpret that as a connection problem or a bug somewhere, log the event and abort the connection.


text:
Q: How do I use a MySQL user-defined function (UDF) in Django? I'm trying to figure out how to construct a Django filter which includes terms which depend on user-defined functions (UDF) defined in MySQL.
My UDFs handle a branch of computational chemistry called cheminformatics. One of the functions (oe_matches) lets me test if a substructure (expressed as a "SMARTS" string) matches a structure (expressed as a "SMILES" string). You can think of these as isomorphic to regular expressions matching a string.
In my database I have a table of topics called "Nodes". This contains searchable text concerning a research topic. Some of the information in the topic concern molecules. I have a table of molecules. Molecules can be in more than one topic, and topics can be about more than one molecule, so I have:
class Node(models.Model):
    title = models.CharField()
    content = models.CharField()

class Structure(models.Model):
    smiles = models.CharField(max_length=255)
    nodes = models.ManyToManyField(Node)

Now I want to search for all nodes which have "test" in the title or content, and which match the SMARTS pattern "[C;!H0]" (that is, carbons with at least one hydrogen).
Ideally I would like to write this like the following:
q = ((models.Q(title__icontains="test") |
      models.Q(content__icontains="test")
     ).filter(models.Q(structure__node_smiles = oe_match(smarts="[C;!H0]")))
    )

where oe_match is something which knows how to generate the right back-end code for MySQL, in this case 'oe_match("[C;!H0]", Structure.smiles)' and where Django sees the structure__node_smiles and does its many-to-many magic to make the parts go together.
I see that I could get what I want with the raw() interface as (modulo minor syntax errors and using the wrong type of join):
SELECT * FROM Node, Node_Structure, Structure WHERE
     ((Node.title LIKE "%test%" OR Node.content LIKE "%test%") AND
      (Node.id = Node_Structure.node AND
       Node_Structure.structure = Structure.id) AND
      oe_matches("[C;!H0]", Structure.smiles));

I would rather not mix and match my database layers that way. Plus, I'll have to do some code restructuring. (Currently I create a filter, which I later pass to the model for the search.)
Longer term, I want others to use my MySQL UDFs for cheminformatics, and I think some set of high-level Django calls for my potential users (other than the two others I work with), would be good, so even if I can solve the immediate problem with raw(), I would still like to know a high-level solution for the long term.

A: Use QuerySet.extra, which will gladly take your custom function (use the where keyword argument).
http://docs.djangoproject.com/en/1.3/ref/models/querysets/#extra

A: I think it am extremely late to reply to this as I was in school when this question was asked. We can use the custom(User Defined Function) function by using the Func method provided by django.
from django.db.models import Func

class MultiArgFunc(Func):
    def __init__(self, *expressions):
        super().__init__(*expressions)

class NextShardID(MultiArgFunc):
    function = "next_shard_id"

Now you can use the NextShardID function anywhere you like.


text:
Q: JMeter response time is high I have a test plan written using JMeter & in that I have used Regular expression extractor to extract some value and pass it ON to other request in the test plan. I also used the CSV file to pick the value from sheet & used in my test plan.
Now the problem is that while running the script using JMeter, I am getting the high response time. When the JMeter is running the script, I tried to check the same site response manually & in that I was getting a very less response time.
I disabled the listeners & started the script in Non GUI mode but still the response time is on high side.
I need to justify the response time received from the JMeter to the client. Could someone please let me know what am I doing wrong ?
Thanks

A: I used the HTTP Cache Manager with Use Cache-Control/Expires header option which reduces the JMeter response time & nearly in sync with browser timing.


text:
Q: In what context is "msg" a reserved keyword? The following dataTable shows "???messageId???" instead of the correct id:
<p:dataTable id="msgTable" var="msg" value="#{msgModel.messages}">
        <p:column headerText="Id">
            <h:outputText value="#{msg.messageId}" />
        </p:column>
</p:dataTable>

After some tedious debugging, I found that it worked when renaming the var to something else than "msg"
<p:dataTable id="msgTable" var="msg2" value="#{msgModel.messages}">
        <p:column headerText="Id">
            <h:outputText value="#{msg2.messageId}" />
        </p:column>
</p:dataTable>

In what context is "msg" a reserved keyword ? I could not find any documentation about it for html, Javascript or JSF ?

A: It's not a reserved keyword.
The name "msg" is however recognizable as the value of <resource-bundle><var> as seen in faces-config.xml of many JSF tutorials and kickoff applications.
<resource-bundle>
    ...
    <var>msg</var>
</resource-bundle>

The error message which you got also confirms it. When a resource bundle message is not found by given key, by default the very same key is returned surrounded with three quesiton marks, exactly as you've observed:

???key???

See also:

*

*Internationalization in JSF, when to use message-bundle and resource-bundle?


text:
Q: SQL: Calculate the rating based on different columns and use it as an argument I'm trying to calculate the rating based on a table that has 3 columns with different ratings ranging from 1 to 5.
I wanted to calculate the average of these 3 values and then be able to use this as an argument in queries, for example:
Where Rating >3.5
At this moment I have this that gives me the average for all suppliers
SELECT c.Name
    ,(SELECT CAST(AVG(rat) AS DECIMAL(5, 2))
        FROM(
            VALUES(b.Qty_Price),
                  (b.Quality),
                  (b.DeliveryTime)) A (rat))  AS Rating
FROM Order a
JOIN Evaluation b ON b.ID_Evaluation  = a.ID_Evaluation
JOIN Supplier c ON c.NIF_Supplier = a.NIF_Supplier

What I would like now is, for example, to filter the providers that have more than 3 ratings, but I don't know how I can do that. If anyone can help i would be grateful

A: If the query works like you want it, you get the average for all entries, that is.
The WHERE rating > 3.5  cannot be added, as rating does not exist in the context of the SELECT-clause, nor the tables we JOIN.
To overcome this issue, we can keep the query that you have made, call it something different using WITH and SELECT from that sub-query WHERE rating > 3.5
It should look something like this:
WITH Averages(name, rating) AS
  (SELECT c.name
  ,(SELECT CAST(AVG(rat) AS DECIMAL(5, 2))
  FROM(
        VALUES(b.qty_Price),
              (b.quality),
              (b.deliveryTime)) AS (rat))  AS rating
  FROM Order a
  JOIN Evaluation b ON b.ID_Evaluation  = a.ID_Evaluation
  JOIN Supplier c ON c.NIF_Supplier = a.NIF_Supplier)

SELECT name, rating FROM Averages WHERE rating > 3.5;

Now, we simply call the query you provided as Averages for example, and we SELECT from that table WHERE rating > 3.5.
Also note that you can have multiple WITHs to make things easier for you, but remember that a comma (,) is needed to seperate them. In our case, we only have 1 use of WITH ... AS, so no need for a comma or semi-colon after ...= a.NIF_Supplier)
Looks like you typed only "A" before "(rat)", it should be "AS". Also, remember that attributes should be lowercase, it makes it easier for all of us to distinguish tables from attributes.
Cheers!


text:
Q: HOWTO Remove the extra empty space(column) on the right handside of a WPF ListView I have an WPF ListView with three columns. I see that in my ListView appears an extra empty space(column) on the right handside and I do not know why. How can I remove this extra space using XAML?

<ListView x:Name="MyListView"
          Grid.Column="0"
          AlternationCount="{Binding pathList.Count}"
          ItemsSource="{Binding pathList}"
          IsSynchronizedWithCurrentItem="True">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn x:Name="LvItemId"
                            Header="#"
                            Width="20"
                            DisplayMemberBinding="{Binding (ItemsControl.AlternationIndex),
                            RelativeSource={RelativeSource AncestorType=ListViewItem}}"/>
            <GridViewColumn Header="Path"
                            Width="350"
                            CellTemplate="{StaticResource NameColumnTemplate}"/>
            <GridViewColumn  Header="Edit | Delete"
                             Width="80"
                             CellTemplate="{StaticResource AddDelItemTemplate}"/>
        </GridView>
    </ListView.View>
</ListView>

A: Set the HorizontalAlignment property of the ListView to Leftto prevent it from stretching horizontally:
<ListView x:Name="MyListView"
          Grid.Column="0"
          AlternationCount="{Binding pathList.Count}"
          ItemsSource="{Binding pathList}"
          IsSynchronizedWithCurrentItem="True"
          HorizontalAlignment="Left">
          ...


text:
Q: Why my if...else statement doesnt work where is my mistake and how to fix it? Here how i call my query and i want to use simple if...else statement but i make a mistake somewhere can someone explain me where and why ?
 $result = mysqli_query($con, $sql) or die(mysqli_error($con,$sql));
    echo mysqli_error($con);
    $number=mysqli_num_rows($result);
    while ($row= mysqli_fetch_array($result)){
        $brand = $row['brand'];
        $model = $row['model'];
        $reg_num = $row['reg_num'];
        $horse_powers = $row['horse_powers'];
        $color = $row['color'];
        echo $number;
        if($number<1){
            echo "No rented cars for this period !";
        }
        else{
        echo $brand;
        }

    }

A: Please try this code:
    $number = 0;
    $result = mysqli_query($con, $sql);
    if (!$result)
         exit(mysqli_error($con));
    else
         $number = mysqli_num_rows($result);
    if ($number==0) {
        echo "No rented cars for this period !";
    } else {
        while ($number){
            $row = mysqli_fetch_row($result);
            $brand = $row['brand'];
            $model = $row['model'];
            $reg_num = $row['reg_num'];
            $horse_powers = $row['horse_powers'];
            $color = $row['color'];
            echo $brand;
            $number--;
        }
    }

A: The output of this if-statement will always be false.
if($number<1){
   echo "No rented cars for this period !";
}
else{
   echo $brand;
}

The while loop will not run if $number < 1. So if $number < 1 it will never get to the if statement.


text:
Q: Caching duration in Flutter using the plugin cached_network_image? I'm using the flutter plugin cached_network_image: and would like to know, how long the caching duration is for the cached files?
Also if there is a way to modify the caching duration to x-days?
What I also would like to know is, if the files are cached in the original file format or if it gets converted? e.g. *.HEIC -> *.JPEG
Currently I'm simply caching calling: CachedNetworkImage(imageUrl: snapshot.data))
or see below....
...return FutureBuilder(
                      future: FireStorageService.downloadImageFromStorage(
                          context, snapshot.data.items[index].fullPath),
                      builder: (context, snapshot) {
                        if (snapshot.connectionState == ConnectionState.done) {
                          return GridTile(
                            child: Card(
                                child: CachedNetworkImage(imageUrl: snapshot.data)),
                          );
                        }
                        return Container();
                      },
                    );
...

While searching for an answer regarding my questions above, I got faced with the plugin flutter_cache_manager: and saw the Type Duration(days: 7)
If this (using flutter_cache_manage:) is the only way to modify the caching duration, how can I use that in my case?
Anyone has an idea?
Thanks :)

A: CachedNetworkImage can receive a parameter called cacheManager. That means that you can give a custom CacheManager to  your CachedNetworkImage First of all you should add this package to your pubspec.yaml. Then you can add something like this:
CachedNetworkImage(
  imageUrl: snapshot.data,
  cacheManager: CacheManager(
    Config(
      'cacheKey',
      stalePeriod: Duration(days: 7),
    ),
  ),
),

Replace the duration with your wanted duration and the cache key with any String you want. Add other parameters to the Config object if needed.
Just to note, the duration of the cache is 7 days (in this example) from the last use of the cached file, not from the download date.


text:
Q: Processing items within a powershell array - multiple items I have been reading about arrays in powershell and hash tables, I know the basic workings of an array and how to use foreach loop to get items within the array, my challange here is slightly different. I would like to pay what I call a multi dimension array to a script, and process the items contained within the array.
What is my setup.
 $x = (1,"Server1",3,1),(4,"Server2",6,2),(3,"Server3",4,3)
 $k = 'serverid','servername','locationid','appid'    # key names correspond to data positions in each array in $x
 $h = @{}

 For($i=0;$i -lt $x[0].length; $i++){
     $x |
         ForEach-Object{
             [array]$h.($k[$i]) += [string]$_[$i]
         }

 }

What am i trying to achieve ?
I am trying to achieve the structure of a database table within powershell. So literally treating each array item as a row.
So for example
(1,"Server1",3,1),(4,"Server2",6,2),(3,"Server3",4,3)
could be thought of as a table like below
enter image description here
I then want to loop for each item in the array to get the values, similar to the below example
[0].serverid = 1, [0].servername = server1, [0].locationid = 3, [0].applicationID = 1

[1].serverid = 4, [1].servername = server2, [1].locationid = 6, [1].applicationID = 2

what have I done ?
$x = (1,"Server1",3,1),(4,"Server2",6,2),(3,"Server3",4,3)
 $k = 'serverid','servername','locationid','appid'    # key names correspond to data positions in each array in $x
 $h = @{}

 For($i=0;$i -lt $x[0].length; $i++){
     $x |
         ForEach-Object{
             [array]$h.($k[$i]) += [string]$_[$i]
         }

 }

$x

for ($i = 0; $i -lt $x.Count; $i++)
{
    $myserverid = $x[$i][0]
    $myservername = $x[$i][1]
    $mylocationid = $x[$i][2]
    $myappid = $x[$i][3]

    write-host $myserverid
}

The Issues
If I set the following    $x = (1,"Server1",3,1), then the loop is somewhat incorrect which is why I think the approach is wrong (more than one item works i.e   $x = (1,"Server1",3,1),(4,"Server2",6,2),(3,"Server3",4,3)). The loop only works if you have more than one item within the array, hence why I want to re-examine the way the loop works.
Thanks in advance

A: Your approach relies on a nested (jagged) array: That is, you have an array of subarrays, each of which represents the tuple of values you want to assign to properties.
If there's only one subarray, you must create the nested array explicitly, using the unary form of , the array constructor operator:
# Construct a 1-element array that contains the 4-element subarray.
$x = , (1,"Server1",3,1)

With two or more, subarrays, you implicitly get a nested array:
# Construct a 3-element array, each element of which contains a 4-element subarray.
$x = (1,"Server1",3,1), (4,"Server2",6,2), (3,"Server3",4,3)

Note that in PSv5+ you could use a custom class to solve your problem:
class Custom {
  [int] $serverid; [string] $servername;[int] $locationid; [int] $appid
  Custom($propValueArray) {
    $this.serverid = $propValueArray[0]; $this.servername = $propValueArray[1]; $this.locationid = $propValueArray[2]; $this.appid = $propValueArray[3]
  }
}

# Use an array cast to construct [Custom] instances.
# Note the need for (...) around the array, because casts have high
# precedence in PowerShell.
[Custom[]] ((1,"Server1",3,1), (4,"Server2",6,2), (3,"Server3",4,3))

This would allow for processing such as:
# Construct all objects
$objects = [Custom[]] ((1,"Server1",3,1), (4,"Server2",6,2), (3,"Server3",4,3))

# Process each object.
foreach ($object in $objects) {
   ($myserverid = $object.serverid) # assign a property to a var; `()` also outputs
   # ...
}


text:
Q: "How to solve error: ';' expected in Java?" I am trying to run my code line but it shows a minor error.
I also make some effort to put something like \ ; " " but it doesn't work.
public static void message() {
    System.out.println("This program surely cannot");
    System.out.println("have any \"errors")"in it");
}

I expect that this method can run, but it shows that:

Error:(9, 48) java: ';' expected.

A: You need to escape all of the quotes " in the string with backspaces \:
public static void message() {
    System.out.println("This program surely cannot");
    System.out.println("have any \"errors\")\"in it");
}

Otherwise the parser sees that you've ended your string, and will break when there's some random characters after the ) that it doesn't know how to interpret. This is simply a syntax error, and will crash when compiling.
System.out.println("have any \"errors")"in it");
                                     ^^^~~~~~~~~
                                     |||    ^
                                     |||    |
                                     ||| Parser sees these as just random characters
                 String ends here____|||
                                      ||____Here should be a semicolon
                                      |
                                     println( matches this

A: System.out.println("have any \"errors")"in it");

There is a syntax error: you have to escape the quotes:
System.out.println("have any \"errors\")\"in it");


text:
Q: How to deserialize deeply nested JSON without separate classes for each level Say in Java I want to deserialize a JSON string such as:
{
  "classb": {
    "c": "myc"
   }
}

So I can create model classes like so:
@Data
class Classa {
     Classb classb;
}

@Data
class Classb {
    String c;
}

And print the deserialized value like so:
System.out.println(new ObjectMapper().readValue(json, Classa.class).getClassb().getC()  );

So my question is, when we are only interested in a value that is deeply nested in class objects and we need a getter for that value, do we have to create a separate model class for each object, or is there a way to create a single model class which contains the nested classes like this, and be able to access the inner objects with a getter, like  getC()
@Data
class Classa {
    class Classb {
        String c;
    }
}

A: You can implement one of the tree-traversal algorithms, for instance Depth first search algorithm, and iterate over the tree of Nodes until the target property wasn't found (or until the tree is fully explored).
That how iterative implementation of the Depth first search based on functionality of the Jackson's JsonNode might look like:
public static <T> T search(String json, String target, Class<T> tClass) throws JsonProcessingException {

    JsonNode node = new ObjectMapper().readTree(json);

    T result = null;

    Deque<JsonNode> stack = new ArrayDeque<>();
    stack.push(node);

    while (!stack.isEmpty()) {
        JsonNode current = stack.pop();

        if (current.isContainerNode()) {

            for (Iterator<Map.Entry<String, JsonNode>> it = current.fields(); it.hasNext(); ) {

                Map.Entry<String, JsonNode> next = it.next();

                if (next.getKey().equals(target)) {
                    result = tClass.cast(next.getValue());
                }

                stack.push(next.getValue());
            }
        }
    }
    return result;
}

And that's how Depth first search can implemented recursively. Instead of returning null as a default value we can change the return type to Optional (it can be done in the previous version as well).
public static <T> Optional<T> search(String json, String target, Class<T> tClass) throws JsonProcessingException {

    JsonNode node = new ObjectMapper().readTree(json);
    Object result = search(node, target);

    return result != null ? Optional.of(tClass.cast(result)) : Optional.empty();
}

public static Object search(JsonNode node, String target) {
    if (!node.isContainerNode()) return null;

    Object result = null;

    for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext() && result == null; ) {
        Map.Entry<String, JsonNode> next = it.next();

        if (next.getKey().equals(target)) {
            return next.getValue();
        }
        result = search(next.getValue(),target);
    }
    return result;
}


text:
Q: Why doesnt MSDSM device show up for MPIO with Powershell query? When adding a Device to MPIO in the MPIO Window, if you query that device in Powershell it doesnt show up.  However, if you create the device with Powershell, then query, it does.
What is going on here?


text:
Q: How to add an session value to a custom webforms for markters save action? I'm using Sitecore with WebForms For Marketers (WFFM). Between the Content Delivery Server (CDS) and Content Management Server (CMS) is a web service. I have written a custom save action.
I'm looking for a manner to send a session value from the CDS to the CMS server without a custom hidden field. It must be friendly for the Content Editor. Does anyone have a solution?
Thanks a lot.
Jordy

A: I looked into this and the only way I could get it working was with a hidden field.
If you put a Field type of hidden field on the form, in the Save action you can set the hidden fields value to be the value from session and then the save to database action will pass on the data to the web service.
I tried looking at adding extra fields to the collection of fields that goes to the database but the classes I needed were protected.
Would be good to hear if anyone else has a nifty way of getting round this issue though.


text:
Q: Is there a way to perform a like operation on a Uri type column in Slick? I need to filter using like operation in Slick but the column is of type Uri
def uriColumn = column[Uri]("uriColumn")

mytable.filter(r => r.uriColumn like ("http://xyz%"))

like keyword is only for String types
Any help is appreciated.


text:
Q: SQL Server - Exporting a DateTime Value between servers changes value (time zone issue?) Here is how the export works

*

*.NET DataTable is created by a SQL Query

*DataSet is serialized and sent via HTTP Request to an Importer

*Importer Deserializes and performs a series of insert/updates; one per DataTable row

Details

*

*Exporting SQL Server is in the Eastern (US) Timezone

*Importing SQL Server is in the Central (US) Timezone

The Problem

*

*A datetime value is 1-3-2012 00:00:00 Eastern (midnight 1/3/12 Eastern)

*This value is exported through the previous mentioned mechanism

*When it is deposited to the destination (central) SQL Server, it has the value 1-2-2012 23:00:00 (11:00 PM the day before)

The datetime value should not change from one server to the next. It needs to stay 1-3-2012 00:00:00.
What have I tried?

*

*I have confirmed that the corresponding date values are indeed 1 hour off after re-running the export

*I have confirmed that an hour is not being subtracted by my code

*

*Serialization occurs via the BinaryFormatter.Serialize function, with the DataSet itself going right in

*Deserialization occurs via the BinaryFormatter.Deserialize function

*A call to a stored procedure is made with one parameter per column in the DataTable. I have confirmed that there is a direct copy for the date value via the following code: CMD.Parameters("@p" & col.ColumnName).Value = row(col.ColumnName)

*I've analyzed the MSDN for DateTime, but based upon my understanding (storing Date in the first 4 bytes, time in the last 4 bytes) there should never be a switch to a different day, even if each block of 4 bytes represents some relative offset from some base day or time

*I have confirmed that the moment the DataSet is deserialized in the new timezone, all datetimes have shifted 1 hour

This really feels like a timezone issue, but I can't figure out where it might be.

A: Transferring a datetime from one SQL Server to another SQL Server via an UPDATE query across a Linked Server connection will preserve the date and time. 1/3/12 Midnight comes across as 1/3/12 Midnight, despite the time zone change.
However, by injecting the dates into a .NET Dataset, you subject the SQL DateTime variables to a data conversion to .NET DateTime.
The display of a DateTime varies by TimeZone. If you load the same bits in Boston as you do in California via the ToString() function, you will get two different results.
As a result, by the time this code is called, the damage is done

*

*CMD.Parameters("@p" & col.ColumnName).Value = row(col.ColumnName)
To fix this problem, you must either determine the time zone offset and adjust the value, or serialize to a safer format, thus avoiding the .NET DateTime, as mentioned by @competent_tech.
References

*

*SQL Server DateTime

*.NET DateTime - Scroll down to "Datetime Values" section

A: One simple trick to try: serialize the date as a string rather than a .Net datetime type. This will remove any timezone issues.


text:
Q: Django .annotate TruncMonth : How to Get full range of Months I want total earning from each month and display it in graph so im making below query
Here's my query:
        query = UserOrderService.objects.all()

        query = query.annotate(month=TruncMonth('order_booking_date')).values(
            'month').annotate(no_of_services=Count('pk')).annotate(
            total=Sum(F('service_price') * F('quantity'))).order_by('month')

Above query only gives data from months where booking happend
Output:
"data": [
    {
        "no_of_services": 1,
        "total": 26725.0,
        "month": "November"
    },
    {
        "no_of_services": 1,
        "total": 26725.0,
        "month": "December"
    }
]

Where as i want all data from all months Even if there's no data in that particular month
Expected Output:
"data": [
    {
        "no_of_services": 0,
        "total": 0,
        "month": "January"
    },
    {
        "no_of_services": 0,
        "total": 0,
        "month": "February"
    },
    {
        "no_of_services": 0,
        "total": 0,
        "month": "March"
    },

    ...

    {
        "no_of_services": 1,
        "total": 26725.0,
        "month": "November"
    },
    {
        "no_of_services": 1,
        "total": 26725.0,
        "month": "December"
    }
]


text:
Q: Javascript in applescript document.querySelectorAll('input[name$=_comment1]'); I am trying to fill all the text fields in Safari where the name ends with _comment1 with a number obtained from a dialog query.
The source code of the text field looks like:
<input type="text" maxlength="6" size="6" name="233941_142117_comment1" value="" onKeyUp="return autoTab (this, 6, event);" onChange="disableButtons();">

It doesn't fill the fields though. Any ideas?
My applescript is:
set query to text returned of (display dialog "Enter Query" default answer "" buttons {"Input", "Cancel"} default button 1)
log "2"
activate application "Safari"
log "3"
tell application "Safari"

log "4"
do JavaScript "

    let x = document.querySelectorAll('input[name$=_comment1]');
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].value = query;
     }

"

end tell

A: I outlined the problems with your script in the comment I left below your question.  To summarise:
① Your query variable is defined as an AppleScript variable, but goes unused.  You then make a reference to a variable in JavaScript called query, which is undefined and has no value.
② Your do JavaScript command has no target within Safari, which needs to perform the action on a specific tab or document.
Solution:
Without seeing the specific site you're working with, I cannot test my solution, but I'm pretty confident that it should rectify these two explicit errors that are most certainly preventing your script from working.  Whether or not any other unrelated issues crop up depends on the specifics of the website.
So you've defined your AppleScript variable query, which I'm just going to do lazily here:
    set query to "blah blah blah"

The core bit of your script needing amending is here:
    tell application "Safari" to tell ¬
        the front document to do JavaScript ¬
        "x=document.querySelectorAll(\"input[name$='_comment1']\"); " & ¬
        "for(let i of x){ i.value=" & quoted form of query & "; }"

Your JavaScript itself is totally fine (although I slightly modified it to my own preference, which I perhaps ought not to have done).  The main points here are that I have told Safari that it will be performing the JavaScript in the front document; and that the JavaScript now makes use of the AppleScript query variable with which it uses to set the value of the <input> fields.
Having tested a variant of this on some arbitrary website I found, it appeared successful.
Let me know how it turns out.


text:
Q: Ответ на WebRequest.Get Разрабатываю приложение на Unity3d для платформы WEBGL, и на данный момент мне нужно написать сервер. Мне надо чтобы приложение при старте получало строку с сервера, потом по ходу работы несколько раз (когда захочет пользователь) уже отправляла строку на сервер.
Так как tcpClient/listener'ы не работают (?) на WEBGL, придется использовать www или webrequest классы. Я знаю как отправлять GET/POST запросы клиента через webrequest, но не знаю как слушать и получать эти запросы на сервере. Сервер пишется на .net (консолька или forms).
Вопрос: как слушать поступающие запросы? С tcpListener допустим мы в параллельном потоке в цикле слушаем, а тут как? Какие классы использовать? Допустим, клиент отправил GET запрос на сервер, сервер должен проверить заголовки, и если все правильно, отправить ответ (строку).
Спасибо.


text:
Q: Can an adjective modify an adjective in "low-resistant infectious agents"? I was translating a Russian sentence and came up with "low-resistant infectious agents":

Infectious agents in animals (including birds) can be divided into four groups based on their resistance to chemical disinfectants: low-resistant, resistant, highly resistant and super resistant.

I googled for "low-resistant" and there are examples, although those seem to have been penned by non-native speakers of English. Would "low-resistant infectious agents" be acceptable with the hyphen, or should I instead use some other word?  I thought of  "slightly" but "slightly resistant infectious agents" looks a bit odd.. "weakly resistant infectious agents"?
I'm unsure which word to pick if not "low-resistant". If if modify it to "low-resistance", then it would fall out of tune with the other three terms in the range.

A: I don't think "low" is a good choice. I would use "somewhat" or "moderately" resistant instead:

Based on their review, the researchers estimate that between 39 percent and 51 percent of surgical site infections and 27 percent of post-chemotherapy infections are caused by bacteria already somewhat resistant to antibiotics.
Antibiotic Resistance May Threaten These Patients

or this of "moderately resistant" and "highly resistant" in Kucers' The Use of Antibiotics Sixth Edition
I don't think "resistance" is a good substitute for "resistant".
If you compare results from Google Books between "high resistance" and "highly resistant", "high resistance" returns results that even when they are in a medical context are describing something other than an infectious agent, for example,

using antibiotics with a "low resistance potential" in place of those with a "high resistance potential," (*)

In addition, the PSV Figure 9.1 High resistance flow proximal to severe occlusive disease. (A) Common carotid Doppler has a high resistance, triphasic waveform secondary to ICA occlusion. (*)

and "highly resistant" favors results related to infection or infestation. Using "resistance" instead of "resistant" doesn't make much of a grammatical difference, but it does seem to run contrary to what is commonly used in other similar contexts.

A: No, "low-resistant" should be "minimally resistant". But you could also label your categories with nouns:  low resistance, normal resistance, high resistance, and almost complete resistance.


text:
Q: resolveTopDef, TopDefnApp, ResolveTopDefinition? @Tomasp has several blog entries (here's one) that refer to a way of using [<ReflectedDefinition>] and ResolveTopDefinition to extract the quotation from a method as an alternative to wrapping the definition in <@ ... @> (or is it <@@ ... @@>?).
In any case, I can't get any of these things to compile now and I think the features have been changed - but I don't know to what and pretty much the only mentions I find on google of these names are of or related to Tomas's blog and work.
What is the current way?
I've seen Eval.TryGetReflectedDefinition, but that requires a MethodBase and that approach doesn't seem like it should be necessary unless I'm trying to reflect on another/already compiled assembly.
Thanks!

A: The API around quotations and reflected method definitions has been changing quite a bit (and I wrote some of the blog posts in the very early days), so this is the most out-of-date part of my blog. Sorry about that!
Anyway, the following simple snippet demonstrates the current API:
[<ReflectedDefinition>]
let foo a b = a + b

open Microsoft.FSharp.Quotations

match <@@ foo 1 2 @@> with
// Matches a call to a static method that is marked as `ReflectedDefinition`
| Patterns.Call(None, DerivedPatterns.MethodWithReflectedDefinition body, args) ->
    // Return the actual quotation - simply call the body that represents
    // the function with all the arguments as arguments.
    Expr.Applications(body, args |> List.map (fun a -> [a]))
| e -> e

If you're doing lots of quotation processing, then it's probably a good idea to open both Patterns and DerivedPatterns to make the code shorter (but on the other hand,  "dot" makes it easy to explore the modules).
The key thing here is MethodWithReflectedDefinition which is a pattern that can match any MethodInfo (and there is a similar one for properties) and returns its quotation when it is a method with ReflectedDefinition attribute. You can also place the attribute on a module that contains the functions.


text:
Q: Exact time measurement for performance testing What is the most exact way of seeing how long something, for example a method call, took in code?
The easiest and quickest I would guess is this:
DateTime start = DateTime.Now;
{
    // Do some work
}
TimeSpan timeItTook = DateTime.Now - start;

But how exact is this? Are there better ways?

A: As others said, Stopwatch should be the right tool for this. There can be few improvements made to it though, see this thread specifically: Benchmarking small code samples in C#, can this implementation be improved?.
I have seen some useful tips by Thomas Maierhofer here
Basically his code looks like:
//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;

//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;

//warm up
method();

var stopwatch = new Stopwatch()
for (int i = 0; i < repetitions; i++)
{
    stopwatch.Reset();
    stopwatch.Start();
    for (int j = 0; j < iterations; j++)
        method();
    stopwatch.Stop();
    print stopwatch.Elapsed.TotalMilliseconds;
}

Another approach is to rely on Process.TotalProcessTime to measure how long the CPU has been kept busy running the very code/process, as shown here This can reflect more real scenario since no other process affects the measurement. It does something like:
 var start = Process.GetCurrentProcess().TotalProcessorTime;
 method();
 var stop = Process.GetCurrentProcess().TotalProcessorTime;
 print (end - begin).TotalMilliseconds;

A naked, detailed implementation of the samething can be found here.
I wrote a helper class to perform both in an easy to use manner:
public class Clock
{
    interface IStopwatch
    {
        bool IsRunning { get; }
        TimeSpan Elapsed { get; }

        void Start();
        void Stop();
        void Reset();
    }

    class TimeWatch : IStopwatch
    {
        Stopwatch stopwatch = new Stopwatch();

        public TimeSpan Elapsed
        {
            get { return stopwatch.Elapsed; }
        }

        public bool IsRunning
        {
            get { return stopwatch.IsRunning; }
        }

        public TimeWatch()
        {
            if (!Stopwatch.IsHighResolution)
                throw new NotSupportedException("Your hardware doesn't support high resolution counter");

            //prevent the JIT Compiler from optimizing Fkt calls away
            long seed = Environment.TickCount;

            //use the second Core/Processor for the test
            Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

            //prevent "Normal" Processes from interrupting Threads
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

            //prevent "Normal" Threads from interrupting this thread
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
        }

        public void Start()
        {
            stopwatch.Start();
        }

        public void Stop()
        {
            stopwatch.Stop();
        }

        public void Reset()
        {
            stopwatch.Reset();
        }
    }

    class CpuWatch : IStopwatch
    {
        TimeSpan startTime;
        TimeSpan endTime;
        bool isRunning;

        public TimeSpan Elapsed
        {
            get
            {
                if (IsRunning)
                    throw new NotImplementedException("Getting elapsed span while watch is running is not implemented");

                return endTime - startTime;
            }
        }

        public bool IsRunning
        {
            get { return isRunning; }
        }

        public void Start()
        {
            startTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = true;
        }

        public void Stop()
        {
            endTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = false;
        }

        public void Reset()
        {
            startTime = TimeSpan.Zero;
            endTime = TimeSpan.Zero;
        }
    }

    public static void BenchmarkTime(Action action, int iterations = 10000)
    {
        Benchmark<TimeWatch>(action, iterations);
    }

    static void Benchmark<T>(Action action, int iterations) where T : IStopwatch, new()
    {
        //clean Garbage
        GC.Collect();

        //wait for the finalizer queue to empty
        GC.WaitForPendingFinalizers();

        //clean Garbage
        GC.Collect();

        //warm up
        action();

        var stopwatch = new T();
        var timings = new double[5];
        for (int i = 0; i < timings.Length; i++)
        {
            stopwatch.Reset();
            stopwatch.Start();
            for (int j = 0; j < iterations; j++)
                action();
            stopwatch.Stop();
            timings[i] = stopwatch.Elapsed.TotalMilliseconds;
            print timings[i];
        }
        print "normalized mean: " + timings.NormalizedMean().ToString();
    }

    public static void BenchmarkCpu(Action action, int iterations = 10000)
    {
        Benchmark<CpuWatch>(action, iterations);
    }
}

Just call
Clock.BenchmarkTime(() =>
{
    //code

}, 10000000);

or
Clock.BenchmarkCpu(() =>
{
    //code

}, 10000000);

The last part of the Clock is the tricky part. If you want to display the final timing, its up to you to choose what sort of timing you want. I wrote an extension method NormalizedMean which gives you the mean of the read timings discarding the noise. I mean I calculate the the deviation of each timing from the actual mean, and then I discard the values which was farer (only the slower ones) from the mean of deviation (called absolute deviation; note that its not the often heard standard deviation), and finally return the mean of remaining values. This means, for instance, if timed values are { 1, 2, 3, 2, 100 } (in ms or whatever), it discards 100, and returns the mean of { 1, 2, 3, 2 } which is 2. Or if timings are { 240, 220, 200, 220, 220, 270 }, it discards 270, and returns the mean of { 240, 220, 200, 220, 220 } which is 220.
public static double NormalizedMean(this ICollection<double> values)
{
    if (values.Count == 0)
        return double.NaN;

    var deviations = values.Deviations().ToArray();
    var meanDeviation = deviations.Sum(t => Math.Abs(t.Item2)) / values.Count;
    return deviations.Where(t => t.Item2 > 0 || Math.Abs(t.Item2) <= meanDeviation).Average(t => t.Item1);
}

public static IEnumerable<Tuple<double, double>> Deviations(this ICollection<double> values)
{
    if (values.Count == 0)
        yield break;

    var avg = values.Average();
    foreach (var d in values)
        yield return Tuple.Create(d, avg - d);
}

A: A better way is to use the Stopwatch class:
using System.Diagnostics;
// ...

Stopwatch sw = new Stopwatch();

sw.Start();

// ...

sw.Stop();

Console.WriteLine("Elapsed={0}",sw.Elapsed);

A: Stopwatch is fine, but loop the work 10^6 times, then divide by 10^6.
You'll get a lot more precision.

A: I'm using this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
System.Diagnostics.Stopwatch timer = new Stopwatch();

timer.Start();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

statusCode = response.StatusCode.ToString();

response.Close();

timer.Stop();

A: As others have said, Stopwatch is a good class to use here. You can wrap it in a helpful method:
public static TimeSpan Time(Action action)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    action();
    stopwatch.Stop();
    return stopwatch.Elapsed;
}

(Note the use of Stopwatch.StartNew(). I prefer this to creating a Stopwatch and then calling Start() in terms of simplicity.) Obviously this incurs the hit of invoking a delegate, but in the vast majority of cases that won't be relevant. You'd then write:
TimeSpan time = StopwatchUtil.Time(() =>
{
    // Do some work
});

You could even make an ITimer interface for this, with implementations of StopwatchTimer, CpuTimer etc where available.

A: Use the Stopwatch class

A: System.Diagnostics.Stopwatch is designed for this task.


text:
Q: Product Sales Target - Power BI I want to calculate the product target value for the data I was given in Power BI. I saw that the target value should be 25% of total sales for a product in the same period of the previous year.
The data I was given comprises 9 tables. The only ones that have important information for this calculation are the following:
Table Product:

Released
Model Code
Model
Family
Discontinued

1/1/2020
5
iPhone XS
IPhone
FALSE

30/5/2020
9
iPhone 13
IPhone
FALSE

...
...
...
...
...

Invoices Table:

STORE_ID
PRODUCT_ID
ORDER_NO
ORDER_QT
UNIT_PRICE
DELIVERY_COST
TAX_RATE
ORDER_DATE
DELIVERY_DATE
CUSTOMER_ID

...
...
...
...
...
...
...
...
...

Should I use a parameter for this or create a new table?


text:
Q: TypeError: client.on is not a function -error I keep getting this error, TypeError: client.on is not a function
What am I doing wrong and how do I fix this issue?
Here's the code:
  const DiscordPage = d;
  await fill_discord(DiscordPage, username, password, email);

  const client = d._client;
  var token;

  client.on('Network.webSocketFrameSent', ({requestId, timestamp, response}) => {
    try {
      const json = JSON.parse(response.payloadData);
      if(!token && json["d"]["token"]){
        token = json["d"]["token"];
        write_log(true, `Token: ${token}`);
      };
    } catch(e){};
  })
  await break_captcha(DiscordPage);


text:
Q: 404 Error on running a simple class that extends HTTPServlet The following code is my web.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MySimpleServletProject</display-name>

<servlet>
<servlet-name>xmlServlet</servlet-name>
<servlet-class>myServletPackage.XmlServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>xmlServlet</servlet-name>
<url-pattern>/xmlServletpath</url-pattern>
</servlet-mapping>
</web-app>

The following code is a simple class that extends the HTTPServlet class:
package myServletPackage;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XmlServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("Msg from 'XmlServlet' class");

}

}

When I try to run this code on Tomcat 7, it's displaying the following error message:
HTTP Status 404 - /MySimpleServletProject/servlet/myServletPackage.XmlServlet
--------------------------------------------------------------------------------
type Status report
message /MySimpleServletProject/servlet/myServletPackage.XmlServlet
description The requested resource (/MySimpleServletProject/servlet/myServletPackage.XmlServlet) is not available.
--------------------------------------------------------------------------------
Apache Tomcat/7.0.12"

Can someone please tell me what's wrong with this code? And please suggest how I can successfully run this.

A: You must call the url
http://yourHost/MySimpleServletProject/xmlServletpath/

and not the servlet-class that you've configured.

A: Here, while you are trying to access your Servlet via url.. The url-mapping you have done in your web.xml must map with the url you have typed in the browser..
Thus after the localhost definition, you should provide the context path and then follow with the url you have given in between the <url-pattern> tags in web.xml !
So, the url would be like
localhost:8084/MySimpleServletProject/xmlServletpath


text:
Q: Refering to related object in ListView I am trying to create some kind of 'panel control'. I need to manage my objects directly from ListView. I'll show you transparent (I believe) schema what I'm trying to solve.
Models
class Category(models.Model):
    cat_name = models.CharField(max_length=120)

class Product(models.Model):
    category = models.ForeignKey(Category)
    prod_name = models.CharField(max_length=120)

Views
 class CategoryListView(ListView):
        model = Category

        def get_context_data(self, *args, **kwargs):
            context = super(CategoryListView, self).get_context_data(*args, **kwargs)
            # two class based forms created for models
            context['form_category'] = CategoryForm()
            context['form_product'] = ProductForm()
            return context

        def post(self, request, *args, **kwargs):
            form_category = CategoryForm(request.POST or None)
            if form_category.is_valid():
                new_category = form_category.save(commit=False)
                new_category.save()
                return redirect('category_list')
            return Http404

templates
I use two modal window to open my forms which I added to my context views
<button>Modal btton opens product form</button>
{% for category in object_list %}

{{ category.cat_name}}

                <button>Modal btn opens product form</button>

               {% for product in category.product_set.all %}

{{ product.prod_name }}

                    Delete

               {% endfor %}

    {% endfor %}

    <form action="." method="POST">{%csrf_token%}
        {{ form_category.as_p }}
        <input type="submit" value="add category">
    </form>

    <form action="." method="POST">{%csrf_token%}
        {{ form_product.as_p }}
        <input type="submit" value="add product">
    </form>

For first form (CategoryForm) it's working fine because whole page refers to that (model = Category). Now is the question - how to create second object on that page. I can do this in DetailView using urls and parameter like slug, id or pk and after passing it as value but I want to do this from that page without moving to detail page.
Secondly I was thinking how to delete products from list but there is the same problem how to let django know that witch object I would like to remove.
Thanks.


text:
Q: JavaFX: keep window on desktop I want to create a desktop widget (windows 10) with JavaFX. Is there any way to keep the window behind all others on the desktop? Also how to prevent it to minimize when clicking the show desktop button, or at least notice it.

A: After a bit of research it seems to be impossible at the moment to do this with java, although it is possible with the win32api and c++.


text:
Q: Getting linking error 2019 although class is not derived from CString class in VS2010 i am getting the following error

error LNK2019: unresolved external symbol "public: class
  ATL::CStringT > > __thiscall
  CFILicenseSettings::GetCodeStartup1(void)"
  (?GetCodeStartup1@CFILicenseSettings@@QAE?AV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@XZ)
  referenced in function
  __catch$?ValidateLicense@CFIServerDlg@@AAE_NXZ$0  E:\TIMSWebServerManager_lic\TIMSWebServerManager\TIMSWebServerManager.obj   TIMSWebServerManager

My function defination is as follows:
CString CFILicenseSettings::GetCodeStartup1()
{
CString a = "why";
return a;
}

the declaration of the function is as follows:-
CString     GetCodeStartup1();

When i searched the web for the above error i found that this error is because my class is derived from  CString class,but this is not the case.....
I get this error when i call the function GetCodeStartup1();
if i comment the calling of function GetCodeStartup1(); my program compile successfully
How can i remove the error?
Thanks in advance


text:
Q: Widget showing products on Homepage, can't find phtml file of it (Magento 2) I have a widget added in CMS to show product items of a category on my homepage. I need to make changes in the code around the items. Unfortunately path hints doesn't show me which phtml file it is.
I made changes in the following files without success:
Magento_Catalog > templates > product > widgets > (tried all files)

Magento_Catalog_Widget > templates > product > widget > content > grid.phtml

But no change to the output.

A: I found the mistake, correct it must be Magento_CatalogWidget and not Magento_Catalog_Widget.
Correct path:
Magento_CatalogWidget > templates > product > widget > content > grid.phtml


text:
Q: Special rename with htaccess I'm trying to make some URL changes using .htaccess.
I need to rewrite or redirect from this:
example.com/masonry_gallery/project1

To this:
example.com/project1-detalle

In other words, that is to remove the /masonry_gallery/ part, and adding "-detalle" at the end of the URL.
I have tried several combinations without any luck. I appreciate if someone could give me a hand.
UPDATE: This is how the htaccess file looks like now:
RewriteRule ^masonry_gallery/(project1)$ /$1-detalle [R,L]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

A: From your example it's a one-to-one redirect. Try the in your .htaccess file:
RedirectMatch 302 ^/masonry_gallery/(project1)$ /$1-detalle

This assumes you are not already using mod_rewrite for other rewrites/redirects.
UPDATE: Since you are using WordPress (which uses mod_rewrite) try the following instead at the top of your .htaccess file:
RewriteRule ^masonry_gallery/(project1)$ /$1-detalle [R,L]

Change this to a 301 only when you are sure it is working OK (if this is intended to be a permanent redirect). ie. Change R to R=301.

there will be some other projects in the future, so the URL will probably change on the part it says "project1", to include project2, project3, project4, etc... Could you please consider this to include something like (*) or the required value in order for it to work with any number?

By "number" I assume any number of digits 0-9 (but at least 1 digit), then try the following:
RewriteRule ^masonry_gallery/(\d+)$ /$1-detalle [R,L]


text:
Q: Iniciar un proyecto de Integration Services Project desde un botón de un Windows Forms tengo 3 proyecto creados. Visual Studio C#
1-El primer proyecto es un Integration Services Project, lo que hace este proyecto es descargar un archivo txt que se encuentra en drivehq y lo guarda en una carpeta.
2-El segundo proyecto es un Integration Services Project que se encarga de migrar el archivo descargado a una base de datos.
3-El tercer proyecto es un Windows Forms, está conectado a una base de datos. El proyecto #2 se encarga de subir la información descargada del proyecto #1 a esa base de datos.
En el proyecto de Windows Forms hay algunos botones, como eliminar, buscar e insertar usuarios a la base de datos.
PREGUNTA:
Quiero agregar 2 botones al windows forms que se llamen "Descargar" y "Migrar" y deseo que esos botones cuando sean presionado hagan el funcionamiento del proyecto #1 y el proyecto #2.
Añadí los 2 proyectos existentes a el proyecto de Windows Forms, si se ejecuta todo correctamente, se descarga el archivo, lo guarda en una carpeta y luego lo sube a la base de datos y se refleja, el problema es que se ejecuta todo al mismo tiempo y no cuando yo quiera. Necesito crear los botones que  me permitan hacerlo cuando yo quiera ejecutar.


text:
Q: Why doesn't echo php in css.php not work? I've created a CSS file with a PHP-extention, called all.php. This file looks like:
<?php
header("Content-type: text/css; charset=utf-8");

session_start();

$color = $_SESSION['color']; ?>

.className {
   background-color: <? echo $color; ?>;
}

This file's called on every page using
<link rel="stylesheet" href="css/all.php" media="screen">

When I echo the $_SESSION as plain text on a php file, everything works just fine. So, the SESSION is set properly, somehow it doens't work in the css.php file. What am I doing wrong?

A: You probably have short tags turned off in your php.ini (which you should do).
Instead of <? echo $color; ?>;
Use <?php echo $color; ?>;
or <?= $color; ?>;

A: Found the solution. In the original document I started the page with the header, then session_start(). Those should be switched. The page has to start with session_start(), otherwise it will be treated as CSS.

A: Inside the css.php the file itself doesnt know about the $_SESSION variable you have set in your files where you're including the css.php file, because it doesnt know which Session you use.
echo session_id(); outside css.php to get your Session Id. I mean where you get values back from your Session variables like you mentioned.
Then set session_id() = (the id here) inside your css.php


text:
Q: Computer turns itself on after any off mode Whenever I shut down my computer, or put it in sleep/hybernate, it turns on after two seconds. It doesn't post, it just powers on and then idles. To actually turn it off, I switch off the psu. The problem is now, whenever I switch the psu on and try to boot, it doesn't always turn on. It takes a good amount of flicking the psu switch on and off before the motherboard lights up.
So far I've determined the things its not:

*

*its not caused by the mouse or network waking up the computer. I've been able to go into hybernate for the past year. And all "wake on X" settings in the bios are diabled.

*its not a scheduled task waking up the computer at a given hour, it occurs every single time

*its not due to an upgrade or new installation, since I haven't done either in a very long time

I'm sure its a hardware issue. So I'd like to know, is my psu dead, or the motherboard? The psu is an Antec Earthwatts 600w, the motherboard is an Asus P5Q-E, both one year old.

A: While it could be either, the PSU is the more likely candidate, and probably easier/cheaper to replace.  Try swapping the PSU out for a known-good (or "new", that works too) PSU of equal or greater wattage.
If your problems disappear, blame the PSU and move on.

A: This turned out to be two problems.

The problem is now, whenever I switch
  the psu on and try to boot, it doesn't
  always turn on. It takes a good amount
  of flicking the psu switch on and off
  before the motherboard lights up.

As quack pointed out, the PSU was a likely candidate. It was clearly dying, so I replaced it. Now the power always turned on. However, the following problem remained:

Whenever I shut down my computer, or
  put it in sleep/hybernate, it turns on
  after two seconds. It doesn't post, it
  just powers on and then idles.

While attempting to solve this, I went about the following:

*

*Cleared the BIOS many, many times

*Tried all possible permutations of bios options relating to power and sleep

*Systematically removing hardware/peripherals and then booting/sleeping, until I ended up with only motherboard, cpu, psu, one stick of ram, and a power cord connected (I scheduled a task that put the computer to sleep one minute after boot to test)

*Investigated the event viewer for problems

*ran powercfg -LASTWAKE to get a report on what woke up the computer

This led me to replace the motherboard. Now I have no problems either booting or sleeping. So in conclusion, the replacement of both the PSU and the motherboard solved the problem.

A: Try clearing the BIOS by completely removing power and using the CMOS jumper. Then take BIOS default settings and go into ACPI and turn off any S2/S3 sleep or hibernate modes. Look for and turn off any settings about what devices can wake up the machine, particularly network.
If that doesn't work also check try toggling any BIOS settings about legacy versus USB keyboards and mice.


text:
Q: Passing 'this' pointer to MouseProc of SetWindowsHookEx Generally, whenever we want to wrap a Window/Thread in a C++ object, we do so by passing the this pointer via SetWindowLong/GetWindowLong or SetProp/GetProp for a Window, and as lpParameter for CreateThread/etc.
My question is specific to Hooks. What is the elegant approach to pass the 'this' pointer to SetWindowsHookEx's callback procedures, or in other words How to wrap a hook's callback procedure ?
Since SetWindowsHookEx does not accept any UserData argument, I don't see much options apart from using un-encapsulated i.e. global/static/TLS data.

A: You are expected to have just one instance of a given hook, so global data is not an issue.
If you are developing a library allowing multiple hook instances that can be dynamically added or removed, do not add multiple hooks at the OS level.  Instead, add a library-level hook procedure that walks the list of hook instances.  Since you maintain this list, you can track whatever "user data" alongside each entry you want.

A: The 'most elegant approach' is to use a thunk. It's a small piece of code generated at runtime that holds your this pointer. This is the approach that ATL uses even for regular windows.
See

*

*What is a thunk?

*How to generate the code for thunks

*C++ WinAPI Wrapper Object using thunks (x32 and x64)


text:
Q: length of video supported in html's video tag I have a problem with video streaming. I have a file 19279141 bytes of lenght and when I want send them using "chunk transfer", On browser site video is played but not buffered like for shorter file, mayebe somebody know where can be problem ?

A: http://net.tutsplus.com/tutorials/html-css-techniques/html5-audio-and-video-what-you-must-know/
Have a look at "Anatomy of the Video Element" => "preload". This is what you are looking for. It seems to be the browsers decision whether to buffer the video or not.
Please note the "Monitoring download progress" section as well. It gives you an idea on how to track the progress.


text:
Q: jQuery Plugin into Ember component I am trying to turn this jQuery plugin https://github.com/xoxco/jQuery-Tags-Input into an Ember component.
import Ember from 'ember';

export default Ember.Component.extend({

tagName : "input",
type : "text",
attributeBindings : [ "name", "type", "value", "id"],

_initialize: function() {

    Ember.assert("Tags Input has to exist on Ember.$.fn.tagsInput", typeof Ember.$.fn.tagsInput === "function");

    this.$('#tags').tagsInput({'width':'100px'});

}.on('didInsertElement')
});

Then in my handlebar file {{tag-input id="tags"}}
But it seems that the jQuery isn't working as it is just a standard input box. This is the generated HTML <input id="tags" class="ember-view" type="text"></input>
But if I copy this.$('#tags').tagsInput({'width':'100px'}); into the console and run it the element uses the plugin.
What would be the reason that the plugin wouldn't get fired on didInsertElement?

A: In addition to what kunerd said, you might need to schedule this to after everything is fully rendered by scheduling your code to the afterRender queue in the run loop, like this:
_initialize: function({
  Ember.run.scheduleOnce('afterRender', this, function() {
    this.$().tagsInput({'width': '100px'});
  });
}).on('didInsertElement')

Ember.run is a slightly complicated topic, but essentially things happen in order in "queues" that Ember fires off, and the afterRender queue is the one that happens after everything is rendered.
Here's a pretty good blogpost on Ember.run, and here's an even more in-depth book-like repository on it.

A: Your problem is that this.$("#tags") searches for a DOM element with id: tags inside your components DOM element.
To solve your problem, you should use this.$().tagsInput({..}) instead.
Also see this JSBin for a working example.

A: Add setup jquery code into your component.js like following:
import Ember from 'ember';

export default Ember.Component.extend({

tagName : "input",
type : "text",
attributeBindings : [ "name", "type", "value", "id"],

setupTagsInputPlugin: Ember.on('didRender', function() {
    this.$("#tags").tagsInput({
width:"100px"
    });
  }),

});


text:
Q: Can I use libjpeg to read JPEGs with an alpha channel? There seems to be some debate about whether JPEGs with alpha channels are valid or not.  The answer I had always understood to be correct is that in the JPEG FAQ, which is essentially "No".  (This is reiterated in another question on Stack Overflow.)
However, Java's JPEGImageWriter in Sun's ImageIO library will happily write and read grayscale and RGB images with an alpha channel, even though there are virtually no applications on Linux I've tried so far that will load such JPEGs correctly.  This has been reported in the past as a bug, but Sun's response is that these are valid files:

This is not an Image I/O bug, but rather a deficiency in the other applications
  the submitter mentions.  The IIO JPEGImageWriter is able to write images with
  a color model that contains an alpha channel (referred to in the IJG native
  source code as the "NIFTY" color spaces, such as RGBA, YCbCrA, etc.), but many applications are not aware of these color spaces.  So even though these images
  written by the IIO JPEG writer are compliant with the JPEG specification (which
  is blind to the various color space possiblities), some applications may not
  recognize color spaces that contain an alpha channel and may throw an
  error or render a corrupted image, as the submitter describes.
Developers wishing to maintain compatibility with these other alpha-unaware
  applications should write images that do not contain an alpha channel (such as
  TYPE_INT_RGB).  Developers who want the capability of writing/reading an image
  containing an alpha channel in the JPEG format can do so using the Image I/O
  API, but need to be aware that many native applications out there are not quite
  compliant with the YCbCrA and RGBA formats.
For more information, see the Image I/O JPEG Metadata Format Specification and Usage Notes:
  http://java.sun.com/j2se/1.4.1/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html
Closing as "not a bug".
    xxxxx@xxxxx   2003-03-24

I'm working with a Java application that creates files like these, and want to write some C code that will load these as fast as possible. (Essentially the problem is that the Java ImageIO library is remarkably slow at decompressing these files, and we would like to replace the loader with native code via JNI that improves this - it's a performance bottleneck at the moment.)
There are some example files here - apologies to anyone who's coulrophobic:

*

*http://mythic-beasts.com/~mark/example-jpegs/
And here you can see the results of trying to view the grayscale+alpha and RGB+alpha images with various bit of Linux software that I believe use libjpeg:
grayscale image with alpha channel view with various programs http://mythic-beasts.com/~mark/all-alpha-bridges.png

(source: mark at mythic-beasts.com)
So it looks as if the color space is just being misinterpreted in each case.  The only allowed values in jpeglib.h are:
/* Known color spaces. */

typedef enum {
        JCS_UNKNOWN,            /* error/unspecified */
        JCS_GRAYSCALE,          /* monochrome */
        JCS_RGB,                /* red/green/blue */
        JCS_YCbCr,              /* Y/Cb/Cr (also known as YUV) */
        JCS_CMYK,               /* C/M/Y/K */
        JCS_YCCK                /* Y/Cb/Cr/K */
} J_COLOR_SPACE;

... which doesn't look promising.
If I load these images with a slightly modified version of example.c from libjpeg, the values of cinfo.jpeg_color_space and cinfo.out_color_space for each image after reading the header are as follows:
gray-normal.jpg: jpeg_color_space is JCS_GRAYSCALE, out_color_space is JCS_GRAYSCALE
gray-alpha.jpg: jpeg_color_space is JCS_CMYK, out_color_space is JCS_CMYK

rgb-normal.jpg: jpeg_color_space is JCS_YCbCr, out_color_space is JCS_RGB
rgb-alpha.jpg: jpeg_color_space is JCS_CMYK, out_color_space is JCS_CMYK

So, my questions are:

*

*Can libjpeg be used to correctly read these files?

*If not, is there an alternative C library I can use which will cope with them?

Obviously there are at least two other solutions to the more general problem:

*

*Change the software to output normal JPEGs + a PNG file representing the alpha channel

*Somehow improve the performance of Sun's ImageIO

... but the first would involve a lot of code changes, and it's not clear how to go about the latter.  In any case, I think that the question of how to use libjpeg to load such files is likely to be one of more general interest.
Any suggestions would be much appreciated.

A: Even if you store your images as 4 channel jpeg images, there's no standardized way I know of how to specify the color format in the jpeg file.
The JFIF standard assumes YCbCr.

A: Have you already tried libjpeg-turbo? It is supposed to be able to decode RGBA and there is already a Java wrapper for it.

A: I have tried running libjpeg-turbo on color images that have an alpha channel and which have been saved with java's ImageIO as jpeg.
This is how I compiled libjpeg-turbo for linux 64-bit:
$ autoreconf -fiv
$ mkdir build
$ cd build
$ sh ../configure --with-java CPPFLAGS="-I$JAVA_HOME/include -I$JAVA_HOME/include/linux"
$ make
$ cd ..
$ mkdir my-install
$ cd build
$ make install prefix=$PWD/../my-install libdir=$PWD/../my-install/lib64

This is how I run Fiji with the correct library path and classpath, to include libjpeg-turbo:
$ cd Programming/fiji
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/../java/libjpeg-turbo/libjpeg-turbo/my-install/lib64
$ ./fiji -cp $PWD/../java/libjpeg-turbo/libjpeg-turbo/my-install/classes/turbojpeg.jar

This is a small jython script to read such jpeg+alpha files:

######
path = "/home/albert/Desktop/t2/trakem2.1263462814399.1347985440.1111111/trakem2.mipmaps/0/17.07may04b_GridID02043_Insertion001_00013gr_00005sq_00014ex.tif.jpg"

from org.libjpegturbo.turbojpeg import TJDecompressor, TJ
from java.io import File, FileInputStream
from java.awt.image import BufferedImage
from jarray import zeros

f = File(path)
fis = FileInputStream(f)
b = zeros(fis.available(), 'b')
print len(b)
fis.read(b)
fis.close()

d = TJDecompressor(b)
print d.getWidth(), d.getHeight()
bi = d.decompress(d.getWidth(), d.getHeight(), BufferedImage.TYPE_INT_ARGB, 0)

ImagePlus("that", ColorProcessor(bi)).show()
####

The problem: no matter what flag I use (the '0' above in the call to decompress) from the TJ class (see http://libjpeg-turbo.svn.sourceforge.net/viewvc/libjpeg-turbo/trunk/java/doc/org/libjpegturbo/turbojpeg/TJ.html), I cannot get the jpeg to load.
Here's the error message:

Started turbojpeg.py at Thu Jun 02 12:36:58 EDT 2011
Traceback (most recent call last):
  File "", line 15, in
    at org.libjpegturbo.turbojpeg.TJDecompressor.decompressHeader(Native Method)
    at org.libjpegturbo.turbojpeg.TJDecompressor.setJPEGImage(TJDecompressor.java:89)
    at org.libjpegturbo.turbojpeg.TJDecompressor.(TJDecompressor.java:58)
    at sun.reflect.GeneratedConstructorAccessor10.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.python.core.PyReflectedConstructor.constructProxy(PyReflectedConstructor.java:210)

java.lang.Exception: java.lang.Exception: tjDecompressHeader2(): Could not determine subsampling type for JPEG image

So it appears that either libjpeg-turbo cannot read jpeg with alpha as saved by ImageIO, or there is a very non-obvious setting in the call to "decompress" that I am unable to grasp.


text:
Q: declare an array with pointer within the bounds of the available RAM I want to create an array using pointers but I want to set its capacity to the maximum available RAM. I've tested this method:
void init()
{
  long  maxSize = 0x7fffffff;
  long capacity = maxSize / sizeof(int);
  int* _array = new int[capacity];
}

but this method fails and gives me this error at runtime:
Unhandled exception at 0x7651A6E2: Microsoft C++ exception: std::bad_alloc at memory location 0x012FF780.
So how can I allocate my array at the maximum available size?

A: You should understand that if you have 10 GB of free RAM, it does not mean that you can allocate an array of 10 GB. Imagine that the letter e denotes an empty gigabyte and the letter b denotes a busy one. And in real life, your RAM will look something like this
eebeebbeeebeebe We can notice that here 10 GB are free, but we cannot allocate an array on 10 GB (let's not forget, at arrays elements go consistently in storage). So the only way I can advise is to go through the dimensions until you find the largest free.
So your code might looks like this(but NOTE, you can improve size by using std::realloc instead of new + delete, and I'm using binary search to imrove perfomance)
size_t min = 0;
size_t max = std::numeric_limits<size_t>::max();

int *ptr = new int[min];

while (max - min > 1)
{
    size_t middle = (max - min) / 2 + min;
    try
    {
        int *temp = new int[middle];
        min = middle;
        delete[] ptr;
        ptr = temp;
    }
    catch (const std::exception &e)
    {
        max = middle;
        continue;
    }
}
std::cout << "max_size is " << min << '\n';


text:
Q: Regular expression: how to ignore block of text I use some macros in my HTML enclosed in {..}. I parse it before HTML output. Regex is looks like /\{(.*?)\}/ (I simplified it for example). But later I found the problem. If HTML contains JavaScript then it is corrupted when it contains curly braces.
So I need to apply my regex to text that is not inside <script...></script> tags. How it can be done?


text:
Q: How to set default value to last day of year in laravel migration column I want to set default value to the last day of year in laravel migration column, for example "31-12-2021" but I want year to be changed automatically every year

A: My understanding is that migration files are used to set table columns data types only, and the timestamps are supported data types inside the database.
So, you can't make a dynamic default value other than a timestamp.
I will suggest this logic inside your Model:
class User extends Eloquent {

    public $timestamps = false;

    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->created_at = //the calculation of the last day of the year
        });
    }

}

Edit:
As @Andy commented you can get the last day of the year like:
$model->created_at = date("Y-m-d", strtotime("last day of december"));


text:
Q: Installing Visual Studio 2010 on a SharePoint "Farm" Instlling a trial VS2010 on my workstation hoping to develop some simple custom web parts for our SharePoint 2010 webs. As soon as I try to create an appropriate projectd (Empty SharePoint project) I'm warned that VS2010 must be installed on the same server as SharePoint.
I can do this, but on which server... there are 5 of them on our farm. APP01, APP02, WFE01 (web front end), WFE02, and SQL.
Many thanks!

A: Don't install Visual Studio on any of those servers. Install SharePoint on your development computer, then once you develop your solutions deploy them to your test and finally production SharePoint servers as wsp files.


text:
Q: collapsable panel not working properly I am facing an issue working with panel collapse where I have a to create dynamic data-target and id's for panel because I have list of items in ng-repeat but the problem is the collapsible panel is not in the scope of the triggering panel
Here is the html code:

{{topics}}

Question Lists

                        <input type="text" class="form-control" ng-model="search" ng-change="fnSearchQList(search)">

                    <button class="btn btn-primary pull-right" ng-click="fnshowInputQList()">

                            Add Question List

                    </button>

Controller code is as below:
$scope.fngetQList = function(topics,index) {
        $scope.index = index;
    };

the array of topics is for example:["html","css","angular"]
I have no idea what I am doing wrong but when I click on 1st item the panel is getting opened with "collapse in " class but when I click on second item there still the "collapse in " class is getting appened which results in closing of the panel instead of opening the panel.
working example:
http://jsfiddle.net/Lvc0u55v/6625/
Any help would be appreciated.

A: i dont know if this is correct but it does what you want. i added the popup div inside the ng-repeat

{{topics}}

Question Lists

                           <button class="btn btn-primary pull-right">Click here</button>


text:
Q: ASP.NET Core 3.0: Display GIF when OnPost() gets hit I am trying to put a GIF onto my website, and looking through other sources, I've found that I need to use a little bit of Ajax and Javascript to do so. However, I have no experience with either of them. Would anyone be able to post a solution for a web app using razor pages that would allow me to display a loading gif after I reach the onPost function on one of my pages? Any links would also be great! The solutions I've found so far seem to be for aspx files, and I don't have those within my project, nor do I understand how to convert the code to a cshtml / cshtml.cs format. Thank you for any help!
Edit: Going off the Demo that was posted in the solutions, I've been able to add in the script that was posted, but there are still issues.
This is the code that I have on my page:
@page
@model CustomerPageTest.Pages.Assessment.UploadModel
@{
    ViewData["Title"] = "Upload";
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

3) Import RVTools Spreadsheet (.xls or .xlsx)

    <form enctype="multipart/form-data" method="post">

                    <input asp-for="@Model.FormFile" type="file" class="text-light">

                    <input asp-for="@Model.CustomerId" type="hidden" />

                    <input asp-for="@Model.AssessmentId" type="hidden" />

                    <button id="buttonSubmit" asp-page-handler="Upload" class="btn btn-dark" type="submit">Upload File</button>

    </form>

@section scripts{

}

As you can see I have a portion that takes in an Excel file, so my onPost cannot be a JsonResult OnPost() function, instead, it is a Task<IActionResult> OnPostUploadAsync(IFormFile files). I'm not sure how this affects the loading GIF. I also removed the token portion of the script because I don't completely understand what it is, but I don't think that it is needed here. Thank you for the help! Unfortunately, the solutions I've received for this haven't been enough to help me figure solve this issue.

A: Here is a demo worked:
test.cshtml:

    <form method="post">
        </form>

        <button id="showGif">show</button>

@section scripts{

}

test.cshtml.cs:
public JsonResult OnPost() {
            return new JsonResult("success");
        }

startup.cs:
public void ConfigureServices(IServiceCollection services)
        {

            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

        }

result:

XSRF-token:
Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks. You don't have to write any additional code. Antiforgery token generation and validation is automatically included in Razor Pages. In ajax post,the request fails, there is no AntiForgeryToken present on the page.So you need to add "XSRF-TOKEN" to the Header.
Use <form method="post"></form>so that you can find $('input:hidden[name="__RequestVerificationToken"]').val() in html
Since the script sends the token in a header called X-CSRF-TOKEN, configure the antiforgery service to look for the X-CSRF-TOKEN header:
 services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");


text:
Q: How to sort column header values of crosstab in jasper? My column values in jasper crosstab has month names.
Problem is they are sending from backend in various objects, so I can't sort month name coming from backend.
<
Because of that this issue has occurred.

I want to sort these columns in Jan, Feb, Mar, Apr, May Aug order.
Can I do that setting a if else if else condition in column value in jasper?

A: To sort your crosstab header you have two options:

*

*Create a Comparator class in java and pass that to the columnGroup's bucket expression in comparatorExpression

*Create a measure that is sortable and pass that to orderByExpression.
In this example I will use method 2 and presume that the backend returns the month in date format MMM, hence I create a date object and get the time from this. If the month name is not in MMM format you would need to implement a ternary expression as suggested by Alex K.
new java.text.SimpleDateFormat("yyyy-MMM-dd").parse("2000-" + $F{Month} + "-01").getTime()

Create the measure:
<measure name="monthSort" class="java.lang.Long">
    <measureExpression><![CDATA[new java.text.SimpleDateFormat("yyyy-MMM-dd").parse("2000-" + $F{Month} + "-01").getTime()]]></measureExpression>
</measure>

Add the measure to the orderByExpression in the columnGroup (avoiding null pointer if variabile is not instanced yet)
<columnGroup name="Month" height="20" totalPosition="End">
    <bucket class="java.lang.String">
        <bucketExpression><![CDATA[$F{Month}]]></bucketExpression>
        <orderByExpression><![CDATA[($V{monthSort}==null?0:$V{monthSort})]]></orderByExpression>
    </bucket>
    ....
 </columnGroup>

Full example
Data
+------+-------+-------+
| Name | Month | Value |
+------+-------+-------+
| cat1 | Jan   |   121 |
| cat1 | Feb   |    52 |
| cat1 | Aug   |    73 |
| cat1 | Mar   |    14 |
| cat2 | Feb   |    54 |
| cat2 | Apr   |    80 |
| cat2 | Dec   |    10 |
| cat2 | Jan   |    20 |
+------+-------+-------+

jrxml
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="SortValue" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="0ba3ded0-a5d4-435b-a2b1-c61ecd71ac00">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Months"/>
    <style name="Crosstab_CH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Crosstab_CG" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Crosstab_CT" mode="Opaque" backcolor="#005FB3">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Crosstab_CD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <queryString language="csv">
        <![CDATA[]]>
    </queryString>
    <field name="Name" class="java.lang.String"/>
    <field name="Month" class="java.lang.String"/>
    <field name="Value" class="java.lang.String"/>
    <summary>
        <band height="300" splitType="Stretch">
            <crosstab>
                <reportElement x="0" y="0" width="520" height="70" uuid="13bf3aea-b677-4389-bbd5-60cb98bad0c6">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                </reportElement>
                <rowGroup name="Name" width="60" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{Name}]]></bucketExpression>
                    </bucket>
                    <crosstabRowHeader>
                        <cellContents mode="Opaque" style="Crosstab_CH">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="f9becd93-ee0a-443b-bf24-d3c5f903d2b7"/>
                                <textFieldExpression><![CDATA[$V{Name}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabRowHeader>
                    <crosstabTotalRowHeader>
                        <cellContents mode="Opaque" style="Crosstab_CT">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="87613864-7410-44f6-a39f-7a727545db9d"/>
                                <text><![CDATA[Total Name]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalRowHeader>
                </rowGroup>
                <columnGroup name="Month" height="20" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{Month}]]></bucketExpression>
                        <orderByExpression><![CDATA[($V{monthSort}==null?0:$V{monthSort})]]></orderByExpression>
                    </bucket>
                    <crosstabColumnHeader>
                        <cellContents mode="Opaque" style="Crosstab_CH">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="f8957674-bebb-4c29-9799-ff0b1756d910"/>
                                <textFieldExpression><![CDATA[$V{Month}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabColumnHeader>
                    <crosstabTotalColumnHeader>
                        <cellContents mode="Opaque" style="Crosstab_CT">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="50a78979-ea87-457d-aced-36a474659b62"/>
                                <text><![CDATA[Total Month]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalColumnHeader>
                </columnGroup>
                <measure name="Value_MEASURE" class="java.lang.String" calculation="First">
                    <measureExpression><![CDATA[$F{Value}]]></measureExpression>
                </measure>
                <measure name="monthSort" class="java.lang.Long">
                    <measureExpression><![CDATA[new java.text.SimpleDateFormat("yyyy-MMM-dd").parse("2000-" + $F{Month} + "-01").getTime()]]></measureExpression>
                </measure>
                <crosstabCell width="60" height="20">
                    <cellContents mode="Opaque" style="Crosstab_CD">
                        <textField isBlankWhenNull="true">
                            <reportElement x="0" y="0" width="60" height="20" uuid="f53a65f4-1f08-4856-92a4-09267c6c073c"/>
                            <textFieldExpression><![CDATA[$V{Value_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" columnTotalGroup="Month">
                    <cellContents mode="Opaque" style="Crosstab_CT">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="0a17d733-1388-4df9-b754-182eaa09eca8"/>
                            <textFieldExpression><![CDATA[$V{Value_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="Name">
                    <cellContents mode="Opaque" style="Crosstab_CT">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="2bcf8a9c-8315-4508-9397-4850b08957f9"/>
                            <textFieldExpression><![CDATA[$V{Value_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="Name" columnTotalGroup="Month">
                    <cellContents mode="Opaque" style="Crosstab_CT">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="5431126e-8ed1-4c20-be7b-f88df55039c2"/>
                            <textFieldExpression><![CDATA[$V{Value_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
            </crosstab>
        </band>
    </summary>
</jasperReport>

Output


text:
Q: search 4-5 bytes sequence in big file I have file ~ 1.5GB
I need to find in this file 3 billion sequences of bytes. One sequence may be 4 or 5 bytes.
Find the first position, or to make sure that such a sequence in the file no.
How to do it fastest?
RAM limit on computer - 4GB

A: Use grep. It's highly optimized for finding things in large files.
If that's not an option, read about the Boyer-Moore algorithm it uses and implement it yourself. It'll take a lot of tweaking to reproduce the same speed grep has though.

A: Use Preprocessing.
I think you should just create an Index, make a run through the file, recording the first instance of every unique 4 byte sequence. Store the 4 byte sequence and the first occurring position in a different file, sorted by the byte sequence.
Using a simple binary search on the Index file will efficiently find your sequence.
You could be more clever and use hashing to reduce the search to O(1).

A: Check out the Searchlight search engine.
This program allows multiple sequences of up to 10 ASCII bytes to be stored within a single file.  You then point it at a file, directory, file of filenames, file of directory names, arraylist of filenames or an arraylist of directory names and away it goes!!
Furthermore, it reports the file byte position/offset of each sequence found.