text:
Q: EditText In ListView <?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent">
    <!-- Header -->
    <LinearLayout android:id="@+id/header"
        android:background="#FFFFFF"
        android:padding="10dip"
        android:orientation="horizontal"
        android:paddingBottom="5dip"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        >
        <TextView android:id="@+id/heading"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:text="Items"
            android:gravity="left"
            android:layout_weight="1"
            android:textColor="#CC6633"
            android:textSize="25px"
            android:textStyle="bold"
        />
        <Button
            android:text="Add To Order"
            android:id="@+id/btnOrder"
            android:layout_weight="1"
            android:textSize="15px"
            android:gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
        </Button>
    </LinearLayout>
    <LinearLayout android:id="@+id/header"
        android:background="#FFFFFF"
        android:padding="5dip"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        >
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_gravity="center"
            android:padding="5dip"
            android:id="@+id/linearLayout2">
            <TextView
                android:id="@+id/txtnameItem"
                android:text="Item"
                android:gravity="left"
                android:textColor="#000000"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
            </TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:padding="5dip"
            android:gravity="left"
            android:id="@+id/linearLayout2">
            <TextView
                android:id="@+id/txtpriceItem"
                android:gravity="left"
                android:text="Price"
                android:layout_weight="1"
                android:textColor="#000000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:layout_gravity="left">
            </TextView>
            <TextView
                android:id="@+id/txtorderItem"
                android:gravity="right"
                android:text="Order"
                android:layout_weight="1"
                android:textColor="#000000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right">
            </TextView>
        </LinearLayout>
    </LinearLayout>

    <!-- List Divider -->
    <View android:layout_width="fill_parent"
        android:layout_height="5dip"
        android:background="#C85A17" />

    <!-- ListView (list_items) -->
    <LinearLayout android:id="@+id/layout"
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <ListView android:id="@+id/listview"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:descendantFocusability="beforeDescendants"
            android:layout_width="fill_parent">
        </ListView>
    </LinearLayout>
</LinearLayout>

finalorderitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:orientation="vertical"
  android:background="#FFFFFF"
  android:layout_height="fill_parent">
    <LinearLayout
        android:layout_margin="15dip"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:background="#FFFFFF"
        android:orientation="horizontal"
        android:id="@+id/linearLayout1">
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_gravity="center"
            android:padding="3dip"
            android:paddingRight="0dip"
            android:id="@+id/linearLayout2">
            <TextView
                android:id="@+id/txtnameFinalOrderItem"
                android:textSize="20px"
                android:textStyle="bold"
                android:text="col_1"
                android:gravity="left"
                android:textColor="#000000"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
            </TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:textStyle="bold"
            android:id="@+id/linearLayout2">
            <EditText
                android:text=""
                android:id="@+id/edttextFinalOrderQty"
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:onClick="setFocus"
                android:numeric="integer"
                android:layout_height="wrap_content">
            </EditText>
            <TextView
                android:id="@+id/txtfinalpriceFinalOrderItem"
                android:gravity="left"
                android:layout_gravity="center"
                android:text="col_2"
                android:layout_weight="1"
                android:textSize="20px"
                android:textColor="#000000"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
            </TextView>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

so now i make a CustomAdapter which extends BaseAdapter class, all things work very fine, list view appear correctly, but whenever i click on edittext to enter some value then it lost his focus due to getView() function, so please suggest me what can i do for this

A: You can add a windowSoftInputMode description in the AndroidManifest.xml file:
<activity
android:name= "YourActivityName"
android:windowSoftInputMode="adjustPan"
/>


text:
Q: Ordenar array multidimensional desde una llave específica Estuve investigando por todos lados y aún así no he encontrado una solución para mi problema:
Tengo un array multidimensional el cual construyo desde una consulta a MySQL y me devuelve lo siguiente:
Array ( [51] => Array ( [name] => Kiwi-Fresa Sin Azúcar [value] => 19 ) [58] => Array ( [name] => Pan de muerto [value] => 20 ) [14] => Array ( [name] => Mango sin azúcar [value] => 16 ) [15] => Array ( [name] => Limón [value] => 11 ) [2] => Array ( [name] => Avellana Sin Azúcar [value] => 17 ) [21] => Array ( [name] => Pistache [value] => 4 ) [28] => Array ( [name] => Chocolate con Avellana [value] => 3 ) [23] => Array ( [name] => Stracciatella [value] => 7 ) [39] => Array ( [name] => Vainilla [value] => 14 ) [22] => Array ( [name] => Chocolate Belga [value] => 5 ) [31] => Array ( [name] => Pera Sin Azúcar [value] => 4 ) [17] => Array ( [name] => Mamey [value] => 3 ) [27] => Array ( [name] => Tiramisú [value] => 3 ) [60] => Array ( [name] => Te Chai [value] => 1 ) [18] => Array ( [name] => Mandarina sin azúcar [value] => 8 ) )

O en jSON (que es como realmente lo imprimo para pasarlo a JS):
{"51":{"name":"Kiwi-Fresa Sin Az\u00facar","value":19},"58":{"name":"Pan de muerto","value":20},"14":{"name":"Mango sin az\u00facar","value":16},"15":{"name":"Lim\u00f3n ","value":11},"2":{"name":"Avellana Sin Az\u00facar ","value":17},"21":{"name":"Pistache","value":4},"28":{"name":"Chocolate con Avellana","value":3},"23":{"name":"Stracciatella","value":7},"39":{"name":"Vainilla ","value":14},"22":{"name":"Chocolate Belga","value":5},"31":{"name":"Pera  Sin Az\u00facar ","value":4},"17":{"name":"Mamey","value":3},"27":{"name":"Tiramis\u00fa","value":3},"60":{"name":"Te Chai","value":"1"},"18":{"name":"Mandarina sin az\u00facar","value":8}}

Mi duda es cómo puedo ordenar este arreglo de manera ascendente o descendente teniendo en cuenta la llave "value"

A: Lo pude resolver, dejo el código por si alguien tiene el mismo problema:
function comp($a, $b) {
if (strcmp($a["value"], $b["value"]) == 0) {
  return strcmp($a["name"], $b["name"]);
}else {
  return ($a["value"] < $b["value"]) ? -1 : 1;
}

   }

  usort($Desc,"comp");

A: Aquí tienes una solución de una sola línea:
usort($array, function ($a, $b) { return $b['value'] - $a['value']; });

Al consultar la variable $array después de que se ejecutó la línea anterior, el arreglo estará ordenado.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there anyway to assign custom property for html element in it's tag? Need pure html + js solution Maybe this is weird, but this is what I need.
For example, we can do this:
var elem = document.getElementById("some_id");

if ("asd" in elem)
    alert(elem.asd); // and this in second pass
else
    elem.asd = "dsa"; //this will be executed first

I want something like this:
<input type = "button" value = "test btn" asd = "something" />

But this does not work. maybe there is some other way?
I really can't use body.onload to assign needed things.

A: Don't create non-standard expando attributes. HTML 5 introduces the data-* attribute set which is designed for adding custom data to HTML elements.
<input type="button" value="test btn" data-asd="something">

You can then access them through the dataset property.
var button = document.querySelector('input');
alert(button.dataset.asd);

If you want to support old browsers, you can use getAttribute:
var button = document.querySelector('input');
alert(button.getAttribute('data-asd'));

Or a library with a compatibility routine, such as jQuery:
var button = $('input');
alert(button.data('asd'));

A: Your HTML is good enough. But for accessing attribute you should say like bellow.
var attr = elem.getAttribute("asd");
alert(attr);


text:
Q: What if files change while rsync is running? I am using rsync to copy ~10GB of small files. What happens if the files in the source directory are modified while rsync is running?

A:
What happens if the files in the source directory are modified while rsync is running?

That depends if they are modified before rsync is running as well. As @Sachin said if they are not modified before the transfer then modifications during the transfer won't be picked up, however:

if you are modifying a file while it's being transferred, then probably the checksum will fail and it'll go round again. And if it goes around twice, and it still fails, then it prints a message saying; Error, checksum failed, file changed during transfer?

A: rsync first scans the files and builds a list. so once the file is listed for sync, rsync will sync the latest change of file. but if the file is not in the list of files to be synced, which was built before starting the sync operation, then it will not sync it.


text:
Q: In Excel, How can I find same words in a range from left? I scraped a seller website and now need to find same product variants from title. How can I find same words for variant title?
EXAMPLE IN THE BELOW:

A: I would prefer doing this via VBA however it is still doable with formula.
Looking at your sample strings, you need to remove one, two or three words from right to extract the common string.
What you need is to remove the last one word from the end, and look for an exact match using * wildcards.
If removing one word is not enough to find a match, you should do this for two words, then three words and so on if you need more.
Below is the output of the formulas for stripping one, two, and three words respectively:

CELL B2: Formula to strip one word from right and look for a match
=IFNA(IFNA(IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1)&"*",A3:$A$14,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1),""),IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1)&"*",$A$1:A1,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1),"")),"STRIPPING ONE WORD NOT ENOUGH")

CELL C2: Formula to strip one word, ifna then two words from right and look for a match
=IFNA(IFNA(IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1)&"*",A3:$A$14,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1),""),IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1)&"*",$A$1:A1,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1),"")),IFNA(IFNA(IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1)&"*",A3:$A$14,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1),""),IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1)&"*",$A$1:A1,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1),"")),"STRIPPING TWO WORDS NOT ENOUGH"))

CELL D2: Formula to strip one word, ifna then two words, ifna then three words from right and look for a match
=IFNA(IFNA(IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1)&"*",A3:$A$14,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1),""),IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1)&"*",$A$1:A1,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))-1),"")),IFNA(IFNA(IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1)&"*",A3:$A$14,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1),""),IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1)&"*",$A$1:A1,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-1))-1),"")),IFNA(IFNA(IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-2))-1)&"*",A3:$A$14,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-2))-1),""),IF(MATCH("*"&LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-2))-1)&"*",$A$1:A1,0)>0,LEFT(A2,FIND("[",SUBSTITUTE(A2," ","[",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))-2))-1),"")),"STRIPPING THREE WORDS NOT ENOUGH")))

