text:
Q: sort write failed standard output broken pipe--Linux I am using following commands in my script:
max_length=`awk '{print length}' $File_Path_Name/$filnm | sort -nr | head -1`;
min_length=`awk '{print length}' $File_Path_Name/$filnm | sort -nr | tail -1`;

where the filenm variable contains the name of the file and File_Path_Name contains the directory path.
While executing this from script I am getting the error

sort: write failed: standard output: Broken pipe

Any suggestions what I am doing wrong?

A: you don't need to scan the file twice for getting max/min
try
$ read max min < <(awk '{print length}' file | sort -nr | sed -n '1p;$p' | paste -s)

or you can avoid sorting as well by calculating max/min within awk
$ awk    '{len=length}
   NR==1  {max=min=len}
   max<len{max=len}
   min>len{min=len}
   END    {print max, min}' file


text:
Q: Storing a function name in object and calling it later I am working on a single page application, and I've so far successfully created a system that easily lets me switch between pages, now I think I need a way to call specific functions when opening a certain page.
For each page I have a function declared, for example #page1 has page1_func, #page2 has page2_func and so on.
The pages are all stored in this fashion
var appPages  = {
    "page1": {
        "id": "#page1",
        "title": "Page 1 Title",
        "callback": page1_func
    },

    "page2": {
        "id": "#page2",
        "title": "Page 2 Title",
        "callback": page2_func
    }
};

There's another function that takes care of the navigation, which when called with fetches the information about that page i.e its title and id to update the DOM.
I also want that function to actually be able to call the functions that's in the page's callback property.
function NavigateToPage( page )  {
    ..
    ..
    appPages[ page ].callback( "some args" );
}

However this isn't working as I am declaring functions at the end of the script, but as far as I know declare a function at the end or the beginning it doesn't matter, it is always available though in my case the console tells me the page1_func isn't defined.
I need help with a better solution to this problem

A: This is works though.

const appPages  = {
  page1: {
    id: '#page1',
    title: 'Page 1 Title',
    callback: page1_fn,
  },

  page2: {
    id: '#page2',
    title: 'Page 2 Title',
    callback: page2_fn,
  }
};

function triggerCallback(page) {
  appPages[page].callback('args...');
}

triggerCallback('page1');

function page1_fn(arg) {
  document.write(arg);
}

function page2_fn(arg) {
  document.write(arg);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS Align wrapper to the top+bottom of the screen Im trying to align the wrapper class to the top and bottom of the screen so when the user scrolls up/down the body background NEVER shows or leaves a gap.
The HTML and portions of the CSS are shown below;
CSS
body{
    font: 14px/18px 'Nunito', sans-serif Arial, Tahoma, Verdana, sans-serif;  /* Normal text font */
    width: 100%;
    height: 100%;
    background:url('../img/bgs/bg-1.jpg'); /* Actual background */

    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
    margin:0px;
}
#wrapper
{
    width: 1000px;
    margin: 0 auto;
    min-height: 100%;
    height:100%;
    height: auto !important;
    background: white;

}

HTML

                           more html + content

                                   more html + content

A: The space you see is a margin, collapsing to the body margin. To prevent this you can simply add overflow: hidden to both wrapper and footer, or set paddings (top and bottom respectively) to them.


text:
Q: How to Make A button do more than one action xcode Ok So In My Xcode project I Have A button That I need to do the same method twice but with A Different Image Plz Help
Code:
UIImage * toImage = [UIImage imageNamed:@"CharacterBackwards.png"];
[UIView transitionWithView:self.view
                  duration:0.01f
                   options:UIViewAnimationOptionTransitionNone
                animations:^{
                    self->Guy.image = toImage;
                } completion:NULL];

sleep(0.4);

A: This is what methods are for. Create a method that takes an image name:
- (void)transitionToImage:(NSString *)imageName {
    UIImage * toImage = [UIImage imageNamed:@"CharacterBackwards.png"];
    [UIView transitionWithView:self.view
                      duration:0.01f
                       options:UIViewAnimationOptionTransitionNone
                    animations:^{
                        self->Guy.image = toImage;
                    } completion:NULL];
}

Now have your button handler call this twice:
- (IBAction)buttonHandler {
    [self transitionToImage:@"CharacterBackwards.png"];
    [self performSelector:@selector(transitionToImage:) withObject:@"CharacterForwards.png" afterDelay:0.4];
}


text:
Q: Is it a good practice to force developer to comply with a protocol in objective C? I am developing a simple set of reusable code. I have created a protocol to group a set of methods and ask the user at run time for data.
I think that setting a delegate would be mandatory. Can I force the developer at runtime to set the delegate by throwing an assert stating the reason?
Is this a good practice to enforce the user of my classes by using asserts? Does it have a design level flaw?

A: First the "good practice" question:

*

*Don't make methods required unless they actually are.

*Don't make methods optional if they aren't.

*Not a critical one, more of an opinion

*

*Provide a method initWithDelegate: if a delegate is required

*I often come across data structures where I don't know that there is a delegate pattern until I investigate. With the specific init method, I'm made aware of it earlier.

You can cause warnings at compile time by simply adding the @required indicator to your protocol:
@protocol SuperAwesomeProtocol <NSObject>

@required
-(void) requiredMethod1;
-(void) requiredMethod2;

@optional
-(void) optionalMethod1;
-(void) optionalMethod2;

@end

//and making your delegate specific:
@property (nonatomic, assign) id<SuperAwesomeProtocol> delegate;

You can still cause runtime asserts with:
if (!delegate || ![delegate respondsToSelector:@selector(requiredMethod1)])
{
    //Assertion failure
}

A: Yes I think it is good practice to use protocol in the application..
Protocols declare methods that can be implemented by any class.
Below are the situation in which use of protocol is good.

*

*To declare methods that others are expected to implement

*To declare the interface to an object while concealing its class

*To capture similarities among classes that are not hierarchically
related


text:
Q: std::find on a vector of object pointers I have a class A with a member which is a vector of object pointers of another class B
class A
{
    std::vector<B*> m_member_A

Now I want to perform a std::find on m_member_A.
E.g.
if(std::find(m_member_A.begin(), m_member_A.end(), B_obj*) != m_member_A.end())
std::find doesn't make sense on such a vector. How do I achieve such a functionality?
How would it change if it were a vector of objects of B (not pointer)?

A: Vector works perfectly fine with std::find
auto result = std::find(m_member_A.begin(), m_member_A.end(), itemToFind);
if (result != m_member_A.end()) {
  // found it!
}

Or if you need to dereference the pointer:
auto result = std::find_if(m_member_A.begin(), m_member_A.end(),
  [] (B* item) {
    if (item == nullptr) return false; // may want to do something else here
    return *item == someValue;
  });
if (result != m_member_A.end()) {
  // found it!
}

Demo: http://ideone.com/jKCrG5

A: If you want to find a value pointer at by the pointer, instead of a given pointer, you can use std::find_if with a suitable functor:
struct Foo
{
  int i;
};

bool operator==(const Foo& lhs, const Foo& rhs) { return lhs.i == rhs.i; }

std::vector<Foo*> v = ....;

Foo f{42};

std::find_if(v.begin(), v.end(), [&f](const Foo* p) { return *p == f; });

A: If you want to compare values instead of comparing pointers, you might want to use std::find_if instead:
bool IsFoo (B* _item) {
    bool result = false;

    if ( _item != nullptr && _item->value == 1 ) //Whatever is your criteria
        result = true;

    return result;
}

std::vector<B*> m_member_A;
B* instance = std::find_if (m_member_A.begin(), m_member_A.end(), IsFoo);


text:
Q: Cannot create table in Phpmyadmin interface only I installed the new version of XAMMP v3.2.1 and update my Phpmyadmin  to Phpmyadmin 4.4.2
I can create database but I cannot create a table using Phpmyadmin interface, it display this message like this

Fatal error: Cannot redeclare class Application_Octetstream_Download in C:\xampp\phpMyAdmin\libraries\plugins\transformations\Application_Octetstream_Download.class.php on line 42

Note: I try to create table in other IDE(like MySQL Server), it successfully create and reflect to Phpmyadmin


text:
Q: How to clean up after using dojo? I have written an app using dojo that allocates a lot of data during its lifetime. Is there a way I can ensure that all the memory has been released when I am done?
Is there a method like dojo.data.destroyAllStores() that I can use with the <body onunload> tag?
Thanks.

A: You're considering using "onunload", so I think you want to free memory when users are leaving the page.
Javascript objects are not shared from one page to another, leaving the HTML page should probably cause your browser to clear the associated memory (your browser has a javascript GC).
Unless you're creating memory leaks by connecting DOM & javascript objects (circular references that won't be cleared by DOM and JS GCs). But that's another problem.
More details on DOM/JS memory leaks.


text:
Q: Accessing column from update table in subquery in mysql with multiple sets I'm trying to update several fields in mysql query and I can't adapt the solution from here to my problem:
update m_day md1,
(select ma.col as ia, mb.col as ib
from m_day md join m_another ma on md.some=ma.some
join m_bother mb on md.someb = md.someb
where md.ID = **md1.ID**) src
set md1.A = src.ia, md1.B = src.ib
where md1.date > '2015-10-10'

I get [Err] 1054 - Unknown column 'md1.ID' in 'where clause'
The purpose of this query is to add some missing data into md table.

A: You are setting an equality on md1 on the subquery where it is not defined. Do you want to set the md.id=ma.id, instead, or do you want that qualification outside of the parentheses, as follows;
update m_day md1,
(select ma.col as ia, mb.col as ib, ma.id as id
from m_day md join m_another ma on md.some=ma.some
join m_bother mb on md.someb = md.someb) src
set md1.A = src.ia, md1.B = src.ib
where md1.date > '2015-10-10' and src.ID = md1.ID


text:
Q: Use PHP webservice in iPhone app I have developed a webservice in PHP. It uses the MySQL database. In this, I have used JSON. I want to fetch data from this webservice in my iPhone app. I have used a function which has one parameter. How can I use this in the iPhone?
Webservice:
<?php

echo getdata($_REQUEST['lastupdate']);

function getdata($lastupdatedate){

    $json = '{"foo-bar": 12345}';

    $obj = json_decode($json);

    //print $obj->{'foo-bar'}; // 12345

    $con = mysql_connect("localhost","un","pwd");

    if (!$con)

    {

    die('Could not connect: ' . mysql_error());

    }

    //print_r($con);

    mysql_select_db("roster", $con);

    $query = "select * from rates where LastUpdated = '".$lastupdatedate."' order by LastUpdated limit 1";

    $rs = mysql_query($query) or die($query);

    //print_r($rs);

    while($row=mysql_fetch_assoc($rs)){

    $record[] = $row;

    }

    $data = json_encode($record);

    header('Cache-Control: no-cache, must-revalidate');

    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

    header('Content-type: application/json');

    return $data;

}

?>

I am requesting the URL: http://domain/t1.php?lastupdate=2012-09-01 01:00:00.

A: You would create an request for http://domain/t1.php?lastupdate=2012-09-01 01:00:00 and then parse your response JSON.
Depending on how your code should function (onload or based on some user action) your code should function similar to this example from raywenderlich.com
Basic code snippets:
- (void)viewDidLoad
{
    [super viewDidLoad];

    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:yourURLValue];
        [self performSelectorOnMainThread:@selector(fetchedData:)
          withObject:data waitUntilDone:YES];
    });
}

- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
        JSONObjectWithData:responseData //1

        options:kNilOptions
        error:&error];

    NSArray* JSONResultValues = [json objectForKey:@"yourKey"]; //2

    NSLog(@"Results: %@", JSONResultValues); //3
}


text:
Q: About projection and orthogonal projection Let $V$ be an inner product space. Given any linear operator $T$ on $V$ is it always possible that $V=N(T)+R(T)$, if so how to prove it? Furthermore, is it correct to say that not every such $T$ s.t. $V=N(T)\oplus R(T)$ but if so, it uniquely determine an orthogonal projection? I'm thinking about what's needed to make a linear operator $T$ a projection, and what's needed to further make such $T$ become orthogonal projection.
I'm learning linear algebra so normally everything should be considered finite-dimensional, but the definitions of (orthogonal-)projection I read are not restricted on finite-dimensional, and it's quite confusing, for example if $V$ is infinite dimensional, and $W$ is a finite dimensional subspace of $V$, then $V=W\oplus W^\perp$, but is this still correct if $W$ is not finite dimensional?

A: By the dimension theorem, $\dim V=\dim N(T) +\dim R(T)$, so whenever these have nontrivial intersection (e.g. with $T(x, y) =(0, x)$) we don't have $V=N(T) +R(T) $.
A linear operator $T$ is a projection iff it is idempotent, i.e. $T^2 =T$.
Then any vector $x$ can be decomposed as $x=(x-Tx) \ +\ Tx\ \in N(T) +R(T)$, and if $x\in N(T) \cap R(T)$, then $Tx=0$ and $x=Ty$ for some $y$, so $x=Ty=TTy=Tx=0$.
It shows that in this case we indeed have $V=N(T)\oplus R(T)$, and $T$ effectively projects $a+b\mapsto b$.
Conversely, if $V=A\oplus B$ then the projection $a+b\ \mapsto b$ is clearly idempotent.
To talk about orthogonality, an inner product has to be considered on $V$, which induces an adjoint $T^*$ for every linear operator $T$, uniquely determined by the equation $\langle Tx, y\rangle =\langle x, T^*y\rangle$ (in an orthonormal basis, the matrix of $T^*$ is just the (complex conjugated) transpose of the matrix of $T$).
Now, if $T^2=T$, we will have $N(T) \perp R(T)$ iff $T^*=T$ (selfadjoint).
Supposed $T^*=T=T^2$, if $a\in N(T) $ and $b\in R(T) $, we have
$$\langle a, b\rangle =\langle a, Tb\rangle =\langle a, T^*b\rangle =\langle Ta, b\rangle = 0$$
meaning $a\perp b$.
Conversely, if $A\perp B, \ V=A\oplus B$ and $T=a+b\mapsto b$ is an orthogonal projection, then, with the decompositions $x=x_A+x_B, \ y=y_A+y_B$, we have
$$\langle Tx, y\rangle = \langle x_B, \, y_A+y_B\rangle =\langle x_B, y_B\rangle=\langle x, Ty\rangle$$
showing $T^*=T$.

A: *

*First, $N(T)^\perp = R(T^*)$ is always true in a finite dimensional space. Suppose rows of $T$ is $r_1,\cdots, r_n$, then if $x\in N(T)$
$$
Tx=\begin{bmatrix}
\langle r_1,x \rangle\\
\langle r_2,x \rangle\\
\vdots \\
\langle r_n,x \rangle
\end{bmatrix}=0
$$
and $x$ is perpendicular to the generators of $R(T^*)$. Also, in the finite dimensional space, $V=W \oplus W^\perp$ is always true, so $V=N(T)\oplus R(T^*)$.
If $R(T)=R(T^*)$, which is equivalent to $T$ being orthogonal $T=T^*$, then $V=N(T) \oplus R(T)$. In a finite dimensional real vector space, this is equivalent to $T$ being symmetric.

*So $V=R(T^*) \oplus N(T)$ (of course) does not uniquely determine $T$. But if you assume that $T$ is an orthogonal projection, then $T$ is uniquely determined. For each $x\in V$,  $x=x_R + x_N$ where $x_R\in R(T^*)$ and $x_N\in N(T)$ are uniquely determined. Then let $S(x):=x_R$. This is an orthogonal projection. We only need to prove the $T=S$, so compute the following
$$
\langle (T-S)x,(T-S)x\rangle =\langle Tx, Tx \rangle - \langle Tx, Sx \rangle - \langle Sx, Tx \rangle + \langle Sx, Sx\rangle \\
=\langle T(1-S)x, x\rangle+ \langle S(1-T)x, x\rangle=0
$$
since $(1-S)x, (1-T)x \in N(T)$. Thus $(T-S)(x)=0$ and $T=S$.

*When you are working with the inner product space, it is natural to consider it as a topological space with topology given by the distance $\|x-y\| = \sqrt{\langle x-y,x-y\rangle}$. If you are not familiar with a topology, just keep in mind that $x_n$ converges to $x$ if and only if $\|x-x_n\|$ converges to $0$; $x_n$ is a Cauchy sequence if and only if $\|x_n-x_m\|$ converges to $0$ when $n\geq m \to \infty$. Convergence of a sequence implies that it is Cauchy, but the converse is not generally true. Then the completeness of this space (that is, every Cauchy sequence converges) is usually crucial. For example, consider the space of polynomial functions defined on the closed interval $(0,1)$, and define the innerproduct as $\langle f, g \rangle = \int_0^1 f(x)g(x)dx$. Then this is not complete since the following sequence of polynomials is a Cauchy sequence but does not converges:
$$
1, 1+x, 1+x+\frac{x^2}{2!}, 1+x+\frac{x^2}{2!}+\frac{x^3}{3},\cdots
$$
If you are familiar with the Taylor expansion, you will see that this converges to $e^x$, but $e^x$ is defnitely not a polynomial. Of course we need to check that this is a Cauchy sequence, but I will skip it. This is the reason why we are usually dealing with $l^2$ space or $L^2$ space
$$
L^2([0,1]) = \left\{f:[0,1]\to \mathbb{R}|\int_0^1 \{f(x)\}^2dx <\infty \right\}\\
l^2(\mathbb{N}) = \left\{a_n :\mathbb{N} \to \mathbb{R} | \sum_{i=0}^\infty a_n^2 \leq \infty\right\}
$$
and those $complete$ inner product spaces are called a Hilbert space.

*However, in a Hilbert space $H$, $H= W \oplus W^\perp$ is still not generally true for any subspace $W$. For example, let $H= l^2(\mathbb{N})$ where the inner product of $(a_n)$ and $(b_n)$ is given by $\sum_n a_n b_n$. Now take $W$ to be a subspace of $H$ whose elements are of the form $(a_1, a_2, \cdots)$ and $a_i$'s are all zeroes except for finitely many terms. This is not a closed subspace―closedness means every limit is in itself―since
$$
x_k=(1,1/4,1/9,\cdots, 1/k^2,0,0,0,\cdots)
$$
are all in $W$ but its limit is not in $W$, which is
$$
x=(1,1/4,1/9,\cdots).
$$
It is easy to see that $W^\perp=0$, since if $(a_n)\in H$ is nonzero, there is a nonzero term $a_k\neq 0$ and
$$
(b_n)=(0,0,\cdots, 0, \stackrel{\textrm{$k$th}}{a_k}, 0 ,\cdots)\in W
$$
and $\langle (a_n), (b_n) \rangle = a_k^2 \neq 0$.

*When $W$ is closed, $H = W \oplus W^\perp$ is still true. Find the orthonormal (Hilbert) basis $\{v_1, v_2, v_3, \cdots \}$ of $W$, and
$$
\sum_{i=1}^\infty \langle x , v_i \rangle v_i
$$
always converges and is in $W$ by the closedness. Then it is easy to check that
$$
x-\sum_{i=1}^\infty \langle x , v_i \rangle v_i \in W^\perp
$$
and thus we have the unique expression
$$
x= \sum_{i=1}^\infty \langle x , v_i \rangle v_i + \left(x-\sum_{i=1}^\infty \langle x , v_i \rangle v_i \right)
$$
proving $H = W \oplus W^\perp$.

*Edit: I added the last paragraph.

*Finally, if $T$ is an operator on a Hilbert space, and if it is continuous (which is equivalent to the boundedness of $T$), $N(T)=T^{-1}(0)$ is still closed since $0$ is closed, we get $H=N(T) \oplus N(T)^\perp$. If $T$ has its dual operator $T^*$, which means $\langle Tx,y\rangle = \langle x,T^*y \rangle$, then $H= \textrm{Im} (T^*) \oplus \textrm{Ker} T$.


text:
Q: PHP Warning: mkdir(): Not a directory when creating directory I'm trying to recursively create directories, but I get this PHP warning:
Code:
<?php mkdir('data/1/0', 0755, true);

Output:
PHP Warning: mkdir(): Not a directory in /home/myScript.php on line 1

This is running on Linux.

A: from the manual book, we can see:
bool mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

http://www.php.net/manual/en/function.mkdir.php
When we try to mkdir data/1/0, actually we can mkdir 0/ under the directory data/1. But when data/1 happens to be a file instead a directory, php will issue a warning PHP Warning:  mkdir(): Not a directory
So, when you come with this warning, you can check that the prefix of the pathname is a file, where a directory was expected.


text:
Q: .NET developer starting a social networking site, suggestions? I am a relatively new programmer; a bachelors in CS, about 2 years out of college, working mostly with .NET in C#. I am fairly fluent with SQL interaction/scripting, and have done a little work with ASP.NET (mostly maintaining an existing site).
I'm interested in starting a website in my free time, the closest thing I can describe to it is a social networking site. An extremely friendly UI and communication between the members is very important.
I'm wondering if I should attempt this from scratch via ASP.NET because of my experience with C#, .NET, and SQL Server, or should I try to learn a framework like RoR? or perhaps a CMS like Drupal or Joomla? Really, any direction such as articles, books, etc would be very helpful. Thanks!
Edit: It should be noted I have a Windows Server 2008 machine I was planning on hosting the site from, though it is not absolutely necessary.

A: If you want to use asp.net, I would suggest you to use ASP.NET MVC:
http://www.asp.net/mvc/
I started with Contact Manager tutorial:
http://www.asp.net/learn/mvc/tutorial-26-cs.aspx
It is easy and helps you understand the basics. When you'll understand the basics, take a look at http://sharparchitecture.net/. It allows you to create fast application using ASP.NET MVC and nHibernate using many recommended patterns.
I would advise against using CMS, because it is much more educational to build application from sratch.
jQuery, which is practically a part of ASP.NET MVC, will allow you to make smooth interfaces.
I am creating MVC based bugtracker and I learned a lot during last year.

