text:
Q: How do I loop through a set of numbers, do some addition and append to an array? My goal here is to create an array with the sum totals of every combination of 2 numbers on a set of dice. I'm creating the beginning of a loop that adds die1[0] to die2[0..5] before going through die1[1] + die2[0..5] and so on.
I've got this code below and I'm doing something wrong. I want to be able to call specific numbers in the array, such as dieSums[4], and get one number. Any idea what i'm doing incorrectly here?
die1 = [1,2,3,4,5,6]
die2 = [1,2,3,4,5,6]

dieSums = []

count = 0
while count <= 5 do
  dieSums << die1[0] + die2[count]
  count += 1
  puts dieSums[5]
end

A: A while loop, as you've written it, isn't very Rubyonic. (Rubinic?) A more idiomatic way to iterate over the elements of an array:
#!/usr/bin/ruby

die1 = [1,2,3,4,5,6]
die2 = [1,2,3,4,5,6]

dieSums = []

die1.each do |d1|
    die2.each do |d2|
        dieSums << d1 + d2
    end
end
puts dieSums[5]

Of course, die1 and die2 are identical in this case, so you could replace die2 with die1 and it'd all work out.

A: You are calling puts dieSums[5] inside the loop. dieSums[5] won't exist until the last iteration. It'll work if you call it outside the loop:
die1 = [1,2,3,4,5,6]
die2 = [1,2,3,4,5,6]

dieSums = []

count = 0
while count <= 5 do
  dieSums << die1[0] + die2[count]
  count += 1
end

puts dieSums[5] #=> 7

A: As a side note: notice that you are over-complicating the problem (because you think in imperative terms, take a look at Functional programming). The sum of all possible values for two dice:
>> die = [1,2,3,4,5,6]
>> die.product(die).map { |v1, v2| v1 + v2 }
=> [2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10, 11, 7, 8, 9, 10, 11, 12]

*

*Call uniq at the end if you don't want repeated values.

*Use repeated_combination(2) instead of product if you don't care about the order.

*Note that die.product(die) = die.repeated_permutation(2))

Finding all the sums for N dice is almost as simple:
>> die.repeated_permutation(5).map { |values| values.inject(:+) }


text:
Q: Found input variables with inconsistent numbers of samples: [889, 418] I am making a logistic regression model and have separate training and testing dataset file. All my code works perfect on fitting and prediction of model, but when I apply (Classification_report(y, prediction))
then it shows (Found input variables with inconsistent numbers of samples: [889, 418]) error. My testing dataset have only 418 rows while training has 889 rows.
Please tell me how can I fix this??

A: When the error is outputting "inconsistent number of samples", it means that your y and prediction variables have a different first dimension. In your case, one of the variables have their first dimension as 889 and the second variable has the first dimension as 418.
As for fixing this, this could be solved with a simple np.reshape(), however if that doesn't work you may have to look at your code again to find out where you might have messed up in the predictions and/or in the y variable

redpajama_set_name: RedPajamaStackExchange


text:
Q: catch input on change event with javascript First of all, I'm using this function:
jQuery(document).on('propertychange change click keyup input paste', 'input[name="wager_id_111"]', function(){
        var thisValue = jQuery(this).val();
        var amountReal = jQuery('.amount_visible');

        if ( thisValue != '' ){
            var amount_in_btc = thisValue / 1000;
            amount_in_btc = amount_in_btc.toFixed(5);
            amount_in_btc = parseFloat(amount_in_btc);
            amountReal.show(1, function(){
                amountReal.find('span').html('= ' + amount_in_btc);
            });
        } else {
            amountReal.hide();
        }
    });

and it works when user types amount it the input. The problem is, when input value is being changed via code, so I can't detect it was changed. Becouse there is buttons how much amount add to input (like 1, 10, 50, 100) and when users selects one of those, input value is being changed jQuery('input[name="wager_id_111"]').val(newVal); but as I said the function I showed below can't catch this. What the option would be to make it work?
Fiddle:
fiddle link

A: you can add this line of code: $('input[name="wager_id_111"]').trigger('change'); to your .click() function
demo: http://jsfiddle.net/et3gsf9w/1/

A: The solution is to place the code that operates the input value into a function, and call it two times, one when the event is raised and the other one via code.


text:
Q: AttributeError: 'AsyncResult' object has no attribute 'head' AttributeError: 'AsyncResult' object has no attribute 'head'
In my views.py file the error throwing at data = df.head(50) when i'm running and retrive the data as asynchronous background task.
 Could anybody help me here?
task.py
@shared_task
def eda_flow_task(path, mode):
    sleep(30)
    try:
        with adls_client.open(path, mode) as f:
            df = pd.read_csv(f, low_memory=False)
        return 'data load success'
    except Exception as e:
        response_dict.update({'error': str(e)})

view.py
def eda_flow(request):
    path = '/data/satyajit/us_amz.csv'
    mode = 'rb'
    df = eda_flow_task.delay(path, mode)
    data = df.head(50)
    json_records = data.reset_index().to_json(orient ='records')
    data = []
    data = json.loads(json_records)
    context = {'data': data}
    return render(request, "home/tables-simple.html", context)

A: The following statement is wrong: df = eda_flow_task.delay(path, mode)
delay() returns AsyncResult, not Pandas data-frame... I am not even sure you can return data frame as it probably is not serializable. I certainly never tried it so I do not know. In the case it is as I suspect (not serializable), you should return an object of type that is serializable, like a list of objects for an example.
Your task actually returns a string data load success or None in case of an exception.
In order to get result of Celery task you need to do the following:
res = eda_flow_task.delay(path, mode).get()  # NOTE: this blocks!

As mentioned above, res will most likely end up being a hard-coded string.


text:
Q: mtime - Set date format Looking over the manual, I can't figure out how to set the date format.
I am using the following to locate folders that are in 'dd-mm-yyyy' name, but realise that it may not be working due to the date format.
Is there any way to set the date format of '-mtime'?
find "${backup_dest}" \
    -maxdepth 1 -type d -mtime +3 \
    -name '[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]' \
    -execdir mv {} $folder_trash_path/{}-"${site[$i]}" ';'

A: Old find(1) implementatons and the POSIX standard only allow -mtime parameters that are plain numbers and that refer to a time offset that counts in days.
Modern find(1) implementations permit something like: -mtime -3y2m4d referring to all files that have been modified during the past 3 years + 2 months + 4 days.
If you like to refer to a specific time, then you may only use -newer together with a time stamp reference file that could be created with the touch program.


text:
Q: Express route declaration I have 2 routes such as,
router.get("/project/:id", (req,res) => {

console.log(1);

});

router.get("/project/active", (req,res) => {

console.log(2);

})

Whenever I call the /project/active route, /project/:id route is getting called.
Any tips here would help.

A: Your wildcard route with :id in it is greedy and is matching everything including the /project/active URL.
In this route definition:
router.get("/project/:id", ...)

The :id part is a wildcard.  It matches ANYTHING.  So, /project/anything will match that, including /project/active.  Since routes are matched in Express in the order they are declared, your router.get("/project/:id", ...) route matches first and takes the request.
There are four ways around this:

*

*Don't design or declare conflicting routes that might both match a particular URL.  In this particular case, you would change one of your two URLs to something unique such as /project/id/:id and /project/active or /project/:id and /activeproject.  Then, these two route handlers will never conflict.

*Very carefully order your routes from the most specific to the least specific.  In this case, you would put router.get("/project/active", ...) before router.get("/project/:id", ...).  That gives the more specific route a chance to match before the wildcard route gets to take the request.  But, note that this means that your id value can never be named active.