Looking at your sample strings in your question, you should use the formula in Cell D2 since you have three or less words to be stripped. If you have four or more, follow the logic and replace "STRIPPING THREE WORDS NOT ENOUGH" with the formula for one word (and repeat this for more words). Just copy/paste the formulas for the rest of your list.
A Reminder: My list ends at A13 so I used A14 in my formula. You should change it according to the length of your list.
Another Reminder: These formulas are based on your sample strings so if you encounter any problems with this formula in your original list, then you should also include these sample strings to your question as well for a feasible solution.

A: I would consider using Fuzzy match with Microsoft add-in if you have a Microsoft Windows operating system with Microsoft Excel 2010 or newer installed.
Download: https://www.microsoft.com/en-gb/download/details.aspx?id=15011
It is easy to use and the key advantage is that you can easily extend it when you encounter new terms. You can also manually inspect matches in a simple fashion and tweak match parameters to get better results.
You can create mapping tables to achieve your goal. Consider a simplified example as having a reference table of expected expressions which new values are compared against. You are given a score of how likely it is they are match/are the same.
From the MS Fuzzy read me:

A challenging problem in data management is that the same entity may
  be represented in multiple ways throughout the dataset. For instance,
  customer "Andy Hill" might also be present as "Mr. Andrew Hill" or
  "Hill, Andrew R.". Variations can result from merging independent data
  sources, spelling mistakes, inconsistent naming conventions and
  abbreviations, or records with additional/missing information.
Fuzzy Lookup technology, developed by Microsoft Research, allows you to
  quickly identify data records which are textually similar. You can
  identify fuzzy duplicates within a single table or perform a fuzzy
  join between two different tables.

Additional:
1) Tutorials for Add-in
2) Geek out: If you are interested in a technical application of fuzzy matching see this amazing answer by @Alain and surrounding discussion:
Getting the closest string match
3) Technical resources on Fuzzy Lookup

*

*Microsoft Research Data Cleaning Project

*Transformation-based Framework for Record Matching

*Efficient Exact Set-Similarity Joins