A: Given your existing experience (c#/asp.net/sql server), resources (server 2008), and interests (RoR, Drupal, Joomla), I have two recommendations:

*

*ASP.Net MVC.  It gives you a similar architecture and some of the features of RoR, but in a way that fits your server and your skills.

*A social networking site is likely aiming more than a little too high, in terms of bandwidth and server requirements (you'll need more than a consumer level connection and more than one sever), time (it's a bigger task to build than it seems), and reach (the space is well-filled - you don't have the marketing power to be a player).

Until recently I would have recommended you build your own blog engine as an alternative.  That used to be a sort of developer rite of passage, to not only have your own blog but the write the code that runs it.  However, that seems played out as hosted options like wordpress have matured (though I still believe that if you blog about .Net technologies you might want to find an asp.net-based platform).
Instead, you might try writing a url-shortening service, twitter client (and site to host the project for downloads, etc), or web-based iPhone app. Those all seem to be very much in vogue right now.

A: Based from your given knowledge and experience, use either asp.net mvc or webforms( or combine them if you want ) then start it from scratch. You will gain a lot of knowledge and you can tweak or customize your site the way you want to envision it. And one more thing, it's a real fun since you're going to get hook to it (coding,designing ui,debugging etc.) ! I can say this because I built a social networking site ( http://joecaps.com ) in asp.net complete with chatroom, users can upload photos, users can create their friendslist , users can create their own music playlist , post messages to friends, etc. Have fun!!!!

A: .NET is a very powerful framework and is certainly more than capable of powering the type of site you describe.  Then again so is RoR as well as many other frameworks and platforms for development.  Your best option isn't too worry too much about getting the correct framework but rather to make sure that you choose a framework that at least lets you develop your vision.
Once you have your site running you can re-evaluate if you've made the best technical decisions.  If the site takes off you'll likely need to reinvent it several times over (this may or may not involve rewriting it in different languages or technologies).
If you feel most comfortable with .NET, then it's a very good place to start.  If you think another framework will let you prototype faster, then go with it. The beauty in starting a new site is that you can experiment and throw away as much as you need to before it ever goes live--so feel free to compare and contrast; just don't forget the old slogan "shipping is a feature".  User's really don't care what it's written in, just as long as it exists.

A: I did a semi social networking site (http://www.ramtajogi.com) . it has features like user account, profile, friend request, friends, posts and comments, post views. I am planning to share the code base soon. The basic work is done. I have put all the views in dll(using this http://www.chrisvandesteeg.nl/2010/11/22/embedding-pre-compiled-razor-views-in-your-dll/) , so, I feel its good and can be extended to have pictures and videos, I got initial idea from socialengine.net and phpfox, they are written in php but i was looking for something in .net.
Regards
Parminder


text:
Q: Visual studio debug values changing when looking into them? So i've been writing some unit tests, and there's one test that fails that shouldn't fail, so I started debugging the test. I looked through the properties and after the debugging was finished, the test passed. weird? So, I ran the test again, and it failed again.
Turns out, the properties(in this case .Selected of an listview-item) actually changed when I looked into it, but it didn't when I don't.....
Here's a video I made to show this weird issue.
https://youtu.be/OsUhh-MlOoU

A: The documentation for SelectedItems has this to say:

The SelectedItems property will not contain any items if the property is accessed before the ListView handle is created.

Since you're in a test method I would assume you don't actually show the form, nor the listview, on the screen which would require a handle. As such, the listview doesn't get a handle until you force it to.
The act of expanding the listview object in the debug inspector makes the SelectedItems property suddenly contain the element after all which indicates to me that one of the other properties on the ListView type has a side-effect of triggering this creation of a handle.
Here's a small example that demonstrates a similar situation:
void Main()
{
    var x = new Test();
    Console.WriteLine(x.GoodProperty); // place a breakpoint on this line
    Console.WriteLine(x.BadProperty);
    Console.WriteLine(x.GoodProperty);
}

public class Test
{
    public int GoodProperty { get; set; }
    public int BadProperty => GoodProperty++;
}

If you place a breakpoint on the indicated line, then use your mouse to just mouse over the x.GoodProperty expression in the same line, you'll get 0. You can do this over and over again and it still produces 0.
However, every time you mouse over the x.BadProperty expression, x.GoodProperty will also increase by 1.
The exact same thing would happen if you mouse over x and expand it to show all properties. Depending on whether GoodProperty or BadProperty will evaluate first when you expand x, the expanded view may or may not show a changed GoodProperty value.


text:
Q: Postgres Sql - How to apply Offset on Timestamp My offset-date-time object I store in the DB with 2 columns, one timestamp(UTC) column
and another corresponding offset.
For example, if I get: 2017-05-01T16:16:35+05:00, in the DB I will store this data in 2 columns the first timestamp will have the value in UTC (2017-05-01T11:16:35), and the offset column will have the +5 timezone in minutes so -300 in minutes.
Now I need select this data from DB, but I need to apply offset and again get the data  that was entered: 2017-05-01T16:16:35+05:00.
I can achieve this in Java by selecting both values and applying offset.
But I want to do DB level?

A: Sorry,  I can't add comment because of low score.
I just tried below script, hope it can help.
create table test (id int, col2 timestamp, col3 int);

insert into test values(1, '2017-05-01T11:16:35', -300);

select * from test;

select (col2 - col3 * INTERVAL '1 minute')::varchar(32) ||  (col3/60) :: varchar(20) ||':00' from test;

We can finally get below result:
2017-05-01 16:16:35-5:00

A:
For example, if I get: 2017-05-01T16:16:35-05:00, in the DB I will
store this data in 2 columns the first timestamp will have the value
in UTC (2017-05-01T11:16:35), and the offset column will have the -5
timezone in minutes so -300 in minutes.

https://www.postgresql.org/docs/current/datatype-datetime.html. see: UTC offset for PST (ISO 8601 extended format)
So 2017-05-01T16:16:35-05:00 is an timestamptz type value, therefore at utc timezone value should be 2017-05-01 21:16:35+00!

demo
create table test_timestamp(
    org text,
    tsz timestamptz,
    ts timestamp,
    offsettz interval
);

org as timestamp or timestamptz input text. First we assume that org text format ending with something like '1999-01-08 04:05:06-8:00', the pattern is last part is like [+/-]99:99. the last part refer to the offset time to the UTC.

*

*tsz cast text to timestamptz

*ts ignore timezone, only timestamp.

*offsettz interval can be positive or negative. offsettz is the pattern [+/-]99:99 text cast to interval.
Then create a trigger, the only input is org text, all other 3 column would be computed via trigger.

    CREATE OR REPLACE FUNCTION supporttsz ()
    RETURNS TRIGGER
    AS $$
BEGIN
    NEW.tsz := (NEW.org)::timestamptz at time zone 'utc';
    NEW.ts := (NEW.org)::timestamptz at time zone 'utc';
    NEW.ts := NEW.ts::timestamp;
    IF SUBSTRING((
    RIGHT (trim(NEW.org) , 5)) , 1 , 1) = '-' THEN
        NEW.offsettz := (
        RIGHT (trim(NEW.org)
            , 5))::interval;
    elsif SUBSTRING((
        RIGHT (trim(NEW.org) , 5)) , 1 , 1) = '+' THEN
        NEW.offsettz := (
        RIGHT (trim(NEW.org)
            , 5))::interval;
    elsif SUBSTRING((
        RIGHT (trim(NEW.org) , 6)) , 1 , 1) = '-' THEN
        NEW.offsettz := (
        RIGHT (trim(NEW.org)
            , 6))::interval;
    elsif SUBSTRING((
        RIGHT (trim(NEW.org) , 6)) , 1 , 1) = '+' THEN
        NEW.offsettz := (
        RIGHT (trim(NEW.org)
            , 6))::interval;
    ELSE
        NEW.offsettz := '0::00'::interval;
    END IF;
    RETURN new;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER tg_supporttsz_test_timestamp
    BEFORE INSERT ON test_timestamp FOR EACH ROW
    EXECUTE PROCEDURE supporttsz ();


text:
Q: How to connect SQL Server with Yii2 I got errors when trying to connecting SQL server with yii2.
SQL Server and PHP code are in separated server.
The PHP environment is PHP 7.0.31 on Ubuntu 18.04.
And Database Server Environment is MS SQL SERVER v9.00.1399.06 on Window NT 6.1
And I installed the PDO Drive as following
apt install php7.0-sybase

The following is my main-local.php
'db' => [
        'class' => 'yii\db\mssql\PDO',
        'dsn' => 'sqlsrv:Server=xx.xx.xx.xx;Database=xxxx',
        'username' => '<username>',
        'password' => '<password>',
        'charset' => 'utf8'
],

And i got the following error message.
Invalid Configuration – yii\base\InvalidConfigException
Missing required parameter "dsn" when instantiating "yii\db\mssql\PDO".

1. in /var/www/html/ms/vendor/yiisoft/yii2/di/Container.php at line 466

2. in /var/www/html/ms/vendor/yiisoft/yii2/di/Container.php at line 370 – yii\di\Container::resolveDependencies([yii\di\Instance, yii\di\Instance, yii\di\Instance, yii\di\Instance], ReflectionClass)

Seems related to class reflction but I have no idea on how to solve it.
Hope someone can give a help hand on this.

A: Try
'db' => [
    'class' => 'yii\db\Connection',
    'driverName' => 'sqlsrv',
    'dsn' => 'sqlsrv:Server=xx.xx.xx.xx;Database=xxxx',
    'username' => '<username>',
    'password' => '<password>',
    'charset' => 'utf8'
],

A: below my solution for mssql connection:
from phpinfo() i know that
PHP Extension Build API20190902,TS,VC15
then in file php.ini in folder ..\xampp\php
insert this
extension=php_pdo_sqlsrv_74_ts_x64.dll
extension=php_sqlsrv_74_ts_x64.dll
I have downloaded this dll from microsoft site
Put the dll in folder ..\xampp\php\ext
in your framework of yii2, in file ..\basic\config\db.php
this is the connection string
'class' => 'yii\db\Connection',
'dsn' => 'sqlsrv:Server=xxxxx\xxxxx;Database=xxxxx',
'username' => 'xxx',
'password' => 'xxxxxxx',
'charset' => 'utf8',

I hope that will be useful.
Regards
Alessio


text:
Q: How do I filter my text so that spaces are taken into account? I am creating a searchbox for my app where the user can type stuff into the box and titles are returned in the recyclerView below the searchbox. The titles are in a php file on the server- the results are filtered, matching what the user types into the search box.
So for example, one of the titles in my php file is:
red onions

If the user types red, the recyclerView shows as he types:
red cabbage
red mushrooms
red onions

This part is working correctly.
But when the user types red o nothing shows in the recyclerView. Whereas, in fact, red onions should be appearing.
I'm sure this is happening because in my app I am breaking the php titles into separate words, so the space (" ") between red and onions is causing a problem.
Any idea how I might resove this?
The reason I am splitting the title into words in the first place is so if the user types the second word, onions, red onions will show as a result in the recyclerView, rather than nothing at all.
Here's my code:
      @Override
            public Filter getFilter() {
                return new Filter() {
                    @Override
                    protected FilterResults performFiltering(CharSequence charSequence) {

                        //the text entered in the search box
                        String charString = charSequence.toString();

                        //if searchbox is empty, show the whole list
                        if (charString.isEmpty()) {
                            categoryListFiltered = categoryList;
                        } else {
                            List<Category> filteredList = new ArrayList<>();

                            for (Category row : categoryList) {

                                //split the php title into separate words
                                String[] title_in_php = row.getName().split(" ");

                                //for every split word
                                for (String split_title : title_in_php) {

//if the search term entered is a whole word in the title
                        if (split_title.toLowerCase().startsWith(charString.toLowerCase())) {

                                        filteredList.add(row);

                                    }
                                }
                            }

                            categoryListFiltered = filteredList;
                        }

                        FilterResults filterResults = new FilterResults();

                        filterResults.values = categoryListFiltered;
                        return filterResults;
                    }

                    @Override
                    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                        categoryListFiltered = (ArrayList<Category>) filterResults.values;
                        notifyDataSetChanged();
                    }
                };
            }

A: Once you entered red o, it will first check red and it will add row to filteredList because charString starts with red but checking the o wont add the row to filteredList because charString doesn't start with o
Try this (based on the comments):
if (split_title.toLowerCase().startsWith(charString.toLowerCase())) {
    filteredList.add(row);
}
else if (row.getName().contains(charString.toLowerCase()) {
    if (!filteredList.contains(row)) {
        filteredList.add(row);
    }
}

if for checking the split_title (ex.red) - filteredList.add(row);
else if will check if the row contains the charString(whole string- ex. red o) - filteredList.add(row);
if (!filteredList.contains(row)) is just to check if the row is already on the list. If not then add it. (To avoid duplication)
Another way is to split charString:
String[] charString= charSequence.toString().split(" ")

and iterate it:
for (int i=0; i<charString.length; i++) {
    for (int n=0; n<title_in_php.length; n++) {
        if (split_title.toLowerCase().startsWith(charString.toLowerCase()) || charString[i].toLowerCase() == title_in_php[n].toLowerCase() || row.getName().contains(charString.toLowerCase()) {
            if (!filteredList.contains(row)) {
                filteredList.add(row);
            }
        }
    }
}

so it will check if charString starts with title_in_php OR if charString = title_in_php OR if row contains charString checking the list of title_in_php per charString
[red] starts with [red/onion] OR [red] = [red/onion] OR [red onion] contains [red o]


text:
Q: Why videoPlayerController.value.isPlaying = false after videoPlayerController.play() is called? Recently I am using flutter plugin vieo_player, during the time I encounter a problem:
videoPlayerController.value.isPlaying's value is false after videoPlayerController.play() is called, which I expected to be true.
VideoPlayerController get controller => widget.controller;
controller.play();
print("isPlaying = ${controller.value.isPlaying}");// print false

A: The reason is play() is an async function:

When value.position == value.duration, it will run into await line, in which case controller.value will not change immediately.
If you use await before controller.play(), controller.value.isPlaying will be true.


text:
Q: How to open up comments to all visitors The "Leave a Reply" section at the bottom of my pages is asking for a login before visitors can comment. Is there any way I can turn this off so anybody can leave a comment?

A: Go to yoursite... /wp-admin/options-discussion.php
Is Users must be registered and logged in to comment selected?
If so, unselect it and Save Changes.


text:
Q: Chrome HSTS Error: ERR_CERT_AUTHORITY_INVALID I am using a self-signed certificate on my openmediavault setup. On Firefox, there is an option to add an exception to that, but on Chrome it complains with the error code: ERR_CERT_AUTHORITY_INVALID
It also does not allow me to continue the unsecure website and displays the following error:

xxx.com normally uses encryption to protect your information. When
  Chrome tried to connect to xxx.com this time, xxx.com returned unusual
  and incorrect credentials. Either an attacker is trying to pretend to
  be twitter.com, or a Wi-Fi login screen has interrupted the
  connection. Your information is still secure because Chrome stopped
  the connection before any data was exchanged.
       Network errors and attacks are usually temporary, so this page will probably work later.

I tried to use Incognito window, but it is the same error.
I also imported the self-signed certificate by exporting and then double-clicking on it.
Using Windows 10
PS: I also used this but did not solve my issue.


text:
Q: Snowflake Native SSO through Okta - "Failed to connect to okta. Error code=401" I have cloned Snowflake-connector-net source code and made a TestApp where I'm testing authenticators. I'm stuck with Native SSO through Okta - I get the following message:
Snowflake Internal Error: Unable to connect. One or more errors occurred. (Response status code does not indicate success: 401 (Unauthorized).)
Here's the code snippet with the ConnectionString. Please point out what I'm doing wrong.
static void Main(string[] args)
{
  using (IDbConnection conn = new SnowflakeDbConnection())

    try
    {
      conn.ConnectionString = "account=[mySnowflakeAccount];authenticator=https://[companyName].okta.com;user=[myOktaAccount];password=[myOktaPassword];port=443;connection timeout=0";

      conn.Open();
      conn.Close();
      Console.WriteLine("Success");

    }

    catch (Exception e)
    {
      Console.WriteLine(e.Message);
    };

  Console.Read();
}


text:
Q: Not able to set MediaControllerCompat.TransportControls I am trying to set onclick listener in notification button but as i press a button i am getting an error like this:
java.lang.RuntimeException: Unable to start service unnion.neelay.test1.MediaService@6fec2a5 with Intent { act=beatbox.neelay.dummybeat.ACTION_PLAY flg=0x10000000 cmp=unnion.neelay.test1/.MediaService bnds=[455,632][519,696] }: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.media.session.MediaControllerCompat$TransportControls.play()' on a null object reference
                                                                     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3034)
                                                                     at android.app.ActivityThread.access$2200(ActivityThread.java:153)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.media.session.MediaControllerCompat$TransportControls.play()' on a null object reference
                                                                     at unnion.neelay.test1.MediaService.handleIncomingActions(MediaService.java:890)
                                                                     at unnion.neelay.test1.MediaService.onStartCommand(MediaService.java:202)
                                                                     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3017)
                                                                     at android.app.ActivityThread.access$2200(ActivityThread.java:153)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

but earlier It was working properly this is the method which is shown in the error.
private void handleIncomingActions(Intent playbackAction) {
    if (playbackAction == null || playbackAction.getAction() == null) return;

    String actionString = playbackAction.getAction();
    if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
        transportControls.play();
    } else if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
        transportControls.pause();
    } else if (actionString.equalsIgnoreCase(ACTION_NEXT)) {
      //  transportControls.skipToNext();
        transportControls.skipToNext();
    } else if (actionString.equalsIgnoreCase(ACTION_PREVIOUS)) {
      //  transportControls.skipToPrevious();
        transportControls.skipToPrevious();
    } else if (actionString.equalsIgnoreCase(ACTION_STOP)) {
       // transportControls.stop();
        transportControls.stop();
    }
}

 public PendingIntent playbackAction(int actionNumber) {
    Intent playbackAction = new Intent(this, MediaService.class);
    switch (actionNumber) {
        case 0:
            // Play
            playbackAction.setAction(ACTION_PLAY);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 1:
            // Pause
            playbackAction.setAction(ACTION_PAUSE);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 2:
            // Next track
            playbackAction.setAction(ACTION_NEXT);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 3:
            // Previous track
            playbackAction.setAction(ACTION_PREVIOUS);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 4:
            playbackAction.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        default:
            break;
    }
    return null;
}

any advice what i am doing wrong will be helpful.
and I call the method like view.setOnClickPendingIntent(R.id.btnPause, playbackAction(1));
.I am trying to make it work in lockscreen thats why I am changing the notification to foreground as earlier i was overriding the onbackbutton ,hope some one can help me thx in advance.


text:
Q: GLSL - Bump Mapping based on Noise I am trying to create a stucco texture similar to the image below in an GLSL fragment and vertex shader.

I know there are multiple ways to accomplish this. However, I want to focus on perturbing the surface normal in the fragment shader based on the values I receive from the noise function.
My thought process is the following..

*

*Send the noise function my current position scaled by some scalar.

*Once I have my noise, I can then perturb the surface normal and use it with my Phong shading model.

However, I'm not sure where I go from there.
Here is what I have so far.
Vertex shader - Calculate Tangent is a helper method to build the tangent vector based on the object norm.
#version 120
varying vec3 LightDir;
varying vec3 EyeDir;
varying vec3 MCPoint;

main(){
 MCPoint = gl_Vertex.xyz;

 EyeDir = vec3(gl_ModelViewMatrix * gl_Vertex);
 vec3 LightPosition = gl_LightSource[0].position.xyz;
 vec3 tangent = calculateTangent(gl_Normal);

 // Building the Tangent matrix
 vec3 n = normalize(gl_NormalMatrix * gl_Normal);
 vec3 t = normalize(gl_NormalMatrix * tangent);
 vec3 b = cross(n, t);

 vec3 v;
 v.x = dot(LightPosition, t);
 v.y = dot(LightPosition, b);
 v.z = dot(LightPosition, n);
 LightDir = normalize(v);

 v.x = dot(gl_vertex.xyz, t);
 v.y = dot(gl_Vertex.xyz, b);
 v.z = dot(gl_Vertex.xyz, n);
 EyeDir = normalize(v);

 gl_Position = ftransform();
}

Fragment Shader - so far...
#version 120
varying vec3 LightDir;
varying vec3 EyeDir;
varying vec3 MCPoint;

main(){

  vec2 _noisexy = noise2(MCPoint.xy * 1.65);

  // offset normal

  // Calculate phong shading based on LightDir, EyeDir, & Newly distorted Normal

 gl_FragColor= intensity * vec4(my_surface_color, 1.0);
}

Now, to my actual questions.

*

*What normal do I offset? Would I offset the object normal? I have been reading that the bump mapping should take place in object space.

*What is the best way to apply the offset to the normal?
Some system info:
Mac OSX - OpenGL 3.2 - Shader must be able to work on older macs that do not have the new 3.2 support.


text:
Q: Imputed data: how to check residuals of the pooled analysis I used mice (Multiple imputation by chained equations) to impute my dataset with missing variables. Next, I did a linear regression on the imputed datasets (m=50) and pooled the results according to Rubin's Rules.
However, I am not sure how should I now check the residuals. On each imputed dataset or is there a way to check the residuals for the pooled model?


text:
Q: Code blocks: A debugging check in this application has failed (loss of precision) I keep getting the following error after running my code
The debugger has failed error
The weird thing is no matter what I do to the code I keep getting the same error. For example, I commented out the packages and the defined function V_trap
Commented out half the code and still get the same error
Furthermore, before this error, I get the cmd prompt with the previous result from the first run.
Even if I try doing a simple hello world code I get the same error
Hello World, same error
This error started yesterday, I am not sure what happened. I was trying to look at how to make a normal distribution in c++ yesterday.
I have already tried reinstalling code blocks, but the error still persists.


text:
Q: SQL Database does not show up after copying it to (localdb)\MSSQLLocalDB in "sql server object explorer" visual studio 2015 After the Crash of my Laptop I was able to recover the data that I had on the hard drive. In the meantime I have a new Laptop and I'm restoring my last ASP.NET MVC Core Project in Visual Studio 2015 (Community).
In this Project I've created a database using EF Core Code First.
In SQL Server Object Explorer (on my old Laptop) the database was showing up.
Visual Studio saved the data under the path "C:\Users\USERNAME".
In appsetting.json the Connection string was "DATABASEDbConnection": "Server=(localdb)\\mssqllocaldb;Database=DATABASE_v1;Trusted_Connection=True;MultipleActiveResultSets=true".
My new Laptop has the exact Name of the old one.
I've copied the database in the same Location as before.
But:

*

*the database does not Show up in SQL Server Object Explorer, and I have no idea how to bind it again

*if I try to run my Project I get this error:
SqlException: Cannot open database "DATABASE_v1" requested by the login. The login failed Login failed for user 'USER-PC\USER.
How can I bind again my database?

A: After googling a couple of hours, I've found the solution.
I started Microsoft SQL Server Management Studio and added a reference to (localdb)\MSSQLLOcalDB and from there it was possible to bind my database located in C:\Users\USERNAME.
The localdb instance in VS seems to be influenced by SQL Server Management Studio. The latter rules binding to user's DBs.
I'm wondering why localdb does not start authomatically when running SQL Server Management Studio.


text:
Q: Prove that a given function is locally Lipschitz and therefore differentiable a.e.
Consider $u:S^1\times (0,T)\to \mathbb R$ a $C^1$ function, and define
  $$v(t)=\max_{p\in S^1} u(p,t)$$
  Prove that $v$ is locally Lipschitz and deduce that $$\frac {dv}{dt}(t_0)=\frac{\partial u}{\partial t}(p_0,t_0)$$ where $p_0$ is any maximum point for $u(\cdot, t_0)$.

For point one my idea was to prove that at least one maximum point at height $t$ (viewing the domain as a vertical cylinder) has a neighbourhood which contains a differentiable curve made of maximum points for $u$. Therefore, in that neighbourhood (i.e. for $t$ near to $t_0$) one could use that $u$ is $C^1$. But is that true? And is this really the best way?
For point two, I know that locally Lipschitz implies absolutely continuous which implies a.e. differentiable. But how could I deduce the (however intuitive) formula for the derivative?
Furthermore, I'm quite sure that the result absolutely continuous $\Longrightarrow$ differentiable a.e. is more advanced than the level at which the problem was given. Isn't there a simpler way for this special case?
Thank you in advance.

A: Let $t_1, t_2 \in (0,1)$. Assume $v(t_1) \ge v(t_2)$ (If not, switch $t_1$ and $t_2$). Let $x_1\in \mathbb S^1$ so that $v(t_1) = u(x_1, t_1)$. Then
$$|v(t_1) - v(t_2)| = v(t_1) - v(t_2)  \le u(x_1, t_1) - u(x_1, t_2)\le M |t_1 - t_2|,$$
where
$$M=\sup_{(x,t) \in \mathbb S^1 \times [t_1 , t_2]} |\partial _t u|.$$
Thus $v$ is locally Lipschitz.
Let $t_0$ be such that $v$ is differentiable and $x_0 \in \mathbb S^1$ so that $v(t_0) = u(x_0, t_0)$. Then
$$v'(t_0) = \lim_{t\to t_0^+} \frac{v(t) - v(t_0)}{t-t_0} \ge \lim_{t\to t_0} \frac{u(x_0, t)-u(x_0, t_0)}{t-t_0} = \frac{\partial u}{\partial t}(x_0, t_0)$$
similarly, by considering $t\to t_0^-$, we have $v'(t_0) \le  \frac{\partial u}{\partial t}(x_0, t_0)$. Thus we have the equality.


text:
Q: What is the derivative of $\cos^4(x)$? I'm not sure if we use the power rule, or if the chain rule is needed for this particular problem.

A: It's chain rule in this case:
So you have $f(x) = \cos^4(x)$:
So $f'(x) = -4\cos^3(x)\sin(x)$

A: first think of the rule of power derived from:
$$ (v^k)'= kv^{k-1} v'. $$
thus,
$$ y = ((\cos x)^4) = 4 (\cos x)^3 \cdot (\cos x)', $$
and as $ (\cos v)'= - \sin v \cdot v' $, we obtain finally
$$y'=4\cos ^3 x\cdot (-\sin x\cdot 1), $$
i.e.,
$$y'=-4\sin x\cdot \cos^3x $$

A: It's the chain rule.
If $f(x) = \cos^4(x)$ then $f(x)=g(h(x))$ where $g(x)=x^4$ and $h(x)=\cos(x)$.
Hence $f'(x)=g'(h(x)) h'(x)=4\cos^3 (x) (-\sin x) = -4\cos^3(x)\sin(x)$.


text:
Q: Understanding Iptables rules to prevent DDoS Following IPTables rules exist on my system as some preventive measures against DDoS attacks
-A INPUT -s 255.0.0.0/8 -j LOG --log-prefix "Spoofed source IP"
-A INPUT -s 255.0.0.0/8 -j DROP
-A INPUT -s 0.0.0.0/8 -j LOG --log-prefix "Spoofed source IP"
-A INPUT -s 0.0.0.0/8 -j DROP

Is it restricting private IP Address Group with the assumption that packets originating from private IP Address range from Internet are actually spoofed IP Address.
Also, How to calculate the corresponding IP Address range from the above subnets ?

A: The -A INPUT -s adds a rule for any packets with the source subnets specified on the line.
Therefore, in your example, you are logging and dropping all packets that have a source IP address that starts with 255 and all that start with 0, such as 255.1.2.3.4 or 0.56.78.90
The idea here is that there should will never be packets that start with those addresses and therefore if they do appear, they must be spoofed.
There are actually many more invalid or reserved IP addresses that the ones you've listed which could be added to that list.
There are plenty of resources on subnets and plenty of online subnet calculators to help you out.  In your case, the /8 states that the first 8 bits of the IP address specify the network and all the others (the remaining 24) specify a host within that subnet.  In both examples, the first octet (8 bits) is the network and the other three octets can be any value. Your 255.0.0.0/8 therefore can be from 255.0.0.0 to 255.255.255.255 and your 0.0.0.0/8 can be from 0.0.0.0 to 0.255.255.255.


text:
Q: Enabling Exchange Online SMTP Client Authentication with Powershell I'm trying to enable Authenticated SMTP in Exchange Online via PowerShell.
I was semi successful with my attempts.
$Users = Get-CASMailbox -ResultSize unlimited
$Users | where {$_.SmtpClientAuthenticationDisabled -eq $true} | Set-CASMailbox -SmtpClientAuthenticationDisabled $False
This resulted in about 75% of the users having SMTP Authentication activated. But weirdly not all of them.
$Users = Get-CASMailbox -ResultSize unlimited
$Users | where {$_.SmtpClientAuthenticationDisabled -eq $true -or $null -or ""} | Set-CASMailbox -SmtpClientAuthenticationDisabled $False
Showed the same results.
As did:
$Users = Get-CASMailbox -ResultSize unlimited
$Users | where {$_.ImapEnabled -eq $true} | Set-CASMailbox -SmtpClientAuthenticationDisabled $False
So apparently this has nothing to do with the state of SmtpClientAuthenticationDisabled since I tried all possible states and used ImapEnabled -eq $true as a condition which is $true for every user.
I just started working with PowerShell and only have some basic programming knowledge. This setting has to be changed for about 80 accounts right now, but in a week or two about 4000 accounts will be synchronized with AzureAD and therefore Exchange Online. So far I haven't received an answer from the company which synchronizes the accounts on wether or not it's possible to set the state of  SmtpClientAuthenticationDisabled when the synchronization happens. I expect that I will have to do it myself.
All users have an active Office 365 Licence and an active Exchange Online Plan.
Does anyone have some insight as to why only most but no all of the users accept this setting?
Edit:
When trying to execute your suggested script or when trying to execute my own commands I run into the issue that '$user' returns '$null' which I don't understand.
Setting SmtpClientAuthenticationDisabled for  failed, error: Cannot bind argument to parameter 'Identity' because it is null.

This also happens when im only executing this:
$Users = Get-CASMailbox -ResultSize Unlimited
foreach($user in $users) {Write-Host "$($user.DisplayName)"}

It just returns nothing.
I think there is something fundamental that I don't understand.
If I just list the contents of '$users' PowerShell returns a list of all the users with the related settings like 'SmtpClientAuthenticationDisabled'.

A: If you want your complete organization to use the same setting, you should leave the values of the users $null. Instead set the TransportConfig.
Get-TransportConfig

Then check the value. If it is set to 'False', all users with a $null-value for SmtpClientAuthenticationDisabled will have the default setting of 'False'.
If set to 'True', change to 'False' instead:
Set-TransportConfig -SmtpClientAuthenticationDisabled $false

To answer your original question, of why the users are not updated properly. I think it has something to do with the fact that 'SmtpClientAuthenticationDisabled' is not a filterable attribute in the first place. So you will always have to query your complete dataset, which is not very elegant.
You could do something like the following to check and see what happens exactly:
$Users = Get-CASMailbox -ResultSize Unlimited
foreach($user in $Users){
    if($user.SmtpClientAuthenticationDisabled -eq $null -or $user.SmtpClientAuthenticationDisabled -eq $true){
        try{
            Set-CASMailbox -Identity $user.ExchangeObjectId.guid -SmtpClientAuthenticationDisabled $false -ErrorAction Stop
            Write-Host "$($user.DisplayName) succesfully set to correct state" -ForegroundColor Green
        }catch{
            Write-Host "Setting SmtpClientAuthenticationDisabled for $($user.DisplayName) failed, error: $_" -ForegroundColor Red
        }
    }else{
        Write-Host "$($user.DisplayName) already has the correct state: $($user.SmtpClientAuthenticationDisabled)" -ForegroundColor Green
    }
}

But personally I would change the above script to use it to set all values to $null:
Set-CASMailbox -Identity $user.ExchangeObjectId.guid -SmtpClientAuthenticationDisabled $null -ErrorAction Stop


text:
Q: Wifi not found: Ubuntu 18.4 / HP Please advise (not an expert, please keep it clear and simple):
I installed Ubuntu 18.4 on my HP 15 laptop. Everything else I managed to fix but Ubuntu does not find WIFI. I googled and tried several suggested solutions but the solutions I tried did not work did not work because there are "broken packages".
How do I

*

*Fix broken packages?

*Fix WiFi?


text:
Q: Selenium problem dismissing pop-up window I have started creating a selenium script that needs to automate upload of files to a Wordpress site. So far it works to login! A pop-up window is then displayed. I need to automate closing this window. Here's my code:
Actions actions = new Actions(driver);
IWebElement QuitGuide = driver.FindElement(By.TagName("graybutton"));
QuitGuide.Click();

this is the HTML element:
<graybutton class="normal mcg_quit_page">Quit Guide</graybutton>

If I add a breakpoint to this and step through using the debugger then it works fine. However, when I run it the Click method doesn't seem to have any effect.
Any help appreciated.


text:
Q: Upgrade pip in Amazon Linux I wanted to deploy my Python app on Amazon Linux AMI 2015.09.1, which has Python2.7 (default) and pip (6.1.1). Then, I upgraded the pip using the command:
sudo pip install -U pip

However, it seemed broken, and showed the message when I tried to install packages:
pkg_resources.DistributionNotFound: pip==6.1.1

I found out that pip remove the previous files located in /usr/bin/, and installed the new one in /usr/local/bin. Thus, I tried to specify the location by using the command:
sudo pip install -U --install-option="--prefix='/usr/bin'" pip

Nevertheless, it still installed the new one in /usr/local/bin. In addition to that, pip could not work well with sudo although it successfully installed. The error message :
sudo: pip2.7: command not found

Is there a way to properly manage pip?

A: The problem is partly answered by your question. The Amazon AMI doesn't consider /usr/local/bin to be part of the root account's PATH. You can fix this by updating the root account's ~/.bashrc to include it.
Something like this...
export PATH=$PATH:/usr/local/bin

A: After struggling with this for hours and reading comments
which pip gave /usr/bin/pip , but the actual pip was located at /usr/local/bin/pip due to pip upgrade and clean up was not complete
So removing the pip in /usr/bin/

sudo rm /usr/bin/pip

and also adding the new pip to your export path

vim ~/.bash_profile
PATH=$PATH:$HOME/bin:/usr/local/bin

exit terminal, and login back
which pip should give /usr/local/bin/pip
pip install --upgrade pip

A: Try:
sudo which pip

This may reveal something like 'no pip in ($PATH)'.
If that is the case, you can then do:
which pip

Which will give you a path like /usr/local/bin/pip.
Copy + paste the path to pip to the sbin folder by running: sudo cp /usr/local/bin/pip /usr/sbin/
This will allow you to run sudo pip without any errors.

A: This works for me
sudo /usr/local/bin/pip install --upgrade pip

A: To add to angelokh
sudo `which pip` install --upgrade pip

A: Struggled with this for a while.  Here's what I've found:

*

*ec2_user finds the pip executable, but has a module import error due to other having no read/execute permissions on the pip folders in the /usr/local/lib/python2.7/site-packages folder.  This is actually okay, since in most cases, pip installs fail when not run as root anyway.

*sudo cannot find pip.

*Entering root with sudo su - allows pip to be run without issue.

The reason sudo pip stops working after the upgrade, is because the executable (or symbolic link) is removed from /usr/bin.  However, what remains is a file called pip-27, which contains the following:
#!/usr/bin/python2.7
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==6.1.1','console_scripts','pip2.7'
__requires__ = 'pip==6.1.1'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip==6.1.1', 'console_scripts', 'pip2.7')()
    )