*If your ids are uniquely identifiable and different from strings like active (like suppose an ID is all numbers or always contains some numbers), then you can code a regex for the ID that would only match your id values and would not match regular words like `active.

*Code your wildcard route to individually check for things it should not match and call next() to continue routing to other routes.

A: That happens because you specify a dynamic route before a specific route.
The right one should be:
router.get("/project/active", (req,res) => {
  console.log(2);
});

router.get("/project/:id", (req,res) => {
  console.log(1);
});

In Node.js, we know something that is called a middleware stack. Basically, your requests will pass through middlewares until something gives out a response. Routers are also examples of middlewares.
In this case, your route assumes that /active is an id, as you defined /:id first before /active. Different things (should be your expected behavior) would happen if you switched the order.
References:

*

*Middleware Stack


text:
Q: connection between winding number and topological degree I'm writing a thesis on the topological degree (mapping or Brower degree), and I'm having trouble with the equation, that links the mapping degree to the winding number in $\mathbb{R}^2$(marked below by '?').
$$v_{f \circ \gamma}(0)=\frac{1}{2 \pi i} \int_\gamma \frac{f'(z)}{f(z)} dz \stackrel{?}{=} \sum_{i=1}^k v_\gamma (z_i) \alpha_i=\operatorname{deg}(f,U_1(0),0)$$
Here $z_i$ are the roots of $f$, $\alpha_i$ their multiplicity, $\gamma$ is the the unit circle.
My question is: Why is the winding number of $f \circ \gamma$ at $0$ the same as the sum of the winding numbers of $\gamma$ around the zeropoints of $f$ times their multiplicities?


text:
Q: I am facing errors with npm install command npm ERR! code EEXIST
npm ERR! path C:\Users\Mohlomi\AppData\Roaming\npm\ng.ps1
npm ERR! Refusing to delete C:\Users\Mohlomi\AppData\Roaming\npm\ng.ps1: node_modules/@angular/cli/bin/ng symlink target is not controlled by npm C:\Users\Mohlomi\AppData\Roaming\npm\node_modules\@angular\cli
npm ERR! File exists: C:\Users\Mohlomi\AppData\Roaming\npm\ng.ps1
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Mohlomi\AppData\Roaming\npm-cache\_logs\2022-08-10T14_50_39_626Z-debug.


text:
Q: Creating MongoDB like update document in C# I am trying to create a MongoDB like update document in my C# code. This is not used to update the MongoDB but the API I am using expects the data in this format.
I tried using MongoDB.Driver NuGet package and tried to create the document like this.
class Program
{
    class MyTest
    {
        public string Name { get; set; } = String.Empty;
        public string Description { get; set; } = String.Empty;
    }

    public static void Main()
    {
        var v = Builders<MyTest>.Update
            .Set(t => t.Name , "TestName")
            .Set(t => t.Description ,"TestDescription");

    }
}

This code compiles and runs. But I need the output in string format. Something like:
$set: {Name:"TestName",Description:"TestDescription"}

Is there anyway to get a string representation like that?

A: This should work:
var output = v.Render(BsonSerializer.LookupSerializer<MyTest>(), new BsonSerializerRegistry());

This will render the Update document to a BsonValue.


text:
Q: How to explain that function has positive and negative values around zero? I have following function
$$f(x)=\begin{cases}
x^2\cos\left(\frac1x\right) &\text{if }x\neq0\\
0 &\text{if }x=0
\end{cases}$$
How can I prove that this function in every area of zero has positive and negative values? I thought about finding appropriate sequences, but I can't come up with idea which exactly. Could someone clue me in on good solution?

A: Hint: as $x^2$ is always positive, show that every neighborhood of zero has a point $x$ at which $\cos(1/x)$ is negative and a point $y$ at which $\cos(1/y)$ is positive.

A: $x^2$ is always non-negative. For integer $n$, when $x=\frac{1}{2n\pi}$, $\cos (\frac1x) =+1$, and when $\frac{1}{(2n+1)\pi}$,  $\cos (\frac1x) = -1$
So take your neighborhood of zero, take any point $p>0$ in that neighborhood, take any integer $n > \frac{1}{p}$, and the points $x=\frac{1}{2n\pi}$ and $\frac{1}{(2n+1)\pi}$ satisfy your conditions.

A: Very easy: all you need is that for every $\varepsilon>0$ you get positive and negative cosine values above $1\over\varepsilon$.

A: lets make a sequence $a_n$ such that $ n \rightarrow \infty$ then $x \rightarrow 0$
definition :$$a_n=\frac{1}{n\pi}$$   now put $a_n$ as $x$
  $$lim_{x\rightarrow 0}x^2cos(\frac{1}{x})=\\lim_{n\rightarrow \infty}(\frac{1}{n\pi})^2cos(n\pi) \rightarrow 0$$ but ,note that $$x=a_n=\\(\frac{1}{n\pi})^2cos(n\pi)=\\(\frac{1}{n\pi})^2(-1)^n=\\\frac{(-1)^n}{(n\pi)^2}$$ goes to zero but alternatively $\pm$


text:
Q: findstr command to find a phrase instead of a single word findstr /S "stored procedure"  *.*
returns all the files with the string "stored" as opposed to "stored procedure".
Does anyone know what I am doing wrong? Thanks

A: You need to use the /c: option to tell findstr to search for the entire string not to search for individual components.  Your command will find any file with "stored" or "procedure".
findstr /S /c:"stored procedure" *.*

Will find any files with the string "stored procedure" in them.


text:
Q: ajax autocomplete extender is not working I have an autocompleate extender on textbox which shows records as a list from database but whern I click on texbox and start typing nothing happned. my html code is
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
         Enabled="True"  TargetControlID="TextBox1" ServicePath="~/WebService.asmx"
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="2"
                CompletionInterval="1000"
                EnableCaching="true"
                CompletionSetCount="20"
                DelimiterCharacters=";, :"
                ShowOnlyCurrentWordInCompletionListItem="true" >
    </asp:AutoCompleteExtender>

And my web service is
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Data;
    using MySql.Data.MySqlClient;
    using System.Configuration;

     /// <summary>
     /// Summary description for WebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
     public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public static List<string> GetCompletionList(string prefixText, int count)
    {
        MySqlConnection con = new MySqlConnection(ConfigurationManager.AppSettings["cn"]);
        if (con.State == ConnectionState.Closed)
            con.Open();
        MySqlCommand cmd = new MySqlCommand("SELECT gotra FROM tbgotra WHERE gotra LIKE '%" + prefixText + "%'",con);
        List<string> k = new List<string>();
        using (MySqlDataReader sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                k.Add(sdr["gotra"].ToString());
            }
        }
        con.Close();
        return k;
    }
   }

A: Try adding this line, i remember i had the same problem once where it worked for me locally but not live.
[WebMethod]
[System.Web.Script.Services.ScriptMethod] <-- Add this line
public static List<string> GetCompletionList(string prefixText, int count)
....

A: you Should to use
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>

in before the TextBox1

A: try this signature for web method:

public string[] GetCompletionList(string prefixText, int count, string contextKey)

I think extender wont accept any other return type besides string[]

A: In my case, I had to un-comment this line in the ASMX file
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

A: In my case it was issue with the css class below, I've had it in the source but without z-index property.
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
ClientIDMode="Static" MinimumPrefixLength="1" ServiceMethod="GetAllStaff"
TargetControlID="txtTeacherName" ServicePath="~/webservices/WebService.asmx"
CompletionInterval="50" EnableCaching="true" CompletionSetCount="20"
ShowOnlyCurrentWordInCompletionListItem="true"
CompletionListCssClass="CompletionListCssClass">
</ajaxToolkit:AutoCompleteExtender>

<style>
.CompletionListCssClass {
    font-size: 12px;
    color: #000;
    padding: 3px 5px;
    border: 1px solid #999;
    background: #fff;
    width: 300px;
    float: left;
    position: absolute;
    margin-left: 0;
    overflow: auto;
    height: 200px;
    cursor: pointer;
    z-index: 10000001 !important;
}
</style>


text:
Q: On the arithmetic of powers of subseries of the exponential series Let $p$ be a prime number and $q=p-1$. I'm trying to prove that the nonzero coefficients $a_{qk}$ ($k\ge1$) of the power series
$$ \sum_{k\ge1} a_{qk} z^{qk} := \left( \sum_{k\ge0} \frac{z^{qk+1}}{(qk+1)!} \right)^q $$
satisfy the congruence
$$ a_{qk} \cdot (qk)! \equiv -1 \mod p. $$
I've managed to work out that: There is a combinatorial formula for this power series. First of all, the series being raised to the $q$th power can be written
$$ f(z) = \frac1q \sum_{1\le i\le q} \zeta^{-i} e^{\zeta^iz} = \sum_{k\ge0} \frac{z^{qk+1}}{(qk+1)!} $$
where $\zeta$ is a primitive $q$th root of unity. And its $q$th power can be expressed in terms of the derivative
$$ f'(z) = \frac1q \sum_{1\le i\le q} e^{\zeta^iz} = \sum_{k\ge0} \frac{z^{qk}}{(qk)!} $$
by the formula
$$
    f(z)^q  = \frac1{q^{q}} \sum {q\choose i_1,\dots,i_{q}} {\big|C_q\cdot(i_1,\dots,i_q)\big|} \zeta^{-\big(1\cdot i_1+2\cdot i_2+\cdots+q\cdot i_{q}\big)} f'\Big(\big(i_1\zeta^1+\cdots+i_{q}\zeta^{q}\big)z\Big) $$
where the sum ranges over $C_{q}$-orbits of weak compositions $i_1+\cdots+i_{q}=q$, $i_k\ge0$, and where $\big|C_q\cdot(i_1,\dots,i_q)\big|$ denotes the size of the $C_q$-orbit of the weak composition.
It is straightforward to show that Fermat's little theorem extends to $\mathbf{F}_p[\zeta]/(\zeta^q-1)$ in the sense that the Frobenius is the identity, and it follows that $q$th powers in this ring are fixed by exponentiation by any positive integer power.
This reduces proving the claim to verifying it for the coefficient of $z^q$, i.e. verifying the congruence
$$
  -1 \equiv \sum {q\choose i_1,\dots,i_{q}} {\big|C_q\cdot(i_1,\dots,i_q)\big|} \cdot \zeta^{-\big(1\cdot i_1+2\cdot i_2+\cdots+q\cdot i_{q}\big)} \Big(i_1\zeta^1+\cdots+i_{q}\zeta^{q}\Big)^q \mod p.
$$
I've done this by computer for the primes up to $p=17$ but haven't found a general argument.

A: Your argument is in fact almost complete. It reduces the problem to checking the normalized coefficient $a_q$ of $z^q$ is congruent to $-1$ mod $p$, but since $$ f = z + \frac{z^{q+1}}{(q+1)!} + \dots ,$$ we have $$f^q = z^q + \frac{ q z^{2q}}{ (q+1)!} + \dots$$ and so $$a_q = q! \equiv -1 \mod p.$$

Here is an alternate "bijective" presentation of the same argument. We can interpret $a_n$ combinatorially as the number of $q$-colorings of the numbers from $1$ to $n$ such that each color is used a number of times congruent to $1$ mod $q$.
For $n \geq p$, there is an action of $\mathbb Z/p$ on this set of colorings by rotating the colorings of the numbers $n+1-p, n+2-p, \dots, n$. The number of colorings is congruent mod $p$ to the number of fixed points of this action. A coloring is fixed if the last $p$ numbers have the same color.
Since $q=p-1$, removing the last $q$ numbers in such a coloring doesn't affect the congruent mod $q$ of the number of times each coloring is used, and this gives a bijection between fixed points and colorings of the first $n-q$ numbers satisfying the same congruence condition.
So $a_n \equiv a_{n-q} \mod p$ for $n>q$ and $a_q$ is the number of $q$-colorings of $\{1,\dots, q\}$ with all colors occurring exactly once, which is $q! \equiv -1 \mod p$.


text:
Q: Swift 2 Decode base64 always return nil I'm trying to decode the following string from base64 without any exit. It always returns nil. I have tried to change NSDataBase64DecodingOptions to IgnoreUnknowCharanters but it doesn't work either. I also tried to remove the padding like this answer says swift base64 decoding returns nil but the length of my string is divisible by 4 so It doesn't works.
string
PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=

option 1
if let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters),
        let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
        print(decodedString) // foo
    }

option 2
 if let decodedData = NSData(base64EncodedString: pnpData, options: NSDataBase64DecodingOptions.init(rawValue: 0)),
        let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
        print(decodedString) // foo
    }

Hope you can help me. Thanks!!

A: Just in case someone is trying to Solve this issue moving from Java to Swift.
This Answer helped me out, you might need to append("==")
Swift 3 base64 decode return nil
You might need to append("==")

A: I doubt on string "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M="
This works, that string getting encode and decode too
    let utf8str = "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=".dataUsingEncoding(NSUTF8StringEncoding)
    let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
    let encodedString : String = base64Encoded!
    print(encodedString) // my encoded data

    let decodedData = NSData(base64EncodedString:  encodedString, options:NSDataBase64DecodingOptions(rawValue: 0))
    let decodedString : String = String(data: decodedData!, encoding: NSUTF8StringEncoding)!
    print(decodedString) // my plain data

This doesn't work, that decoded string dont get encode
    let decodedData = NSData(base64EncodedString:  "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=", options:NSDataBase64DecodingOptions(rawValue: 0))
    let decodedString : String = String(data: decodedData!, encoding: NSUTF8StringEncoding)!
    print(decodedString) // my plain data

This could be reason, check on https://www.base64decode.org/

Though special characters can't be hold in String.

A: maybe you can follow this
https://github.com/krzyzanowskim/CryptoSwift#data-padding
and use following method to decode(i guess your string is encoded by aes cbc and base64, if you want to decode this string, you must know the encode key and iv)
"PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=".decryptBase64ToString(cipher)


text:
Q: Android Fragment ошибка с обработкой OnClick В чем может быть ошибка запуска приложения? Ошибка возникла при добавлении обработчика кнопки. Вот код:
package com.drusilovihi.tabbedapp_b1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

public class TabFragment1 extends Fragment implements View.OnClickListener {
    private Mail m ;
    private ImageButton imgSend;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        m = new Mail("*************", "*******");
        imgSend.findViewById(R.id.imageButton);
        imgSend.setOnClickListener(this);

        return inflater.inflate(R.layout.tab_fragment_1, container, false);
    }

    public void sendEmail(View view){
        String[] toArr = {"toemail1@domain1.tld"}; // This is an array, you can add more emails, just separate them with a coma
        m.setTo(toArr); // load array to setTo function
        m.setFrom("fromEmail@domain.tld"); // who is sending the email
        m.setSubject("subject");
        m.setBody("your message goes here");

        try {
            //m.addAttachment("/sdcard/myPicture.jpg");  // path to file you want to attach
            if(m.send()) {
                // success
                Toast.makeText(getActivity(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
            } else {
                // failure
                Toast.makeText(getActivity() ,"Email was not sent.", Toast.LENGTH_LONG).show();
            }
        } catch(Exception e) {
            // some other problem
            Toast.makeText(getActivity(), "There was a problem sending the email.", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getActivity(), "Нажата кнопка.", Toast.LENGTH_LONG).show();
        sendEmail(v);
    }
}

Стэктрейс:

06-17 17:56:10.732 13330-13330/com.drusilovihi.tabbedapp_b1 E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.ImageButton.findViewById(int)' on a null object reference android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)

A: @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab_fragment_1, container, false);

    imgSend = rootView.findViewById(R.id.imageButton);
    imgSend.setOnClickListener(this);
    m = new Mail("*************", "*******");

    return rootView;
}

A: Вы пытаетесь получить кнопку так:
imgSend.findViewById(R.id.imageButton);

Но таким способом можно получить виджет только в активити. В фрагмегте нужно сначала получить View самой разметки через инфлейт, потом искать уже в этом View свой виджет.
Код в этом ответе . Получаем разметку в rootView, потом ищем свою кнопку в этом rootView, а не в вакууме, как у вас сейчас


text:
Q: Why is this not animating? I implemented corePlot in my xcode project. I have a pie chart that I'm trying to animate. Here is my code:
- (void)configureChart
{
    CPTGraph *graph = self.hostView.hostedGraph;

    CPTPieChart *pieChart = [[CPTPieChart alloc] init];
    pieChart.dataSource = self;
    pieChart.delegate = self;
    pieChart.pieRadius = (self.hostView.bounds.size.height * 0.7) / 2;
    pieChart.startAngle = M_PI_4;
    pieChart.sliceDirection = CPTPieDirectionClockwise;

    [graph addPlot:pieChart];

This is what  I tried:
    CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotation.removedOnCompletion = YES;
    rotation.fromValue = [NSNumber numberWithFloat:0.0f];
    rotation.duration = 1.0f;
    rotation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotation.delegate = self;
    [pieChart addAnimation:rotation forKey:@"rotation"];
}

When I run the app, it doesn't animate. What am I doing wrong, and how can I fix it?
Update 1
I tried the following:
[CPTAnimation animate:pieChart property:@"startAngle" from:pieChart.startAngle to:pieChart.endAngle duration:1.0];

That didn't have the desired effect. The chart would show for a second, then disappear.
Update 2
I'm trying to get this effect: http://jsfiddle.net/ozgr1wfx/
I'm not sure what I'm doing wrong.

A: Don't animate the layer transform. Animate the start angle instead. Otherwise, any labels and other annotations will rotate with the plot.
From the Plot Gallery example app:
[CPTAnimation animate:piePlot
             property:@"startAngle"
                 from:CPTFloat(M_PI_2)
                   to:CPTFloat(M_PI_4)
             duration:0.25];

As noted in the comments, angles are given in radians (pi radians = 180 degrees).

A: I finally got it thanks to @RoryMcKinnel.
[CPTAnimation animate:pieChart property:@"endAngle" from:pieChart.startAngle + M_PI * 2 to:pieChart.startAngle  duration:2.0];

This will animate your pie chart like this: http://jsfiddle.net/ozgr1wfx/.
Again. Thanks to @RoryMcKinnel who put me on the right track to get it!


text:
Q: Is there a way to specify an "empty" C# lambda expression? I'd like to declare an "empty" lambda expression that does, well, nothing.
Is there a way to do something like this without needing the DoNothing() method?
public MyViewModel()
{
    SomeMenuCommand = new RelayCommand(
            x => DoNothing(),
            x => CanSomeMenuCommandExecute());
}

private void DoNothing()
{
}

private bool CanSomeMenuCommandExecute()
{
    // this depends on my mood
}

My intent in doing this is only control the enabled/disabled state of my WPF command, but that's an aside. Maybe it's just too early in the morning for me, but I imagine there must be a way to just declare the x => DoNothing() lambda expression in some way like this to accomplish the same thing:
SomeMenuCommand = new RelayCommand(
    x => (),
    x => CanSomeMenuCommandExecute());

Is there some way to do this? It just seems unnecessary to need a do-nothing method.

A: Assuming you only need a delegate (rather than an expression tree) then this should work:
SomeMenuCommand = new RelayCommand(
        x => {},
        x => CanSomeMenuCommandExecute());

(That won't work with expression trees as it's got a statement body. See section 4.6 of the C# 3.0 spec for more details.)

A: I don't fully understand why do you need a DoNothing method.
Can't you just do:
SomeMenuCommand = new RelayCommand(
                null,
                x => CanSomeMenuCommandExecute());

A: Action doNothing = () => { };

A: I thought I would add some code that I've found useful for this type of situation. I have an Actions static class and a Functions static class with some basic functions in them:
public static class Actions
{
  public static void Empty() { }
  public static void Empty<T>(T value) { }
  public static void Empty<T1, T2>(T1 value1, T2 value2) { }
  /* Put as many overloads as you want */
}

public static class Functions
{
  public static T Identity<T>(T value) { return value; }

  public static T0 Default<T0>() { return default(T0); }
  public static T0 Default<T1, T0>(T1 value1) { return default(T0); }
  /* Put as many overloads as you want */

  /* Some other potential methods */
  public static bool IsNull<T>(T entity) where T : class { return entity == null; }
  public static bool IsNonNull<T>(T entity) where T : class { return entity != null; }

  /* Put as many overloads for True and False as you want */
  public static bool True<T>(T entity) { return true; }
  public static bool False<T>(T entity) { return false; }
}

I believe this helps improve readability just a tiny bit:
SomeMenuCommand = new RelayCommand(
        Actions.Empty,
        x => CanSomeMenuCommandExecute());

// Another example:
var lOrderedStrings = GetCollectionOfStrings().OrderBy(Functions.Identity);

A: This should work:
SomeMenuCommand = new RelayCommand(
    x => {},
    x => CanSomeMenuCommandExecute());

A: Action DoNothing = delegate { };
Action DoNothing2 = () => {};

I used to initialize Events to a do nothing action so it was not null and if it was called without subscription it would default to the 'do nothing function' instead of a null-pointer exception.
public event EventHandler<MyHandlerInfo> MyHandlerInfo = delegate { };

A: Starting with C# 9.0 you can specify discards _ for required parameters. Example:
Action<int, string, DateTime> action = (_, _, _) => { };


text:
Q: Latex compatible code for both siunitx version 1 and 2 On one system, I have siunitx version 1 and on another, I have version 2 (I think).
I already converted my code to be compatible with version 1, so that my table looks like:
\begin{tabular}{@{} |c|S[tabformat=3.2]|c| @{}}
...

And my import looks like:
\usepackage[load-configurations = version-1]{siunitx}

However, that doesn't work with siunitx 1. It throws an error that the load configuration is unknown. The error:
! LaTeX Error: Unknown option `load-configurations' for package `siunitx'.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.3894 \ifx
\@empty\si@emulate\@empty\else
The option `load-configurations' was not declared in package `siunitx', perhaps
you
misspelled its name. Try typing <return> to proceed.
(/usr/share/texmf-texlive/tex/latex/siunitx/config/si-prefix.cfg
File: si-prefix.cfg 2009/09/21 v1.3a siunitx: SI Multiple prefixes

How can I fix this so that it works with both versions?

A: If you want to force version 2 to load the version 1 options without using load-configurations then you can put a v1 option into the load line, for example
\documentclass{article}
\usepackage[tabformat=2.2]{siunitx}
\begin{document}

\SI{10}{\m}

\begin{tabular}{S[tabformat=3.2]}
  123.45 \\
\end{tabular}

\end{document}

Note that the idea of having an explicit option to load the older options is that you really should have the same version of packages across systems.


text:
Q: Cambiar caracteres de un documento HTML por campos de la base de datos Lo que estoy intentando hacer es lo siguiente, tengo una tabla con palabras reservadas como se muestra a continuación:

por otro lado tengo un formato html que tiene incluido etiquetas especiales

y que al momento de obtener el formato este pueda reemplazar las etiquetas especiales por los campos de mi BD.
Nota : la tabla con palabras reservadas no es fijo, es decir puede agregarse mas palabras, al igual que el formato de documento este puede tener una o mas de una etiqueta especial.
El resultado final seria algo así, pero como se observan solo se cambio una etiqueta especial, el query que use para este caso fue

El resultado final deseado es cambiar las etiquetas especiales por los datos de un trabajador y así para el siguiente...

finalmente el query que se realizo no es dinámico, porque si intento hacerlo con subQuery no obtengo el resultado que necesito.

A: Si he entendido bien lo que necesitas, yo te recomiendo que utilices un Cursor para iterar sobre tu tabla de palabras reservadas y una tabla temporal en la que primero copiaremos los registros a modificar y despues vamos actualizando con los cambios realizados en cada iteración, es decir, con cada palabra reservada.
No conozco las tablas así que ajusta el código, pero seria algo asi:
CREATE TABLE #tablaTemporal
(ideTrab int,
desCuer nvarchar(MAX))

INSERT INTO #tablaTemporal
SELECT  ideTrab,
        DesCuer
FROM @FormDocuTrab

DECLARE @codCamp nvarchar(100)
DECLARE @descCamp nvarchar(100)

DECLARE curs CURSOR FOR
    SELECT codCamp, descCamp
    FROM TablaPalabrasReservadas

OPEN curs
FETCH NEXT FROM curs INTO @codCamp, @descCamp
WHILE @@FETCH_STATUS = 0
    BEGIN

        UPDATE #tablaTemporal
        SET DesCuer = REPLACE(t1.DesCuer, @descCamp, t2.NomTrab)
        FROM @FormDocuTrab t1
        INNER JOIN M_Trab t2 ON t2.IdeTrab = t1.IdeTrab

    FETCH NEXT FROM curs INTO @codCamp, @descCamp
    END
CLOSE curs;
DEALLOCATE curs;

SELECT  ideTrab,
        DesCuer
FROM #tablaTemporal

DROP TABLE #tablaTemporal


text:
Q: 404 status error in ajax response of asp .net mvc application after deployment "The page can not be found" error comes to response of ajax in asp .net mvc project after deployment. When I debug everything is fine, ajax works correctly The ajax function is below and works fine while debugging. The server is IIS6; is it about some permissions in sever or anything else?
In View:
@Html.Hidden("url_Prefix", Url.Action("SinavSonuc", "Sonuc"))

In Javascript:
var veri = { 'tcNo': $('input#tcNo').val(), 'evrakSayi': $('input#evrakSayi').val() };
var _url = $('input#url_Prefix').val();

$.ajax({
    url: _url,
    type: 'POST',
    data: veri,
    success: function (result) {
        ...
    },
    error: function (error, textstatus) {
        var errorAlert = JSON.stringify(error);
        alert(errorAlert);
    }
});

A: I solved the problem. The reason is "Verify that file exists" choice was checked in wildcard application map insertion of "C:\WINDOWS\microsoft.net\Framework64\v4.0.30319\aspnet_isapi.dll" at iis6 deployment. I make "Verify that file exists" choice unchecked, and ajax works perfectly.


text:
Q: Low performance in React Native with Redux I have discovered some issues with performance in my react native app. It seems to be caused by react-redux bundle.
As you can see in the video
Redux/Flux/setState comparing
there is a significant delay between action dispatching and view rendering. On real devices it looks even worse.
There are no API calls in this example. Only simple actions dispatching and state changes. On other hand Facebook Flux implementation and simple call of setState work much more faster.
Any ideas how to improve the app performance?
I am using
react: v15.2.1,
react-native: v0.29.2,
react-redux: v4.4.5,
View
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import {Map} from 'immutable';

import * as testActions from '../reducers/test/testActions';
import {Actions} from 'react-native-router-flux';

const actions = [
  testActions
];

function mapStateToProps(state) {
  return {
      ...state
  };
}

function mapDispatchToProps(dispatch) {
  const creators = Map()
          .merge(...actions)
          .filter(value => typeof value === 'function')
          .toObject();

  return {
    actions: bindActionCreators(creators, dispatch),
    dispatch
  };
}

........

<View style={styles.box}>
    {PRICE_FILTERS.map(filter =>{
        let price_cont_style = {};
        let price_text_style = {};
        if (filter.id == PRICE_FILTERS[3].id){
            price_cont_style.marginRight = 0;
        }
        if (filter.id == this.props.test.price){
            price_cont_style.backgroundColor = 'black';
            price_text_style.color = 'white';
        }
        return(
        <TouchableOpacity
            key={filter.id}
            style={[styles.price_cont, price_cont_style]}
            onPress={()=>this.props.actions.setPrice(filter.id)}>
        <Text
            style={[styles.price_text, price_text_style]}>
            {filter.label}
        </Text>
        </TouchableOpacity>
        );
    })}
</View>

......

export default connect(mapStateToProps, mapDispatchToProps)(PerformanceTest);

Actions
const {
    TEST_SET_PRICE,
} = require('../../lib/constants').default;

export function setPrice(filter) {
  return {
    type: TEST_SET_PRICE,
    payload: filter
  };
}

Reducer
const {
    TEST_SET_PRICE,
} = require('../../lib/constants').default;
const InitialState = require('./testInitialState').default;
export default function authReducer(state = InitialState, action) {
  switch (action.type) {

  case TEST_SET_PRICE:
        if (state.price!=action.payload){
            return {price:action.payload}
        } else{
            return state;
        }

    }
    return state;
}

A: As it turned out the cause of this issue is all components from navigation chain are staying unmounted and get rerendered behind of the current scene
See more details here
Possible navigation issue in React Native/Redux app

A: I've noticed that in your video, you have redux-logger enabled, but flux and setState do not log into console.
It might be console.log that causes this performance drop. There is a known issue, here is an explanation.
Try to turn off console logging and see how it affects performance.


text:
Q: When using awk to parse a CSV file, why does it ignore empty cells? I have some scripts which use awk to parse a CSV file. I have noticed that, if a cell is empty, awk simply moves to the next cell. This means, if I ask it to read column 4, but that cell is empty, it prints the data from column 5, e.g.:
echo "1@2@3@@5" | awk -F "@*" '{print $4}'

My expected result is that it will print nothing, because column 4 is empty.

*

*Why is awk skipping column 4?

*How can I get awk to not ignore empty columns?

A: The problem is not what you think. awk is not ignoring empty cells; it is parsing that line as 4 fields instead of 5.
[me@home]$ echo "1@2@3@@5" | awk -F "@*" '{print NF}'
4

That's becuase you're using @* as your field separator which allows one or more consecutive @ as your field separator (@, @@, @@@, ... are all valid field separators).
Try using -F "@" instead.
[me@home]$ echo "1@2@3@@5" | awk -F "@" '{print NF}'
5
[me@home]$ echo "1@2@3@@5" | awk -F "@" '{print $4}'

[me@home]$ echo "1@2@3@@5" | awk -F "@" '{print $5}'
5


text:
Q: How do I build a SQL insert query that allows me to insert a blank into a numeric field? I have some values from an Excel workbook that I'm adding into an array. Eventually, I loop through the array and build a sql insert query (using Excel VBA) with the values stored into the array.
I debugged the sql query string I built and it appears as this:
INSERT INTO RAPTOR_BG.Project_Attributes (
    P-Key,
    Contract_Currency,
    FX_Rate,
    Rate_Discount,
    Study_Award,
    BLD,
    Submitted_Date
)
VALUES (
    '1111111|7-22-2020',
    'USD',
    '0.91',
    '',
    '5-29-2019',
    '',
    '7-22-2020'
);

Both Rate_Discount and BLD are numeric and won't accept ' '. Is there a way to get sql to accept this blank as a null? I did some research and I saw that some people have had success using a case statement, but all of the examples I've seen use variables or something like this (@SomeName) found in the answer here.
I've tried adapting my code to fit the examples I've seen by doing the below, but it kicked an error stating that at least one of the result expressions in a CASE specification must be an expression other than the NULL constant.
*insert statement from before*

VALUES (
    '1111111|7-22-2020',
    'USD',
    '0.91',
    CASE WHEN '' is null then null end,
    '5-29-2019',
    '',
    '7-22-2020'
);

I'm going to be running my code on several hundred workbooks and some of these values will be blank and others won't be so I can't necessarily hardcode a null instead of the ' '. Is there a way to work around getting the numeric fields to accept a blank as null?

A: Ok, I figured this one out. Please find the answer below.
INSERT INTO RAPTOR_BG.Project_Attributes (
    P-Key,
    Contract_Currency,
    FX_Rate,
    Rate_Discount,
    Study_Award,
    BLD,
    Submitted_Date
)
VALUES (
    '1111111|7-22-2020',
    'USD',
    '0.91',
    CASE WHEN '' is null then 0 end,
    '5-29-2019',
    CASE WHEN '' is null then 0 end,
    '7-22-2020'
);


text:
Q: Read binary file with C++ and translate some contents in it I am trying to learn more about binary files, so I started with HexEdit, and I manually wrote a file and created a template for it. Here is my work:

Now, I started working on a console application in C++ Win32 to read the contents in that file and make them look friendly. Here is part my code:
typedef unsigned char BYTE;

long getFileSize(FILE *file)
{
    long lCurPos, lEndPos;
    lCurPos = ftell(file);
    fseek(file, 0, 2);
    lEndPos = ftell(file);
    fseek(file, lCurPos, 0);
    return lEndPos;
}

int main()
{
    const char *filePath = "D:\\Applications\\ColorTableApplication\\file.clt";
    BYTE *fileBuf;          // Pointer to our buffered data
    FILE *file = NULL;      // File pointer

    if ((file = fopen(filePath, "rb")) == NULL)
        printf_s("Could not open specified file\n");
    else {
        printf_s("File opened successfully\n");
        printf_s("Path: %s\n", filePath);
        printf_s("Size: %d bytes\n\n", getFileSize(file));
    }

    long fileSize = getFileSize(file);

    fileBuf = new BYTE[fileSize];

    fread(fileBuf, fileSize, 1, file);

    for (int i = 0; i < 100; i++){
        printf("%X ", fileBuf[i]);
    }

    _getch();
    delete[]fileBuf;
        fclose(file);   // Almost forgot this
    return 0;
}

(I provided that much code because I want to be clear, to help you get the idea about what I am trying to do)
First of all, I need to get the first 14 bytes and write them in the console as text, and then, in a for I need to write something like this for each color:
black      col_id = 1; R = 00; G = 00; B = 00;
red        col_id = 2; R = FF; G = 00; B = 00;
etc...

How can I read and translate these bytes?

A: It is correct as you have it to write out the 14 bytes.
a technique is to create a struct with the layout of your records, then cast e.g. (C-style)
typedef struct
{
  char name[10];
  long col_id;
  unsigned char R;
  unsigned char G;
  unsigned char B;
} rec;

rec* Record = (rec*)(fileBuf + StartOffsetOfRecords);

now you can get the contents of the first record
Record->name, ...

getting next record is just a matter of moving Record forward
++Record;

You could also have a struct for the header to make it more convenient to pickout the number of records, it is good to use stdint.h in order to get well defined sizes. also to pack structures on byte boundary to make sure no padding is done by the compiler i.e. #pragma pack(1) at the top of your source.
typedef struct
{
  char signature[14];
  uint32_t tableaddress;
  uint32_t records;
} header;

typedef struct
{
  char name[10];
  uint32_t col_id;
  unsigned char R;
  unsigned char B;
  unsigned char G;

} rec;

so instead when you read you could do like this
header Header;
rec* Record;

fread(&Header,sizeof(header),1,file);
fread(fileBuf,1,fileSize,file);

Record = (rec*)(fileBuf); // first record can be accessed through Record


text:
Q: How can I optimize my PowerShell - LDAP Query? I have created a script that reads from a CSV (or other dataset, but not posting that side) and creates users in my AD environment.
Basically, whatever dataset is passed into the script will be processed, and then a user will be created if they do not exist. If the user exists in the AD already, then the script skips over the entry. This is a CREATE only script.
It's pretty slow, and I'd like to improve the performance whilst keeping the functionality. Can you give me any tips as to how I can make this perform better?
import-csv "c:\PSScripts\LDAP\ADMigrate.csv" | ForEach-Object {

# Define the User OU
$usersOU = [ADSI] "LDAP://ou=Students, dc=live,dc=tcicollege,dc=edu"

# Check for existing users
$existingUsers = ($usersOU.psbase.children | Where-Object {$_.psBase.schemaClassName -eq "User"} | Select-Object -expand Name)
$userQuery = $existingUsers -contains $_.'AccountName'
if ($userQuery) {
    echo $_.'AccountName' " already exists in Directory."
} else {

    # Create a new user
    $newUser = $usersOU.create("user","cn=" + $_.'AccountName')

    # Set Account AttributesAMAccountName
    $newUser.Put("sAMAccountName", $_.'AccountName')
    $newUser.Put("givenName", $_.'FirstName')
    $newUser.Put("employeeID", $_.'StudentID')
    $newUser.Put("sn", $_.'LastName')
    $newUser.Put("department", $_.'Department')
    $newUser.Put("company", $_.'SyStudentID')
    $newUser.Put("UserPrincipalName", $_.'AccountName' + "@live.tcicollege.edu")
    $newUser.Put("mail", $_.'AccountName' + "@live.tcicollege.edu")
    $newUser.Put("displayName", $_.'LastName' + "," + " " + $_.'FirstName')

    # First Commit
    $newUser.SetInfo()
    $newUser.userAccountControl="66048"
    $newUser.Put("pwdLastset", -1)
    $newUser.SetPassword($_.'Password')

    # Final Commit
    $newUser.SetInfo()
    echo $_.'AccountName' " created successfully."
  }
}

Thank you in advance for any help you can offer.

A: Try the static Exists() method to find if the user exists in the Students OU:
$user = [ADSI]::Exists("LDAP://cn=$($_.AccountName),ou=Students, dc=live,dc=tcicollege,dc=edu")
if(!$user)
{
   "create code goes here"
}

The $usersOU value is static so you can take it out, place it before the import-csv command.


text:
Q: When copying single player world to server, I lose my structures! Whenever I try to copy my customized pvp map that I made in single player, I lose all of the structures that I have created. It is very frustrating as I put some serious time and effort into creating the map. Any help would be much appreciated.

A: Please check in the server.properties if world_name is the same as the name of the world folder which the world is in (e.g. if the name of the world is "Mah Survival Map", world_name has to be "Mah Survival Map" too.)


text:
Q: Find the amount of variation due to another covariate I'm trying to explain a binary outcome (cardiovascular disease) with a categorical predictor (gene level, coded as 0, 1, or 2 depending on the number of risk alleles present).
I'm trying to determine if the effect of the gene on cardiovascular disease is due to its known effect on an additional continuous covariate (blood glucose level), or whether it has a separate mechanism of action on cardiovascular disease. I'm not trying to find that other method of action, just to see if the effect of the gene on cardiovascular disease is due to its known effect on blood glucose, or whether it is independent of this. How, in your opinions, would one go about this? I'm trying to find some new tests that I haven't heard of before.
Here's what I've done/thought of:

*

*I've included an interaction term in the model to test whether the the expression of the gene is modified by the covariate.  I got a significant P for the interaction term, so I know that the effect of the gene on the response is modified by the covariate.

*I've looked at the Nagelkerke's pseudo R2 for a model with only the gene, only the covariate, and both of them together.  I've found that the R2 of the combined models is less than the sum of the individual models (only by about 0.9%).  From this I thought that since the gene explained ~ 2% of variation alone, but only added an additional ~1.1% of variation when taked onto the covariate only model, that part of the explained variance of the gene is actually due to its effect on the covariate.
i.e. R2Gene only = ~0.02; R2Covariate only = ~0.2; R2Gene and coariate = ~0.211.  So alone it explained ~ 2% variation, but when the covariate was included in the model, it only added 1.1% of variation.  Is it legitimate to say that some portion of the variation explained by the gene is actually due to the variation in covariate?
So my question is: a) are these things that I've done kosher, and b) how would I go about finding whether the variation explained by the gene is actually explained by the gene's effect on a covariate.
Thank you for your time, any and all opinions are valuable and helpful.