A: You can use VLOOKUP. According to this tutorial (https://www.excel-university.com/perform-approximate-match-and-fuzzy-lookup-in-excel/),
=VLOOKUP(C7, Table1, 2, FALSE)

Where:

*

*C7 is the value to find

*Table1 is the lookup range

*2 is the column that has the value we wish to return

*FALSE means we are not performing a range lookup


text:
Q: Generics in C# - Cannot convert 'classname' to 'TGenericClass' UPDATE: This isn't about getting it to compile. The question is, why does the C# compiler allow the cast when using an interface, but it can't figure out the type when I use a class that implements the same interface.
I am getting the following error:
Cannot convert type 'Amber.BLL.iWeb.Session.AppSession' to 'TService'

Here is the code:
public override TService GetService<TService>()
{
    if ( typeof( TService ) == typeof( IAppSession ) )
    {
        AppSession session = new AppSession();
        return (TService) session;
    }
    throw new Exception( String.Format(
        "iWebFactoryProvider cannot create services of type '{0}'.",
        typeof( TService ).Name ) );
}

As it so happens, the AppSession class implements the IAppSession interface. If I change the line of code that instantiates AppSession to use the interface, like this:
IAppSession session = new AppSession();

suddenly everything compiles fine.  I also note that it compiles fine if I do this:
AppSession session = new AppSession();
return (TService) (IAppSession) session;

In case it matters, the GetService() is overriding a method whose signature is declared like this:
public virtual TService GetService<TService>() where TService : class

In short, I can't figure out what the rules should be here so I can know how to avoid this situation in the future. Why was the compiler happy to cast the interface, but not happy to cast the interface's implementing class?
I note that this question is asking about a similar issue, but the answer isn't detailed enough for me to understand how it applies to my situation.

A: You can convert the object by using (TService)(Object)instance or use constraints on the generic parameter.
The reason why the compiler is happy about the cast, is simply that he doesn't know what is behind the instance of a interface so the cast may succeed. When casting from class to generic type T he doesn't know if the cast is valid and throws a error at compile time. Of course he could do this also after compile but there is a good reason for this, imagine...
return (TService)myinstance;

is exchanged by:
return (CustomService)myinstance;

and the myinstance variable is not compatible with the type CustomService.
But a cast from a interface to TService may succeed, or from Object to TService.

A: Have you tried adding a constraint for IAppSession?
public virtual TService GetService<TService>() where TService : IAppSession, class

That linked question is exactly the same issue. The compiler doesn't know that TService can be an AppSession.

A:
Why does the C# compiler allow the cast when using an interface, but it can't figure out the type when I use a class that implements the same interface?

Good question. Consider the following:
public interface I {}
public class D {} // Note that D does not even implement I!
public class E
{
    public static M<T>(T t)
    {
        D d1 = (D)t; // Illegal
        D d2 = (D)(object)t; // Legal
        D d3 = (D)(I)t; // Legal
    }
}

Let's break your question up into three questions.

Why is the cast directly from T to D illegal?

Suppose it were legal. Then E.M<D>(new D()) would work just fine; we'd cast the T to D and in fact it is a D, so no problem.
Now suppose we create an entirely different assembly with:
class C
{
    public static explicit operator D(C c) { whatever }
}

And you call E.M<C>(new C()) in that assembly..  What do you reasonably expect to happen?  You have an object of type C, it is being cast to D, and there is an explicit conversion operator right there from C to D. Most people would reasonably expect that the explicit conversion operator would be called.
But how on earth is the compiler supposed to realize when compiling the body of M that someone in the future might create a class C in a completely different assembly? The compiler has no way to emit the call to the conversion operator when compiling M. So we have three choices:

*

*Make cast operators sometimes use explicit conversion operators and sometimes not, depending on whether you're in a generic or not.

*Make cast operators start the compiler again at runtime to look for explicit conversion operators that might have been added in different assemblies after the original code was compiled.

*Disallow the cast in the first place.

In short, our choices are (1) make generics inconsistent, (2) make generics slow and unpredictable, or (3) disallow a feature that is already working against genericity.  This is an easy choice to make; we chose (3).
If you want (2), you can have it in C# 4; dynamic starts the compiler again at runtime and works out whether there is an explicit conversion operator.

Why is the cast indirectly from T to D via object legal?

Because now no user-defined conversion can be relevant; there is never a user-defined conversion from object to anything.

Why is the cast indirectly from T to D via I legal?

Because now no user-defined conversion can be relevant; there is never a user-defined conversion from an interface to anything.
Bonus question:

But D does not even implement I! What's up with that?

A derived class of D might:
class F : D, I {}
...
E.M<D>(new F());

Now t can be cast to I because it might implement I, and I can be cast to D because it might be F.
If D were sealed then it would not be legal to cast from I to D because then there could not possibly be a derived F type.


text:
Q: Linear Regression and High Dimensional Categorical Data I've read that mean encoding is useful for classification tasks with high dimensional categorical data.
My question:
What kinds of encodings are effective for high dimensional categorical data in linear regression tasks? For example, can mean encoding be adapted?
Some possible applications:

*

*Assigning credit limit using job title (we need to encode job title)

*Predicting wait time at a nightclub from shoe type (we need to encode shoe type)

A: Mean encoding seems to be popular in machine learning, but you should try better ways. The problem that dummy coding (or "one-hot") with many levels uses much memory, can be solved with sparse matrices. But still there might be too many parameters with one for each level, so some kind of collapsing of levels could be useful, see Principled way of collapsing categorical variables with many levels?.
What you should do might also depend on which kind of model you are using (you didn't tell us). For one idea see Strange encoding for categorical features.


text:
Q: Why am I getting an array out of bounds exception, and why am I only generating the number 0? public class ArraysList {

    public static void main(String[] args) {
        int[] scores1;
        int[] scores2;

        scores1 = new int[7];
        scores2 = new int[7];

        int index = 0;
        while (index <= 6) {
            scores1[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
            scores2[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
            index++;
        }

        System.out.println(scores1[index]);
    }
}

I am confused as to why I am getting the exception. I can fix this by changing the size of the array to 8, but I shouldn't have to do that. Also when it is changed to 8, the output is all 0's. I have used 3 different ways of getting a random integer and the outcome is the same every time.

A: Line after the loop, System.out.println(scores1[index]); - the loop condition is index <= 6 which means index is now 7. Thus it is out of range. I think you wanted System.out.println(Arrays.toString(scores1));

A:     int[] scores1;
    int[] scores2;

    scores1 = new int[7];
    scores2 = new int[7];

    int index = 0;
    while (index <= 6) {
        scores1[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
        scores2[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
        index++;
    }

For this line you should rewrite like this. Because index always starts from 0 in array and you are trying to fetch data at index 7 which is not present in array.
 System.out.println(scores1[index-1]);


text:
Q: Create two columns from one, based on two different WHERE clauses SELECT TOP 1000 [Value]
FROM [OnlineQnres].[dbo].[tmp_DataSets]
WHERE [VariableID] in ('1')
UNION ALL
SELECT TOP 1000 [Value]
FROM [OnlineQnres].[dbo].[tmp_oDataSets]
WHERE [VariableID] in ('4')

The above query produces 2000 rows; 1000 with Value for VariableID = 1, and 1000 with Value for VariableID = 2. What I want is 1000 rows, with one column (val1) containing the values for VariableID = 1, and the other column (val2) with the values for VariableID = 2.

A: ;WITH x AS
(
  SELECT TOP (1000) Value, row_num = ROW_NUMBER() OVER (ORDER BY Value)
    FROM OnlineQnres.dbo.tmp_oDataSets
    WHERE VariableID = '1'
), y AS
(
  SELECT TOP (1000) Value, row_num = ROW_NUMBER() OVER (ORDER BY Value)
    FROM OnlineQnres.dbo.tmp_oDataSets
    WHERE VariableID = '4'
)
SELECT val1 = x.Value, val2 = y.Value
FROM x INNER JOIN y
ON x.row_num = y.row_num;

As I stated in a comment, for this correlation to be meaningful, you need to define how the ROW_NUMBER() is calculated (or indicate how these two sets of values are related). In this case it will correlate the smallest value for variableID = 1 with the smallest value for variableID = 2, the 2nd smallest value for variableID = 1 with the 2nd smallest value for variableID = 2, etc.
Also, as others noted, to get predictable results, you need to define TOP (1000) with a separate ORDER BY.
Essentially, if you have these rows in the table, and pretend you are only looking for two of each variableID:
VariableID    Value
----------    -------
1             foo
1             bar
4             mort
4             splunge

What does the result look like? Should it be:
val1    val2
------  -------
foo     mort
bar     splunge

If so, why? If not, why not? Or should it be:
val1    val2
------  -------
foo     splunge
bar     mort

If so, why? If not, why not? Or should it be:
val1    val2
------  -------
foo     NULL
bar     NULL
NULL    mort
NULL    splunge

Or something else entirely?
There are other query approaches too, but they depend on your requirements, and how the rows are linked other than the fact that they are "any" row that match the WHERE clauses.
Flimsy requirements lead to flimsy answers, sorry.


text:
Q: C# BeginAcceptTcpClient returns multiple tcp clients when browser tries to connect I am trying to create a HTTP/1.1 web server using TcpListener class in C#.
I have created this basic code for receiving incoming connections to the web server.
namespace TCPServer
{
    using System;
    using System.Net;
    using System.Net.Sockets;

    class Program
    {
        private static TcpListener listener;

        private static int count;

        static void Main(string[] args)
        {
            listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, 8080));
            listener.Start();

            BeginAccept();

            while (true)
            {
                Console.ReadLine();
            }
        }

        static void BeginAccept()
        {
            listener.BeginAcceptTcpClient(BeginAcceptCallback, null);
        }

        static void BeginAcceptCallback(IAsyncResult result)
        {
            var id = ++count;
            Console.WriteLine(id + " Connected");

            BeginAccept();
        }
    }
}

But when I run this program and try to connect to http://localhost:8080/ in my web browser (google chrome) I read 3 different connections coming in.
Output:
1 Connected
2 Connected
3 Connected

Only one of these connections contains the prolog and headers of the http request, the other 2 seem to be empty.
Is this standard behavior?
If so, what are the other 2 connections used for?
Or is there something I am doing wrong?


text:
Q: Не меняется текст UILabel У меня есть некоторый UILabel titleLabel, который инициализируется в конструкторе, Frame же указывается в LayoutSubview.
По задумке, при нажатии кнопки (вызывается метод btnOKClicked) должен меняться текст того самого titleLabel:

    public void btnOKClicked()
    {
        titleLabel.Text = "Changed";

        Thread.Sleep(1000);

Однако ничего не происходит.
Вопрос:чего я не понимаю?

A: Оказалось, что Thread.Sleep(x) заблокировал основной поток
Заменил его    await Task.Delay(x)


text:
Q: How to state that a class is related to ALL instances of another class via a property Have two questions

*

*Given classes A, B and object property p (A->B). How to say that for any a from A and any b from B a is mapped via property p to b (a p b)?
In other words A has property p and every instance of A is mapped to all instances of B via propery p.

*Now we have 3 classes A, B, C and 2 properties p1 (A->B or domain A, range B) and p2 (B->C or domain B, range C).
How to say in Protege that for any a from A and any c from C there exists a b from B for which a p1 b and b p2 c?


text:
Q: Uniform bounds for a coupled parabolic system of PDE (linear) Let $V=H^1(\Omega)$ and $H=L^2(\Omega)$ where $\Omega$ is a compact Riemannian manifold. Define $W = \{ w \in L^2(0,T;V) : w_t \in L^2(0,T;V^*)\}$.
Consider the system, with $u^\epsilon, v^\epsilon \in W,$
$$u^\epsilon_t + Au^\epsilon + Bu^\epsilon +\epsilon v^\epsilon = f$$
$$v^\epsilon_t - Av^\epsilon + \epsilon u^\epsilon = g$$
$$u^\epsilon(0) = u^\epsilon(T) - l(u^\epsilon(T))$$
$$v^\epsilon(T) =  v^\epsilon(0) - l(v^\epsilon(0))$$
$$\text{Condition (1)}$$
where $A:L^2(0,T;V) \to L^2(0,T;V^*)$ is a bounded self-adjoint linear map such that $\langle Aw,w\rangle \geq C_1\int_0^T|w|^2_{V} - C_2\int_0^T|w|^2_H$, $B:L^2(0,T;V) \to L^2(0,T;V^*)$ is a bounded linear map, where $l \in H^*$ and $f$ and $g$ are given in $L^2(0,T;V^*)$ and the equation is considered in $L^2(0,T;V^*)$ and Condition (1) an extra condition involving $l(u^\epsilon(0))$ and $l(v^\epsilon(T))$ which happens to imply that
$$\int_0^T\frac{d}{dt}\int_\Omega u(t)v(t) = 0.$$
Question : Is it possible to obtain any estimates on $u^\epsilon$ and $v^\epsilon$ in any norms (eg. $|u^\epsilon|_{L^2(0,T;V)}$ or $|u^\epsilon_t|_{L^2(0,T;V^*)}$) that are independent of $\epsilon$?

*

*The aim is to send $\epsilon \to 0$ and extract weak-convergent subsequences so that I can deduce something about the system
$$u_t + Au + Bu= f$$
$$v_t - Av = g.$$
Specifically I only care about the equation for $u$.

*Does anyone know any techniques? I tried testing the equations with $u^\epsilon, v^\epsilon$ and so on but couldn't achieve it. Gronwall gives me a $|u^\epsilon(0)|$ and $|v^\epsilon(0)|$ on the right hand side which is not wanted.

*Maybe I should consider a different regularisation with $\epsilon$ since I am unable to find any uniform bounds.


text:
Q: Webkit, IE deselecting text I'm working on making a contentEditable jQuery plugin.  I've created a 'tools' bar to perform actions to the text such as making it bold, italics etc using execCommand.  The problem is that when you select text and click one of the buttons (divs with onclick events) it deselects the text you had selected (all browsers).  To fix this I have used:
toolBar.onmousedown=function(){return false};

Which works well in Firefox and Opera.  I'm trying to use
toolBar.onselectstart = function(){return false};

which prevents text selection in IE.  However, neither webkit or IE work.  I've seen this done with input buttons before, but I'd rather use divs.  Any ideas?

A: A simple alternative is to use <button> tags for your toolbar. That way it doesn't lose the text selection in the first place.

A: I solved this problem by reselecting the text.
On mouseup I capture the selection information:
$.getSelection = function() {
    // ie has its own way of doing things from here on.
    if($.browser.msie) return document.selection.createRange();

    if (window.getSelection) {
        var selection = window.getSelection();
    }
    else if (document.selection) { // should come last; Opera!
        var selection = document.selection.createRange();
    }

    if (selection.getRangeAt)
        var range = selection.getRangeAt(0);
    else { // Safari!
        var range = document.createRange();
        range.setStart(selection.anchorNode, selection.anchorOffset);
        range.setEnd(selection.focusNode, selection.focusOffset);
    }
    if (!range.toString().match(/[^\t\r\n ]/)) return false;

    var ret = {};

    // start end length text

    ret.startContainer  = range.startContainer;
    ret.start   = range.startOffset;
    ret.endContainer    = range.endContainer;
    ret.end     = range.endOffset;
    ret.length = ret.end - ret.start;
    ret.collapsed   = range.collapsed;

    return ret;
};

This is stored somewhere of your choosing.
I then either reselect the text if the browser is w3c compliant for DOM Range (i.e. all but ie) and perform the execCommand:
function handleReselection() {
    if($.browser.msie) {
        return this.selection;
    }
    else {
        setSelection(this.selection);
        return document
    }
}

function setSelection(selection) {
    var sel = window.getSelection();
    sel.removeAllRanges();
    var range = document.createRange();
    range.setStart(selection.startContainer, selection.start);
    range.setEnd(selection.endContainer, selection.end);
    sel.addRange(range);
}

handleReselection().execCommand('bold', false, null);


text:
Q: How to use value of selected option to run query? I'm fairly new to JavaScript and PHP so I have no idea what I'm doing for the most part. I'm making  a Room Reservation System. What I want to do is get the selected option value from the 'room' select box so that I can use that value to run a query so that the time retrieved in the From and To select boxes has the available times for that specific room.
// To display all rooms in the database into the select box
    $select_query = "SELECT * FROM rooms";
    $result = $conn->query($select_query);
    if($result->num_rows > 0){
        $options = mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
    $today_date = date('Y-m-d');
    $disable_query = "SELECT room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '$today_date'";
    $start_from = 8;
    $end_from = 21;
    $start_to = $start_from+1;
    $end_to = $end_from+1;
    $disable = $conn->query($disable_query);
    $from_booked = [];
    $to_booked = [];
    if($disable->num_rows>0){
        while($row = $disable->fetch_assoc()){
            $from_booked_hour = date_parse($row['booking_start'])['hour'];
            $to_booked_hour = date_parse($row['booking_end'])['hour'];
            $from_booked = range($from_booked_hour, $to_booked_hour-1);
            $to_booked = range($from_booked_hour+1, $to_booked_hour);
        }
    }

This is my PHP code. I want to get the value of the selected room so that the query will include a room_id that is equal to the value of the selected room as well.
Room
<select required class="form-select form-select-lg" name="room" id="room" onchange="selectbox(this.options[this.selectedIndex].value);">
    <option selected disabled value="">Select a room</option>
    <?php
        foreach($options as $option){
    ?>
    <option value=<?php echo $option['room_id'];?> ><?php echo $option['room_name']?></option>
    <?php
        }
    ?>
</select>

            From
            <select required name="from" id="from" class="form-select form-select-lg">
                <option selected disabled value="">Pick a time</option>
                <?php
                    for($hour = $start_from; $hour <= $end_from; $hour++){
                        if(in_array($hour, $from_booked)){
                            if($hour < 10){
                                echo "<option disabled value = '0".$hour.":00:00'>".$hour.":00</option>";
                             }
                             else {
                                echo "<option disabled value = '".$hour.":00:00'>".$hour.":00</option>";
                             }

                         }
                         else{
                             if($hour < 10){
                                 echo "<option value = '0".$hour.":00:00'>".$hour.":00</option>";
                             }
                             else {
                                 echo "<option value = '".$hour.":00:00'>".$hour.":00</option>";
                             }

                         }
                     }
                 ?>
             </select>

                 To
                     <select required name="to" id="to" class="form-select form-select-lg">
                        <option selected disabled value="">Pick a time</option>
                        <?php
                            for($hour = $start_from+1; $hour <= $end_from+1; $hour++){
                                if(in_array($hour, $to_booked)){
                                    if($hour < 10){
                                        echo "<option disabled value = '0".$hour.":00:00'>".$hour.":00</option>";
                                    }
                                    else {
                                        echo "<option disabled value = '".$hour.":00:00'>".$hour.":00</option>";
                                    }

                                }
                                else{
                                    if($hour < 10){
                                         echo "<option value = '0".$hour.":00:00'>".$hour.":00</option>";
                                     }
                                     else {
                                         echo "<option value = '".$hour.":00:00'>".$hour.":00</option>";
                                     }

                                 }
                             }
                         ?>
                     </select>

I've tried AJAX and XMLHttpRequest to send the value from JavaScript to PHP but it's but both methods are not working. This is all in 1 php file by the way. I'm not sure if I'm doing anything wrong or if there is a simpler way to achieve what I want to achieve.
In my js file, I had the code for my last attempt at using AJAX to send the variable to PHP
function selectbox(val){
    $.ajax({
        url: 'home.php',
        type: 'POST',
        data: {
            'value': val
        },

        success: function(data){
            alert(data);
        }
    });
}

In my PHP, I had code that verify that it received the variable but it didn't work
if(isset($_POST['value'])){
    $room_id = $_POST['value'];
    echo "";
}

A: You are missing the quotes in the selected option value.
There is a short way to get the select value with jquery or raw js.
With jQuery you can use onchange="$(this).val()"
With Raw JS you can use onchange="this.value"
Both will return the selected value. Run the below code and check the console network you will see the value=test 1 or any selected value.
And in your PHP just print the value like below.
<?php
    print_r($_POST);
    if(isset($_POST['value'])){
        echo $_POST['value'];
    }
?>

function sendAjax(val){
  alert(val);
  console.log(val);
  $.ajax({
    url:'home.php',
    method:"POST",
    data:{'value':val},
    success:function(data){
      console.log(data);
    }
  });
}

<select required class="form-select form-select-lg" name="room" id="room" onchange="sendAjax(this.value);">
    <option selected disabled value="">Select a room</option>
    <option value="Test 1">Test 1</option>
    <option value="Test 2">Test 2</option>
    <option value="Test 3">Test 3</option>
    <option value="Test 4">Test 4</option>
    <option value="Test 5">Test 5</option>
</select>

A: In web development things can be achieved in different ways. You're on the right path but you're missing some understanding of how everything sticks together.
PHP runs on the server, produces HTML code that gets sent to the browser. Browser runs html and js code.
Learn a bit more about PHP, GET, POST, and forms in general.
Then learn a bit JavaScript to get form data and how to use Ajax.
Then try to solve each problem individually: Example: First fix retrieving selected value with JavaScript and alert it to the browser before even worrying about sending it to PHP.
Then think of how you want your user experience to be. Is it a search form or booking form? Cause if it is search you could change form method to "get", either you might want to use "post".
Finally you could choose a solution to your problem.
A) When user selects room, reload the page with the room_id in the URL.

*

*On room select box, listen to change event, for example with onchange attribute, and call js function that will retrieve the selected value

*From that function, redirect with JavaScript to the URL of your script and adding the room id as query parameter, would end up something like: index.php?room_id=123

*Finally, now the page reloads, and in your PHP code you can check if room_id parameter has been set in the $_GET array, and if has been, then you can add it to your SQL query
(Btw also read about SQL injection and escaping params with php/mysql to keep your app safe)

B) When the user selects room, make an Ajax call to get values based on room
Say you don't want your whole page reload, you'd do something like:

*

*Say you have your main form on index.php

*You have your room select as usual

*And you have another select that depends on room

*Well this second select you have to leave it blank, without options

*Then you create a JavaScript function called say: loadFromOptions()

*Inside it you simply add some options to your select box, from JavaScript (google that)

*Now you can open Chrome's developer tools, the Console tab, and run that function by writing it inside the console

*Now you should see your "from" select being populated with some dummy options that you added

*Now, you have to add the loadFromOptions() function to be called both on the onchange attribute of room select, but also on page load, because otherwise if your form has a default room selected, no options will be displayed unless changing room

*Finally, to make the data real, modify your loadFromOptions() function

*From inside it, get the selected value of your rooms select, and for now just alert it or console.log it

*You can locate your rooms select by its id, and then get its value

*Now create a new php file named say, from_dropdown_options.php

*In that php file, you only add logic that will get the room parameter and query the database and spit a list of Option tags

*Say when you open from_dropdown_options.php?room_id=123 in your browser, and you view page source, you should only see option tags

*Finally, from your js function, make an Ajax Get request to your dropdown options php passing the room_id retrieved from the select and then assign the Ajax response to the "from" select content by using innerHTML property, ej: roomSelect.innerHTML=ajaxResponse;

*Also a more robust way to do it, if you want to look into it is to use JSON, and respond from your php with JSON data, then loop it from your Ajax Json response, and create an option for each item

*(One way you spit raw html options and stick them to the select, the other way you respond with a structured js data list and you use that data to generate the options with js)

Sorry I haven't posted almost any code examples but the internet is full of them, you just need to understand in what order to stick your pieces.


text:
Q: Check if record has inactivity in last 4 hours Below is my scenario :

*

*Case gets created in salesforce using Email-To-Case and default owner is assigned as Queue.

*Now if case stays with Queue and does not get assigned to any user  (Meaning inactivity on that record) for 4 hours, I need to send an email to a group of user.

I have this query which gives me a record which are updated in last 4 hours. And I'm writing this logic in a class that I will be scheduling to run after 1 hours.
 List<Case> casesUpdatedInLastFourHours = [select id, Subject, LastModifiedDate from Case where LastModifiedDate = TODAY AND HOUR_IN_DAY(LastModifiedDate) > 4];

But how can we get records which are not modified in last 4 hours? Any help of suggestion is highly appreciated.

A: Just make a record trigger flow to execute after 4 hours after creation under your conditions. Then set a checkbox to true and use that as your alarm to fire your logic. Or even better yet, not do the checkbox at all and just fire the email. should be like 2 or 3 nodes altogether. no code


text:
Q: JQueryMobile Datepicker and new framework I was using JQueryMobile's experiment Datepicker for a while and it worked in the old framwork. Yesterday i changed the framework to latest one and found that it breaks the layout of the Datepicker when I click outside.

Has anyone ecountered same problem?? how did you over come it?? it means datepicker will not be supported in the latest framwork??
My code goes as below
<!DOCTYPE html>

    <title>Page Title</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="jquery.mobile-1.1.0.min.css" />
    <link rel="stylesheet"  href="jquery.ui.datepicker.mobile.css" />

</script>

Page Title

        Date Input:
        <input type="date" name="date" id="date" value=""  />

Page Footer

A: I have encountered the same problem and I just changed the date picker API.
Use this one it will give every thing you want, like the UI like iOS, Android, jQuery Mobile, mode, modal etc. to set along with jQuery code.
jQuery mobile datepicker
The problem never comes after using this.

A: Find this code in jquery.ui.datepicker.mobile.js
just below the updateDatepicker();
$( ".ui-datepicker-calendar .ui-btn", dp ).each(function(){
var el = $(this);
// remove extra button markup - necessary for date value to be interpreted correctly
el.html( el.find(".ui-btn-text").text() );
});

replace
el.html( el.find(".ui-btn-text").text() );

with
el.text( el.text() );

It worked for me :)

A: You could also use this one:
Jquery Mobile datepicker
I have not checked whether this works with 1.1, but it's kept up to date and provides a ton of features.

A: after a lot of search on Internet, especially comparing datebox and jqueryui datepicker (mobiscroll and mobipick are no good to me as i'am looking for a calendar view, i got to the point where i decided to use ui datepicker for few reasons :

*

*i use it from longtime, i know it well enough

*i needed the beforeShowDay (event if it is certainly possible to have similar fonction using datebox and events/callbacks) to customize days with classes

*i needed a header with possibilities to change month and year (also possible in datebox)

*with this experiment i already had a datepicker with a jquerymobile feel & look

I used it with :

*

*jquery 1.8.3

*jquery mobile 1.2.0

*jqueryui datepicker 1.8.21 (get it from here)

using datepicker with more recent versions breaks the layout on month/year change.
from here, i got the files i needed. I used several answers i found on different stackoverflow questions, to make the following changes :

*

*no change on jquery.ui.datepicker.mobile.css

*jquery.ui.datepicker.mobile.js new code :
(function ($, undefined) {

//cache previous datepicker ui method
var prevDp = $.fn.datepicker;

//rewrite datepicker
$.fn.datepicker = function (options) {

var dp = this;

//call cached datepicker plugin
var retValue = prevDp.apply(this, arguments);

//extend with some dom manipulation to update the markup for jQM
//call immediately
function updateDatepicker() {
    $(".ui-datepicker-header", dp).addClass("ui-body-c ui-corner-top").removeClass("ui-corner-all");
    $(".ui-datepicker-prev, .ui-datepicker-next", dp).attr("href", "#");
    $(".ui-datepicker-prev", dp).buttonMarkup({ iconpos: "notext", icon: "arrow-l", shadow: true, corners: true });
    $(".ui-datepicker-next", dp).buttonMarkup({ iconpos: "notext", icon: "arrow-r", shadow: true, corners: true });
    $(".ui-datepicker-calendar th", dp).addClass("ui-bar-c");
    $(".ui-datepicker-calendar td", dp).addClass("ui-body-c");
    $(".ui-datepicker-calendar a", dp).buttonMarkup({ corners: false, shadow: false });
    $(".ui-datepicker-calendar a.ui-state-active", dp).addClass("ui-btn-active"); // selected date
    $(".ui-datepicker-calendar a.ui-state-highlight", dp).addClass("ui-btn-up-e"); // today"s date
    $(".ui-datepicker-calendar .ui-btn", dp).each(function () {
        var el = $(this);
        // remove extra button markup - necessary for date value to be interpreted correctly
        // only do this if needed, sometimes clicks are received that don't require update
        // e.g. clicking in the datepicker region but not on a button.
        // e.g. clicking on a disabled date (from next month)
        var uiBtnText = el.find(".ui-btn-text");
        if (uiBtnText.length)
            el.html(uiBtnText.text());
    });
};

//update after each operation
updateDatepicker();

   $( dp ).on( "click change", function( event, ui)
{
$target=$(event.target);
if(event.type=="click" && ($target.hasClass("ui-datepicker-month") || $target.hasClass("ui-datepicker-year")))
    event.preventDefault();
else
    updateDatepicker( event);
});

//return jqm obj
if (retValue) {
    if (!retValue.jquery) return retValue;
}
return this;
};

})(jQuery);

i use on() instead of click event and i preventDefault on click on month/year select menu.
And i use it this way :
$form
    .trigger( "create" )
    .find( "input[type='date'], input:jqmData(type='date')")
    .each(function()
        {
        $(this)
            .after( $( "
" ).datepicker(
                {
                altField            : "#" + $(this).attr( "id" ),
                altFormat           : "dd/mm/yy",
                showOtherMonths     : true,
                selectOtherMonths           : true,
                showWeek            : true,
                changeYear          : true,
                changeMonth         : true,
                beforeShowDay       : beforeShowDay
                }));
        });

with beforeShowDay being a function returning an array (see jqueryui datepicker manual).
It works for me this way and i now i just need to add events to only show calendar when date input got focus.
A link to jsbin example

A: copy of answer elsewhere :
I worked on updating the jquery ui datepicker to latest versions of jquery , jqueryui and jquery mobile so for jq1.9.1 jqui 1.10.2 and jqm 1.3.0. I prefered to leave as is my previous answer so you can see how it evolved.
the changeMonth and changeYear dropdown needed special care to work (unstylying was frequent)
here it is how i updated the experimental jqueryui datepicker for jqmobile :
js bin code snippet
You can link to the datepicker script instead of the whole jqueryui package.
The readonly prop prevents the keyboard to appear on ios
It is just a tweak of the datepicker to make it work on jqm, the goal would be to be able to override the _generatehtml function of datepicker widget and being able to give as input te jquery mobile theme to use. So you'll not need that whole bunch of addClass and avoid unnecessary DOM manipulation
I only tested for ios 6 (iphone, ipad) and desktop (chrome, firefox, safari), let us know about other tests.
Hope it helps as mush as needed it :)
here is all the code separated in html, js and css :
HTML
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Jqueryui 1.10.2 datepicker Integration in jquery mobile 1.3.0 and jquery 1.9.1 by aureltime</title>
    <link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/jquery.mobile/1.3.0/jquery.mobile-1.3.0.min.css">

jQuery UI's Datepicker Styled for mobile adapted by Aureltime

        <form action="#" method="get" id="form">

                Date:
                <input type="date" name="date" id="date" value=""  />

        </form>

JS
//reset type=date inputs to text
$.mobile.page.prototype.options.degradeInputs.date = true;

$("#form").trigger("create");
$( document )
  .on( "pageinit", function(){

$("#date")
    .prop("readonly", "true")
    .on("click", function(){
$input=$(this);
$next=$input.next();

if($next.hasClass("hasDatepicker"))
  $next.hide();

$input
      .hide()
      .after( $( "
", {   id  :   "datepicker_"+$input.attr("id")}).datepicker(
        {
          altField          : "#" + $input.attr( "id" ),
          altFormat         : "dd/mm/yy",
          defaultDate       : $input.val(),
          showOtherMonths   : true,
          selectOtherMonths : true,
          //showWeek        : true,
          changeYear        : true,
          changeMonth       : true,
          //showButtonPanel : true,
          //beforeShowDay   : beforeShowDay,
          onSelect          : function( dateText, inst)
          {             $("#datepicker_"+$input.attr("id")).hide();
$input.show();
          }
        }));
    });
        });

(function($, undefined ) {

    //cache previous datepicker ui method
    var prevDp = $.fn.datepicker;

    //rewrite datepicker
    $.fn.datepicker = function( options ){

        var dp = this;

        //call cached datepicker plugin
        prevDp.call( this, options );

        //extend with some dom manipulation to update the markup for jQM
        //call immediately
        function updateDatepicker(event){

          $( ".ui-datepicker-header", dp ).addClass("ui-body-c ui-corner-top").removeClass("ui-corner-all");
            $( ".ui-datepicker-prev, .ui-datepicker-next", dp ).attr("href", "#");
            $( ".ui-datepicker-prev", dp ).buttonMarkup({iconpos: "notext", icon: "arrow-l", shadow: true, corners: true});
            $( ".ui-datepicker-next", dp ).buttonMarkup({iconpos: "notext", icon: "arrow-r", shadow: true, corners: true});
            $( ".ui-datepicker-calendar th", dp ).addClass("ui-bar-c");
            $( ".ui-datepicker-calendar td", dp ).addClass("ui-body-c");
            $( ".ui-datepicker-calendar a", dp ).buttonMarkup({corners: false, shadow: false});
            $( ".ui-datepicker-calendar a.ui-state-active", dp ).addClass("ui-btn-active"); // selected date
            $( ".ui-datepicker-calendar a.ui-state-highlight", dp ).addClass("ui-btn-up-e"); // today"s date

            if(typeof event != "undefined")
                {
                var classe= $(event.target).attr("class");
                //alert(classe);
                }
          $( ".ui-datepicker-calendar .ui-btn", dp ).each(function(){
                    var el = $(this);
                    var buttonText = el.find( ".ui-btn-text" );
                    // remove extra button markup - necessary for date value to be interpreted correctly
                    if(buttonText.length)
                        el.html( el.find( ".ui-btn-text" ).text() );
                    });
        //      }

        $( dp )
            .off()
            .on( "click", updateDatepicker)
            .find("select")
            .on( "change", function(event){updateDatepicker(event);});
        }

        //update now
        updateDatepicker();

        //return jqm obj
        return this;
    };
})( jQuery );

CSS
div.hasDatepicker{ display: block; padding: 0; overflow: visible;  margin: 8px 0; }
.ui-datepicker {  overflow: visible; margin: 0; max-width: 500px;  }
.ui-datepicker .ui-datepicker-header { position:relative; padding:.4em 0; border-bottom: 0; font-weight: bold; }
.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { padding: 1px 0 1px 2px; position:absolute; top: .5em; margin-top: 0; text-indent: -9999px; }

.ui-datepicker .ui-datepicker-prev { left:6px; }
.ui-datepicker .ui-datepicker-next { right:6px; }
.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
.ui-datepicker select.ui-datepicker-month,
.ui-datepicker select.ui-datepicker-year { width: 49%;}
.ui-datepicker table {width: 100%; border-collapse: collapse; margin:0; }
.ui-datepicker td { border-width: 1px; padding: 0; text-align: center; }
.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em 0; font-weight: bold; margin: 0; border-width: 0; text-align: center; text-decoration: none; }

.ui-datepicker-calendar th { padding-top: .3em; padding-bottom: .3em; }
.ui-datepicker-calendar th span, .ui-datepicker-calendar span.ui-state-default { opacity: .3; }
.ui-datepicker-calendar td a { padding-top: .5em; padding-bottom: .5em; }

A: I have made a custom datetime picker effective for android and iphone flip (both date and time in two flips) hope it will help
https://github.com/ngethe/jQM-DateBoxNgethe


text:
Q: Bind Google Analytic's Data Feed to Google Charts i have used Google Analytic API Version 3 and i can get data from it with this C# codes:
DataQuery _chartquery = new DataQuery(dataFeedUrl);
        _chartquery.Ids = str;
        _chartquery.Dimensions = "ga:date";
        _chartquery.Metrics = "ga:pageviews";
        _chartquery.Sort = "ga:date";
        _chartquery.GAStartDate = DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd");
        _chartquery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
        DataFeed _chartfeed = service.Query(_chartquery);

here i can get _charfeed as DataFeed, now i want to bind this feed to Google chart, can you tell me how should do this?


text:
Q: How can I have an access to a TextBox in a UiElementCollection? My question seems to be simple and I hope it is.
I have a dynamic collection of TextBox in a UiElementCollection.
The TextBox are children of a StackPanel.
My goal is simple :
Create a new TextBox with the Text of for example UiElementCollection[1].
TextBox myTextBox = new TextBox();                        // New TextBox
UiElementCollection myCollection = myStackPanel.Children; // New Collection

// If I call this :
myCollection[8] = myTextBox;
// Error when I call my method
// --> System.ArgumentException

// If I call this  :
myTextBox = myCollection[8];
// Error in my code
// --> Cannot convert.. UiElement to Controls.TextBox

string myString = myTextBox.Text;

Any one can help me to handle this please ? Thanks.

A: You have to cast it first, there is no implicit conversion:
myTextBox = (TextBox)myCollection[8];

Of course, it is likely a good idea to check if that was a TextBox first using is, or do a null check and as.
Also, the standard note for WPF applies here, in general you should be accessing such data through bindings, not direct UI manipulation.


text:
Q: SQL how to join two tables with same column names but different data in SQL In need you help with that.
I have two databases with 42 column names and need merge to another database with the same 42 columns with the same column names but different values.
DT1
Column0 | Column1 | column3 | column… | column42
1234 example 345 final1
1234 example 567 final3
1234 example 789 final5
12345 example 7890 final9
12345 example 890 final10

DT2
Column0 | Column1 | column3 | column… | column42
4567 example 345 final1
4567 example 567 final3
4567 example 789 final5
45678 example 7890 final9
45678 example 890 final10

DT Result
Column0 | Column1 | column3 | column… | column42
1234 example 345 final1
1234 example 567 final3
1234 example 789 final5
12345 example 7890 final9
12345 example 890 final10
4567 example 345 final1
4567 example 567 final3
4567 example 789 final5
45678 example 7890 final9
45678 example 890 final10

Thanks!
my code
#directory where report results will be saved
report_result = r"path\report_result_%s.csv"%today
report_result_sql_query =""" Select b.column1, b.column2, b.column3, ... b.column42
,a.column1, a.column2, a.column3, ... a.column42
FROM table1 b
FULL OUTER JOIN table2 a
ON a.column1=b.column2
WHERE b.column2 like '%ff%'AND (a.column3 is null or a.column3= '0' or a.column3= ' ') AND a.column2 like '%ff%' AND b.column5 >= '{}' AND a.column5>= '{}'""".format(day,yyday)
print(report_result_sql_query)
report_result_colour = web_service(report_result_sql_query)
print(report_result_colour.shape)
ORC_genesis1_colour.to_csv(report_results_final, index=False)

It is not giving an error however it is giving zero rows and columns but when I run both tables in two separate SQL queries I get results so I assume something is wrong in my join

A: Don't use FULL OUTER JOIN, use UNION ALL:
SELECT column0, column1, column3, column42
FROM   DT1
WHERE  column1 is null
OR     column1= '0'
OR     column1= 'example'
UNION ALL
SELECT column0, column1, column3, column42
FROM   DT2
WHERE  column42 like 'f%';

Which, for the sample data:
CREATE TABLE DT1 (Column0, Column1, column3, column42) AS
SELECT 1234,  'example', 345,  'final1' FROM DUAL UNION ALL
SELECT 1234,  'example', 567,  'final3' FROM DUAL UNION ALL
SELECT 1234,  'example', 789,  'final5' FROM DUAL UNION ALL
SELECT 12345, 'example', 7890, 'final9' FROM DUAL UNION ALL
SELECT 12345, 'example', 890,  'final10' FROM DUAL;

CREATE TABLE DT2 (Column0, Column1, column3, column42) AS
SELECT 4567,  'example', 345,  'final1' FROM DUAL UNION ALL
SELECT 4567,  'example', 567,  'final3' FROM DUAL UNION ALL
SELECT 4567,  'example', 789,  'final5' FROM DUAL UNION ALL
SELECT 45678, 'example', 7890, 'final9' FROM DUAL UNION ALL
SELECT 45678, 'example', 890,  'final10' FROM DUAL;

Outputs:

COLUMN0
COLUMN1
COLUMN3
COLUMN42

1234
example
345
final1

1234
example
567
final3

1234
example
789
final5

12345
example
7890
final9

12345
example
890
final10

4567
example
345
final1

4567
example
567
final3

4567
example
789
final5

45678
example
7890
final9

45678
example
890
final10

fiddle


text:
Q: windows ce 5.0 dll - Can it be fixed address? I have been asked by a client to add OpenSSL to their Windows CE 5.0 based product.  They need OpenSSL to operate in FIPS mode, which requires a known address at compile time for the library.  I have no problems if I build an EXE because I can always rely on an base address of 0x10000 for the EXE, which the FIPS mode check uses to validate the EXE.
The issue I am having is that I need the OpenSSL code to be built into a DLL which is called from another DLL which is called by the main app EXE who calls other DLLs.  So how do I know the address of the my DLL runtime?
The only way I know how to make all this work is if the DLL in question pops up a message box or writes to disk the address for one of its functions, which I can then compare to the offset in the map file when I built that DLL and get the base address for the DLL.  Then I can go back with that address, rebuild the OpenSSL stuff, and then rebuild my DLL and it all works.  FIPS mode is enabled because the address specified at compile time is the address in use runtime.
While this seems to solve the issue, I do not like that this base address may change if other DLLs change or if this DLL changes to add or remove code.  But I guess as long as everything is static, this approach might be okay.
My question:
Is there any way to fix the address of a DLL that is loaded runtime?  Or is BIB and ROM my only option here?  Just want to double check if I could be doing something differently.  Right now if any DLL used by my EXE changes, or if my EXE changes to use more or less DLLs, it might change the load address for my DLL which in turn will disable FIPS mode, so I would have to rebuild the OpenSSL library with the new base address and then rebuild my DLL to get working again.  I am trying to avoid that while still running that OpenSSL library code from a DLL, but I'm not sure it is possible.  Other than moving away from CE 5.0, any recommendations?  Thx.

A: You should be able to use the /BASE linker option:

/BASE Sets a base address for the program, overriding the default location
  for (...) a DLL (at 0x10000000). The operating system first attempts to load a program at its specified or default base address. If sufficient space is not available there, the system relocates the program. To prevent relocation, use the /FIXED option.

If, for whatever reason, the /BASE option doesn't work, an alternative could be to implement a separate OpenSSL exe, and provide a proxy dll to enable clients to communicate with the OpenSSL process.


text:
Q: php app sessions are confused when working with two chrome browsers I have a php application with MySQL database. users and their passwords are stored in the database. the problem is that, sometimes, several users work on the same computer simultaneously, each with its session. When we used the system with internet explorer, it worked well, but now started using google chrome.
what happens is that the sessions are confused, suddenly, the user "x", performs some operation, and the session becomes the session user "Y".
 I wish you could help me, because I do not want to return to Internet Explorer. Thank you.
Here I leave the code as open the session:
$cons = "SELECT * FROM users WHERE login = '$textLogin' AND password = '$pwd'";
$result = mysql_query($cons, $conexion);
if ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{

    /*
    session_name(encriptar($textLogin));
    session_start(encriptar($textLogin));
    */
    session_set_cookie_params(0);
    session_start();
    $nroId = session_id();

    session_set_cookie_params(0);
    session_id($nroId);
    if(!isset($_SESSION))
    {
    session_start();
    }

/*  session_register($nroId);*/

    $_SESSION["loginUsr"] = $row["login"];
    $_SESSION["passwordUsr"] = $pwd;
    $_SESSION["idUser"] = $row["idUser"];
    $_SESSION["name"] = $row["name"];
    $_SESSION["lastname"] = $row["lastname"];

}

And this code is executed every time a php page is called (The session_id is sent every time in the url as "login") :
$sigueCheckS = 0;
if ($_SERVER['REQUEST_METHOD'] == "GET") {
    if (isset($_GET["login"])) {
        $textLogin = $_GET["login"];
        $sigueCheckS = 1;
    } else {
        $sigueCheckS = 0;
        $textLogin = "";
    };
};
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    //if (!empty($_REQUEST["login"])) {
    if (isset($_REQUEST["login"])) {
        $sigueCheckS = 1;
        $textLogin = $_REQUEST["login"];
    } else {
        $sigueCheckS = 0;
        $textLogin = "";
    };
};

if ($sigueCheckS == 1) {
    session_id($textLogin);
    /*COMENTAR ESTAS TRES LINEAS*/
    $horas = 4;
    $tiempo = $horas * 3600;
    ini_set("session.gc_maxlifetime",$tiempo);
    /*COMENTAR ESTAS TRES LINEAS*/
    session_set_cookie_params(0);
    session_start();
     if (!isset($_SESSION["idUsuarioUsr"])) {
        //echo "
no registrado";
        echo "";
        return;
    };
} else {
    //echo "
todo bien";
    echo "";
    return;
};

A: Try Canary:
If your computers are running Windows or OSX you can use Google Chrome Canary. Just install the plugin and click the sessions cookie icon at the end of the address bar. It will open a new window with it's own session data.


text:
Q: Subgroups of a multiplicative group. The multiplicative group $G$ has eight elements $e, a, b, c, ab, ac, bc, abc$, where $e$ is the identity. The group is commutative, and the order of each of the elements $a, b, c$ is $2$.

*

*State the orders of the elements $ab$ and $abc$.

*Find four subgroups of $G$ of order $4$.

*Give a reason why no group of order $8$ can have a subgroup of order $3$.
I don't know what happens to the orders of two elements when they're multiplied together, or how to create a group with order four, and I think the last question has something to do with Lagrange but I'm not sure. Basically I don't understand the question at all so any help would be really appreciated. Don't worry this is for revision not an assignment so don't be afraid to be super specific.
Thanks

A: I'm assuming multiplicative means abelian. If it doesn't, let me know, but I'm not sure what else it could mean.

*

*$(ab)^2=a^2b^2=ee=e \implies |ab|=2$ and $(abc)^2=a^2b^2c^2=eee=e \implies |abc|=2$

*$\langle a,b \rangle \leq G$, $\langle a,c \rangle \leq G$, $\langle b,c \rangle \leq G$, and $\langle a,bc \rangle \leq G$ all have order $4$.

*It is precisely because of Lagrange. The order of any subgroup $\textbf{must}$ divide the order of the total group and obviously, $8$ does not divide $3$.
Let me know if you have questions on notation.

A: If the order of an element $a$ is $n$ and $a^t=e$ then $n$ divides $t$. Indeed, we can write $t=qn+r$ for some $0\le r<n$ and then $e=a^{qn+r}=(a^n)^qa^r=e^qa^r=a^r$, so we have $a^r=e$. By the definition of order, $r=0$, so $t=qn$, as claimed.
For commutative groups, if $m$ and $n$ are respectively the orders of $a$ and $b$, then, let $k=\text{lcm}(m,n)$. Then $(ab)^k=a^kb^k=ee=e$. Then the order of $ab$ must be a divisor of $k$.
This is not necessarily true if the group is not commutative. (The identity $(ab)^k=a^kb^k$ only works in commutative groups, or more precisely, if the particular elements $a$ and $b$ commute).
To create a subgroup of order four, note that you must pick $e$ and, for the moment, another element. This new second element can't have an order greater than $3$ (otherwise, you would add too many elements, because if you add $a$ then you must also add $a^2$, $a^3$, etc), but the order of every element in $G$ is $2$ (or $1$ for $e$), so you can pick any one. Let's remain simple and pick $a$.
Now we have $e$ and $a$. Since $a^2=e$, $a$ is its own inverse, so $\{e,a\}$ is a subgroup. (This idea is important: if the order of $a$ is $n$, then $a^{n-1}$ is the inverse of $a$). Then we need another element. Let's add $b$. We have $\{e,a,b\}$. This is not a subgroup, because $ab$ is not in the set$^*$. Let's add it, then. Is $\{e,a,b,ab\}$ a subgroup?
To finish, no, a group with $8$ elemnts can't have a subgroup with $3$ elements, and this can be easily proved with Lagrange's theorem.
$(*)$: This is not as obvious as it may seem. You must prove that $ab$ is not $e$, $a$ or $b$. For example: $ab$ is not $e$ because $a^2=e$, so if $ab$ were $e$ then $a^2=ab$ and $a=b$, a contradiction with the description of the group. Could you prove that $ab$ is not $a$ or $b$?
Remark: I have proposed questions, but I don't really expect explicit answers. They are only to make you think.


text:
Q: How to display the name that matches the ID without refreshing/submitting the form in Django? I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page.
For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number".
I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered.
My page currently loads, but there is never a call to the function/url that searches for the name to display it on the page (because there isn't one). I'm not sure where I might be missing the part that connects these two areas of the code or how to connect these, as I am not too familiar with html and Django, most of this has been trial and error.
models.py
class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
    employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
    work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False)
    station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True,  blank=True)