So, that's where our error comes from, as the upgrade clearly doesn't clean this file up.  Not entirely clear on where the name translation from pip to pip-2.7 occurs.
As mentioned in another answer, pip now exists in /usr/local/bin after the upgrade, which is no longer in the sudo secure path.  You can add this path to the secure_path variable by running sudo visudo.  Another alternative, if you'd prefer to not add that path to your secure_path is to make a symbolic link to the new pip executable in /usr/bin.

A: I think the best strategy in this case is to manage pip is as part of a virtual environment using virtualenv rather than messing with the system-level version.
If you're OK with that, here's the basic idea:

*

*Install the version of virtualenv packaged with the version of pip you are looking to upgrade to to the system-level pip (e.g. virtualenv==15.1.0 comes with pip==9.0.1):

$ sudo pip install -U virtualenv==15.1.0
You are using pip version 6.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting virtualenv==15.1.0
  Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
    100% |████████████████████████████████| 1.8MB 135kB/s
Installing collected packages: virtualenv
  Found existing installation: virtualenv 12.0.7
    Uninstalling virtualenv-12.0.7:
      Successfully uninstalled virtualenv-12.0.7
Successfully installed virtualenv-15.1.0

I used the virtualenv release notes to find out which version of pip corresponds to which version of virtualenv.

