Q: Clean up Array of words I have a function that strips html and places the words in an array and then uses array_count_values. Im trying to report the number of occurences of each word. The array outputed is very messy. I tried to clean it up, and I'm getting nowhere. I want to remove telephone numbers, and for some reason phrases are pushed together. Also the first array seems to be null, but isset() or empty() doesn't seem to unset it.
$body = $this->get_response($domain);
                $body = preg_replace('//i', '', $body);
                $body = preg_replace('##i', '', $body);

                $openTag = '';
                $start = strpos($body, $openTag);
                $start += strlen($openTag);

                $closeTag = '';
                $end = strpos($body, $closeTag);

                // Return if cannot cut-out the body
                if ($end <= $start || $start === false || $end === false) {
                    $this->setValue('');
                    return;
                }

                $body = substr($body, $start, $end - $start);
                $body = preg_replace(array(
                       '@@si',    // Strip out javascript
                       '@@siU',     // Strip style tags properly
                       '@<![\s\S]*?--[ \t\n\r]*>@',         // Strip multi-line comments including CDATA
                       '/style=([\"\']??)([^\">]*?)\\1/siU',// Strip inline style attribute
                       ), '', $body);

                $body = strip_tags($body);
                $body = array_filter(explode(' ', $body), create_function('$str', 'return strlen($str) > 2;'));
                $body = array_map('trim', $body);
                $words = $body;

                $i = 0;

                $words = array_count_values($words);

                foreach($words as $word){

                    if (empty($word)) unset($words[$i]);
                    $i++;

                }

                echo "
";
                    print_r($words);
                    echo "
";

outputs
Array
(
    [] => 28
    [333.444.5555] => 1
    [facebook] => 2
    [twitter] => 2
    [linkedin] => 2
    [youtube

                googleplus] => 1
    [About

    History
    Our] => 1
    [Mission
    Who] => 1
    [This
     That
     Other] => 1
    [Us

English

    FA
    Football] => 1
    [Media
    Pay] => 2
    [Per] => 4
    [Think
    Fast] => 2
    [Marketing
    Design] => 1
    [Consulting

Case] => 2

A: I'm afraid explode(' ', $body) is not enough because space is not the only white space character. Try preg_split instead.
$body = array_filter(preg_split('/\s+/', $body),
            create_function('$str', 'return strlen($str) > 2;'));


Q: Is there any form designer available for Google Android I am a new comer in Android development, I have downloaded and installed the Android SDK, but not find any GUI or Form designer, can any one know about some Form designer in for Android, Thanks in advance.

A: As d. correctly mentioned the built-in designer does not truly represent your view.
And if we keep in mind that even after 4 years of trying, Microsoft's equivalent for their XAML code still doesn't reach minimum usefulness level, I would strongly recommend to go manual. It's faster, much more difficult but equally rewarding. Once you get a hang of editing the XML files manually the development becomes much easier and WAY faster in my humble opinion.
Regards

A: This answer is very late to the game but each new release of the Eclipse Android plugin improves the layout GUI editor. The one released yesterday (9.0.0) is light years ahead of the original tools which were awful.

A: The form designer is part of the Android Development Tools (ADT) Plugin for Eclipse which comes with the Android SDK.

A: Google has not announced any plans for a wysiwyg designer for Android app development. However, there is a tool available for this. Check out this link http://www.designerandroid.com/?p=165


Q: Python Calling Current Directrory I am using fasitai library and when ı tried the loading model ı want to take model from current directory.
learn = load_learner('This arg. have to my current directory','model.pkl')

I tried os.get_cwd() and ' ./ ' but they aren't worked. Thanks

A: I found the solution
learn = load_learner('','model.pkl')

the first arg. had to be space '' .


Q: RoR NameError - Ruby on Rails MySQL NameError in GenresController#index
uninitialized constant GenresController
RAILS_ROOT: C:/Users/Will/Desktop/INSTAN~1/rails_apps/talewiki
I've created a table called Genres and when I try to connect to it via local host I get the above error.
Any ideas?

A: With all the questions you're asking I believe you're an absolute beginner regarding ROR. Perhaps you should visit some tutorials to learn rails.
I don't know what your genre model describes, but I think it will have a name.
Basic steps for a basic genre model:

*

*Delete the table for your genres if created manually (with SQL code)
DROP TABLE genres;

*generate a complete scaffolding for genres:
$ ruby script/generate genre name:string
$ rake db:migrate

*Now you have a complete controller for all CRUD actions for a simple genre model
If I were you I would read some tutorial about RoR, because you make the impression that you don't understand RoR or the MVC principle behind it. A good start would be: http://storecrowd.com/blog/top-50-ruby-on-rails-tutorials/

A: You need to generate a controller to handle the index action when your browse your application on localhost
ruby script/generate controller genres index

run that from your console within your application and it will generate the GenresController with the action index (it will be an empty action but you shouldn't see an error when browsing http://localhost:3000/genres/)

A: file
C:/Users/Will/Desktop/INSTAN~1/rails_apps/talewiki/app/controllers/genres_controller.rb

must be present


Q: How to intercept exe files launch from windows explorer? i want to be notified when when user trys to open a file from the explorer.
How could this be done?
I tired hooking some winapi in the explorer.exe with no hope.
I also want to intercept this call and cancel it.

A: You might want to have a look at a similar question: Intercept windows open file
Also for the people asking why someone would want to do this or immediately jump to malware conclusions. There are a number of legitimate uses for this. Especially if you are creating a B2B product that deals with automation or control over a customer's PC environment.


Q: React Typescript ESLint "extends" parsing error I have a react typescript code that looks like the following in Button.tsx:
   import * as React from 'react';

   type ButtonOwnProps<E extends React.ElementType = React.ElementType> = {
     children?: React.ReactNode;
     variant?: 'contained' | 'outlined';
     as?: E;
   };

I am getting the following eslint error:
Parsing error: Unexpected token, expected ","

  1 | import * as React from 'react';
  2 |
> 3 | type ButtonOwnProps<E extends React.ElementType = React.ElementType> = {
    |                       ^
  4 |   children?: React.ReactNode; eslint

Can anyone help me understand where I did wrong?


Q: How to filter a RecyclerView using Kotlin? I just started to use kotlin and room database, in my fragment i have a RecyclerView and an EditText which i would use as search for the RecyclerView. The RecyclerView's adapter is inside my ViewModel observable and i've actually set a TextWatcher to my EditText but as the data of the RecyclerView comes from my room DataBase how should i set that filtering?
When the EditText is empty i should return items from the LiveData observable..
Here is my Fragment code:
private lateinit var recyclerView: RecyclerView
private lateinit var txtSearch: EditText
private val articoliViewModel: ArticoliViewModel
    get() = (activity as MainActivity).articoliViewModel

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = view.findViewById(R.id.recyclerView)
    txtSearch = view.findViewById(R.id.txtSearch)

    val adapter = ArticoliListAdapter()
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(activity)

    articoliViewModel.articoli.observe(viewLifecycleOwner) { articoli ->
        // Update the cached copy of the words in the adapter.
        articoli.let { adapter.submitList(it) }
    }

    txtSearch.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })

}


Q: Show with a counterexample that $A\nsubseteq A^A$ Definition
A set $R$ is a (binary) relation if any its element is a ordered pair, that is $z\in R$ if and only if there exist $x$ and $y$ such that $z=(x,y)$. In particular if $R$ is contained in the cartesian product of two set $A$ and $B$ we say that $R$ is a relation of between $A$ and $B$ and if $B$ is equal to $A$ we say that $R$ is a relation in $A$.
Definition
If $R$ is a relation we call domain of $R$ that set whose elements are a first coordinate of some pair of the relation, that is
$$
\text{dom}\,R:=\{x:\exists\,y\,\text{such that}\,(x,y)\in R\}
$$
and analogously the range of $R$ is that set whose elements are the second coordinate of the relation, that is
$$
\text{rank}\,R:=\{y:\exists\,x\,\text{such that}\,(x,y)\in R\}
$$
So it is possible to prove that the above two defined set exist using the $ZFC$'s formalism but this now has not matter so we proceed to give the following well know definition.
Definition
A function $f$ is a relation such that if $(x,y)$ and $(x,z)$ are such that $(x,y),(x,z)\in f$ then $y=z$.
Definition
Let $A$ and $B$ sets. So the set whose element are functions from $A$ to $B$ is denoted by the symbol $B^A$.
Again it is possible to prove that the above defined set exist using $ZFC$'s formalism but now this again has not matter.
So by the previous things I thought that any element $a$ of a (not empty) set $A$ could be regarded as a costant function so that I ask to me if $A$ is a subset of $A^A$ but this seems to me very stranger and so I would like to know the opinon of anyone with more competences of mine. In particular I have observed that if $a\in A^A\cap A$ then $a\subseteq A\times A$ and so either $a=\emptyset$ either there exist $c,d\in A$ such that $a=(c,d)\in\{\{c\},\{c,d\}\}$ but by this I did not deduce any contradiction. So could someone help me, please?

A: Formally, it is false that $A \subseteq A^A$ for a generic set $A$. Take for instance $A = \{*\}$. Then, $A^A = \{\{(*,*)\}\}$ (i.e. the only function in $A^A$ is the identity on $A$), so $* \in A$ but $* \notin A^A$, thus $A \not\subseteq A^A$. Actually, $A$ and $A^A$ are disjoint in this case.
However, there is a canonical injection of $A$ into $A^A$, the one correctly defined by Wuestenfux in his answer:

Each element $a \in A$ can be identified with the constant function
\begin{align}
f_a \colon& \, A \to A
\\
&\,\,x \mapsto a
\end{align}

In this way, each element $a \in A$ can be thought as an element of $A^A$. Therefore, "morally" (but not formally) $A \subseteq A^A$.

Note that there is an error in your argument. If you assume $a \in A^A \cap A$, then $a \subseteq A \times A$, but possibly there is no $a \in A^A \cap A$ and you are assuming something impossible. Indeed, from $a \in A^A \cap A$ it follows that $a \in A^A$ (and hence $a \subseteq A \times A$) and $a \in A$, but we have just seen that this can be impossible, for instance when $A = \{*\}$ and so $A^A \cap A = \emptyset$.