This is the model where the name is stored
alldata/models.py
class Salesman(models.Model):
    slsmn_name = models.CharField(max_length=25)
    id = models.IntegerField(db_column='number', primary_key=True)

I was reading I can add to the "attrs" in the widget an 'onchange' part, but I am not too familiar with how to approach this and tying it to the ajax request from forms and not the html.
forms.py
class WarehouseForm(AppsModelForm):
    class Meta:
        model = EmployeeWorkAreaLog
        widgets = {
            'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
        }
        fields = ('employee_number', 'work_area', 'station_number')

views.py
def enter_exit_area(request):
    form = WarehouseForm(request.POST or None)

    if form.is_valid():

        # Submission stuff/rules

    return render(request, "operations/enter_exit_area.html", {
        'form': form,
    })

def get_employee_name(request):
    employee_number = request.GET.get('employee_number')

    try:
        employee = Salesman.objects.get(id=employee_number)
    except Salesman.DoesNotExist:
        return JsonResponse({'error': 'Employee not found'}, status=404)

    employee_name = employee.slsmn_name
    return JsonResponse({'employee_name': employee_name})

urls.py
urlpatterns = [
    url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),

    path('get-employee-name/', views.get_employee_name, name='get_employee_name'),
]

The ajax request I tried to create is at the end of this html. I modified a similar request I found, but it does not actually display anything on the screen, not sure if I'm missing an area where the request is actually never being called, as I am not too familiar with how these types of requests work.
enter_exit_area.html
{% extends "base.html" %}