*Create the virtual environment:

$ virtualenv myenv
New python executable in /home/ec2-user/myenv/bin/python2.7
Also creating executable in /home/ec2-user/myenv/bin/python
Installing setuptools, pip, wheel...done.

*Activate the virtual environment and confirm the version and location of the upgraded pip:

$ source myenv/bin/activate
(myenv) $ pip -V
pip 9.0.1 from /home/ec2-user/myenv/local/lib/python2.7/dist-packages (python 2.7)
(myenv) $ which pip
~/myenv/bin/pip

This should allow you to install packages to this virtualenv using the pip version of your choice, without the need for sudo.

A: I think you've didn't installed the pythonXX-pip package.
I've upgraded mine straight to Python3.4, these commands works for me.
sudo su
yum install python34
yum install python34-pip


text:
Q: How to find minimum and maximum among a list of integers in Python without using built-in functions from console In the following code, I am unable to accept the input list values from console.
    s=[]
for i in range(10):
    s[i]=int(input('enter integers from 1 to 10\n'))

mini=11
for temp in s:
    if mini>temp:
            mini=temp
print('minimum : '+str(mini))

maxi=0
for temp in s :
    if maxi<temp:
        maxi=temp
print('maximum :'+str(maxi))

IndexError : list argument index out of range.
Cant find where index went out of range.Please help, thanks in advance.