A: Each element $a\in A$ can be identified with the constant function $f_a:A\rightarrow A:x\mapsto a$. In this way, $a$ can be thought as an element of $ A^A$.


Q: Transmission lines I have a little confusion about power transmission lines. In my home town, there are 4 conductors parallel to each other coming down from the main road on steel poles. Then, on every street, two conductors are distributing power to each home. Now, the four condctors which are coming down from the road — are these are called bundled condutors (no spacers are present between them)? Are they a 3 phase 4 wire system? And also explain the conductors that are distributing power on the streets.

A: They are almost certainly not bundled conductors (see Electrotechnik).  Those are only used on high voltage transmission lines.
They are very likely to be a 3-phase 4-wire system, with three phase (live, hot) conductors and one shared neutral.  Premises that only need a single-phase supply will get a tap off one phase and the neutral.


Q: Injecting javascript into page via url I'm trying to run a javascript code via url to change values of the form in the page.
Here is the content of the HTML page.

<form method='post'>
Name: <input type='text' id='name' value='' />

Family: <input type='text' id='family' value='' />

Email: <input type='text' id='email' value='' />

<input type='submit' value='Submit' />

</form>

Now, I enter the following value in the URL section of chrome:
javascript:document.getElementById('name').value = 'string1';

What happens is my whole page will go blank and only the value "string1" will be displayed in the page.
However, running the following code works properly:
javascript:document.getElementById('name').value = 1;

It will change the value of the name field to 1.
I'm wondering what is causing this problem.
Note: The purpose of this work is to inject code into webview in android.
Any advice is appreciated.

A: Try this.
javascript:document.getElementById('name').value = 'string1'; undefined;

Tack on a 'undefined;' to any script that returns a string.

A: That is because you are using single quotes after the attribute value
value=''

and you changing it's value in javascript using
document.getElementById('name').value='string1';

so the html becomes
<input type='text' id='name' value=''string1''

you can fix it using
value=""

or using
document.getElementById('name').value="string1";

A: well i tried the following code

<form method='post'>
Name: <input type='text' id='name' value='' />

Family: <input type='text' id='family' value='' />

Email: <input type='text' id='email' value='' />

<input type='submit' value='Submit' />

</form>
<button onclick="change()">Click me</button>

and it works just fine the problem is in your script
do you created a function to change the value or just putted the code in a script tag like this


Q: What is the advantage of dynamic memory control? For example, I want to make a stack. I can do it in that way, using the dynymic memory control, with new and delete opereations:
#include <iostream>

using namespace std;

struct List
{
    int x;
    List *Next,*Head;
};

void Add(int x, List *&MyList)
{
    List *temp=new List;
    temp->x=x;
    temp->Next=MyList->Head;
    MyList->Head=temp;
}

void Show(List *MyList)
{
    List *temp=MyList->Head;

    while (temp!=NULL)
    {
    cout<<temp->x<<" ";
    temp=temp->Next;
    }
}

void ClearList(List *MyList)
    {
    while (MyList->Head!=NULL)
    {
    List *temp=MyList->Head->Next;
    delete MyList->Head;
    MyList->Head=temp;
}
}

int main()
{

    List *MyList=new List;

    MyList->Head=NULL;

    for (int i=0;i<10;i++) Add(i,MyList);
    Show(MyList);

    ClearList(MyList);
    delete MyList->Head;
    delete MyList;
}

And also I can just make a stack in that way and do anything with it:
std::stack<int> MyStack;

So, which one is better? What is the advantage of a stack with dynamic memory allocation? In what cases should I use first/second variants?

A: The both stacks use dynamically allocated memory for their nodes (though for std::stack it depends on underlying container).
Of course it is better to use standard class. It was already tested and written by qualified programmers and it is flexible enough: you can use several standard containers to implement the stack because standard stack is a container adapter.
In fact you can write your own underlying container for std::stack as for example a wrapper around an array and in this case the whole stack will be placed in the stack memory though its size of course will be fixed.:)
Nevertheless the standard stack also has many drawbacks. For example you can  not use std::forward_list as the underlying container. I made a proposal to specialize standard class std::stack for std::forward_list.

A: which one is better depends surely on the use case. But generally I would advise you to use the STL implementation of the stack, because it is heavily used and therefore tested perfectly.
Furthermore, you'll get a perfect abstraction of a stack with the STL implementation.
Second, the STL implementation is also using dynamic memory allocation, so from this point of view there is no difference to your implementation.

A: Using dynamic memory gives the advantage of adding possible memory leaks and/or segmentation faults to your program.
I only use dynamic memory when forced to. Forcing example: working with a library that uses c-strings for parameters and return values.


Q: Cannot open new project or old project in Visual Studio 2012
Recently I have installed VS 2012 and SQL Server Management Studio. When I try to open the New Project, I'm getting this error:

Web application projects are currently configured to use IIS Express. To switch back to using the Visual Studio Development server, change the development server option under the Projects and Solutions/Web Projects category of the Tools/Options menu. Configuring IIS Express failed with the following error:
  Filename: redirection.config
  Error: Cannot read configuration file

I was Search about that issue. But  the given solution doesn't fix my problem.
I have tried

*

*Control Panel -> Programs and Features -> Turn Windows Features on or off... inside that, we had to select Internet Information Services -> Web Management Tools -> IIS 6 Management Compatibility -> IIS Metabse and IIS 6 configuration compatibility."

*true replace it with the string True.

Could someone please help?


Q: How to use for loop to calculate moving average with a window size of 10 using 5th column I have a data.csv file containing 5 columns. now I want to use for loop to calculate moving average with a window size of 10 using 5th column in R.
for(i in 1: length[ , 5]-9) {
 data$Mean [i] <- mean (data[i,5]:data[(i+9),5])
}

This means to calculate the mean of 10 consecutive rows and store them in the same data frame by creating a new column
It is calculating wrong and I am getting the error as follows.....

Error in data[i, 5]:data[(i + 9), 5] : NA/NaN argument

A: You have made a couple of mistakes in the line that calculates the mean. The most significant one is that when you try to calculate the mean for the last 9 rows of your dataframe, you go out of bounds. ie, if your dataframe has 100 rows, by row 92 your are trying to get the mean of rows 92:101; of course, there is no row 101.
It should be something like this:
for(i in 1: length(data[ , 5]-9)) {
    data$Mean [i] <- mean(data[i:min(i+9, nrow(data)),5])
}

Also, it's generally a bad idea to use data as a variable name, since there already is a data() function in base R. Simply choose a similar name, like "mydata"
A reproducible example follows, that will get the mean of the next ten rows, OR the mean of the n next rows for the last 9 rows.
mydata <- data.frame(col_1 = rnorm(100),
                     col_2 = rnorm(100),
                     col_3 = rnorm(100),
                     col_4 = rnorm(100),
                     col_5 = rnorm(100))

for(i in 1: length(mydata[ , 5]-9)) {
    mydata$Mean [i] <- mean(mydata[i:min(i+9, nrow(mydata)),5])
}

head(mydata)

If you dont' want to get the mean for the last ten rows, do this instead:
for(i in 1: length(mydata[ , 5]-9)) {
    mydata$Mean [i] <- ifelse( i + 9 <= nrow(mydata),
                               mean(mydata[i:min(i+9, nrow(mydata)),5]),
                               NA)
}


Q: Bluetooth Low Energy Android - Search in Background I would like to know whether it is possible to check in the background if someone enters or leaves the a beacon Region?
In iOS for example you can use the methods didEnterRegion or didExitRegion to send notifications from the background.
Is there any native possibility or has someone a workaround?

A: Android doesn't have any "native" iBeacon capability at all, but you can see iBeacons using my company's open source Android iBeacon Library, which has APIs similar to those native to iOS 7.
In the case of iOS, the CLLocationManagerDelegate gives you access to the didEnterRegion and didExitRegion callbacks that you describe.  In the Android iBeacon Library, the equivalent is the MonitorNotifier interface that gives you the same callback methods.
Making these callbacks successfully fire for apps that aren't in the foreground is a little tricky on both iOS and Android.  On Android, you need to start a service of your own that runs when the Android device starts up, and bind to the IBeaconManager in that service.
Setting this up isn't super easy, so we developed a Pro Android iBeacon Library that does all this automatically.  Examples are here.
EDIT: Both libraries above have been discontinued in favor of the free and open source  Android Beacon Library which has all the feature of the pro library described above.


Q: Data Clensing in SQL Server I've got a table in the following format:
Name    Address1    Address2    Address3
Joe     NULL        1 A Road    London
Bob     2 A Lane    NULL        London

I'd like to run an update to move all the values left where there are nulls so that I end up with:
Name    Address1    Address2    Address3
Joe     1 A Road    London      NULL
Bob     2 A Lane    London      NULL

Please help!
Thanks,
Josh

A: BEGIN TRANSACTION
update person set Address1 = Address2, Address2 = null
  where Address1 is null and Address2 is not null;
update person set Address2 = Address3, Address3 = null
  where Address2 is null and Address3 is not null;
update person set Address1 = Address2, Address2 = null
  where Address1 is null and Address2 is not null;
select top 100 * from person
ROLLBACK TRANSACTION

This would get very ugly if you had lots of address fields, but for 3 is acceptable. Remember to test any script copy and pasted from the interwebs in a transaction that you rollback so you don't get your database wiped :)
EDIT:
With further info (6 address fields):
You could do like above only repeat 5 times to move so in worst case you where still done
Declare StoredProcedure OneRound
BEGIN
  update person set Address1 = Address2, Address2 = null
    where Address1 is null and Address2 is not null;
  update person set Address2 = Address3, Address3 = null
    where Address2 is null and Address3 is not null;
  update person set Address3 = Address4, Address4 = null
    where Address3 is null and Address4 is not null;
  update person set Address4 = Address5, Address5 = null
    where Address4 is null and Address5 is not null;
  update person set Address5 = Address6, Address6 = null
    where Address5 is null and Address6 is not null;
END

Declare StoredProc FixAllAddresses
BEGIN
  call OneRound
  call OneRound
  call OneRound
  call OneRound
  call OneRound
END