A: You may want to look at modeling the system as a set of directed acyclic graphs. Given gene (G), glucose level (L) and outcome (O), there are a few possible combinations:
1) G -> L -> O # gene affects blood glucose level which in turn affects outocome
2) (X -> G) & (X -> L) -> O # A third unknown parameter (such as population structure) affects both gene and glucose level, which in turn affect outcome
3) G -> O & L -> O # Both gene and glucose level independently affect outcome
4) G -> O -> L # Gene affects outcome which is in turn reflected in the glucose level
You can pose these models as sets of regression equations and check which model is best fit for you data, based on their prior and likelihoods.
These slides have a good introduction and references therein.


text:
Q: How to Use Laravel Passport Token System I am planning to use Laravel Passport System for the ANGULAR 6 API. Installed as per the documentation.
But I have a bit of confusion. Please try to Resolve It.
1. How to provide a token ?
This is the Correct Method?
https://stackoverflow.com/questions/54201827/how-to-use-laravel-passport-access-tokens

OR
Coding LIKE is correct Method ?:
$request->request->add([
            'username' => $request->email,
            'grant_type' => 'password',
            'client_id' => env('PASSWORD_CLIENT_ID'),
            'client_secret' => env('PASSWORD_CLIENT_SECRET'),
            'scope' => '',
]);
// forward the request to the OAuth token request endpoint and Return Token