A: You should be appending, you cannot index an empty list so s[i] will fail straight away with s[0] as the list is empty:
s = []
for i in range(10):
   s.append(int(input('enter integers from 1 to 10\n')))

mini,maxi = 0, 11
for temp in s:
    if temp < mini:
        mini = temp
    if temp > maxi:
        maxi = temp
print('minimum : '+str(mini))
print('maximum :'+str(maxi))

You can also check the two in a single loop as above instead of doing two iterations over s.
You can also use a list compt to create your list of numbers:
s = [int(input('enter integers from 1 to 10\n')) for _ in range(10)]

A: you should append to the list.
s=[]
for i in range(10):
    s.append(int(input('enter integers from 1 to 10\n')))

mini=11
for temp in s:
    if mini>temp:
        mini=temp
print('minimum : '+str(mini))

maxi=0
for temp in s :
    if maxi<temp:
        maxi=temp
print('maximum :'+str(maxi))


text:
Q: Sums of convex functions strictly convex in one variable Let $f_i:\mathbb{R}^n\to\mathbb{R}$, $i=1,2,\ldots,n$ be twice continuously differentiable, convex functions in $x = (x_1,x_2,\ldots,x_n)$. Let each $f_i$ be strictly convex in $x_i$. Is the function $$g(x) = \sum_{i=1}^n f_i(x)$$ strictly convex in $x$?

A: No. Consider $f_1 = f_2 = x^2+2xy+y^2.$


text:
Q: How to Write c# script for creating msi package in visual studio i know that wix installer can be used to create msi package in visual studio but in my case i have a wpf form where the user can select the path of the source file(the file that is going to be deployed) and the output path (Msi package is created here) .When the user click  create msi button then the script runs and creates the msi package in the selected output path.
I came to know that using wix# we can write script but i don't know how to run the script from wpf application.


text:
Q: About the dimension of the longitudinal component of vector field According to this lecture note http://www.staff.science.uu.nl/~wit00103/qft05.pdf
page 115. Consider a Lagrangian for a massive vector field

$$L = -\frac{1}{4} (\partial_{\mu} V_{\nu}  - \partial_{\nu} V_{\mu}  )^2 - \frac{1}{2} M^2 V_{\mu}^2 + ie V_{\mu} \bar{\psi} \gamma^{\mu} \psi  - \bar{\psi} (\partial \!\!\!/ +m)\psi    $$

It is said

Note that the dimension of the vector field is generically equal to 1, but since the longitudinal
  component carries no derivatives in $L$, its dimension is equal to 2.

I could not get why the dimension of the longitudinal component is 2. How to see that?

A: the longitudinal components are derivatives of scalars, $\partial_\mu\phi$. For a massive spin-1 $V_\mu$ they appear only in the mass term $M^2_V V_\mu^2$. That is where the dimension $2$ comes from.


text:
Q: getting 3rd-party SW that can only write ASCII output to write binary data Question
How can I make a program, capable of writing output files exclusively in ASCII, able to write binary data (specifically, 32-bit float)?

*

*How I envision the best answer:  some technique to encode a float value to ASCII characters such that the program can write that ASCII-encoded value (to a .txt file) and the resulting .txt, renamed to a .bin, has the byte structure set up so that it can then be directly read as binary (preferably float32 or float16, big- or little-endian).

*How I envision a workaround:  a technique to write the ASCII values to, say, a .vbs or .bat file which can then be launched through a system call from within the program.  The .vbs/.bat/etc. would take the (hard-coded from ASCII) values and write them out in the desired binary format.

Background

*

*Details on my setup:  I have a 3rd-party software ("3PSW") application (an industry-standard for optical analysis, FYI) with a convenient macro language that I use to set up long-duration computational analysis.  3PSW can do a system call.  I run it on Windows XP.

*Why the problem is significant:  (A) It takes longer to write the output data in say a large 1000x1000 matrix, and this IO bottleneck is limiting the scope of what we can study with 3PSW (B) the ASCII output takes up significantly more disk space than binary, (C) I need the 3PSW's output to be in a specific binary format in order to be read by another program.

*My present workaround:  I have MATLAB scripts to read the ASCII output and write it out in the desired binary format.  While this establishes functionality, the reformat/rewrite step introduces even more time in the procedure, and sometimes MATLAB & 3PSW both hang due to RAM memory usage.  Computational duration costs are limiting the granularity with which we can explore our solution space, compromising the quality of our results.  Having the reformat done by say VBSCRIPT instead of RAM-intensive MATLAB would decrease the chance that MATLAB &/or 3PSW hang due to memory, even if not impacting duration.

*I have notified 3PSW's vendor regarding this and am at their mercy whether they plan to include it in a future release.

Any help/suggestion/guidance/redirection is most welcome, as is your time in consideration.  Thank you.

A: I don't think what you want is possible without rewriting the application. If the application is capable of writing its output to STDOUT instead of to a file you could implement a filter that transforms the ASCII data stream to a binary stream before writing it to a file, but that's about it.


text:
Q: htaccess redirect issue, appending variables after URL I've had a look at a few threads, which are broadly based on this.
The problem I have is that I am redirecting all non www URL's to www and then push http to https, so my eventual URL starts as https://www.
From there, the redirects on internal pages start to append the variables at the end of the URL, IE:
http://www.domain.co.uk/internal-doors/range - when redirected to https://www.domain.co.uk/internal-doors/range formats as https://www.domain.co.uk/internal-doors/range?id=range - appending all my URL variables at the end.
My full htaccess is as follows:
Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_USER_AGENT} libwww-perl.*
RewriteRule .* – [F,L]

RewriteBase /
Options -Indexes
RewriteRule ^(admin|blog|images|imports)($|/) - [L]

ErrorDocument 404 /404.php

RewriteRule ^internal-doors/([^/\.]+)/([^/\.]+)/?$ offering.php?id=$1&o=$2 [NC,QSA]
RewriteRule ^internal-doors/([^/\.]+)/?$ detail.php?id=$1 [NC,QSA]
RewriteRule ^information/([^/\.]+)/?$ content.php?p=$1 [L]
RewriteRule ^external-doors/([^/\.]+)/([^/\.]+)/?$ offering.php?id=$1&o=$2 [NC,QSA]
RewriteRule ^external-doors/([^/\.]+)/?$ detail.php?id=$1 [NC,QSA]
RewriteRule ^accessories/([^/\.]+)/?$ detail.php?id=$1 [NC,QSA]

RewriteCond %{REQUEST_FILENAME}     !-f
RewriteCond %{REQUEST_FILENAME}     !-d
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ range.php?s=$1&r=$2 [L,QSA]

RewriteCond %{REQUEST_FILENAME}     !-f
RewriteCond %{REQUEST_FILENAME}     !-d
RewriteRule ^([^/\.]+)/?$ category.php?s=$1 [L,QSA]

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType image/x-icon "access plus 2592000 seconds"
  ExpiresByType image/jpeg "access plus 2592000 seconds"
  ExpiresByType image/png "access plus 2592000 seconds"
  ExpiresByType image/gif "access plus 2592000 seconds"
  ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
  ExpiresByType text/css "access plus 604800 seconds"
  ExpiresByType text/javascript "access plus 2592000 seconds"
  ExpiresByType application/x-javascript "access plus 2592000 seconds"
  ExpiresByType application/javascript "access plus 2592000 seconds"
  ExpiresByType text/html "access plus 600 seconds"
  ExpiresByType application/xhtml+xml "access plus 600 seconds"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\\.(ico|jpe?g|png|gif|swf)$">