{% block main %}
    <form id="warehouseForm" action="" method="POST" novalidate >
        {% csrf_token %}

                {{ form.employee_number.help_text }}
                {{ form.employee_number }}

                {{ form.work_area.help_text }}
                {{ form.work_area }}

                <button type="submit" name="enter_area" value="Enter">Enter Area</button>

    </form>

{% endblock main %}

How can I call the function from the HTML? Could I do it in such a way that when the user enters 6 numbers it checks? (All employee numbers are 6 digits)

A: The url has to be the endpoint url which you defined in your url.py file

You can append to your GET request a url parameter like: /get-employee-name/<your employee number here>
I recommend taking a look at URL Dispatcher to create url parameters within your django url definitions
I also recommend using underscores NOT dashes in your url definitions.

So a pseudo working config would be
urls.py
urlpatterns = [
    url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),

    path('get_employee_name/<int:employeeNum>', views.get_employee_name, name='get_employee_name'),
]

views.py
def get_employee_name(request, employeeNum): #You get the employeeNum variable from urls.py
    try:
        employee = Salesman.objects.get(id=employee_number)
    except Salesman.DoesNotExist:
        return JsonResponse({'error': 'Employee not found'}, status=404)

    employee_name = employee.slsmn_name
    return JsonResponse({'employee_name': employee_name})