$res = Route::dispatch(request()->create('oauth/token', 'POST', $this->loginCredentials($request)));
$this->api_response = json_decode($res->getContent());
return response()->json(['token' => $this->api_response,'usersDetail' =>  $user], 200);

Which Method need to use and Why Please Elaborate it.?
2. How to handle Refresh Token System for Angular?
Like in Refresh (Mouse button Refresh) need to Call Laravel API? How It should be? Please elaborate with Laravel and Angular Codes.
please answer this question Detaily. looking for a good Answer!!!

A:
How to provide a token ?
  This is the Correct Method?
  OR Coding LIKE is correct Method ?

It uses a different grant. The correct method is according to your application needs. Before you implement OAuth, you need to learn about grant types :
Authorization code grant
The authorization code grant should be very familiar if you've ever signed into an application using your Facebook or Google account.
Implicit grant
The implicit grant is similar to the authorization code grant with two distinct differences.
It is intended to be used for user-agent-based clients (e.g. single page web apps) that can't keep a client secret because all of the application code and storage is easily accessible.
Secondly instead of the authorization server returning an authorization code which is exchanged for an access token, the authorization server returns an access token
Resource owner credentials grant
This grant is a great user experience for trusted first party clients both on the web and in native device applications.
Client credentials grant
The simplest of all of the OAuth 2.0 grants, this grant is suitable for machine-to-machine authentication where a specific user's permission to access data is not required.
Refresh token grant
Access tokens eventually expire; however some grants respond with a refresh token which enables the client to get a new access token without requiring the user to be redirected.