Header set Cache-Control "max-age=2692000, public"
</FilesMatch>
<FilesMatch "\\.(css)$">
Header set Cache-Control "max-age=2692000, public"
</FilesMatch>
<FilesMatch "\\.(js)$">
Header set Cache-Control "max-age=2592000, private"
</FilesMatch>
<FilesMatch "\\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</FilesMatch>
Header unset ETag
Header unset Last-Modified
</IfModule>

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Hopefully this makes sense. There are a few other threads about this, but I can't see a clear definitive answer to stop URL's appending at the end of a redirect.
Thanks in advance.

A: To clarify the summary I gave, the order in which the rules are process is important. firstly enforce the https protocol and then deal with any other rewrite rules that handle dynamic url rewriting.
# Enforce https
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R,L]

# other rules


text:
Q: ArgumentCountError - Too few arguments I am just learning codeigniter and I have a page to update my database. but I get an error like this:

Type: ArgumentCountError
Message: Too few arguments to function Inhouse::ubah(), 0 passed in D:\xampp\htdocs\slc\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Filename: D:\xampp\htdocs\slc\application\controllers\Inhouse.php
Line Number: 120

How can I fix this problem? This is my code:

Controller :
public function ubah($id)
    {
        $data['title'] = 'Change Form - Data IHT Program';
        $data['inhouse'] = $this->Inhouse_model->getInhouseById($id);
        $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('subtitle', 'Subtitle', 'required');
        $this->form_validation->set_rules('overview', 'Overview', 'required');
        $this->form_validation->set_rules('goals', 'Goals', 'required');
        $this->form_validation->set_rules('agenda1', 'Agenda 01', 'required');
        $this->form_validation->set_rules('agenda2', 'Agenda 02', 'required');
        $this->form_validation->set_rules('agenda3', 'Agenda 03', 'required');
        $this->form_validation->set_rules('agenda4', 'Agenda 04', 'required');
        $this->form_validation->set_rules('agenda5', 'Agenda 05', 'required');
        $this->form_validation->set_rules('agenda6', 'Agenda 06', 'required');
        $this->form_validation->set_rules('agenda7', 'Agenda 07', 'required');
        $this->form_validation->set_rules('agenda8', 'Agenda 08', 'required');
        $this->form_validation->set_rules('trainer', 'Trainer', 'required');

        if ($this->form_validation->run() == FALSE) {
            if (!$this->session->userdata('email')) {
                $this->load->view('templates/header', $data);
            } else {
                $this->load->view('templates/login_header', $data);
            }
            $this->load->view('inhouse/ubah', $data);
            $this->load->view('templates/footer');
        } else {
            // cek jika ada gampar yg diupload
            $upload_image = $_FILES['image']['name'];

            if ($upload_image) {
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '5048';
                $config['upload_path'] = './assets/img/inhouse/';

                $this->load->library('upload', $config);

                if ($this->upload->do_upload('image')) {
                    $old_image = $data['inhouse']['image'];
                    if ($old_image != 'default.jpg') {
                        unlink(FCPATH . 'assets/img/inhouse/' . $old_image);
                    } else {
                        $new_image = $this->upload->data('file_name');
                        $this->db->set('image', $new_image);
                    }
                } else {
                    echo $this->upload->display_errors();
                }
            }

            $this->db->set('image', $new_image);
            $this->db->where('id', $id);
            $this->db->update('inhouse', $data);

            $this->Inhouse_model->ubahInhouseProgram();
            $this->session->set_flashdata('flash', 'Diubah!');
            redirect('admin/product');
        }
    }

Model :
public function ubahInhouseProgram()
    {
        $data = [
            "image" => $this->input->post('image', true),
            "title" => $this->input->post('title', true),
            "subtitle" => $this->input->post('subtitle', true),
            "overview" => $this->input->post('overview', true),
            "goals" => $this->input->post('goals', true),
            "agenda1" => $this->input->post('agenda1', true),
            "agenda2" => $this->input->post('agenda2', true),
            "agenda3" => $this->input->post('agenda3', true),
            "agenda4" => $this->input->post('agenda4', true),
            "agenda5" => $this->input->post('agenda5', true),
            "agenda6" => $this->input->post('agenda6', true),
            "agenda7" => $this->input->post('agenda7', true),
            "agenda8" => $this->input->post('agenda8', true),
            "trainer" => $this->input->post('trainer', true)
        ];
        $this->db->where('id', $this->input->post('id'));
        $this->db->update('inhouse', $data);
    }

View :

Change Form Data IHT Program

                    <?= form_open_multipart('inhouse/ubah'); ?>

                    <input type="hidden" name="id" value="<?= $inhouse['id']; ?>">

Picture

                                <img src="<?= base_url('assets/img/inhouse/') . $inhouse['image']; ?>" class="img-thumbnail">

                                    <input type="file" class="custom-file-input" id="image" name="image">
                                    Choose file

                        Title
                        <input type="text" name="title" class="form-control" id="title" value="<?= $inhouse['title'] ?>">
                        <?= form_error('title') ?>

                        Subtitle
                        <textarea type="text" name="subtitle" class="form-control" id="subtitle" rows="3"><?= $inhouse['subtitle']; ?></textarea>
                        <?= form_error('subtitle') ?>

                        Overview
                        <textarea type="text" name="overview" class="form-control" id="overview" rows="8"><?= $inhouse['overview'] ?></textarea>
                        <?= form_error('overview') ?>

                        Goals
                        <textarea type="text" name="goals" class="form-control" id="goals" rows="3"><?= $inhouse['goals'] ?></textarea>
                        <?= form_error('goals') ?>

                        Agenda 01
                        <input type="text" name="agenda1" class="form-control" id="agenda1" value="<?= $inhouse['agenda1'] ?>">
                        <?= form_error('agenda1') ?>

                        Agenda 02
                        <input type="text" name="agenda2" class="form-control" id="agenda2" value="<?= $inhouse['agenda2'] ?>">
                        <?= form_error('agenda2') ?>

                        Agenda 03
                        <input type="text" name="agenda3" class="form-control" id="agenda3" value="<?= $inhouse['agenda3'] ?>">
                        <?= form_error('agenda3') ?>

                        Agenda 04
                        <input type="text" name="agenda4" class="form-control" id="agenda4" value="<?= $inhouse['agenda4'] ?>">
                        <?= form_error('agenda4') ?>

                        Agenda 05
                        <input type="text" name="agenda5" class="form-control" id="agenda5" value="<?= $inhouse['agenda5'] ?>">
                        <?= form_error('agenda5') ?>

                        Agenda 06
                        <input type="text" name="agenda6" class="form-control" id="agenda6" value="<?= $inhouse['agenda6'] ?>">
                        <?= form_error('agenda6') ?>

                        Agenda 07
                        <input type="text" name="agenda7" class="form-control" id="agenda7" value="<?= $inhouse['agenda7'] ?>">
                        <?= form_error('agenda7') ?>

                        Agenda 08
                        <input type="text" name="agenda8" class="form-control" id="agenda8" value="<?= $inhouse['agenda8'] ?>">
                        <?= form_error('agenda8') ?>

                        Trainer
                        <input type="text" name="trainer" class="form-control" id="trainer" value="<?= $inhouse['trainer'] ?>">
                        <?= form_error('trainer') ?>

                    <button type="submit" name="ubah" class="btn btn-primary mt-5">Change Data</button>
                    </form>

A: Get Argument like this "$this->uri->segment(2)"
exp:- htts://localhost/ci/50/60
$this->uri->segment(2) // O/P 50
$this->uri->segment(3) // O/P 60
for more information go here Segments
public function ubah(){
 $this->uri->segment(2);
}

A: I guess , this error occurs only when you try to access to controler without arguments like
http://localhost/slc/index.php/ubah

If you access the controler like following , there shouldn't be an error
http://localhost/slc/index.php/ubah/2

You can fix this by setting a default value to $id
public function ubah($id = -1){
    if($id != -1){
         //put your code here
    }else{
        show_404();
    }
}

A: Thanks for all of your answers, i really appreciate you guys for helping me to fix my code..
but, i just removing the "action" from my form_opener_multipart();
From this :
<?= form_open_multipart('inhouse/ubah'); ?>

Into this :
<?= form_open_multipart(); ?>

I do not really understand why it can be like that, but now my program can be run, can you guys explain to me? i'll really appreciate that.
And there is another problem, the other column of my database table can be updated except "the image" column.


text:
Q: coerce column names from column factors and populate I have data like
set.seed(6)
df <- data.frame(t = as.Date("2014/1/1")+seq(0,100.25,.25),
    name = paste(sample(c("Alert_","NonOp_"),402,replace=TRUE),
                  sample(1:10,402,replace=TRUE),sep=""),
    unit = c(rep(1:10,each=40),10,10))
head(df)

Here is some representative data
head(df)
            t     name   unit
1  2014-01-01  NonOp_3      1
2  2014-01-01  NonOp_6      1
3  2014-01-01  Alert_5      1
4  2014-01-01  Alert_7      1
5  2014-01-02  NonOp_4      1
6  2014-01-02  NonOp_2      1

How to generate a table from the names, where the table has columns of unit, t, and then names in the name column gets coerced into columns of name factored without the Alert/NonOp, and the values in the factored names columns should be NA, A (for alert), and N (for NonOp).  Here is the type of table I'm looking for, if all the numbers above were for unit 1.
unit               t   name_1 name_2 name_3 name_4 name_5 name_6 name_7 name_8 ...
   1      2014-01-01       NA     NA      N     NA      A      A      A     NA
   1      2014-01-02       NA      N     NA      N     NA     NA     NA     NA

The goal is to the named alerts / nonops into a table ordered by unit / t and write the table to a file.  And read the file into excel.

A: It sounds like the following is what you're looking for:
library(reshape2)
newdf <- cbind(df, colsplit(df$name, "_", c("V1", "V2")))
newdf$V1 <- factor(newdf$V1, c("NonOp", "Alert"), c("N", "A"))
newdf$V2 <- paste0("name_", newdf$V2)
head(newdf)
#            t    name unit V1     V2
# 1 2014-01-01 NonOp_3    1  N name_3
# 2 2014-01-01 NonOp_6    1  N name_6
# 3 2014-01-01 Alert_5    1  A name_5
# 4 2014-01-01 Alert_7    1  A name_7
# 5 2014-01-02 NonOp_4    1  N name_4
# 6 2014-01-02 NonOp_2    1  N name_2

head(dcast(newdf, t ~ V2, value.var = "V1"))
#            t name_1 name_10 name_2 name_3 name_4 name_5 name_6 name_7 name_8 name_9
# 1 2014-01-01   <NA>    <NA>   <NA>      N   <NA>   <NA>   <NA>   <NA>   <NA>   <NA>
# 2 2014-01-01   <NA>    <NA>   <NA>   <NA>   <NA>   <NA>      N   <NA>   <NA>   <NA>
# 3 2014-01-01   <NA>    <NA>   <NA>   <NA>   <NA>      A   <NA>   <NA>   <NA>   <NA>
# 4 2014-01-01   <NA>    <NA>   <NA>   <NA>   <NA>   <NA>   <NA>      A   <NA>   <NA>
# 5 2014-01-02   <NA>    <NA>   <NA>   <NA>      N   <NA>   <NA>   <NA>   <NA>   <NA>
# 6 2014-01-02   <NA>    <NA>      N   <NA>   <NA>   <NA>   <NA>   <NA>   <NA>   <NA>

Basically, start by splitting the "name" column into two columns, and then use dcast. The other steps are mostly cosmetic.