You could also use a cusor (warning psydo code) I have not looked up the syntax for T-SQL cursors and it has been a while so I will get the details wrong, check the syntax in the online help.
Declare cursor @personCursor for select ID,Address1,Address2,... from person;
OPEN @personCursor
FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...)
while(@@FETCH_STATUS)
BEGIN
  IF @addr1 is null
  BEGIN
    IF @addr2 is not null
    BEGIN
      @addr1 = @addr2
      @addr2 = null
    END
    ELSE IF @addr3 is not null
      @addr1 = @addr3
      @addr3 = null
    BEGIN
    -- Boaring, ugly code goes here for addr4,addr5,addr6
    END
  END

  IF @addr2 is null
    IF @addr3 is not null
    BEGIN
      @addr2 = @addr3
      @addr3 = null
    END
    ELSE IF @addr4 is not null
      @addr2 = @addr4
      @addr4 = null
    BEGIN
    -- Boaring, ugly code goes here for addr5, addr6
    END
  BEGIN

  -- repeat for addr3, addr4,

  if @addr5 is null
  BEGIN
    IF addr6 is not null
    BEGIN
      @addr5 = @addr6
      @addr6 = null
    END
  END

  END
  update person set address1 = @addr1, address2 = @addr2, ...
    where PersonId = @personId
  FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...)
END

The Stored proc begin called 5 times makes for less code and may be less error prone, the cursor only iterates through your people once, but does not filter. I suspect the stored proc solution below will be faster but it will depend on your data.

A: David's solution is the most efficient. One that might be more easily extend-able for greater numbers of columns is.
;WITH cte
     AS (SELECT *,
                 MAX(CASE WHEN RN=1 THEN value END) OVER (PARTITION BY ContactId) AS new_Address1,
                 MAX(CASE WHEN RN=2 THEN value END) OVER (PARTITION BY ContactId) AS new_Address2,
                 MAX(CASE WHEN RN=3 THEN value END) OVER (PARTITION BY ContactId) AS new_Address3
         FROM   #Addresses
                OUTER APPLY (SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN value IS NULL THEN 1 ELSE 0 END, idx) AS
                                   RN, idx, value
                             FROM   (VALUES(1,Address1),
                                           (2,Address2),
                                           (3,Address3)) t (idx, value)) d)
UPDATE cte
SET    Address1 = new_Address1,
       Address2 = new_Address2,
       Address3 = new_Address3


Q: How to filter out different classes into an array How will I take product with same category into a string or an array?

What I want exactly is to filter them and append them into a new div to create a filterable animation using GSAP. This is actually a WordPress WooCommerce product page.
Last time I created a popup using GSAP, and in that I used something called split() function:
triggers.each(function(){
    let listClassName = $(this).attr('class').split(' ');
    let revealClassName = String(listClassName[listClassName.indexOf(listClassName.find(element => element === 'dasrgsap__reveal-trigger')) + 1]);
    const sectionReveal = $('.dasrgsap__reveal-content.' + revealClassName);
    const colReveal = $('.dasrgsap__reveal-content.' + revealClassName + ' .et_pb_column');
});

The trigger was (dasrgsap__reveal-trigger sandra) and the popup content container was (dasrgsap__reveal-container sandra). Both were given two separate classes, which made it easier to split and access them.
In this case, WooCommerce product list items are given too many classes, so the only class I can play with to get a specific category is the product_cat-'product-category'.
I want to get a string or array of the same product category, and I want to split product_cat- and category-1 and get an array of that category, but I'm not able to do it.
Is this even possible?

A: This is only a guess but is this what you were after

$("li").each(function() {
  var category = $.makeArray(
    $(this)
    .attr("class")
    .slice(
      $(this).attr("class").indexOf("-") + 1,
      $(this).attr("class").length
    )
  );
  // console.log(category);

  var product = $.makeArray($(this)
    .attr("class")
    .slice(0, $(this).attr("class").indexOf("-")))
  // console.log(category);

  var completeList = $.merge(product, category);
  console.log(completeList)

});

https://jsfiddle.net/7xcpjr59/
I hope it helps


Q: NLog structuring logging masking Suppose we are writing the following structured log message
logger.Info("User's Password is {Password}", "1234567890");

I would like to mask a password property because it is a sensitive data. I found this issue but I think it is a very difficult way.
For example, I have found the extension that resolves a similar task for serilog. It is very simple to use. But I didn't find any useful information for Nlog.
How to achieve it with nlog library?
I will appreciate any suggestions.

A: You could use RegisterObjectTransformation, introduced in NLog 4.7.
For example:
LogManager.Setup().SetupSerialization(s =>
    s.RegisterObjectTransformation<object>(o =>
    {
        var props = o.GetType().GetProperties();
        var propsDict = props.ToDictionary(p => p.Name, p => p.GetValue(o));

        propsDict.Remove("password");

        return propsDict;
   }));

Please note, in terms of performance you maybe need something like a reflection cache and smart optimizations.

A: I suggest that you wrap the secret password in an object like this:
public class SecretWrapper : IFormatable
{
    private readonly string _secret;

    public SecretWrapper(string secret)
    {
        _secret  = secret;
    }

    public string GetSecret() => _secret; // Not a property to avoid basic reflection

    public override string ToString() => "******"

    public string ToString (string format, IFormatProvider formatProvider) => ToString();
}

NLog will never output the secret-value:
logger.Info("User's Password is {Password}", new SecretWrapper("1234567890"));


Q: Proof that $n!$ is divisible by $(n+1)^2$ for $n=xy+x+y$ I noticed the other day that for $n>8, n\in\mathbb{N}$, the factorial $n!$ seems to be divisible by $(n+1)^2$ when $n$ can be written in the form $xy+x+y$ (where $x,y\geq1$ and $\in\mathbb{N}$). Some examples:

*

*$n=14=2 \times 4+2+4$ (i.e. $x=2$, $y=4$), and we have $14!|15^2$

*$n=15=3 \times 3+3+3$ (i.e. $x=y=3$), and we have $15!|16^2$,

*$n=19=3 \times 4+3+4$ (i.e. $x=3$, $y=4$), and we have $19!|20^2$,

*...

This seems to hold for the first $15$ values I checked, so it seemed natural to try to prove it for all $n=xy+x+y$, however I could not find a proof. Here is my attempt:
Plugging $xy+x+y$ into the expressions above and noticing that $xy+x+y+1=(x+1)(y+1)$, we need to prove that
$$
(xy+x+y)!|(x+1)^2(y+1)^2,
$$
or
$$
\Gamma((x+1)(y+1))|(x+1)^2(y+1)^2.
$$
It is easy to prove that
$$
\Gamma((x+1)(y+1))|(x+1)(y+1)
$$
however I am struggling to prove the same for $(x+1)^2(y+1)^2$. Any hints?

A: Wlog. $x\le y$.
If we are lucky, we find $x+1,2(x+1),y+1,2(y+1)$ as different elements among the factors $1,2,3,\ldots, n$ and we are done.
How can we fail to be lucky? The four candidates may be too large or not be different after all. As we assume $x\le y$, the following list is exhaustive:

*

*It may happen that $2(y+1)>n=xy+x+y$. This implies $x=1$. And indeed, $x=1$, $y=2$ gives $n=5$ and $36$ does not divide $5!$. More generally if $y+1$ is prime, then $(2y+1)!$ is not divisible by $(y+1)^2$.

*It may happen that $x+1=y+1$, which of course means that $x=y$. If $x\le 3$, we have $n\le 8$, which is excluded. If $x\ge 4$,  we can use the factors $x+1,2(x+1),3(x+1),4(x+1)$ instead. These are guaranteed to be different and we have $4(x+1)\le xy+y<n$.

*It may happen that $2(x+1)=y+1$. Then we can use $x+1,2(x+1)=y+1, 3(x+1), 2(y+1)$ instead.

Thus

If $n=xy+x+y>8$ with positive integers $x,y$ then $(n+1)^2\mid n!$ except when $n+1$ is twice a prime.

A: $\color{Green}{\text{Question}}$ :
Find all integers $n$;
such that $\color{Green}{(n+1)! \mid n!} $ .

$\color{Blue}{\star \ \ \ \ \text{condition}}$ :
Now suppose that $n+1$ can be written
in the form $n+1=ab$;
with $2 < a,b$.
Also assume that one of the following occures:

*

*If $a= b$; then $5 \leq a=b$.

*If $a=2b$; then $5 \leq b  $.

*If $2a=b$; then $5 \leq a  $.

With the condition as in
$\color{Blue}{\star}$ ;
we claim that
the assertion is $\color{Blue}{\text{true}}.$

Let $n, a, b$ to be fixed as above in $\color{Blue}{\star}$ .
Notice that if we let $x:=a-1$ and $y:=b-1$
then one can easilly see that:
$$n=xy+x+y.$$

$\color{Blue}{\text{Remark(I)}}$ :
With the notation as in $\color{Blue}{\star}$;

*

*If $a=b$ , with $5 \leq a$
then we have:
$$b < 2b < 3b < 4b < ab=n+1 \Longrightarrow b < 2b < 3b <4b \leq n=ab-1 \ ; $$
so we can conclede that:
$$(b)(2b)(3b)(4b)=24(ab)^2=24(n+1)^2 \mid n! ;$$
which implies that: $(n+1)^2 \mid n! \ \ $ .

*

*If $a=2b$ ;  with $5 \leq b$
then we have:
$$b < 2b < 3b < 4b < ab=n+1 \Longrightarrow b < 2b < 3b <4b \leq n=ab-1 \ ; $$
so we can conclede that:
$$(b)(2b)(3b)(4b)=6(ab)^2=6(n+1)^2 \mid n! ;$$
which implies that: $(n+1)^2 \mid n! \ \ $ .

*

*If $2a=b$ ;  with $5 \leq a$
then we have:
$$a < 2a < 3a < 4a < ba=n+1 \Longrightarrow a < 2a < 3a <4a \leq n=ba-1 \ ; $$
so we can conclede that:
$$(a)(2a)(3a)(4a)=6(ab)^2=6(n+1)^2 \mid n! ;$$
which implies that: $(n+1)^2 \mid n! \ \ $ .

*