Which OAuth 2.0 grant should I use?
A grant is a method of acquiring an access token. Deciding which grants to implement depends on the type of client the end user will be using, and the experience you want for your users.

How to handle Refresh Token System for Angular?

Access tokens eventually expire; The client sends a POST request with following body parameters to /oauth/token:

*

*grant_type with the value refresh_token

*refresh_token with the refresh token

*client_id with the the client's ID

*client_secret with the client's secret

*scope with a space-delimited list of requested scope permissions. This is optional; if not sent the original scopes will be used, otherwise you can request a reduced set of scopes.

$http = new GuzzleHttp\Client;

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'refresh_token',
        'refresh_token' => 'the-refresh-token',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'scope' => '',
    ],
]);

return json_decode((string) $response->getBody(), true);

Or you can using Angular HTTPInterceptor for token refreshing. HTTP Interceptors are used for adding custom logic for logging, modifying response, error handling, but one common case is to automatically attach authentication informations to request and to refresh token in order to maintain user session active.

Ref :

*

*https://oauth.net/

*https://alexbilbie.com/guide-to-oauth-2-grants/


text:
Q: Convert video files for Maemo (Nokia N900) using ffmpeg/mencoder I'm a newbie in video encoding so I'm looking for some expert advice.
I'm looking to transcode media files with ffmpeg or mencoder (or something other) on Ubuntu for my Nokia N900 running Maemo.
I'd prefer mencoder, because of ffmpeg's crazy dependencies.

*

*Video output should be AVC/H.264 (probably hardware accelerated on device).

*Audio output in AAC (should have preferred Vorbis but not supported natively and requires .mkv which is also not completely supported).

*Output video should retain the original aspect ratio.

*Resolution of screen is 800x480 (16:10).

(Explanation of why-this-value-is-chosen would be really appreciated).

A: If you are a newbie as you're saying, Handbrake might be more your thing. It's available for Mac OS X, Linux and Windows. Last I checked it was in Ubuntu's repositories, but here's a PPA just to be sure.

I've had good results on my N900 with the following settings:
Container: MP4 file (MKV files are not supported by the N900 by default.)
iPod 5G support: on (Just in case you decide to share a video with an Apple-loving friend.)
Picture:
Width: 400px (Although the horizontal resolution of the N900 is 800px, video tends to skip for me at that resolution.)
Keep aspect ratio: on
Video:
Video codec: H.264 (Results in smaller files than ffmpeg; both work though.)
Avg. bitrate: 500/600kbps
2-Pass encoding: on
Audio:
Audio codec: AAC (faac) (Most compatible, best sound quality.)
Mixdown: Stereo (You only have two speakers or a headphone, why waste bandwidth on more channels?)
Bitrate: 64/80/96/128kbps (If you have good headphones, go with 96/128kbps.)
All other options may be left unchanged (or feel free to experiment).

A: Here is the code I written in Ruby. It uses ffmpeg to encode and does some calculations to determine the correct size/resolution of output to preserve the original aspect ratio.
http://code.google.com/p/vikrant-incubator/source/browse/ruby/ffmpeg_n900.rb

A: I found the command-line tool xvidenc did a good job for a similar device (Open Pandora).  xvidenc is a Q&A style front-end to mencoder.  It is not so easy to use mencoder or ffmpeg directly, if you desire a good result!
There is a similar tool h264enc, which can make video that matches your specific requirements; but I recommend to use xvid.
These tools allow to save the commands to a shell script, you can then edit it and apply it to different files.  I changed the filters so that my videos are first scaled to height 480, then cropped to 800x480.  It seems to work well.
You could also try avconv, the new version of ffmpeg.
I'll update this answer with a link to my encoding scripts (based on xvidenc and h264enc).


text:
Q: xamarin.forms entry binding on blur It appears the default binding trigger for an entry text is the TextChanged event.  I want to defer updating the source until the blur event.    In WPF there was the UpdateSourceTrigger parameter that could be set to modify the binding trigger, but there isn't any documentation I've found on this in Xamarin.Form.
How can that be achieved in Xaramin.Forms with binding in XAML.   For obvious reasons, I don't want to manually handle it in the code behind.

A: This question is old but still actual. Especially for fields with decimal point...
First option to use Xamarin Community Toolkit EventToCommandBehavior (or similar implementations, like Prism). Then possible to bind "Unfocused" event to some command:
    <Entry.Behaviors>
    <xct:EventToCommandBehavior
        EventName="Unfocused"
        Command="{Binding MyCustomCommand}" />
    </Entry.Behaviors>