Another approach would be to use my cSplit function and dcast.data.table from the "data.table" package.
Skipping things like creating "name_blah" and replacing "NonOp" with "N" and so on, you can just directly do:
dcast.data.table(cSplit(df, "name", "_"), t ~ name_2, value.var = "name_1")
#               t     1 10     2     3     4     5     6     7  8  9
#   1: 2014-01-01    NA NA    NA NonOp    NA    NA    NA    NA NA NA
#   2: 2014-01-01    NA NA    NA    NA    NA    NA NonOp    NA NA NA
#   3: 2014-01-01    NA NA    NA    NA    NA Alert    NA    NA NA NA
#   4: 2014-01-01    NA NA    NA    NA    NA    NA    NA Alert NA NA
#   5: 2014-01-02    NA NA    NA    NA NonOp    NA    NA    NA NA NA
#  ---
# 398: 2014-04-10    NA NA    NA    NA    NA    NA NonOp    NA NA NA
# 399: 2014-04-10    NA NA    NA    NA NonOp    NA    NA    NA NA NA
# 400: 2014-04-10 NonOp NA    NA    NA    NA    NA    NA    NA NA NA
# 401: 2014-04-11    NA NA    NA NonOp    NA    NA    NA    NA NA NA
# 402: 2014-04-11    NA NA Alert    NA    NA    NA    NA    NA NA NA

A: You could also use dplyr
library(dplyr)
library(tidyr)
res <- df %>%
separate(name, c("V1", "V2")) %>%
mutate(V1=substr(V1, 1, 1), V2 =paste0("name_", V2)) %>%
select(-unit) %>%
spread(key=V2, value=V1)

library(gtools)
res1 <- res[,c(1,mixedorder(names(res)[-1])+1)]
 head(res1,2)
  #         t name_1 name_2 name_3 name_4 name_5 name_6 name_7 name_8 name_9
 #1 2014-01-01   <NA>   <NA>      N   <NA>   <NA>   <NA>   <NA>   <NA>   <NA>
 #2 2014-01-01   <NA>   <NA>   <NA>   <NA>   <NA>      N   <NA>   <NA>   <NA>
 # name_10
 #1    <NA>
 #2    <NA>


text:
Q: Airflow Kubernetes pod for worker can't start task I have Airflow 2.0.2 on GKE.
In airflow.cfg:
executor = KubernetesExecutor
pod_template_file = /opt/airflow/pod_template_file.yaml
worker_container_repository = artifactory-address/my-team-airflow
worker_container_tag = latest
namespace = K8S_NAMESPACE
delete_worker_pods = True
delete_worker_pods_on_failure = False
worker_pods_creation_batch_size = 2
multi_namespace_mode = False
in_cluster = True

In pod_template_file.yaml:
spec:
  serviceAccountName: airflow
  automountServiceAccountToken: true
  containers:
    - name: base
      imagePullPolicy: Always
      resources:
        requests:
          memory: 500Mi
          cpu: 500m
        limits:
          memory: 1000Mi
          cpu: 1000m

In Dockerfile:
ENTRYPOINT ["/opt/airflow/entrypoint.sh"]

in entrypoint.sh:
#!/usr/bin/env bash

case "$1" in
  webserver)
    exec airflow webserver
    ;;
  scheduler)
    exec airflow scheduler
    ;;
  *)
    # The command is something like bash, not an airflow subcommand. Just run it in the right environment.
    exec "$@"
    ;;
esac

I created DAG:
from airflow import DAG
from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator
from airflow.utils.dates import days_ago
from kubernetes.client import models as k8s

args = {
    'owner': 'Simon Osipov',
}

def create_pipeline(dag_):
    org_node = KubernetesPodOperator(
        namespace='my-namespace',
        image='python:3.8',
        cmds=['python', '-c'],
        arguments=['print("HELLO")'],
        labels={'foo': 'bar'},
        image_pull_policy='Always',
        name='sample-pod-task',
        task_id='sample_pod_tasks',
        image_pull_secrets=[k8s.V1LocalObjectReference('my-secret')], # created separatelly
        is_delete_operator_pod=False,
        get_logs=True,
        dag=dag_
)

    org_node

with DAG(
    dag_id='parser-prefix',
    default_args=args,
    start_date=days_ago(2),
    tags=['my-tags']
    ) as dag:
    create_pipeline(dag)

When I ran this DAG, it creates a worker pod with a worker image (my-team-airflow):
Image:         artifactory-address/my-team-airflow:latest
    Image ID:      artifactory-address/my-team-airflow@sha256:ac0d7572f50912414fbf7df9a31dd87c20bfe1f36d8be0d3116c3c01a0992370
    Port:          <none>
    Host Port:     <none>
    Args:
      airflow
      tasks
      run
      parser-prefix
      sample_pod_tasks
      2021-05-26T09:39:50.207073+00:00
      --local
      --pool
      default_pool
      --subdir
      /opt/airflow/dags/6764b9dddbf24495327cd6eedad926ce5204a4f0/my-dag.py

As far as I understand, it supposes to run sh script, see not webserver or scheduler and run all args airflow tasks run parser-prefix sample_pod_tasks 2021-05-26T09:39:50.207073+00:00 --local --pool default_pool --subdir /opt/airflow/dags/6764b9dddbf24495327cd6eedad926ce5204a4f0/my-dag.py
but I am getting an error:
airflow command error: argument GROUP_OR_COMMAND: invalid choice: 'airflow' (choose from 'celery', 'cheat-sheet', 'config', 'connections', 'dags', 'db', 'info', 'kerberos', 'kubernetes', 'plugins', 'pools', 'providers', 'roles', 'rotate-fernet-key', 'scheduler', 'sync-perm', 'tasks', 'users', 'variables', 'version', 'webserver'), see help above.
usage: airflow [-h] GROUP_OR_COMMAND ...

Seems like he is trying to execute airflow airflow, but I cant figure out, why..

A: The problem was with the old name of the image in airflow.cfg. Be sure to review your changes.


text:
Q: How to close window/app when i cant see it? ubuntu Im running ubuntu. I just tried to play supertux but my LCD didnt support the resolution and all i got was a blank screen and music playing. I tried to close it and go back to the desktop by pressing ctrl + z but that didnt work so i had to hard reset my computer!
In future what should i press when this happens?

A: ctrl+alt+backspace will kill your X session and restart is, dumping you at the login window.

A: Switch to a Virtual Terminal (Ctrl+Alt+F4), log in with your password and type "killall programname", after typing the first few letters of the program name, press tab and it should autocomplete. (e.g. killall supertux) When done Ctrl+Alt+F7 returns you to your desktop.


text:
Q: Jmeter -- sending files from JMS-publisher sampler to ActiveMQ For my test case, I need to send full messages (with header & properties) to ActiveMQ and have messages in JSON file format using JMS-publisher sampler.
How can I send JSON files (or files in any format) from JMS-publisher sampler to ActiveMQ?
Or how can I send full messages to ActiveMQ from JMS-publisher sampler?
Thanks in advance.

A: In case anybody interested:
The message content or files cannot be used for adding JMS headers or properties.
Using a JSR223 PreProcessor and grrovy, I managed to reconstruct every message with new message body, headers and properties.
Thanks to: https://jmetervn.com/2016/12/20/jsr223-with-groovy-variables-part-2/


text:
Q: Bootstrap theme for @angular/material Is there a bootstrap theme for @angular/material components?
Those components are very good but I'm using bootstrap as main framework and don't want to change it to material


text:
Q: Does  +  create lists automatically if the line starts with a dash or a bullet? I just noticed that if you have some text and you add a dash in front of the first character, then when you hit Shift + Enter before any character in the text, then it gets rendered as a list.
This way, -hello bla ble becomes a list.
Steps to reproduce:
hello bla ble

-hello bla ble

 - hello bla ble
      ^
      cursor here, press Shift + Enter

Output:
 - hell

 - o bla ble

Same with bullets:
* hola adéu

Becomes
 * hola
 * adéu

A: Yup, it does. The source code of the editor is available here on Google Code Archive and the Markdown.Editor.js file contains the following lines:
// Auto-indent on shift-enter
util.addEvent(inputBox, "keyup", function (key) {
    if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
        var keyCode = key.charCode || key.keyCode;
        // Character 13 is Enter
        if (keyCode === 13) {
            var fakeButton = {};
            fakeButton.textOp = bindCommand("doAutoindent");
            doClick(fakeButton);
        }
    }
});

What does "doAutoindent" do? Well, a couple of lines below, there's some regex magic, which you could analyze further to determine under which conditions the Shift+Enter works.
// When making a list, hitting shift-enter will put your cursor on the next line
// at the current indent level.
commandProto.doAutoindent = function (chunk, postProcessing) {

    var commandMgr = this,
        fakeSelection = false;

    chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
    chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
    chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");

    // There's no selection, end the cursor wasn't at the end of the line:
    // The user wants to split the current list item / code line / blockquote line
    // (for the latter it doesn't really matter) in two. Temporarily select the
    // (rest of the) line to achieve this.
    if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) {
        chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) {
            chunk.selection = wholeMatch;
            return "";
        });
        fakeSelection = true;
    }

    if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) {
        if (commandMgr.doList) {
            commandMgr.doList(chunk);
        }
    }
    if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) {
        if (commandMgr.doBlockquote) {
            commandMgr.doBlockquote(chunk);
        }
    }
    if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
        if (commandMgr.doCode) {
            commandMgr.doCode(chunk);
        }
    }

    if (fakeSelection) {
        chunk.after = chunk.selection + chunk.after;
        chunk.selection = "";
    }
};

Note that the /(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/ regex detects numbered lists with periods (1., 2.) etc. but not the new ones (1), 2)) we got with the CommonMark migration.


text:
Q: How to replace NA in a dataframe for a specific value using the results of another column and taking into account conditions of another column? I have a dataframe composed of 9 columns with more than 4000 observations. For this question I will present a simpler dataframe (I use the tidyverse library)
Let's say I have the following dataframe:
library(tidyverse)
df <- tibble(Product = c("Bread","Oranges","Eggs","Bananas","Whole Bread" ),
             Weight = c(NA, 1, NA, NA, NA),
             Units = c(2,6,1,2,1),
             Price = c(1,3.5,0.5,0.75,1.5))
df

I want to replace the NA values of the Weight column for a number multiplied by the results of Units depending on the word showed by the column Product. Basically, is a rule like:

Replace NA in Weight for 2.5*number of units if Product contains the word "Bread". Replace for 1 if Product contains the word "Eggs"

The thing is that I don't know how to code somehting like that in R. I tried the following code that a kind user gave me for a similar question:
df <- df %>%
mutate(Weight = case_when(Product == "bread" & is.na(Weight) ~ 0.25*Units))

But it doesn't work and it doesn't take into account the fact that if there is "Whole Bread" written in my dataframe it also has to apply the rule.
Does anyone have an idea?

A: Some of them are not exact matches, so use str_detect
library(dplyr)
library(stringr)
df %>%
   mutate(Weight = case_when(is.na(Weight) &
     str_detect(Product, regex("Bread", ignore_case = TRUE)) ~ 2.5 * Units,
     is.na(Weight) & Product == "Eggs"~ Units, TRUE ~ Weight))

-output
# A tibble: 5 × 4
  Product     Weight Units Price
  <chr>        <dbl> <dbl> <dbl>
1 Bread          5       2  1
2 Oranges        1       6  3.5
3 Eggs           1       1  0.5
4 Bananas       NA       2  0.75
5 Whole Bread    2.5     1  1.5