*If $a \neq b$ and $a \neq 2b$ and $2a \neq b$ ;
then we have:
$$b < 2b < ab=n+1 \Longrightarrow b < 2b \leq n=ab-1 \ ; $$
$$a < 2a < ab=n+1 \Longrightarrow a < 2a \leq n=ab-1 \ ; $$
so we can conclede that:
$$(b)(2b)(a)(2a)=4(ab)^2=4(n+1)^2 \mid n! ;$$
which implies that: $(n+1)^2 \mid n! \ \ $ .

Remark(II): Integer $N$
can not be written
in the form $N=ab$;
with $2 < a,b$;
if and only if
$N$ is prime or twice a prime.

Remark(III):
We can split the integres in three cases:

*

*$\color{Red}{   n+1 =   \text{prime numbers and twice of prime numbers;
for which the assertion is wrong!}   }.$

*$\color{Purple}{ n+1= a.a
 \ \ \
\text{for}
\ \ \
a \in \{ 1, 2, 3, 4 \} }.$
This case has only four numbers;
which can you check out that
the assertion is $\color{Blue}{\text{true}}$ only for
$\color{Blue}{n+1=16}$ and
$\color{Blue}{n+1= 1}$ .

*$\color{Purple}{ n+1= a.(2a)
 \ \ \
\text{for}
\ \ \
a \in \{ 1, 2, 3, 4 \} }.$
This case has only four numbers;
which can you check out that
the assertion is $\color{Blue}{\text{true}}$ only for
$\color{Blue}{n+1=18}$ and
$\color{Blue}{n+1=32}$ .

$\color{Green}{\text{Remark(IV)}}$ :
Except for the following cases;
for which the assertion is
$\color{Red}{\text{wrong}}$
1.$\color{Red}{   n+1 =   \text{prime numbers and twice of prime numbers
}   }.$
2.$\color{Red}{ n+1= 4, 9, 2, 8 } .$
for all the other cases
the assertion is
$\color{Blue}{\text{true}}$ .

$\color{Red}{\text{Remark(V)}}$ :
Let $p$ to be an odd prime number;
then we have:
$p^2 \color{Red}{\nmid} (2p-1)! \ \ . $

For example let $p$ to be an odd prime number;
and let's define:
$$n:=2p-1
\ \ \
\text{and}
\ \ \
x:=1
\ \ \
\text{and}
\ \ \
y:=p-1.$$
Notice that we have: $n=xy+x+y$

We calaim that $(2p)^2 \color{Red}{\nmid} (2p-1)!$.
[
Suppose on contrary
that $(2p)^2 \mid (2p-1)!$ ,
on the otherhand notice that
$p^2 \mid (2p)^2$.
So we must have
$p^2 \mid (2p-1)!$
;
which has an obvious contradiction
with the above $\color{Red}{\text{Remark(V)}}$.
]


Q: Wix installer creating registry entry based on user input So, basically what I have is Wix installer, which is modified and I am currently stuck at a problem with registry entry. During install the Installer has a custom dialogue, where user has to choose/insert second path. Which will be stored in the Registry. But instead of inserting what user entered, it inserts "[INSTALLFOLDER]", although it should look something like "C:\Program Files...". I did some research but, didn't find anything that could help me.
All of the code are in the same file.
Main parts of the code are here, first there's this property. Which later should be written into registry.
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER" Secure="yes" />

Later on there's the custom window.
<!-- NetWork path -->
  <Dialog Id="CustomNETDirDlg" Width="370" Height="270" Title="Custom Folder">
    <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)" />
    <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)" />
    <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)">
      <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish>
    </Control>
    <Control Id="Description" Type="Text" X="25" Y="23" Width="280" Height="15" Transparent="yes" NoPrefix="yes" Text="Choose Network Path" />
    <Control Id="Title" Type="Text" X="15" Y="6" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="NetWork Path" />
    <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.InstallDirDlgBannerBitmap)" />
    <Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
    <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
    <Control Id="FolderLabel" Type="Text" X="20" Y="60" Width="290" Height="30" NoPrefix="yes" Text="Choose / Enter Path" />
    <Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes"/>
    <Control Id="CustomChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" />
  </Dialog>
  <!-- / NetWork path -->

Little bit below that is this publish part...
  <Publish Dialog="CustomNETDirDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg">1</Publish>
  <Publish Dialog="CustomNETDirDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" Order="4">1</Publish>
  <Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Property="_BrowseProperty" Value="[CUSTOMPATH]" Order="1">1</Publish>
  <Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish>

And this works for me.
I replaced guid for "reasons". Registry path and everything else seems to be fine, just one thing which is not working,adding  [CUSTOMPATH] property as registry value.I also tried without [] brackets, and so on... Even tried it with  [Manufacturer], worked perfectly fine, inserted Manufacturer into registry. But this here is not working.
<DirectoryRef Id="TARGETDIR">
    <Component Id="RegistryEntries" Guid="{my guid}">
      <RegistryValue Root='HKMU' Key='Software\[Manufacturer]\[ProductName]' Type='string' Value='[CUSTOMPATH]' KeyPath='yes' />
    </Component>
</DirectoryRef>

A: Correct
This is correct because you specify that the content of CUSTOMPATH is actually a reference a different Property (or Directory because a certain point Directory elements become available to be used like Property elements):
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER" Secure="yes" />
<Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes"/>

The above will visualize the content of INSTALLFOLDER so that's ok.
However, the actual value of CUSTOMPATH will never change. It should always remain a reference to another property because you use it with Indirect=Yes.
Possible root cause of your problem
In the next part you assign a value to CUSTOMPATH and that's where I think something goes wrong. I tried the following and it gave me the requested result ("C:\Program Files..." in the registry value).
<Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Property="_BrowseProperty" Value="[INSTALLFOLDER]" Order="1">1</Publish>
<RegistryValue Root='HKLM' Key='Software\Test\TestRegEntry1' Type='string' Value='[INSTALLFOLDER]' KeyPath='yes'/>

If this doesn't work, could you provide me with the logfile?
zzz.msi /lvoicewarmupx debug.log

A: So basically what I did to fix this issue was that I created right beside INSTALLFOLDER another directory. Since I didn't add any files into it, that folder will not be created, but value as such remains.
<Directory Id="INSTALLFOLDER2" Name="!(bind.property.ProductName)"></Directory>
<Directory Id="INSTALLFOLDER" Name="!(bind.property.ProductName)">
    <!-- Here are files I wanted to include -->
</Directory>

Registry entry now looks like this:
<DirectoryRef Id="TARGETDIR">
    <Component Id="RegistryEntries" Guid="here comes your guid">
        <RegistryValue Root='HKMU' Key='Software\[Manufacturer]\[ProductName]' Type='string' Value="[INSTALLFOLDER2]" KeyPath='yes' />
    </Component>
</DirectoryRef>

And Property like this:
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER2" Secure="yes" />

Folder selector controls look like this, so both typing and button (folder selector) work. Dialog that uses them is exactly like InstallDirDlg, but with a different name.
<Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes" />
<Control Id="CustomChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" />


Q: Javascript - .length gives me 0 length Array is initialized
var Collect = [];

So I have a promise arguments so that I'll have a asynchronous in execution since retrieving data from firebase which then push in the array Collect takes a bit of time. Here's my code:
function loadTables(){
    var promise = getDataFirebase();
    promise.then(function(){
        console.log("firsst");
        return ProcessOfData();
    }).then(function(){
        console.log(Collect);            //when printed, it shows the elements collected from firebase so the array is not 0.
         console.log(Collect.length);   // but when printeed here. it gives me 0. why?
        return EndProcessLog();
    }).then(function(){

    });
}

Codes when retrieving data from firebase:
function getDataFirebase(){
    return new Promise (function(resolve,reject){
        refReview.on("value", function(snap){
            var data = snap.val();
            for(var key in data){              //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT
                Collect.push({
                    "RevieweeName": data[key].revieweeID.firstname.concat(" ",data[key].revieweeID.lastname),
                    "ReviewerName": data[key].reviewerID.firstname.concat(" ",data[key].reviewerID.lastname),
                    rating:data[key].rating,
                    content: data[key].content
                })
            }//end of for loop

        }); //end of snap
        resolve();
    });
}

A: Why does it not work? Because you are resolving the promise before the asynchronous method runs. The reason why the object shows the value is the console lazy loading the object.
What do you do? Move the resolve line after the for loop inside the callback.
refReview.on("value", function(snap) {
  var data = snap.val();
  for (var key in data) { //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT
    Collect.push({
      "RevieweeName": data[key].revieweeID.firstname.concat(" ", data[key].revieweeID.lastname),
      "ReviewerName": data[key].reviewerID.firstname.concat(" ", data[key].reviewerID.lastname),
      rating: data[key].rating,
      content: data[key].content
    })
  } //end of for loop
  resolve(); < --RIGHT

}); //end of snap
// resolve(); <-- WRONG

Ideally with a promise you do not use global variables, you pass the value through the resolve.

var myPromise = new Promise(function(resolve, reject) {
  var str = "Hello!";
  resolve(str);
});

myPromise.then(function(value) {
  console.log(value);
});


Q: How to select specific substring length based on a filter I have multiple CSV files with different names, containing today's date, customer number, and then the extension. For example:
2019-01-23 XYZF-105.csv
2019-01-23 ABCD-205.csv
2019-01-23 Different nonstandard name.csv
2019-01-23 ##ABCD-305(Trial).csv

I would like to get the part of the name where it contains the customer number only, like ABCD-305.
Tried using a substring to select 8 characters right from the dot, but that doesn't work for those that have suffix like (Trial).
Neither it work 11 characters from the beginning, as it will include the ##.
Also, it has to avoid the nonstandard names.
I used
$allitems = Get-ChildItem -Path 'C:\Downloads\Customers\*.csv'
$res = @()
foreach ($item in $allitems){
    $item = $item.Name.substring($item.Name.Length - 12,8)
    $res += $Item
}

This way, for the proper names I get good results, but only if the name of the CSV is like 2019-01-23 ABCD-205.csv.
What should be the way to skip the date, skip the .csv extension and get only results with 8 characters, that have a dash after the 4th character?
Thanks in advance