script


text:
Q: How can i unselect an item if another item is selected?
I am having some Views..I want that if one item is selected the other should get unselected automatically. And when (as shown in image) , if suppose 2nd item whose text here is 100 is selected , the first selection should get unselected. How can i keep a reference of the selected item and unselect other item?? Somewhere i came to know about radio button is used in these..but how can someone show this?

A: Whenever you call your "select" method, inside the code it should first clear any selections you have that are previously existing. You can do this by checking the property / state of every eligible selection and then reversing what you did to select it. You can also keep a reference to the current selection as a sort of hack, and just keep updating that and using it to deselect when a new selection is made.

A: Assuming that you mean changing background etc. by "selecting", you can iterate over the parent ViewGroup (e.g. ConstraintLayout, LinearLayout etc.) and select your target view and unselect the rest of views like the following code.
void toggleView(View view, boolean selected) {
    if (selected) {
        view.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getContext(), R.color.bg_grey_2)));
    } else {
        view.setBackgroundTintList(null);
    }
}

void selectOneViewAndUnselectOthers(ViewGroup parentView, View viewToSelect) {
    for (int i = 0; i < parentView.getChildCount(); i++) {
        View tmpView = parentView.getChildAt(i);
        if (tmpView.getId() == viewToSelect.getId()) {
            toggleView(viewToSelect, true);
        } else {
            toggleView(tmpView, false);
        }
    }
}