Other option to add custom Entry component that handle this event, this option fits me better with numeric input with decimal point (float, double, decimal). This a little modified solution from MSDN forum Entry binding Decimal:
public class NumericEntry : Entry
    {
        #region Bindables

        public static readonly BindableProperty NumericValueProperty = BindableProperty.Create(
            "NumericValue",
            typeof(decimal?),
            typeof(NumericEntry),
            null,
            BindingMode.TwoWay,
            coerceValue: (_, value) => (decimal?)value,
            propertyChanged: (bindable, _, __) => SetDisplayFormat((NumericEntry)bindable)
        );

        public static readonly BindableProperty NumericValueFormatProperty = BindableProperty.Create(
            "NumericValueFormat",
            typeof(string),
            typeof(NumericEntry),
            "N0",
            BindingMode.TwoWay,
            propertyChanged: (bindable, _, __) => SetDisplayFormat((NumericEntry)bindable)
        );

        #endregion Bindables

        #region Constructor

        public NumericEntry()
        {
            Keyboard = Keyboard.Numeric;
            Focused += OnFocused;
            Unfocused += OnUnfocused;
        }

        #endregion Constructor

        #region Events

        private void OnFocused(object sender, FocusEventArgs e)
        {
            SetEditFormat(this);
        }

        private void OnUnfocused(object sender, FocusEventArgs e)
        {
            var numberFormant = CultureInfo.CurrentCulture.NumberFormat;
            var _text = Text.Replace(".", numberFormant.NumberDecimalSeparator);

            if (decimal.TryParse(_text, NumberStyles.Number, CultureInfo.CurrentCulture, out var numericValue))
            {
                var round = Convert.ToInt32(NumericValueFormat.Substring(1));
                NumericValue = Math.Round(numericValue, round);
            }
            else
            {
                NumericValue = null;
            }

            SetDisplayFormat(this);
        }

        #endregion Events

        #region Properties

        public decimal? NumericValue
        {
            get => (decimal?)GetValue(NumericValueProperty);
            set => SetValue(NumericValueProperty, value);
        }

        public string NumericValueFormat
        {
            get => (string)GetValue(NumericValueFormatProperty) ?? "N0";
            set
            {
                var _value = string.IsNullOrWhiteSpace(value) ? "N0" : value;
                SetValue(NumericValueFormatProperty, _value);
            }
        }

        #endregion Properties

        #region Methods

        private static void SetDisplayFormat(NumericEntry textBox)
        {
            if (textBox.NumericValue.HasValue)
            {
                textBox.Text = textBox.NumericValue.Value.ToString(textBox.NumericValueFormat, CultureInfo.DefaultThreadCurrentCulture);
            }
            else
            {
                textBox.Text = string.Empty;
            }
        }

        private static void SetEditFormat(NumericEntry textBox)
        {
            if (textBox.NumericValue.HasValue)
            {
                var numberFormant = CultureInfo.CurrentCulture.NumberFormat;
                textBox.Text = textBox.NumericValue.Value.ToString(textBox.NumericValueFormat, CultureInfo.CurrentCulture).Replace(numberFormant.NumberGroupSeparator, string.Empty);
            }
            else
            {
                textBox.Text = string.Empty;
            }
        }

        #endregion Methods
    }

And use it like this:
       // import our component
       xmlns:ex="clr-namespace:BoganPos.Extensions"
       //...
       <ex:NumericEntry NumericValue="{Binding DecimalValue}" NumericValueFormat="F2" Placeholder="Placeholder"/>


text:
Q: TypeScript separator operator behave strange Here is the code:
declare function test1<T extends unknown[]>(value: T): T
const res1 = test1([1, 2, 3]) // type is number[]

declare function test2<T extends unknown[]>(value: [...T]): T
const res2 = test2([1, 2, 3]) // type is [number,number,number]

Playground
as you can see, if I use ... separator operator , I got totally different result type, and I think [...T] is same with T,because T extends  array.
is it a feature I should keep in mind and move on?

A: It's a feature, be it not a very well-documented one. If you check this PR on Variadic tuple types, the section Spreads in array literals contains

The type [...T], where T is an array-like type parameter, can conveniently be used to indicate a preference for inference of tuple types:

declare function ft1<T extends unknown[]>(t: T): T;
declare function ft2<T extends unknown[]>(t: T): readonly [...T];
declare function ft3<T extends unknown[]>(t: [...T]): T;
declare function ft4<T extends unknown[]>(t: [...T]): readonly [...T];

ft1(['hello', 42]);  // (string | number)[]
ft2(['hello', 42]);  // readonly (string | number)[]
ft3(['hello', 42]);  // [string, number]
ft4(['hello', 42]);  // readonly [string, number]

It allows you to pass an array as a tuple without having to add as const (which makes the array and its elements read-only).


text:
Q: ¿Como añado una linea a un log?  if os.path.exists('login.txt'):
     print ("El fichero login.txt existe")
 else:
     print ("El fichero login.txt no existe o la ruta en la que se encuentra es diferente")

¿Cuando el bucle me sale por el else, como puedo añadir esa línea a un log?
¿Hay algún código de retorno en Python como en linux el $? ?

A: No entiendo la relación (si la hay) entre las dos preguntas que pones al final.
Para enviar mensajes a un log puedes simplemente abri el fichero de log en modo append ("a") y usar fichero.write(), o utilizar el paquete logging si tienes necesidades más avanzadas (advertencia, no es apto para principiantes).
Respecto al código de retorno, entiendo que te refieres a que si puedes enviar al shell un exit status, para que éste pueda usarlo como parte de un shell script. La respuesta es afirmativa. Puedes usar sys.exit(codigo_de_salida). Las funciones quit() y exit() también sirven de la misma forma (pues por debajo invocan a sys.exit())

A: *

*En un Notebook:

Puedes ejecutar comandos linux en Python añadiendo ! delante de la linea
Ejemplo:
!echo 'El fichero login.txt no existe o la ruta en la que se encuentra es diferente' >> log_file_path

*En un fichero Python (con extensión .py):

En este caso se puede usar la librería os (función os.system("comando")).
Ejemplo:
import os
os.system("echo 'El fichero login.txt no existe o la ruta en la que se encuentra es diferente' >> log_file_path")
En cuanto a la función de retorno, tal y como se ha comentado, puedes usar la función quit() o sys.exit("Error msg") si quieres mostrar algun error por consola


text:
Q: How keep child object rotation, after remove from parent object I created four objects, and added to the pivot1 object, like mrdoob example in this issue: https://github.com/mrdoob/three.js/issues/1830#issuecomment-5392158, to rotate the four objects around the x-axis pivot1. But after rotate, the individual positions of the four objects are not updated. if I remove the four objects pivot1 they return to starting position.
I need to rotate the four objects in the x-axis and thereafter be able to rotate on the Y axis and Z axis.
How do I do that?
EDIT
Here the code in JSFiddle: http://jsfiddle.net/tKQP6
This is the portion of code that I try to remove from a pivot to use with another.
function clear(pivot) {
    moveEnabled = true;
    for (var i in movedCubes) {
        pivot.remove(movedCubes[i]);
        scene.add(movedCubes[i]);
    }
    movedCubes = [];
}


text:
Q: How to create an object with relationship? i have two models, i want to create an object Theme, so far i can create Product but i can not create Theme, i dont know why
class Product < ApplicationRecord
  has_many :themes
end

and
class Theme < ApplicationRecord
  belongs_to :products

end

with this function i am trying to create
  def create
    @product = Product.find(3)
    @theme = Theme.create(title:'theme' ,description:'description',  products_id: @product)
  end

my migrations are:
class CreateProducts < ActiveRecord::Migration[7.0]
  def change
    create_table :products do |t|
      t.string :name
      t.string :description
      t.integer :price

      t.timestamps
    end
  end
end

and
class CreateThemes < ActiveRecord::Migration[7.0]
  def change
    create_table :themes do |t|
      t.string :title
      t.string :description
      t.belongs_to :products, null: false, foreign_key: true

      t.timestamps
    end
  end
end

i am getting this warning error with this sentence
@theme = Theme.create(title:'theme' ,description:'description',  products_id: @product.id)

this error:
"#<NameError: Rails couldn't find a valid model for Products association. Please provide the :class_name option on the association declaration. If :class_name is already provided, make sure it's an ActiveRecord::Base subclass.\n\n          raise NameError, msg\n          ^^^^^>",

A: Firstly your association and migration are wrong. By convention when you use belongs_to, you need to use singular, not plural
To fix schema, you need to create new migration (usually changing old migrations is bad idea)
change_table :themes do |t|
  t.remove_belongs_to :products, null: false, foreign_key: true
  t.belongs_to :product, null: false, foreign_key: true
end

This will create product_id and delete products_id column in themes table
Than change association to
class Theme < ApplicationRecord
  belongs_to :product
end

And finally to create theme of specific product:
product.themes.create(title: 'theme', description: 'description')

product_id will assign automatically, you don't need specify it


text:
Q: Is there a way to selectively override standard theorem labeling *with* cleveref and hyperref support? I have the following problem:

*

*Document with many different 'types' of theorem, e.g., "theorem", "lemma", "proposition", etc. These are defined in the usual (amsthm) way using environments kttheorem, ktlemma, ktprop, etc.

*In the document proper (not the appendix), suppose chapter 5 contains two theorems: a proposition with label pugsrcute and a theorem with label pugsrsmart. When the document is compiled, these happen to be called Prop. 5.1 and Theorem 5.2 respectively.

*The proof of pugsrcute happens to be quite long and refers to a supporting lemma and a supporting proposition. As a result, the proof of pugsrcute as well as the supporting theorems are placed in the appendix.

*In the appendix, ideally I'd like to be able to insert the following:
\begin{supportfor}{pugsrsmart}
    \begin{ktlemma}
        \label{pugsrsmall}
        ...
    \end{ktlemma}

    \begin{ktprop}
        \label{smalldogsrcute}
        ...
    \end{ktprop}
\end{supportfor}

and have the theorem environments inside supportfor behave normally in all respects except that instead of using the standard numbering scheme, the theorems appear as "Lemma 5.1(a)" and "Proposition 5.1(b)", where 5.1 is the number of label pugsrsmart and where "a" and "b" are the first two letters in alphabetic sequence.

*The \crefs to pugsrsmall and smalldogsrcute would likewise expand to values that respect this alternate numbering scheme, with proper hyperlinks. Hence, \cref{pugsrsmall} would expand to "Lemma 5.1(a)" with "5.1(a)" hyperlinked, and \cref{smalldogsrcute} would expand to "Prop. 5.1(b)", with "5.1(b)" hyperlinked.

Question
Is selective overriding of theorem labeling in this way possible?
MWE
\documentclass{article}

\usepackage{amsthm}
\usepackage[
    colorlinks,
    final,
    hyperfootnotes = false,
    linkcolor      = blue,
    citecolor      = blue]{hyperref}
\usepackage[capitalize]{cleveref}