A: Try the following (PSv3+ syntax):
$res = (Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name |
         Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' |
           ForEach-Object { $_.Matches[0].Value }

*

*(Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name outputs the file names of all CSV files in dir. C:\Downloads\Customers

*Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' uses case-sensitive regex (regular-expression) matching to only select file names that contain 4 ({4}) uppercase chars. [A-Z], followed by -, followed by 3 digits (\d), on word boundaries (\b)

*The ForEach-Object script block then outputs the part of each matching file name that matched the regex ($_.Matches[0].Value), so that only the relevant portions of matching file names are collected in $res, as an array.

A: This would be a good time to use regex.
See https://regex101.com/r/AH00n6/1
and understand the following regex:
.*\s[#]*([A-Z]{4}-[0-9]{3}).*.csv

This is a little extra to capture just the names, but gives more insight into how to control the regex.


Q: Why pl sql assignment operator throws error while reading from sql query? set serveroutput on;
 declare

      v_emp_first_name  US_EMPLOYEES.FIRST_NAME%TYPE;

      BEGIN

       select us_employees.first_name into v_emp_first_name  from us_employees where email = 'jbutt@gmail.com';

       dbms_output.put_line('v_emp_first_name  --> ' || v_emp_first_name);

       v_emp_first_name := select first_name from us_employees where email = 'kris@gmail.com';

       dbms_output.put_line('v_emp_first_name  --> ' || v_emp_first_name);

      END;

When I compile above code the below statement throws error
    v_emp_first_name := select first_name from us_employees where email = 'kris@gmail.com';

Is it not possible to read a column value via a sql query and map that value using  assignment operator ?
If i have the below code alone then it compile and works fine
    select us_employees.first_name into v_emp_first_name  from us_employees where email = 'jbutt@gmail.com';

A: You have issue with this code:
v_emp_first_name := select first_name from us_employees where email = 'kris@gmail.com';

You can not use the assignment operator against the query as you have used.
Replace this assignment := with INTO as follows:
select first_name INTO v_emp_first_name from us_employees where email = 'kris@gmail.com';

A: The short answer is NO. You can't assign the output of a scalar query to a variable. The proper syntax for your "assignment" is the one you are already aware of.
I am sure that you will then ask WHY. Why did Oracle choose that "weird" syntax for assignment, and not the simpler one you tried?
The answer is that in more general cases a select statement may return multiple columns, not just one; and the values from multiple columns can be "assigned" to multiple variables (local to the PL/SQL block) simultaneously. Which, by the way, is the more common usage - people extract one "record" at a time, rather than a single value. So, how would you re-write the "select into" operation as an "assignment" (or multiple "assignments")? There is no natural way to do that.
You may ask why Oracle doesn't allow "your" assignment syntax, in the case of a single column selected, in addition to the select into syntax (which is needed for multi-column rows anyway). The answer is that would be wasteful. We already have a syntax - that we need for more general cases anyway; we don't need one more.
You might say that we could put all the receiving local variables into a record type, and do a single assignment (to a record) even for general "rows" returned by a select. Alas, SQL statements return rows, not records; rows are a SQL concept, and specifically they are not a data type. Perhaps Oracle could do further development along those lines (to add functionality that doesn't exist today), but why bother - they already have a perfectly fine syntax for what you need, and you already know what that syntax is - without needing to define a record type to hold all your local variables, then define a "record type" for rows coming from a SQL select statement, then .....


Q: Can't run code in Android studio due to VT-x disabled When i try to run my code in android studio i got an error"Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.  Enable VT-x in your BIOS security settings (refer to documentation for your computer)." . I did every thing i could but i couldn't fix it . Can anybody tell me in detail how

A: First make sure your processor supports virtualization technology
Intel processors from i3 supports it.
If your processor is above i3, then Go to BIOS and look for an option named VTx or virtualization and Enable it...save changes and exit
Now open your web browser and search for HAxm drivers and install the latest one.
You should be good
P.S: if your processor is below i3, you cannot run avd

A: If your computer does not support Virtualization, there are emulators that don't require it. I know one that many people use is Genymotion.
Alternatively, of course, you can test on a physical device.


Q: Subsubsection table reference is wrong I have problem with referencing a table in my subsubsection of my document. The reference in my paragraph always shows a different number compared to my table.
This is the code I used for creating the table:
\begin{table}[h!]
\begin{center}
\label{table:6.3}
\begin{tabular}{||c || c | c | c | c||}
\hline
x & y & z & u & b \\ [0.5ex]
\hline\hline
\hline
Sharpness & 32.7\% & 5.3\% & 24.2\% & 37.8\%\\
\hline
\hline
\end{tabular}
\end{center}
\caption[xx]
\end{table}

and this is the code I used to reference it on my paragraph:
blablabla \ref{table:6.3}

When compiled, the table shows Table 6.3 but on my paragraph it will reference Table 6.2.3.2 following the numbering of my subsubsection. I want both my paragraph and table reference using the same number.


Q: Windows Process Activation Service won't Start "parameter is incorrect" (Visual Studio 2010 Profiler) I've struggled with this one for a whole day, so here is both the problem & solution:
After profiling an ASP.NET application on Windows 7 (x64), I exited Visual Studio (possibly a crash) and installed some updates which required a reboot. When I loaded back up the ASP.NET Web Application in my Visual Studio Solution was dimmed out, and the Web & WAS services turned out to be stopped.
When I tried starting Windows Process Activation Service, I got the error "parameter is incorrect".

A: I tried the suggestion here and didn't have any success, so then I compared the registry entries for a working WAS service and one that wasn't. Here was that difference:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WAS\Environment
Not Working: Blank
Working:     Cor_Enable_Profiling=0x0

Replacing the empty Environment value with Cor_Enable_Profiling=0x0 allowed the service to start and everything returned to normal. I believe profilers set that to 0x1 when they are profiling your application, it is possible it got deleted during the unexpected shutdown of my profiler.


Q: Web Scraping w/Mechanize and/or BeautifulSoup4 on ASP pages Hello I am a programming n00b and am desperately trying to get some code to work.
I can't really find any good tutorials on ASP scraping/filling in fields and submitting then working with the content.
Here is my code so far:
import mechanize
import re

url = 'http://www.cic.gc.ca/english/work/iec/index.asp'
br = mechanize.Browser(factory=mechanize.RobustFactory())
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)    Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open(url)
response = br.response().read()

What I am trying to do:

*

*Load that URL

*Fill out the 2 form fields

*Submit

*Print the div id stats into python

*Run a loop on a 15 minute timer

*Play a loud sound if anything in div stats changes when it loops

Please advise me the best/fastest way of doing this with minimal programming experience.

A: It's not that difficult once you understand why the second form isn't shown when page is loaded. There's nothing to do with ASP itself, it's rather due to CSS style set to "display: none;" and will only be active once the first Option Select has been filled.
Here is a full sample of what you're after, implemented in Selenium, it's similar to machanize I believe.
The basic flow should be:

*

*load the web browser and load the page

*find the first Option Select and fill it in

*trigger a change event (I chose to send a TAB key) and the second Option Select is shown

*fill in the second Select and find the submit button and click it

*assign a name to the content you get from the div id=stats text

*compared if the text has changed from last fetch
a) if YES, do your BEEP and close the driver page etc.
b) if NO, set a scheduler (I use Python's Event's Scheduler, and run the crawling function again...
That's it! Easy, ok code time -- I used United Kingdom + Working Holiday pair for test:
import selenium.webdriver
from selenium.webdriver.common.keys import Keys
import sched, time

driver = selenium.webdriver.Firefox()
url = 'http://www.cic.gc.ca/english/work/iec/index.asp'
driver.get(url)

html_content = ''
# construct a scheduler
s = sched.scheduler(time.time, time.sleep)

def crawl_me():
    global html_content
    driver.refresh()
    time.sleep(5) # wait 5s for page to be loaded

    country_name = driver.find_element_by_name('country-name')
    country_name.send_keys('United Kingdom')
    # trick's here to send a TAB key to trigger the change event
    country_name.send_keys(Keys.TAB)

    # make sure the second Option Select is active (none not in style)
    assert "none" not in driver.find_element_by_id('category_dropdown').get_attribute('style')

    cateogory_name = driver.find_element_by_name('category-name')
    cateogory_name.send_keys('Working Holiday')

    btn_go = driver.find_element_by_id('submit')
    btn_go.send_keys(Keys.RETURN)

    # again, check if the content has been loaded
    assert "United Kingdom - Working Holiday" not in driver.page_source

    compared_content = driver.find_element_by_id('stats').text
    # here we will end this script if content has changed already
    if html_content != '' and html_content != compared_content:
        # do whatever you want to play the beep sound
        # at the end exit the loop
        driver.close()
        exit(-1)
    # if no changes are found, trigger the schedule_crawl() function, like recursively
    html_content = compared_content
    print html_content
    return schedule_crawl()

def schedule_crawl():
    # set your time interval here, 15*60 = 15 minutes
    s.enter(15*60, 1, crawl_me, ())
    s.run() # and run it of course

crawl_me()

To be honest, this is quite easy and straight forward however it does require you fully understand how html/css/javascript (not javascript in this case, but you do need to know the basic) and all their elements how they work together.
You do need to learn from the basic read => digest => code => experience => do it in cycles, Programming doesn't have a shortcut or the fastest way.
Hope this helps (and I really hope you do not just copy & paste mine, but learn and implement your own in mechanize by the way).
Good Luck!


Q: What is the specific requirement to use Dagger2 in any android application? What are the actual benefits of using dagger2 in an android application? I read the dagger 2 documentation but still not able to find that in what condition I should use dagger2 in my application and what are the benefits of its implementation?

A: 1.) to use Dagger2, you need to include it as a dependency in your project.
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
compile 'com.google.dagger:dagger:2.9'
provided 'org.glassfish:javax.annotation:10.0-b28'

Then you can use Dagger2.

2.) Whenever you have a class which is the dependency of another class.
So if you have something like this:
public int getNewRandomNumber() {
    return new Random().nextInt(5000);
}

Then you have an implicit dependency on Random and it is not mockable.
So you might want to provide this as a dependency to the method instead:
public int getNewRandomNumber(Random random) {
   return random.nextInt(5000);
}

But you might be using Random in a bunch of places, so you might want to provide it to the class itself:
public class RandomGenerator {
    private final Random random;