text:
Q: After the user enters his name to log-in, a welcome message appears We were tasked to make a program about "After the user enters his name to log-in, a welcome message appears"
This is our code:
#include <stdio.h>
// forward references
int readline(char[]); // prototype
void welcome(char[]); // prototype
#define MAX_LINE 100
char userName[MAX_LINE]; // buffer for user name
main()
{
printf("Please enter your name: ");
readline(userName); // ignore returned value
welcome(userName); // say hello to login user
// ...........................
}
int readline(char strBuffer[])
{
int c, count=0;
while((c=getchar()) != '\n')
strBuffer[count++] = c;
strBuffer[count] = '\0'; // null terminated
return count; // #char in the line
}
void welcome(char name[])
{
printf("%s, you are welcome.\n", name);

After we passed this code, our adviser told us some comments (His reply):

*

*Redefine the prototype of readline as:
int readline(char strBuffer[], int maxbuf)
Where maxbuf represents the size of the buffer.

*Change the sample program to use the newly defined readline function and check whether the overflow phenomenom is resolved.

*Write a function void beep(int n) which emits n audio beeps.

We are having a hard time understanding his comments. We would like some help, to understand what is he trying to convey in a simpler explanation. Thank you :'>

A: int readline(char strBuffer[])
{
int c, count=0;
while((c=getchar()) != '\n')
strBuffer[count++] = c;
strBuffer[count] = '\0'; // null terminated
return count; // #char in the line
}

but you can overflow. How bit is the buffer? readline doesn't know. You should have int readline(char strBuffer[], int maxbuf). This should look eerily familiar. There's a reason for that.
Normally we wouldn't have a readline like this, but just call fgets() directly.
if (!fgets(userName, MAXLINE, stdin)) {
    fprintf(stderr, "Error reading standard input");
    return 1;
}
size_t userNameLen = strlen(userName);
if (userNameLen == 0) {
    return 0; // Typically we don't complain about EOF; just exit.
}
if (userName[userNameLen - 1] != '\n') {
    fprintf(stderr, "User name too long");
    return 1;
}
userName[userNameLen - 1] = 0;

Eventually you'll have a completely different form of readline that stretches the buffer until the line fits, but you're not there yet. We make do with this kind of construction for now.


text:
Q: emmet in Visual Studio not working like it did in Sublime I recently switched from Sublime to Visual Studio. Visual Studio has emmet but im wondering how to regain some features that i liked in Sublime.
in sublime when you...
type "div" then emmet would write out

type "pre" then emmet would write out

type "xx" then emmet would write out <xx></xx>
type "ng-container" then emmet would write out <ng-container></ng-container>
How do i get this back in Visual Studio

A: I have faced this issue in visual studio and resolved it.
Step-1:
follow steps in url.
https://marketplace.visualstudio.com/items?itemName=sidthesloth.html5-boilerplate
Step-2:
if it worked cheers
else
it could be issue with select language mode.
on the bottom next of visual studio next to indents select language mode and change it to html.
Thanks & Regards,
Surya kiran.


text:
Q: will_paginate is there a way to set per_page to 'all' Rails 2.3.5 / Will_Paginate Gem 2.3.15
I have a page section where a user can select how many items per page to display (with an 'all' choice).  I don't like having 'all' in there but each item in the list has a checkbox so that bulk operations can be performed against the listed items (a user couldn't select all items the query would return if the items are broken out into pages).
I haven't found an answer looking around, but is there a way to set the :per_page option to 'all'?   I temporarily just put in a jumbo number (1000000) as a work-around.   Is that the only way to do it?
I thought about just replacing the paginate_by_sql condition with a find_by_sql, but then in the view I'd have to add in logic to not write the "<%= will_paginate @items%>"
    if cookies[:items_per_page]
      if cookies[:items_per_page] == 'ALL'
        @items =  Item.paginate_by_sql(sql, :page => params[:page], :per_page => 1000000)
      elsif %w(10 20 30 40 50 75 100).any? {|str| cookies[:items_per_page].include? str}
        @items =  Item.paginate_by_sql(sql, :page => params[:page], :per_page => cookies[:items_per_page].to_i)
      else #cookie doesn't contain a valid choice, default to '10'
        @items =  Item.paginate_by_sql(sql, :page => params[:page], :per_page => 10)
      end
    else #cookie doesn't exist, default to '10'
      @items =  Item.paginate_by_sql(sql, :page => params[:page], :per_page => 10)
    end

A: Item.paginate_by_sql(sql, :page => params[:page], :per_page => Item.count)


text:
Q: Javascript: Check if server is online? What's the fastest way to check if my server is online via JavaScript?
I've tried the following AJAX:
function isonline() {
    var uri = 'MYURL'
    var xhr = new XMLHttpRequest();
    xhr.open("GET",uri,false);
    xhr.send(null);
    if(xhr.status == 200) {
        //is online
        return xhr.responseText;
    }
    else {
        //is offline
        return null;
    }
}

The problem is, it never returns if the server is offline. How can I set a timeout so that if it isn't returning after a certain amount of time, I can assume it is offline?

A: Here's how I achieved checking server availability using Fetch to manage the request and AbortController to handle a timeout within a Node.js application.

function checkServer(url, timeout) {
  const controller = new AbortController();
  const signal = controller.signal;
  const options = { mode: 'no-cors', signal };
  return fetch(url, options)
    .then(setTimeout(() => { controller.abort() }, timeout))
    .then(response => console.log('Check server response:', response.statusText))
    .catch(error => console.error('Check server error:', error.message));
}

A: XMLHttpRequest does not work cross-domain.  Instead, I'd load a tiny <img> that you expect to come back quickly and watch the onload event:
function checkServerStatus()
{
    setServerStatus("unknown");
    var img = document.body.appendChild(document.createElement("img"));
    img.onload = function()
    {
        setServerStatus("online");
    };
    img.onerror = function()
    {
        setServerStatus("offline");
    };
    img.src = "http://myserver.com/ping.gif";
}

Edit:  Cleaning up my answer.  An XMLHttpRequest solution is possible on the same domain, but if you just want to test to see if the server is online, the img load solution is simplest.  There's no need to mess with timeouts.  If you want to make the code look like it's synchronous, here's some syntactic sugar for you:
function ifServerOnline(ifOnline, ifOffline)
{
    var img = document.body.appendChild(document.createElement("img"));
    img.onload = function()
    {
        ifOnline && ifOnline.constructor == Function && ifOnline();
    };
    img.onerror = function()
    {
        ifOffline && ifOffline.constructor == Function && ifOffline();
    };
    img.src = "http://myserver.com/ping.gif";
}

ifServerOnline(function()
{
    //  server online code here
},
function ()
{
    //  server offline code here
});