% environments for theorems and lemmas
\NewDocumentCommand{\ktnewtheorem}{ommm}{  % \ktnewtheorem[usecounter]{type}{Long}{short}
    \IfNoValueTF{#1}
        {\newtheorem {#2} {#3} [section]}
        {\newtheorem {#2} [#1] {#3}}

    \crefname {#2} {#4} {\MakeLowercase{#3}}
    \Crefname {#2} {#4} {#3}
}

\ktnewtheorem            {kttheorem} {Theorem}     {Theorem}
\ktnewtheorem[kttheorem] {ktlemma}   {Lemma}       {Lemma}
\ktnewtheorem[kttheorem] {ktprop}    {Proposition} {Prop.}
\ktnewtheorem[kttheorem] {ktcor}     {Corollary}   {Cor.}

% ktrestate (restate theorem/proposition/lemma/etc.) environment
\newenvironment {ktrestate} [2] [0pt]
    {\vspace{#1}\noindent\textbf{\Cref{#2}.}\hspace{2pt}\begingroup\em}
    {\endgroup}

% placeholder \supportfor{label}; magic should happen here!
\newenvironment {supportfor} [1]
    {\begingroup}
    {\endgroup}

\begin{document}
\setcounter{section}{4}
\section{Pugs}

The following \namecrefs{pugsrcute} was first proved by Leonhard Euler in 1760.

\begin{ktprop}
    \label{pugsrcute}
    Let $c_{\mathrm{pug}}$ be the cuteness factor of a pug.
    Then $c_{\mathrm{pug}} \geq 8\pi^{-1}$ a.s.
\end{ktprop}
\begin{proof}
    See \cref{pugproofs} for proof.
\end{proof}

\noindent Euler hit another home run in 1762.

\begin{kttheorem}
    \label{pugsrsmart}
    Let $P$ be a pug. Then $P$ is as least as intelligent as an Artin representation
    of degree $2$.
\end{kttheorem}
\begin{proof}
    The result follows logically from the fact that abelian L-functions are
    meromorphic for non-trivial characters, and $P$ looks kind of like an L-function
    if you squint really hard.
\end{proof}

\newpage
\section{Appendix}
\label{pugproofs}

First, we prove some supporting results.

\begin{supportfor}{pugsrcute}
    \begin{ktlemma} % Currently "Lemma 6.1"; Should be "Lemma 5.1(a)"
        \label{pugsrsmall}
        Pugs are small.
    \end{ktlemma}
    \begin{proof}
        Just look at them.
    \end{proof}

    \begin{ktprop} % Currently "Proposition 6.2"; Should be "Proposition 5.1(b)"
        \label{smalldogsrcute}
        Small dogs are cute.
    \end{ktprop}
    \begin{proof}
        The result follows from Fermat's celebrated treatise ``On the Adorableness of
        Dogs and Other Small Mammals''.
    \end{proof}
\end{supportfor}

% The following \cref currently expands to "Lemma 6.1 and Prop 6.2". NO!
% Should expand to "Lemma 5.1(a) and Prop. 5.1(b)"!
\noindent Now, we use \cref{pugsrsmall,smalldogsrcute} in the proof of \cref{pugsrcute}.

\begin{ktrestate}[3mm]{pugsrcute}
    Let $c_{\mathrm{pug}}$ be the cuteness factor of a pug.
    Then $c_{\mathrm{pug}} \geq 8\pi^{-1}$ a.s.
\end{ktrestate}
\begin{proof}
    % The following \cref's expand to "Lemma 6.1" and "Prop 6.2". NO!
    % Should expand to "Lemma 5.1(a)" and "Prop 5.1(b)".
    The result follows from \cref{pugsrsmall}, mixed with \cref{smalldogsrcute},
    baked at $350^\circ$ for $25$ minutes, and seasoned to taste.
\end{proof}

\end{document}

Added: Best I Can Do
The following is the best solution I've come up with this far. The compiled document looks right, but there are a number of problems identified in the code.
\documentclass{article}

\usepackage{amsthm}
\usepackage{etoolbox}
\usepackage[
    colorlinks,
    final,
    hyperfootnotes = false,
    linkcolor      = blue,
    citecolor      = blue]{hyperref}
\usepackage[capitalize]{cleveref}

% environments for theorems and lemmas
\NewDocumentCommand{\ktnewtheorem}{ommm}{  % \ktnewtheorem[usecounter]{type}{Long}{short}
    \IfNoValueTF{#1}
        {\newtheorem {#2} {#3} [section]}
        {\newtheorem {#2} [#1] {#3}}

    \crefname {#2} {#4} {\MakeLowercase{#3}}
    \Crefname {#2} {#4} {#3}
    %% ADDED
    \expandafter\def\csname #2Long\endcsname{#3}
    \expandafter\def\csname #2long\endcsname{\MakeLowercase{#3}}
    \expandafter\def\csname #2short\endcsname{#4}
    %% END ADDED
}

\ktnewtheorem            {kttheorem} {Theorem}     {Theorem}
\ktnewtheorem[kttheorem] {ktlemma}   {Lemma}       {Lemma}
\ktnewtheorem[kttheorem] {ktprop}    {Proposition} {Prop.}
\ktnewtheorem[kttheorem] {ktcor}     {Corollary}   {Cor.}

% ktrestate (restate theorem/proposition/lemma/etc.) environment
\newenvironment {ktrestate} [2] [0pt]
    {\vspace{#1}\noindent\textbf{\Cref{#2}.}\hspace{2pt}\begingroup\em}
    {\endgroup}

% placeholder \supportfor{label}; magic should happen here!
\newenvironment {supportfor} [1]
    {\begingroup}
    {\endgroup}

%% BEST I CAN DO
% Problems:
%  - Uses \begin{ktsuppthm}{theoremenv}{label}{extension} rather than the desired
%       \begin{supportfor}{label}
%          \begin{theoremenv}
%    syntax.
%  - Requires all supplemental theorems to be declared in advance (i.e. in document
%    preamble).
%  - Requires proof definitions to specify their extension rather than assigning
%    them automatically.
%  - Requires writing to the .aux file, and is generally hackish.
%  - Version below only supports supplemental theorems for ONE theorem. Support for
%    more would be even messier.

\makeatletter
\def\csxdefaux#1#2{%
    \protected@write\@mainaux{}{%
        \csgdef{\detokenize{#1}}{#2}%
    }%
}
\makeatother

\newcommand* {\ktdefsuppthm} [1] {
    \expandafter\gdef\csname ktsuppthmext#1\endcsname{?}
    \expandafter\gdef\csname ktsuppthmshort#1\endcsname{?}
    \expandafter\gdef\csname ktsuppthmlong#1\endcsname{?}
    \expandafter\gdef\csname ktsuppthmLong#1\endcsname{?}
    \crefname {ktsuppthm#1} {\csname ktsuppthmshort#1\endcsname} {\csname ktsuppthmlong#1\endcsname}
    \Crefname {ktsuppthm#1} {\csname ktsuppthmshort#1\endcsname} {\csname ktsuppthmLong#1\endcsname}
    \creflabelformat {ktsuppthm#1} {\hyperlink
        {L\csname ktsuppthmext#1\endcsname.#1}
        {\labelcref*{\csname ktsuppthmext#1\endcsname}(#1)}}

    \expandafter\newcommand \csname supplabel#1\endcsname [2] {%  \supplabel<x> {type} {label}
        \raisebox{12pt}{\hypertarget {L##2.#1} {}}%
        \csxdefaux{ktsuppthmext#1}{##2}%
        \csxdefaux{ktsuppthmshort#1}{\csname ##1short\endcsname}%
        \csxdefaux{ktsuppthmlong#1}{\csname ##1long\endcsname}%
        \csxdefaux{ktsuppthmLong#1}{\csname ##1Long\endcsname}%
        \expandafter\gdef\csname ktsuppthmext#1\endcsname{##2}%
        \expandafter\gdef\csname ktsuppthmshort#1\endcsname{\csname ##1short\endcsname}%
        \expandafter\gdef\csname ktsuppthmlong#1\endcsname{\csname ##1long\endcsname}%
        \expandafter\gdef\csname ktsuppthmLong#1\endcsname{\csname ##1Long\endcsname}%
        \label[ktsuppthm#1]{##2.#1}%
    }
}

\ktdefsuppthm{a}
\ktdefsuppthm{b}

\newenvironment {ktsuppthm} [4] [0pt]  % ktsuppthm [leadvspc]{type}{label}{ext}
    {%
        \vspace{#1}\noindent\csname supplabel#4\endcsname{#2}{#3}%
        \textbf{\csname #2Long\endcsname~\labelcref*{#3}(#4).}\hspace{5pt}\begingroup\em%
    }
    {\endgroup}
%% END BEST I CAN DO

\begin{document}
\setcounter{section}{4}
\section{Pugs}

The following \namecrefs{pugsrcute} was first proved by Leonhard Euler in 1760.

\begin{ktprop}
    \label{pugsrcute}
    Let $c_{\mathrm{pug}}$ be the cuteness factor of a pug.
    Then $c_{\mathrm{pug}} \geq 8\pi^{-1}$ a.s.
\end{ktprop}
\begin{proof}
    See \cref{pugproofs} for proof.
\end{proof}

\noindent Euler hit another home run in 1762.

\begin{kttheorem}
    \label{pugsrsmart}
    Let $P$ be a pug. Then $P$ is as least as intelligent as an Artin representation
    of degree $2$.
\end{kttheorem}
\begin{proof}
    The result follows logically from the fact that abelian L-functions are
    meromorphic for non-trivial characters, and $P$ looks kind of like an L-function
    if you squint really hard.
\end{proof}

\newpage
\section{Appendix}
\label{pugproofs}

First, we prove some supporting results.

%\begin{supportfor}{pugsrcute}
    \begin{ktsuppthm}{ktlemma}{pugsrcute}{a}% should be: \begin{ktlemma}
        %\label{pugsrsmall}
        % This implementation automatically makes the label pugsrcute.a.
        Pugs are small.
    \end{ktsuppthm}
    \begin{proof}
        Just look at them.
    \end{proof}

    \begin{ktsuppthm}{ktprop}{pugsrcute}{b}% should be: \begin{ktprop}
        %\label{smalldogsrcute}
        % This implementation automatically makes the label pugsrcute.b.
        Small dogs are cute.
    \end{ktsuppthm}
    \begin{proof}
        The result follows from Fermat's celebrated treatise ``On the Adorableness of
        Dogs and Other Small Mammals''.
    \end{proof}
%\end{supportfor}

% Should expand to "Lemma 5.1(a) and Prop. 5.1(b)".
\noindent Now, we use \cref{pugsrcute.a,pugsrcute.b} in the proof of \cref{pugsrcute}.

\begin{ktrestate}[3mm]{pugsrcute}
    Let $c_{\mathrm{pug}}$ be the cuteness factor of a pug.
    Then $c_{\mathrm{pug}} \geq 8\pi^{-1}$ a.s.
\end{ktrestate}
\begin{proof}
    % Should expand to "Lemma 5.1(a)" and "Prop 5.1(b)".
    The result follows from \cref{pugsrcute.a}, mixed with \cref{pugsrcute.b},
    baked at $350^\circ$ for $25$ minutes, and seasoned to taste.
\end{proof}

\end{document}

A: Try with
\newenvironment {supportfor} [1]
    {\renewcommand\thekttheorem{\ref{#1}(\alph{kttheorem})}}
    {}


text:
Q: Null values needs to be displayed in Mongo DB through POJO class I have a Spring batch application written on top of spring boot framework, it is used to read  data from oracle database(using JDBCcursorItemreader) and write to Mongo Database(MongoItemWriter).For each table i'm having a POJO class .Null value field not displaying in mongo collection.By default searilaization omitting the null value columns are omitting and displaying only the non null columns.
is there any other property to include the null fields in mongo DB?
ex: Oracle table

Mongo Collection:
{
"Name":"xyz",
"Number":"16"
}

Want below format:
{
"Name":"xyz",
"Number":"16",
"Date" : null
}

I want to display the date column in mongo DB.I have tried with jsoninclude properties.it is not working. Can anyone suggest on this?
My Code:
Batch File:
package com.sam.oracletomongo;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.flow.support.SimpleFlow;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.partition.PartitionHandler;
import org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler;
import org.springframework.batch.item.data.MongoItemWriter;
import org.springframework.batch.item.data.builder.MongoItemWriterBuilder;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.batch.item.database.support.ListPreparedStatementSetter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.mongodb.core.MongoTemplate;

@Configuration
@EnableBatchProcessing
@Import(AdditionalBatchConfiguration.class)
public class BABatchConfig  {
    @Autowired
    public DataSource datasource;
    @Autowired
    public MongoTemplate mongotemplate;

     @Autowired
        public JobBuilderFactory jobBuilderFactory;
        @Autowired
        public StepBuilderFactory stepBuilderFactory;
        @Bean
        @StepScope
        public JdbcCursorItemReader<BA> itemReaderBA(@Value("#{jobParameters[deltadate]}") String deltadate,@Value("#{jobParameters[rundate]}") String rundate) {
            ListPreparedStatementSetter listPreparedStatementSetter = new ListPreparedStatementSetter();
            List<String> l1=new ArrayList<String>();
            l1.add(deltadate);
            l1.add(rundate);
            listPreparedStatementSetter.setParameters(l1);
            return new JdbcCursorItemReaderBuilder<BA>()
                .dataSource(datasource) // change accordingly if you use another data source
                .name("fooReader")
                .sql("SELECT SA_NO,SA_NAME,DATE1,DATE2,DATE3,ACTIVE FROM SAMPLE WHERE DATE2 between TO_DATE(?,'YYYY-MM-DD') and TO_DATE(?, 'YYYY-MM-DD')")
                .rowMapper(new BARowMapper())
                .preparedStatementSetter(listPreparedStatementSetter)
                .build();
        }
        @Bean
        public MongoItemWriter<BA> writerBA(MongoTemplate mongoTemplate) {

            return new MongoItemWriterBuilder<BA>().template(mongoTemplate).collection("BA")
                    .build();
        }

        @Bean
public Job BAJob() {

            return jobBuilderFactory.get("BA")
                    .incrementer(new CustomParametersIncrementerImpl(datasource))
                    .start(BAstep())
                    .build();
        }

        @Bean
        public Step BAstep() {
            return stepBuilderFactory.get("BAStep1")
                    .<BA, BA> chunk(10)
                    .reader(itemReaderBA(null,null))
                    .writer(writerBA(mongotemplate))

                    .build();
        }

}

Model Class:

package com.sam.oracletomongo;

public class BA {

private String _id;
private String saNo;
private String saName;
private String Date1;
private String Date2;
private String Date3;
private String active;

public String get_id() {
    return _id;
}
public void set_id(String _id) {
    this._id = _id;
}
public String getsaNo() {
    return saNo;
}
public void setBaNo(String saNo) {
    this.saNo = saNo;
}
public String getsaName() {
    return saName;
}
public void setBaName(String saName) {
    this.saName = saName;
}
public String getDate1() {
    return Date1;
}
public void setDate1(String Date1) {
    this.Date1 = Date1;
}
public String getDate2() {
    return Date2;
}
public void setDate2(String Date2) {
    this.Date2 = Date2;
}
public String getDate3() {
    return Date3;
}
public void setDate3(String Date3) {
    this.Date3 = Date3;
}
public String getActive() {
    return active;
}
public void setActive(String active) {
    this.active = active;
}
@Override
public String toString() {
    return "BA [_id=" + _id + ", saNo=" + saNo + ", saName=" + saName + ", Date1=" + Date1 + ", Date2="
            + Date2 + ", Date3=" + Date3 + ", active=" + active + "]";
}

}

Mapper Class:
package com.sam.oracletomongo;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

public class BARowMapper implements RowMapper<BA> {

    public BA mapRow(ResultSet rs, int rowNum) throws SQLException
    {
            BA ba = new BA();
            String id=rs.getString("sA_NO");
            ba.set_id(id);
            ba.setsaNo(rs.getString("sA_NO"));
            ba.setsaName(rs.getString("sA_NAME"));
            ba.setDate1(rs.getString("DATE1"));
            ba.setDate2(rs.getString("DATE2"));
            ba.setDate3(rs.getString("DATE3"));
            ba.setActive(rs.getString("ACTIVE"));
            return ba;
    }

}

A: This $project stage can help you:
  {
    "$project": {
      _id: 0,
      "name": 1,
      "number": 1,
      "Date": {
        "$ifNull": [
          "$Date", //If the Date field is not null
          "null" //If the Date field is null write string 'null' to the field
        ]
      }
    }
  }


text:
Q: How many number square-free integer from 1 to 2013 Question:
Let $Q(x)$ denote the number of square-free (quadratfrei) integers between $1$ and $x$
find $Q(2013)=?$
My try:I know $ 1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39,\cdots $ Square-free integer,and How many numbers square-free integer from 1 to $2013$?
see http://en.wikipedia.org/wiki/Square-free_integer
I know that
Let $Q(x)$ denote the number of square-free (quadratfrei) integers between $1$ and $x$
then
$$Q(x)\approx \dfrac{6x}{\pi^2}$$
then
$$Q(2013)\approx \dfrac{6\times 2013}{\pi^2}\approx 1223.75\cdots$$
But Now  $Q(2013)=?$

A: I don't think there's any way to compute $Q(N)$ exactly without doing something on the order of $\sqrt N$ calculations.  However, here's a formula that organizes things:
$$Q(N)=\sum_{n=1}^\infty \mu(n)\left\lfloor{N\over n^2}\right\rfloor$$
where $\mu(n)$ is the Mobius function.  The sum is actually always finite:  You never have to go past $n=\sqrt N$.  Basically, the Mobius function does the inclusion-exclusion that André Nicolas and Kieren MacMillan referred to.
For $N=2013$, we get
$$Q(2013)=2013-503-223-80+55-41+20-16-11+10+8-6-5\\
+4+4-3+2-2-2-2+1+1+1-1+1+1-1-1-1=1223$$

A: Here's how to work it out explicitly, with a modified Sieve of Eratosthenes approach (see also André Nicholas's comments regarding Inclusion/Exclusion).
There are $\lfloor{2013/4}\rfloor = 503$ numbers in that range divisible by $4=2^2$.
There are $\lfloor{2013/9}\rfloor = 223$ numbers divisible by $9 = 3^2$. However, $\lfloor{2013/36}\rfloor = 55$ of those will also be divisible by $4$, and will thus have been counted in the first pass. So this pass catches $168$.
There are $\lfloor{2013/25}\rfloor = 80$ numbers divisible by $25 = 5^2$. However, $\lfloor{2013/100}\rfloor = 20$ of those will be divisible by $100 = 2^2 \cdot 5^2$, and will thus have been counted in the first pass, and $\lfloor{2013/225}\rfloor = 8$ are divisible by $225=3^2 \cdot 5^2$. But now $2$ are counted twice in the reductions, so this pass actually catches $54$.
There are $\lfloor{2013/49}\rfloor = 41$ numbers divisible by $49 = 7^2$. However, $\lfloor{2013/196}\rfloor = 10$ of those will have been counted in the first pass, and $\lfloor{2013/441}\rfloor = 4$ will have been counted in the second pass, and $\lfloor{2013/1225}\rfloor = 1$. (This is what André Nicholas meant by "Only combinations of small primes will be subject to the Exclusion part".) Again, you need to find those that are excluded twice and add them back in. This pass gives $27$.
Continue this way until $\lfloor{2013/p^2}\rfloor < 1$ for some prime $p$ [n.b. as pointed out by André Nicholas, the last prime you need to check is $p=43$], and you will compute your answer by subtracting the number found in each pass from the original total, $2013$.
Hence your final answer is
$$2013-503-168-54-27-\dots=1223.$$

A: I think it's worth illustrating the role of $\mu(n)$, The Möbius function, in inclusion-exclusion as Barry Cipra alludes to.
We will calculate $Q(N)$. For the $i$th prime $p_i$ (considering only $p_i^2 \le N$) let
$$A_i = \{p_i^2, 2p_i^2, \dots, p_i^2 \lfloor N / p_i^2 \rfloor \}$$
For example $A_1 = \{4, 8, 12, 16, \dots, 4 \lfloor N/4 \rfloor \}$, the multiples of $4$ that are less than or equal to $N$.
We are looking for $$N - \left\vert \bigcup_{i} A_i \right\vert =
N
- \left( \sum_{i} |A_i| \right)
+ \left( \sum_{i < j} |A_i \cap A_j| \right)
- \left( \sum_{i < j < k} |A_i \cap A_j \cap A_k| \right)
+ \cdots  $$
We see that $A_1 \cap A_2$ are numbers that are divisible by $4$ and $9$, or divisible by $36$. Similarly $A_1 \cap A_3$ are numbers divisible by $4 \times 25$ and $A_2 \cap A_3$ are numbers divisible by $9 \times 25$. $A_1 \cap A_2 \cap A_3$ are numbers divisible by $4 \times 9 \times 25$.
Directly from the inclusion-exclusion formula, we see we subtract out numbers that are the product of an odd number of squared (distinct) primes, and add in numbers that are the product of an even number of squared (distinct) primes. Let's say $n^2$ is this product of these squared primes. Then $n$ is the product of distinct primes. There are $\lfloor N/n^2 \rfloor$ of these values (see Kieren MacMillan's answer).
$\mu(n)$ is $-1$ when $n$ is the product of an odd number of distinct primes, $1$ when $n$ is the product of an even number of distinct primes, and $0$ if $n$ is not the product of distinct primes ($n$ is not square-free). This corresponds exactly to the adding and subtracting in our inclusion-exclusion formula! (Note that $\mu(n)=0$ means $n$ is not the product of distinct primes, and so is not considered in the inclusion-exclusion formula).
So we conclude that $\mu(n)$ is a handy way of encoding our inclusion-exclusion principle. $$Q(N) = \sum_{n=1}^{\lfloor \sqrt N \rfloor} \mu(n) \left\lfloor \frac{N}{n^2} \right\rfloor$$
To actually calculate $Q(N)$ we need $\mu(n)$ values up to $\sqrt N$. A variation of the Sieve of Eratosthenes calculates a range of $\mu(n)$ much more efficiently than calculating one value at a time. Algorithms listed on MO.