    public RandomGenerator(Random random) {
        this.random = random;
    }
}

After which the question surfaces: if you need an instance of RandomGenerator, where are you getting Random from?
Surely this is stupid:
RandomGenerator gen = new RandomGenerator(new Random());

Wouldn't it be nicer to do either this:
RandomGenerator randomGenerator = component.randomGenerator();

or
@Inject
RandomGenerator randomGenerator;

Well apparently with Dagger it's pretty easy
@Module
public class RandomModule {
    @Provides
    @Singleton
    Random random() {
        return new Random();
    }
}

@Singleton
@Component(modules={RandomModule.class})
public interface SingletonComponent {
    Random random();
    RandomGenerator randomGenerator();
}

then
@Singleton
public class RandomGenerator {
    private final Random random;

    @Inject
    public RandomGenerator(Random random) {
        this.random = random;
    }
}

or
@Singleton
public class RandomGenerator {
    @Inject
    Random random;

    @Inject
    public RandomGenerator() {
    }
}

You can read more about dependency injection here


Q: Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools? Yesterday I observed some really strange behaviour and wrote a looooong question on it. As @tacoshy correctly pointed out, the question lacked focus. I will therefore, in this post, focus on one single question:

Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools?

Preface
The <head>-element contain the following viewport meta-tag
<meta name="viewport" content="width=device-width, initial-scale=1" />

Before any video shown below, the following have both been performed in Chrome-devtools
Settings > Preferences > Reset defaults and reload
and
The kebab-icon in the responsive view > Reset to defaults
The application.
The code can be found here. It's deployed and can be inspected here.
A React-application with a state (windowWidth) that is updated to window.innerWidth when the resize-event triggers. I also have a container div with min-width set to windowWidth. In short, the container should always have the same min-width as window.innerWidth. The container contains a div with min-width statically set to 400px.
The behaviour
When I only open chrome developer tools and resize the visible window by changing the width of the developer tools, this is the observed behaviour:

*

*window.innerWidth corresponds to the size of the window.

*The scale (from window.visualViewport.scale) remains at 1.

Now we try in Chrome developer tools responsive mode:

*

*The width remains static (781px)

*The entire scale of the viewport goes down.

Further investigations

*

*window.visualViewport.width will produce nearly identical behaviour

*

*(apart from width sometime shifting to a decimal-point value)

*window.screen.width will produce a different but also erroneous behaviour:

*

*The layout doesn't break until the screen becomes smaller than the cyan-coloured element (in the header with min-width: 400px). Then the container seem to shrink quicker and at this point we can also see how the scale starts to go down.

*Setting windowWidth statically to 100vw produces exactly the same behaviour as above.

Solution to the weird behaviour
All of the examples above on the layout breaking have one thing in common: The scale starts to go down instead of the actual width of the viewport. So one could imagine that updating the viewport meta-tag to include minimum-scale=1 would solve the problem, and it does! Using
<meta
  name="viewport"
  content="width=device-width, initial-scale=1, minimum-scale=1"
/>

Produces the following behaviour:

As you can see, the Scale remains at 1 and the layout doesn't break. In fact, adding minimum-scale=1 makes innerWidth, visualViewport.width and screen.width all produce the same expected behaviour in the responsive view of chrome developer tools.
Unfortunately solving that was not the question, the question is and remains:

Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools?

Edit
This strange scaling-behaviour is not mirrored when viewing the page in the Firefox developer tools responsive view.

Edit2
Similar questions
Does Mobile View in Chrome-Dev-Tools force scaling?
Exactly the same problem, solved by adding the meta-tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Which apparently did solve the problem in January 2020, but does not solve the problem today (as we cab see here).

Resize Chrome responsive mode window without changing scale
Also solved by adding:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

which is already present this time around.

Why is Chrome shrinking the view in responsive mode?
Exactly the same behaviour as this mine but the selected solution was a jQuery-hack. The poser also mentioned a similar scaling-problem when tilting your phone and then tilting it back again which I too have experienced (it goes away when adding minimum-width=1 to the viewport metatag).
Summary
It looks like this issue used to be solved by adding
<meta name="viewport" content="width=device-width, initial-scale=1.0">

but now requires
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">

my question in that case remains

*

*Why have they changed this?

*What use is there for the developer to change the scale of the page when resizing the responsive window?

*Is this a feature or a bug?

Edit3
Edge on the other hand does seem to mirror this behaviour.


Q: Output resistance in negative feedback I was studying negative feedback in voltage amplifiers. I found this on Wikipedia for calculating input resistance as shown below.

Following the similar method, I tried to calculate the output resistance with feedback \$Z_{of}\$.
Connected a voltage source \$V_o\$ which supplies a current \$I_o\$. Applying Kirchoff's voltage law to the output loop, we have
\$V_o = I_oZ_o + A_v.V_{in}\$
For negative feedback, \$V_{in} = V_x - V_f\$ and \$V_f = \beta V_o\$. Therefore
\$V_o = I_oZ_o + A_v.(V_x - \beta V_o)\$
\$V_o = I_oZ_o + A_v.V_x - A_v.\beta V_o\$
\$V_o + A_v.\beta V_o = I_oZ_o + A_v.V_x\$
\$V_o(1 + A_v.\beta) = I_oZ_o + A_v.V_x\$
Dividing both the sides by \$I_o\$, we get
\$Z_{of} = \frac{Z_o}{(1 + A_v.\beta)} + \frac{(A_v.V_x)}{(I_o)(1 + A_v.\beta)}\$
The above expression is what I am getting. But the answer is \$Z_{of} = \frac{Z_o}{(1 + A_v.\beta)}\$. I am getting an extra term \$\frac{(A_v.V_x)}{(I_o)(1 + A_v.\beta)}\$.
What is the mistake in my calculation? Please help.


Q: "Lock on the Kernel Object" on windows can make the entire system unresponsive? There's this WIN32 process, which someone says:

The servide takes a lock on the kernel
  object and does not release. After a
  while the machine becomes irresponsive
  and has to restarted. Restanting only
  the service won't fix the issue.

According to my knowledge applications were not supposed to be able to crash the entire system in windows. Does anyone know if such an indecent behavior (taking a lock on the kernel object and not releasing it) can indeed crash the OS? If so why don't we see this more in malicious software?
Some clarifications:
This is not a device driver.
Any amiguity left in the reponse is also ambiguous to me. Please elaborate on the cases you can think of.

A: This doesn't mean anything. There is no "kernel object" in NT, and any lock you could possibly take would be released if the service were restarted.

A: This depends on what type of application it is.  Some applications install and use kernel drivers as part of their usage.  A kernel driver has the most low level access possible in the system and is capable of crashing or hanging the system.  If the process uses a kernel driver, and the description alludes to this, then yes it can crash / hang the system.
I believe Windows Vista started limiting the amount of damage a kernel driver can accidentally do (graphics drivers especially).  But intentionally, you can still cause lots of problems.

A: Depending on which precise kernel object they mean, and which service, this may very well be true. See for instance Raymond Chen on Loader Lock, a kernel lock which applications can monopolize. Restarting the service will then become a problem because the very unload of that service will require the loader lock, too.


Q: Using Parsec with restrictions on parsed result I'm trying to come up with a clever way of parsing assembly code. For example, if the registers are numbered from 0 to 31, I want to accept $31 but not $32.
I would like to do these while I parse the source code, because 1) I want to use the position information. 2) I like it simple.
My best idea is to use a special parser to indicate failure.
For example I could write
import Text.Parsec hiding (label)
import Text.Parsec.Token
import Text.Parsec.Language (emptyDef)
import Text.Parsec.String
import Text.Parsec.Expr
import Text.Parsec.Perm

data Register = Register Integer
  deriving (Eq, Ord, Show)

register :: Parser Register
register = do char '$'
              n <- onlyWhen "Register number must be between 0 and 31"
                            (\n -> n >= 0 && n <= 31) (decimal p)
              return $ Register n

onlyWhen :: String -> (a -> Bool) -> Parser a -> Parser a
onlyWhen mess pred pars
  = do r <- pars
       if pred r then return r
                 else fail mess

p = makeTokenParser emptyDef

It works, but the error message contains traces of the parsing state, which is unfortunate.
What would be the best way to do it? Is there some additional library for doing this kind of things?

A: Try to extract Error messages
getErrorMessage (ParseError p xs) = show p ++ concat $ map messageString xs


Q: Using a list of conditions to filter a DataFrame in Pandas I wish to have a function which takes a list of conditions, of any length, and places an ampersand between all the conditions. Example code below.
df = pd.DataFrame(columns=['Sample', 'DP','GQ', 'AB'],
         data=[
               ['HG_12_34', 200, 35, 0.4],
               ['HG_12_34_2', 50, 45, 0.9],
               ['KD_89_9', 76, 67, 0.7],
               ['KD_98_9_2', 4, 78, 0.02],
               ['LG_3_45', 90, 3, 0.8],
               ['LG_3_45_2', 15, 12, 0.9]
               ])

def some_func(df, cond_list):

    # wrap ampersand between multiple conditions
    all_conds = ?

    return df[all_conds]

cond1 = df['DP'] > 40
cond2 = df['GQ'] > 40
cond3 = df['AB'] < 0.4

some_func(df, [cond1, cond2]) # should return df[cond1 & cond2]
some_func(df, [cond1, cond3, cond2]) # should return df[cond1 & cond3 & cond2]

I would appreciate any help with this.

A: You can use functools.reduce for that:
from functools import reduce

def some_func(df, cond_list):
    return df[reduce(lambda x,y: x&y, cond_list)]
Or, like @AryaMcCarthy says, you can use and_ from the operator package:
from functools import reduce
from operator import and_

def some_func(df, cond_list):
    return df[reduce(and_, cond_list)]
or with numpy - like @ayhan says - which has also a logical and reduction:
from numpy import logical_and

def some_func(df, cond_list):
    return df[logical_and.reduce(cond_list)]
All three versions produce - for your sample input - the following output:
>>> some_func(df, [cond1, cond2])
       Sample  DP  GQ   AB
1  HG_12_34_2  50  45  0.9
2     KD_89_9  76  67  0.7
>>> some_func(df, [cond1, cond2, cond3])
Empty DataFrame
Columns: [Sample, DP, GQ, AB]
Index: []