A: Add to gilly3 answer
In practice, I found the need to use document.body.appendChild quite slow.
Although the question is about pure JavaScript, using some HTML will make that solution much faster.
So I am leaving this code here for anyone looking for speed.
<html>
<head>
    <title>Some page</title>
</head>

<body>
  <img src="https://myserver.com/ping.gif"  onload="pageOnline()" onerror="pageOffline()">

  <script>

  function pageOnline() {
    // Online code
  }

  function pageOffline() {
    // Offline code
  }
</script>
</body>
</html>

A: Use an XMLHttpRequest, then check whether it failed. Not sure if this would work cross-domain though.

A: Make an ajax call and its result will tell.

A: The original answers are still valid, but quite outdated. Here is the approach I took:
import axios from 'axios'
import to from 'await-to-js'

export default async function pingAppReady(healthCheckPath: string, recursive = true) {
  return new Promise<void>(async (resolve, reject) => {
    // Ping the path e.g http://localhost:3000
    const [err] = await to(axios.get(healthCheckPath))

    // resolve if the ping returns no error or error that is not related to the connection
    if (!err) return resolve()
    if (err.code !== 'ECONNREFUSED') return resolve()

    if (!recursive) reject()

    setTimeout(async () => {
      await pingAppReady(healthCheckPath, recursive)
      resolve()
    }, 5000)
  })
}

A: Since XMLHttpRequest did not work for me for cors issues, I found and tried gilly3's answer and it works fine, if you call it once. It fails, when you check a server frequently, since the loaded graphics file is already in the cache of the browser. So I've added a random element as query string to avoid this. (A solution, I'v also found somewhere at stack overflow.)
function checkServer(callback, fqdn, imagepath="/favicon.ico") {
    let img = new Image();
    img.onload = function() { callback(fqdn, true); };
    img.onerror = function() { callback(fqdn, false); };
    img.src = "http://" + fqdn + imagepath + '?r=' + Math.random(); /* avoids caching */
}


text:
Q: How can I monitor which applications make DNS requests on OS X? I'm trying to send all of my unencrypted day-to-day traffic over an SSH tunnel, which is working pretty well with a simple SOCKS proxy. Skype still goes outside, but that's okay, as Skype is encrypted, and I have a few exceptions for sites that refuse service to my choice of SSH endpoint provider (Amazon). Great.
The problem: A lot of DNS requests are still coming through when I watch on tcpdump. Certainly not all of them, but a lot of them. How can I correlate DNS requests to the application making the requests in OS X?

A: Try using Little Snitch to see which applications are trying to use your network connection.

A: Little Snitch won't help that much if the request is satisfied by OS X's high level mechanism (instead of using the resolver library directly). Hands Off might work better as it is intercepting these calls, too (or so it seems).


text:
Q: mysqlsh: How to import a dump file Usually I have a local installation of a MariaDB and when I import an sql-dump I use the following command:
C:\Program\MariaDB\bin\mysql testdb < C:\Downloads\dump.sql -u mariadbadmin -p -h localhost

where testdb ist the database I want to be loaded with the content of dump.sql. Now, I have a remote instance of MariaDB and the administrator installed on my local computer (Windows 10) the client mysqlsh.
I did not succeed to import the dump file. For example I tried:
mysqlsh -h vm-remote -u mariadbadmin -p --mysql testdb <C:\Downloads\dump.sql

which gives me:
Conflicting options: provided host differs frm host in the URI

Can someone show me how is the correct syntax to import a dump file using mysqlsh?

A: I found the following solution
mysqlsh -h vm-remote -u mariadbadmin -p --sql
MySQL  vm-remote:3306  SQL > use testdb;
MySQL  vm-remote:3306  test0  SQL > \.  C:\Downloads\dump.sql

There is an output on the shell for the inserts but it stops after few inserts. So, if ther are millions of inserts not every will be shown.

A: enter into MariaDB as root user
mysqldump --databases testdb > dump.sql


text:
Q: Iframe content not loading when an instance of it's route component exists so given this snippet:
<app-print-result
   *ngIf="!massPrint"
   #printResultComponent
   [widthPx]="printSheetWidthPx"
   [heightPx]="printSheetHeightPx"
></app-print-result>

and knowing that the src of the Iframe will be routed to the PrintResultComponent of the same application that is represented on the snippet as . the iframe will load correctly it's contents if  component shown in the snippet is commented.
Otherwise, the iframe will have its contents set to

not initializing the app or giving any error in the devtools console
Can anyone help with this?
Cheers

A: Solved, it was a problem with the src attribute of the iframe.


text:
Q: Twisted serialport dataReceived() provides fragmented data I am tyring to implement a python program, using Twisted, to communicate witha  bluetooth device. The following is a sample code of what I have implemented:
from twisted.internet import protocol, reactor
from twisted.internet.serialport import SerialPort
from twisted.protocols import basic

class DeviceBluetooth(basic.Int16StringReceiver):

    def connectionMade(self):
        print 'Connection made!'
        self.sendString('[01] help\n')

    def dataReceived(self, data):
        print"Response: {0}".format(data)

        print "-----"
        print "choose message to send: "
        print "1. Stim on"
        print "2. Stim off"
        print "3. Stim status"
        print "4. Help"
        # user input
        ch = input("Choose command :: ")
        if int(ch) == 1:
            self.sendString('[02] stim on\n')
        elif int(ch) == 2:
            self.sendString('[03] stim off\n')
        elif int(ch) == 3:
            self.sendString('[04] stim ?\n')
        elif int(ch) == 4:
            self.sendString('[05] help\n')
        else:
            reactor.stop()

SerialPort(DeviceBluetooth(), 'COM20', reactor, baudrate=115200)
reactor.run()

When I run the program, sometimes I get a response and other times I do not receive anything. And most of the times long responses are fragmented appear as part of the next message. I have through the hyperterminal to make sure that I get the appropriate response from by bluetooth device. So, the problem has to be with my code.
Is there something that I doing wrong in my code?

Additional modification/correction
When I replace dataReceived() function in the above code by stringReceived(), the program never enters this function.
I also tried to above program with the LineReceiver protocol, as the following:
from twisted.internet import protocol, reactor
from twisted.internet.serialport import SerialPort
from twisted.protocols import basic

class DeviceBluetooth(basic.LineReceiver):

    def connectionMade(self):
        print 'Connection made!'
        self.sendLine('[01] help')

    def dataReceived(self, data):
        print"Response: {0}".format(data)

        print "-----"
        print "choose message to send: "
        print "1. Stim on"
        print "2. Stim off"
        print "3. Stim status"
        print "4. Help"
        # user input
        ch = input("Choose command :: ")
        if int(ch) == 1:
            self.sendLine('[02] stim on')
        elif int(ch) == 2:
            self.sendLine('[03] stim off')
        elif int(ch) == 3:
            self.sendLine('[04] stim ?')
        elif int(ch) == 4:
            self.sendLine('[05] help')
        else:
            reactor.stop()

SerialPort(DeviceBluetooth(), 'COM20', reactor, baudrate=115200)
reactor.run()

I have the same problem, as before, with fragmented data from the dataReceived function.

A: Your protocol subclasses Int16StringReceiver which implements message framing using two byte (16 bit) length prefixes.  However, it overrides dataReceived which is the method that implements that framing.  This disables the framing and just delivers whatever bytes happen to be read from the connection - in whatever size they happen to be read.
When you subclass Int16StringReceiver, you're meant to override stringReceived instead.

A: For most of my bluetooth work, I've used 8-bit integers, so I would recommend using Int8StringReceiver. The LineReceiver protocol waits for an endline sequence which defaults to '\r\n' (and the bluetooth radios I use return '\r') so a mismatch on endline sequence would prevent the code from ever entering.
Have you tried to use a non-Twisted library for debugging? I highly recommend Twisted especially for production environments, but PySerial is a great way to poll serial data. (easy_install pyserial should do the trick.) Try this code:
import serial
s = serial.Serial('COM20', 115200, timeout=0)
data = s.read(1024)
print repr(data)

Make sure to use timeout=0 since that will make your read non-blocking.
This will allow you to examine exactly what kind of data is being outputted by the bluetooth radio.
Finally, depending on what kind of bluetooth radio you are using, Windows might decide to move COM20 around, especially if you are using a USB-connected radio.


text:
Q: python imageio image size without loading image to memory I am using imageio with Python. It seems to have a cleaner API than PIL and consorts, so I would like to continue using imageio instead of other tools.
I know how to get image size:
height, width, channels = imageio.imread(filepath).shape

Is there a way to get the size of an image, without needing to load it fully to memory? This should be possible, isnt't it? At least for a number of formats that (I guess) have the image size in the header?


text:
Q: Wordpress new post returns 500 I am creating a new page in Wordpress, but it returns 500:
http://d4zed.com/test-page/
What could be the reason why? The .htaccess looks pretty standard:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /d4zed-new/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /d4zed-new/index.php [L]
</IfModule>

I really have no idea about how Wordpress works internally (though I have quite an experience in Rails), so I am ready to answer your additional questions.
Thank you!

A: Internal Server Error in WordPress can be caused due to various reasons. You can try the following options in order to solve the problem.

*

*Checking wrong .htaccess file
Rename .htaccess file. If the site loads after this then you can infer that the problem is due to wrong .htaccess file. So you have to create a new .htaccess file.

*Increasing Memory Limit
Create a file named php.ini and paste the code memory_limit = 64M; in it and upload it to WordPress root folder as well as to wp-content, wp-admin folders in order to increase the Memory Limit.

*Deactivating plugins
The problem can be caused by an installed plugin. So, by deactivating all plugins and activating one by one you can find out which plugin is making the problem.

*Reuploading WordPress core folders
If the WordPress core files are creating the problem, it can be solved by reuploading wp-admin and wp-includes folders.

*Contacting Hosting Provider
Contact your hosting provider. If it is a server problem they can help you.


text:
Q: convert big number to string without scientific notation e.g.Number.MAX_VALUE.toString() is "1.7976931348623157e+308"
I hope there is no e+308,How to achieve this ?

A: You could do like this:
var n = Number.MAX_VALUE.toString();
var parts = n.split("e+");
var first = parts[0].replace('.', "");
var zeroes = parseInt(parts[1], 10) - (first.length - 1);
for(var i = 0; i < zeroes; i++){ first += "0"; }
// => first === "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"