Q: SQL Datetime as time query I would like the below select statement to be show as time rather than datetime.  I'm aware that a cast as solution is likely however given I am trying to Cast as a "grouped by time", I am not finding a solution.
SELECT
DATEADD(hour, DATEDIFF(hour, 0,dbo.tbReceiptLine.Time), 0) AS Hourly,
DATEADD(minute, DATEDIFF(minute, 0, dbo.tbReceiptLine.Time) / 30 * 30, 0) AS [30 Mins]

I would like to show this as time only.

A: In SQL Server 2008 onwards you can cast to time datatype:
SELECT CAST(dbo.tbReceiptLine.Time as time)

See The ultimate guide to the datetime datatypes


Q: Build asset folder empty : android Studio, using Gradle I have created a simple app in android studio, where I have placed a font under
src/main/assets/fonts/fontName.ttf
When running a build/clean etc. the asset folder in the build stays empty. (build/exploded-aar/com.android.support/appcompat-v7/19.1.0/assets)
The application runs, no instances of the file are found on the device.


Q: Amazon MWS (PHP) - How does the request work I am trying to pull a report in PHP for active listings.
I've made progress, however, I cannot understand how this works and there is nothing out there that can explain it.
For example, in the Samples provided from the PHP library, I see quite a few XML files.  When you run the RequestReportResponse sample, does that generate the XML file, or does the XML file tell the RequestReportResponse what to do based on values and functions?
I am asking because, with the MWS Scratchpad - I select all the necessary fields, submit it then refresh the Amazon Reports page of my seller central section and it shows a pending report.
I'm just asking how the XML content affects the report or how the report can affect the XML.

A: The answer to your question comes in two parts.
Part 1 - Calling the Amazon API
Most MWS requests do not require any file (be it plain text or XML) to be sent to Amazon. For example, all parameters needed to do send RequestReport can (and must) be sent as regular parameters. I'm not sure what Amazon would do if you did submit a file along with it as I've never tried. But then again... why would you?
One of the calls that does require a file to be send is the SubmitFeed call where that file is the actual feed to be submitted. It depends on the type of feed you're submitting if Amazon expects it to be plain text or XML.
Part 2 - Handling Amazon's API responses
When you get information back from Amazon's API, it usually is in XML format (there are a few calls that may return plaintext instead). You will need to decode this data to get your information out.
To make it a bit clearer, I'll outline a typical process for you:
The process of getting all your listings from Amazon:

*

*Do a RequestReport call to Amazon. No XML attached

*Decode the XML that you're getting back (it is a RequestReportResponse). If all went well, you'll get a RequestReportId as part of the response, and Amazon will start processing your request.
Amazon may need a few minutes to actually create the report, in cases of very complex or large requests or during high activity hours it may actually take up to an hour or more. So we need to find out when the request we made is actually done.

*Poke Amazon API with a GetReportRequestList call asking for the status of your request with ReportRequestIdList.Id.1={YourRequestIdHere}. This also does not need a XML attachment.

*Decode the XML that you're getting back. (it is a GetReportRequestListResponse)
If its ReportProcessingStatus is not _DONE_, wait for at least 45 seconds, then repeat from step 3. If the report is actually done, you'll see a valid GeneratedReportId in the response. If it is missing, you'll need to do an extra GetReportList call to find its ID.

*Call GetReport to finally fetch your report with ReportId={YourGeneratedReportIdHere}

*Decode whatever you're getting back. Depending on the type of report you requested, the response may be XML or plain text.
This process is explained in detail (and with a pretty flow chart) in Amazon Marketplace Web Service Reports API Section Reference (Version 2009-01-01)
To finally answer your question with respect to getting active listings from Amazon MWS:
None of the three calls require you to send XML to Amazon. The data you receive from Amazon will be in XML format (with the possible exception step 6 if you requested a plain text report).


Q: clickhouse 1 node out of 3 not syncing I have a 3-node clickhouse cluster, almost identical to the setup in https://github.com/tetafro/clickhouse-cluster.
I ran the CREATE TABLE statement on the 3 nodes, as follows:

CREATE TABLE replica_test.hits_shard
(
 `WatchID` UInt64,
 `JavaEnable` UInt8,
 `Title` String,
 `GoodEvent` Int16,
 `EventTime` DateTime,
 `EventDate` Date,
 `CounterID` UInt32,
 `ClientIP` UInt32,
 `ClientIP6` FixedString(16),
 `RegionID` UInt32,
 `UserID` UInt64,
 `CounterClass` Int8,
 `OS` UInt8,
 `UserAgent` UInt8,
 `URL` String,
 `Referer` String,
 `URLDomain` String,
 `RefererDomain` String,
 `Refresh` UInt8,
 `IsRobot` UInt8,
 `RefererCategories` Array(UInt16),
 `URLCategories` Array(UInt16),
 `URLRegions` Array(UInt32),
 `RefererRegions` Array(UInt32),
 `ResolutionWidth` UInt16,
 `ResolutionHeight` UInt16,
 `ResolutionDepth` UInt8,
 `FlashMajor` UInt8,
 `FlashMinor` UInt8,
 `FlashMinor2` String,
 `NetMajor` UInt8,
 `NetMinor` UInt8,
 `UserAgentMajor` UInt16,
 `UserAgentMinor` FixedString(2),
 `CookieEnable` UInt8,
 `JavascriptEnable` UInt8,
 `IsMobile` UInt8,
 `MobilePhone` UInt8,
 `MobilePhoneModel` String,
 `Params` String,
 `IPNetworkID` UInt32,
 `TraficSourceID` Int8,
 `SearchEngineID` UInt16,
 `SearchPhrase` String,
 `AdvEngineID` UInt8,
 `IsArtifical` UInt8,
 `WindowClientWidth` UInt16,
 `WindowClientHeight` UInt16,
 `ClientTimeZone` Int16,
 `ClientEventTime` DateTime,
 `SilverlightVersion1` UInt8,
 `SilverlightVersion2` UInt8,
 `SilverlightVersion3` UInt32,
 `SilverlightVersion4` UInt16,
 `PageCharset` String,
 `CodeVersion` UInt32,
 `IsLink` UInt8,
 `IsDownload` UInt8,
 `IsNotBounce` UInt8,
 `FUniqID` UInt64,
 `HID` UInt32,
 `IsOldCounter` UInt8,
 `IsEvent` UInt8,
 `IsParameter` UInt8,
 `DontCountHits` UInt8,
 `WithHash` UInt8,
 `HitColor` FixedString(1),
 `UTCEventTime` DateTime,
 `Age` UInt8,
 `Sex` UInt8,
 `Income` UInt8,
 `Interests` UInt16,
 `Robotness` UInt8,
 `GeneralInterests` Array(UInt16),
 `RemoteIP` UInt32,
 `RemoteIP6` FixedString(16),
 `WindowName` Int32,
 `OpenerName` Int32,
 `HistoryLength` Int16,
 `BrowserLanguage` FixedString(2),
 `BrowserCountry` FixedString(2),
 `SocialNetwork` String,
 `SocialAction` String,
 `HTTPError` UInt16,
 `SendTiming` Int32,
 `DNSTiming` Int32,
 `ConnectTiming` Int32,
 `ResponseStartTiming` Int32,
 `ResponseEndTiming` Int32,
 `FetchTiming` Int32,
 `RedirectTiming` Int32,
 `DOMInteractiveTiming` Int32,
 `DOMContentLoadedTiming` Int32,
 `DOMCompleteTiming` Int32,
 `LoadEventStartTiming` Int32,
 `LoadEventEndTiming` Int32,
 `NSToDOMContentLoadedTiming` Int32,
 `FirstPaintTiming` Int32,
 `RedirectCount` Int8,
 `SocialSourceNetworkID` UInt8,
 `SocialSourcePage` String,
 `ParamPrice` Int64,
 `ParamOrderID` String,
 `ParamCurrency` FixedString(3),
 `ParamCurrencyID` UInt16,
 `GoalsReached` Array(UInt32),
 `OpenstatServiceName` String,
 `OpenstatCampaignID` String,
 `OpenstatAdID` String,
 `OpenstatSourceID` String,
 `UTMSource` String,
 `UTMMedium` String,
 `UTMCampaign` String,
 `UTMContent` String,
 `UTMTerm` String,
 `FromTag` String,
 `HasGCLID` UInt8,
 `RefererHash` UInt64,
 `URLHash` UInt64,
 `CLID` UInt32,
 `YCLID` UInt64,
 `ShareService` String,
 `ShareURL` String,
 `ShareTitle` String,
 `ParsedParams` Nested(
 Key1 String,
 Key2 String,
 Key3 String,
 Key4 String,
 Key5 String,
 ValueDouble Float64),
 `IslandID` FixedString(16),
 `RequestNum` UInt32,
 `RequestTry` UInt8
)
ENGINE=ReplicatedMergeTree('/clickhouse/tables/{shard}/tables/hits', '{replica}')
PARTITION BY toYYYYMM(EventDate)
ORDER BY (CounterID, EventDate, intHash32(UserID))
SAMPLE BY intHash32(UserID);

CREATE TABLE replica_test.hits_distributed
(
 `WatchID` UInt64,
 `JavaEnable` UInt8,
 `Title` String,
 `GoodEvent` Int16,
 `EventTime` DateTime,
 `EventDate` Date,
 `CounterID` UInt32,
 `ClientIP` UInt32,
 `ClientIP6` FixedString(16),
 `RegionID` UInt32,
 `UserID` UInt64,
 `CounterClass` Int8,
 `OS` UInt8,
 `UserAgent` UInt8,
 `URL` String,
 `Referer` String,
 `URLDomain` String,
 `RefererDomain` String,
 `Refresh` UInt8,
 `IsRobot` UInt8,
 `RefererCategories` Array(UInt16),
 `URLCategories` Array(UInt16),
 `URLRegions` Array(UInt32),
 `RefererRegions` Array(UInt32),
 `ResolutionWidth` UInt16,
 `ResolutionHeight` UInt16,
 `ResolutionDepth` UInt8,
 `FlashMajor` UInt8,
 `FlashMinor` UInt8,
 `FlashMinor2` String,
 `NetMajor` UInt8,
 `NetMinor` UInt8,
 `UserAgentMajor` UInt16,
 `UserAgentMinor` FixedString(2),
 `CookieEnable` UInt8,
 `JavascriptEnable` UInt8,
 `IsMobile` UInt8,
 `MobilePhone` UInt8,
 `MobilePhoneModel` String,
 `Params` String,
 `IPNetworkID` UInt32,
 `TraficSourceID` Int8,
 `SearchEngineID` UInt16,
 `SearchPhrase` String,
 `AdvEngineID` UInt8,
 `IsArtifical` UInt8,
 `WindowClientWidth` UInt16,
 `WindowClientHeight` UInt16,
 `ClientTimeZone` Int16,
 `ClientEventTime` DateTime,
 `SilverlightVersion1` UInt8,
 `SilverlightVersion2` UInt8,
 `SilverlightVersion3` UInt32,
 `SilverlightVersion4` UInt16,
 `PageCharset` String,
 `CodeVersion` UInt32,
 `IsLink` UInt8,
 `IsDownload` UInt8,
 `IsNotBounce` UInt8,
 `FUniqID` UInt64,
 `HID` UInt32,
 `IsOldCounter` UInt8,
 `IsEvent` UInt8,
 `IsParameter` UInt8,
 `DontCountHits` UInt8,
 `WithHash` UInt8,
 `HitColor` FixedString(1),
 `UTCEventTime` DateTime,
 `Age` UInt8,
 `Sex` UInt8,
 `Income` UInt8,
 `Interests` UInt16,
 `Robotness` UInt8,
 `GeneralInterests` Array(UInt16),
 `RemoteIP` UInt32,
 `RemoteIP6` FixedString(16),
 `WindowName` Int32,
 `OpenerName` Int32,
 `HistoryLength` Int16,
 `BrowserLanguage` FixedString(2),
 `BrowserCountry` FixedString(2),
 `SocialNetwork` String,
 `SocialAction` String,
 `HTTPError` UInt16,
 `SendTiming` Int32,
 `DNSTiming` Int32,
 `ConnectTiming` Int32,
 `ResponseStartTiming` Int32,
 `ResponseEndTiming` Int32,
 `FetchTiming` Int32,
 `RedirectTiming` Int32,
 `DOMInteractiveTiming` Int32,
 `DOMContentLoadedTiming` Int32,
 `DOMCompleteTiming` Int32,
 `LoadEventStartTiming` Int32,
 `LoadEventEndTiming` Int32,
 `NSToDOMContentLoadedTiming` Int32,
  `FirstPaintTiming` Int32,
 `RedirectCount` Int8,
 `SocialSourceNetworkID` UInt8,
 `SocialSourcePage` String,
 `ParamPrice` Int64,
 `ParamOrderID` String,
 `ParamCurrency` FixedString(3),
 `ParamCurrencyID` UInt16,
 `GoalsReached` Array(UInt32),
 `OpenstatServiceName` String,
 `OpenstatCampaignID` String,
 `OpenstatAdID` String,
 `OpenstatSourceID` String,
 `UTMSource` String,
 `UTMMedium` String,
 `UTMCampaign` String,
 `UTMContent` String,
 `UTMTerm` String,
 `FromTag` String,
 `HasGCLID` UInt8,
 `RefererHash` UInt64,
 `URLHash` UInt64,
 `CLID` UInt32,
 `YCLID` UInt64,
 `ShareService` String,
 `ShareURL` String,
 `ShareTitle` String,
 `ParsedParams.Key1` Array(String),
 `ParsedParams.Key2` Array(String),
 `ParsedParams.Key3` Array(String),
 `ParsedParams.Key4` Array(String),
 `ParsedParams.Key5` Array(String),
 `ParsedParams.ValueDouble` Array(Float64),
 `IslandID` FixedString(16),
 `RequestNum` UInt32,
 `RequestTry` UInt8
)
ENGINE = Distributed('hivestack', replica_test, 'hits_shard', rand());

I have an out-of-sync issue with node-2 as follows:

*

*if i insert data to node-2, the data is only seen by node-2

*

*insert ... into node2 => hits_shard then select count(*) fom node1 => hits_shard the result is 0

*if i insert data into node-1 or node-3, it's seen by all 3 nodes.

SELECT * from system.replicas:
replica_test,hits_shard,ReplicatedMergeTree,1,1,0,0,0,0,/clickhouse/tables/02/tables/hits,clickhouse02,/clickhouse/tables/02/tables/hits/replicas/clickhouse02,-1,0,0,0,0,1969-12-31 19:00:00,1969-12-31 19:00:00,1969-12-31 19:00:00,1969-12-31 19:00:00,"","","",0,0,1969-12-31 19:00:00,0,1,1,"","",{'clickhouse02':1}

select * from system.replication_queue is empty
clickhouse version: clickhouse/clickhouse-server:22.4.5.9
zookeeper version: bitnami/zookeeper:3.8.0
I verified that all 3 nodes can talk to each others via clickhouse-client and nc  9000
Would appreciate any tips on how to debug/fix this

A: Are you sure you have the same zookeeper clickhouse settings on all 3 nodes?
Do you insert into Distributed table or insert into ReplicatedMergeTree?
For first case, check on node-2
SELECT * FROM system.distribution_queue FORMAT Vertical
SELECT * FROM system.clusters FORMAT Vertical

and compare <remote_servers> section in your config for all 3 nodes


Q: Azure SQL Database DTU percentage Reach 100% on particular function My scenario is I have a button name(publish) at admin side use for publish agreement and after publish it visible to user-side. Recently I saw when I publish agreement
DTU percent reach almost 100% and I tested rest of all functionality DTU not goes upto 5%.
My database size is 250mb I upgraded the DTU to a higher tier(from B1 to B2,S1,S2,S3) but when publish agreement it reach 100%

process took (3 minute maximum) when publish a large agreement
I checked the Query that taking long time also not complicated
(@EntityKeyValue1 bigint)SELECT
[Extent1].[Revision] AS [Revision],
[Extent1].[ClauseVersionId] AS [ClauseVersionId],
[Extent1].[SourceClauseVersionId] AS [SourceClauseVersionId],
[Extent1].[DisplayHeader] AS [DisplayHeader],
[Extent1].[Body] AS [Body],
[Extent1].[EndUserGuidanceNote] AS [EndUserGuidanceNote],
[Extent1].[DocumentParty_DocumentPartyId] AS [DocumentParty_DocumentPartyId],
[Extent1].[PublishedClause_ClauseId] AS [PublishedClause_ClauseId]
FROM [dbo].[PublishedClauseVersion] AS [Extent1]
WHERE ([Extent1].[PublishedClause_ClauseId] IS NOT NULL) AND ([Extent1].[PublishedClause_ClauseId] = @EntityKeyValue1)

I saw many answer and article but I didn't get any proper solution for this issue.

A: Check if the 2 sides of the comparison matches , Meaning the PublishedClause_ClauseId is also BigInt Data type as the parameter you are using "@EntityKeyValue1" , Mismatching them cause query optimizer to either scan or not use indexes, Match them then redeploy


Q: curl_multi_fdset returns always 1 What I want to do: download multiple files at the same time.
Issue: curl_multi_fdset always return 1.
Issue 2: I don't really understand how fd_set work. I am new to C and the doc is quite confusing.
Sources: I used this example and this progress bar.
My full .cpp: Github
So the problem seems to be in the initializing method:
static void initialize(CURLM *cm, int i, char* url[], std::string filepath)
{
CURL *eh = curl_easy_init();

FILE *fp; // added to the example
fp = fopen(filepath.c_str(), "wb"); // added to the example

curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, callback);
curl_easy_setopt(eh, CURLOPT_WRITEDATA, fp); // added to the example
curl_easy_setopt(eh, CURLOPT_NOPROGRESS, 0); // added to the example
curl_easy_setopt(eh, CURLOPT_HEADER, 0L);
curl_easy_setopt(eh, CURLOPT_URL, url[i]);
curl_easy_setopt(eh, CURLOPT_PRIVATE, url[i]);
curl_easy_setopt(eh, CURLOPT_VERBOSE, 0L);
curl_easy_setopt(eh, CURLOPT_PROGRESSFUNCTION, progress_func); // added to the example

curl_multi_add_handle(cm, eh);
}

However, it also won't work without these additional options. So it has to be something different but I didn't change anything regarding the fd_set. Any help is appreciated.
Call of initialize:
CURLM *cm = nullptr;
CURLMsg *msg;
long L;
unsigned int C = 0;
int M, Q, U = -1;
fd_set R, W, E;
struct timeval T;

curl_global_init(CURL_GLOBAL_ALL);
/* we can optionally limit the total amount of connections this multi handle uses */
curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, (long) MAX);

if ((argc - 2) < MAX)
{
    for (C = 0; C < argc - 2; ++C)
    {
        path = "test" + std::to_string(C) + ".html";
        initialize(cm, C, urls, path);
    }
}

Call of the function which returns 1:
FD_ZERO(&R);
FD_ZERO(&W);
FD_ZERO(&E);

if (curl_multi_fdset(cm, &R, &W, &E, &M))
{
    fprintf(stderr, "E: curl_multi_fdset\n");
    return EXIT_FAILURE;
}


Q: How do I move both files and folders to the specified directory? There is a code that moves files from one directory to another, but it doesn't move folders.
import os,glob
import shutil

inpath = str5
outpath = str6

os.chdir(inpath)
for file in glob.glob("*.*"):

    shutil.move(inpath+'/'+file,outpath)

How to make it move both files and folders to the specified directory?

A: *.* selects files that have an extension, so it omits sub-folders.
Use * to select files and folders.
Then you should see your desired result.
for file in glob.glob("*"):
    shutil.move(inpath+'/'+file,outpath)

A: You can use os.listdir to get all the files and folders in a directory.
import os
import shutil

def move_file_and_folders(inpath, outpath):
    for filename in os.listdir(inpath):
        shutil.move(os.path.join(inpath, filename), os.path.join(outpath, filename))

In your case,
inpath = <specify the source>
outpath = <specify the destination>
move_file_and_folders(inpath, outpath)