text:
Q: WP Query orderby meta key natural sort? I have this code:
$args = array(
    'posts_per_page' => -1,
    'post_type' => 'product',
    'meta_key'   => 'custom key',
    'orderby'    => 'meta_value',
    'order'      => 'ASC',
    'no_found_rows' => true,
    'cache_results' => false,
    'include_children' => false,
    'tax_query' => array(
        array(
            'taxonomy' => $taxonomy,
            'field' => 'id',
            'terms' => array($cat_id)
        )
    )
 );

$loop = new WP_Query($args);

When the custom key is like
FA3
FA1
FA10

the wp query orderby paramaters sorts this as
FA1
FA10
FA3

when I want a nsort-algoritm:
FA1
FA3
FA10

Is there any way of acheiving this with WP_Query? (Or is the only option to create an array and sort that array with nsort())

A: No, not as a straight WP_Query. This is because of several factors, with the main one being that mySQL doesn't natively have a natural sort for alphanumeric columns.
WordPress does support a "meta_value_num" for the orderby parameter, which causes it to cast the values to numeric to perform the sort, and this works when you're putting wholly numeric data in the meta_value's, but since you have a mixed set of text and numbers, you can't use that.
You can add a filter to the posts_orderby and rewrite the orderby clause directly to make it whatever you like. If your data is always going to start with "FA", then you could make your filter return something like this:
LENGTH(meta_value) ASC, meta_value ASC
That first sorts by the length, then by the value. So shorter items come first, giving you a semi-natural sort.

A: In case someone happens to stumble upon this I'll give a you solution, that uses "faked natural sorting" (thanks to Otto) but it also has sorting by multiple custom fields.
function orderbyreplace($orderby ) {
    global $wpdb;
    $new = str_replace($wpdb->prefix.'postmeta.meta_value ASC', 'LENGTH(mt1.meta_value) ASC, mt1.meta_value ASC, mt2.meta_value ASC', $orderby);
    return $new;
}

function get_posts_by_tax_cat($taxonomy, $parent_cat_id) {
    $args = array(
        'posts_per_page' => -1,
        'post_type' => 'product',
        'orderby' => 'meta_value',
        'order' => 'ASC',
        'meta_key' => 'flansoppning',
        'meta_query' => array(
            array(
                'key' => 'flansoppning',
                'value' => '',
                'compare' => 'LIKE'
        ),
        array(
                'key' => 'gangstorlek_mm',
                'value' => '',
                'compare' => 'LIKE'
        )
    ),
    'no_found_rows' => true,
    'cache_results' => false,
    'include_children' => false,
    'tax_query' => array(
        array(
            'taxonomy' => $taxonomy,
            'field' => 'id',
            'terms' => array($parent_cat_id)
        )
    )
  );

//Filter makes it possible to sort on flansoppning (length() gives natural sort) first and then gangstorlek_mm
add_filter('posts_orderby','orderbyreplace');
$loop = new WP_Query( $args );
remove_filter('posts_orderby','orderbyreplace');

$posts = $loop->posts;

if(!empty($posts)) {
        return $posts;
}
return array();
}

A: Complementing the Otto's answer, if you need to modify query for only product post_type, try this:
add_filter( 'posts_orderby', 'modify_posts_orderby', 10, 2 );
function modify_posts_orderby( $orderby_statement, $wp_query ) {
    // do not modify queries in the admin
    if( is_admin() ) {
        return $orderby_statement;
    }

    // only modify queries for 'product' post type
    if( $wp_query->get( 'post_type' ) === 'product' ) {
        $orderby_statement = "LENGTH(meta_value) DESC, meta_value DESC";
    }
    return $orderby_statement;
}


text:
Q: entity framework lazy loading problen I am facing a problem. After running a select statement I make lazy loading false. In that case, reference objects are null. But when debug my code everything works fine.referencr are loaded correctly. if I put waiting time before bl.LazyLoading(false) then it also works. Is there any way to detect reference are loaded? I have to wait until reference loaded. Is their any better Idea?I am not interested to use include() or reference() method.
using (var bl = new BusinessLayer<T>())
{
    bl.LazyLoading(true);
    var list = bl.GetAll();
    //wait
    bl.LazyLoading(false);
    if (list.Any())
    {
        System.Web.HttpContext.Current.Cache.Insert(key, list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
    }
    else
    {
        _logger.WriteInfo(String.Format("{0} list is empty.", key));
        throw new Exception(String.Format("{0} list is empty.", typeof(T).Name));
    }
}

A: Entity Framework has 4 different method for implementing lazy loading mechanism:

*

*Use include method;

*Virtual collection into entity class;

*Select() method;

*Entry() and Load() methods;

Approaches 3 and 4 will still load possible related entities;
More detailed you could read here: https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Organizing library dependencies I've noticed that there seem to be two approaches to linking: a flat and a hierarchical way.
Let me illustrate with two examples:

*

*A Visual Studio solution can contain multiple projects with one of them being the main project. My usual approach is then to add all required libs to the main project and none to the other projects. I like this because that way I don't get "multiple definition"-linker errors. I don't know if this approach has an official name so I'll call it the flat way.

*On the job our team works on a Linux-based traffic generation application. The build system uses Automake. When looking through the makefiles I noticed that each library specifies the libraries it requires (in the noinst_LIBRARIES variable). Each of these libraries can in turn specify their dependencies. This leads to a tree-like structure. So I call it the "hierarchical approach".
What are the best practices for this? It doesn't seem often discussed.

A: It usually comes down to static vs shared libraries.
If you use static libraries, then the main program must usually (always?) be linked against every library that it depends on, either directly or indirectly, hence a flat linking structure.
For shared libraries (or DLLs in Windows), each library bundles up its own dependencies, so the main program only needs to be linked against the libraries it depends on directly, leading to a graph structure.


text:
Q: Submit a Struts 2 form without changing the page? I have a Struts2 form that is included in a DIV overlay on a page.  When I submit this form I want it to hide/show a hidden text area on the bottom of the form that just lets the user know that the form was submitted.  From there the user could close the overlay and return back to their work.  I'm having a problem accomplishing this.  Upon my Return of a SUCCESS or NONE the page will redirect to a blank page if I do not provide it with another page in the return.  How can I submit the form and stay within the same page without redirecting at all?
Currently I am submitting the form using JavaScript
document.forms['formName'].submit();

I am using JavaScript as opposed to the <s:submit/> option because there are other parameters that need to be set on the form itself prior to form submission.

A: What you need is: AJAX.
In Struts2 you can achieve it out-of-the-box with an <sx:div> of the( deprecated since Struts 2.1, but still here and working) Struts2-Dojo Plugin.
Basically, you target the div with the dojo topic, and the result of your Action, a JSP file containing an HTML/JSP snippet, will fill the div without reloading the page.
But if you are using the latest versions of Struts2, you can easily achieve this with Struts2-jQuery Plugin, and you can find all the working example with the code too in its Showcase.
This is an example:
<s:url id="ajax" value="/ajax1.action"/>
<sj:div href="%{ajax}" indicator="indicator">
       <img id="indicator" src="images/indicator.gif"
            alt="Loading..."    style="display:none"/>
</sj:div>

Pretty easy :)
You can obviously alter the href attribute with javascript too, if you need to set parameters at runtime... just get id by id and alter href attribute.

A: You need to use Ajax call.
Please look at the example below,
Struts.xml configuration:

    <action name="**ActionName**" class="**Actionclass**"   method="**Method-calling**">
        <result type="stream">
            <param name="contentType">text/html</param>
            <param name="inputName">inputStream</param>
        </result>
        <result name="input">/Error.jsp</result>
    </action>
</package>

Action Class
public class ActionClass extends ActionSupport
{
    private InputStream inputStream;
public String **Method-calling()**
{
    //Calling Business Logic
            if(Business logic check condition)
                 {
         inputStream=new StringBufferInputStream("return x");
                 }
    else
         {
         inputStream=new StringBufferInputStream("return y");
         }
    return SUCCESS;
}

public InputStream getInputStream()
{
    return inputStream;
}
public String execute()
{
    return SUCCESS;
}

}
Html file Ajax call exxample
jQuery('***#replace-with-tag-id***').on('***blur(can  be any action)***', function() {
    var varE = jQuery('***#replace-with-tag-id***').val();
        jQuery.ajax({
            method:"GET",
            url: "***Actoin-name-struts.xml***.action", //"callAJax.action",
            data: "email="+varEmail,
            success: function(data)
                                    {
                if(""+data == "return x")
                                    {
                                    alert("x has been returned");
                }
                                else
                                    {
                                    alert("y has been returned");
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                alert('Error=' + textStatus);
                alert("errorThrown"+errorThrown);
                alert("response text = "+XMLHttpRequest.responseText);
            }

        });
    }
}).trigger('blur');

I hope, i have cleared your doubt.


text:
Q: Bootstrap clearer height differs I'm usuably using bootstrap to build up my responsive websites and I'm using the clearer-class to enable a correct clearing on mobile devices. As it can be seen in the fiddle below, the clearer-height differs in my last row - because the row is not completely filled.

Test

Test

Test

Test

Test

Test

Test

Test

So the question is:
Why has the last clearfix a height of 190px,
while all other clearfixes have a height of 210px?


text:
Q: how to acces arguments using while loop in java how do I access the contents of arguments starting from the first index using "while loop"?
I tried this one:

and get this error:

A: Test i < args.length before using args[i].  You're testing i at the top of your loop (wrong test, BTW, you want <, not <=), but by that point, it's too late: your while already accessed args[i] and died.
Try this instead:
while (i < args.length && !args[i].equals("Dua puluh")) {
    textUlang = textUlang + "ulang";
    ++i;
}

That way, you're always sure that i is a valid index before you actually try to do args[i].


text:
Q: Check effective permission for user on database object I'm convinced that another question like this must already have been asked somewhere on the internet but I just can't find it.
I'm trying to check the effective permission of a user on an object.  I can easily look up the permission if I've explicitly granted permission:
SELECT TOP(100) * FROM sys.database_permissions p
INNER JOIN sys.database_principals dp ON ( p.grantee_principal_id = dp.principal_id )
WHERE major_id = object_id( 'sp_OACreate' )

But I'm looking for the effective permissions for users with roles like SysAdmin etc for which there won't exist a record.
The end result I'm trying to achieve is to be able to query the effective permission of a user and to then grant permission if they're lacking the permission

A: Ok,
Managed to find this page detailing HAS_PERMS_BY_NAME which seems to have done the trick
DECLARE @User nvarchar(30) = 'MyUser'
DECLARE @Script nvarchar(max)

IF ( CURRENT_USER != 'dbo' )
BEGIN
    Print 'Please execute as ''dbo'' user'
    RETURN
END

IF ( HAS_PERMS_BY_NAME( @User, 'LOGIN', 'IMPERSONATE' ) = 0 )
BEGIN
    Print 'Can''t Impersonate ' + @User
END
ELSE
BEGIN
    DECLARE @HasPermission bit

    EXECUTE AS LOGIN = @User
    SELECT @HasPermission = HAS_PERMS_BY_NAME( 'sp_OACreate', 'OBJECT', 'EXECUTE' )
    REVERT

    IF ( @HasPermission = 'false' )
    BEGIN
        SET @Script = 'USE master; GRANT EXECUTE ON [sys].[sp_OACreate] TO [' + @User + ']'
        EXECUTE sp_executesql @Script
    END
END

Hopefully this will help someone else.


text:
Q: MongoDB Realm Google sign in not working for android app - App Services User Auth Our app's google sign-in is currently not working for a huge part of our user base. I have tried for days to get this thing working and I am fed up with frustration that i am unable to make this work.
I have a question for users with more experience … have you been able to successfully implement Sign in with Google for ALL your users?
I have implemented login with both token and auth code methods … but all tries end with unsuccessful errors.
with google token ID :
   AUTH_ERROR(realm::app::ServiceError:47): illegal base64 data at input byte 342

22:42:09
AUTH
    at io.realm.internal.network.NetworkRequest.onError(NetworkRequest.java:68)

22:42:09
AUTH
    at io.realm.internal.objectstore.OsJavaNetworkTransport.nativeHandleResponse(Native Method)

22:42:09
AUTH
    at io.realm.internal.objectstore.OsJavaNetworkTransport.handleResponse(OsJavaNetworkTransport.java:98)

22:42:09
AUTH
    at io.realm.internal.network.OkHttpNetworkTransport$1.run(OkHttpNetworkTransport.java:102)

22:42:09
AUTH
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)

22:42:09
AUTH
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)

22:42:09
AUTH
    at java.lang.Thread.run(Thread.java:1012)

or
crypto/rsa: verification error

*with google authCode

    error exchanging access code with OAuth2 providerenter

Any help wil be much much appreciated because frankly after reading all forum threads and documention … i am frenkly running out of ideeas.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
        // Start: signin with google
         val gso = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
             //.requestIdToken("555172020768-kd9ggah2uum9dui095fb0es4r9icf0ug.apps.googleusercontent.com")
             .requestServerAuthCode("555172020768-kd9ggah2uum9dui095fb0es4r9icf0ug.apps.googleusercontent.com")
             //.requestIdToken("555172020768-5qa3i5u536svsahannl3k8q8at3l4dgq.apps.googleusercontent.com")
             .requestEmail()
            .build()

        val googleSignInClient = GoogleSignIn.getClient(this, gso)
        val resultLauncher: ActivityResultLauncher<Intent> =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult())
            { result ->
                val task: Task<GoogleSignInAccount> =
                    GoogleSignIn.getSignedInAccountFromIntent(result.data)
                handleSignInResult(task)
            }
        // End: signin with google

        loginwithGoogleButton.setOnClickListener {
            loginWithGoogle(googleSignInClient,resultLauncher)
        }

    private fun loginWithGoogle(googleSignInClient:GoogleSignInClient, resultLauncher: ActivityResultLauncher<Intent>) {
        val signInIntent: Intent = googleSignInClient.signInIntent
        resultLauncher.launch(signInIntent)
    }

    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        showProgressDialog("Autentificare in curs!")
        try {
            if (completedTask.isSuccessful) {
                val account : GoogleSignInAccount? = completedTask.getResult(ApiException::class.java)
                val email: String? = account?.email
                val firstName = account?.givenName

                account?.serverAuthCode?.let { account.email?.let { it1 ->
                    account.givenName?.let { it2 ->
                        astaSaFie(it,
                            it1, it2
                        )
                    }
                } }

            } else {
                Log.e(
                    "AUTH", "Google Auth failed: "
                            + completedTask.exception.toString()
                )
                onLoginFailed("Google Auth failed:,${completedTask.exception.toString()}")

            }
        } catch (e: ApiException) {
            Log.w("AUTH", "Failed to log in with Google OAuth: " + e.message)
            onLoginFailed("Failed to log in with Google OAuth::,${e.message}")
        }
    }

 private fun astaSaFie(token:String, email: String, firstName: String){

       // val googleCredentials = Credentials.google(token, GoogleAuthType.ID_TOKEN)
        val googleCredentials = Credentials.google(token, GoogleAuthType.AUTH_CODE)

        try {
            val urlDecoded = java.util.Base64.getUrlDecoder().decode(token)
            Log.d("JWT", "URL Decoded: $urlDecoded")
        }catch (e:Exception){
            Log.d("JWT","e:$e")
        }

        try {
            val decoded = java.util.Base64.getDecoder().decode(token)
            Log.d("JWT", "Decoded: $decoded")
        } catch (e: Exception) {
            Log.d("JWT", "e: $e");
        }

        try {
            val androidDecoded = android.util.Base64.decode(token, android.util.Base64.DEFAULT)
            Log.d("JWT", "Android Decoded DEFAULT: $androidDecoded")
        } catch (e: Exception) {
            Log.d("JWT", "e: $e");
        }

        try {
            val urlAndroidDecoded = android.util.Base64.decode(token, android.util.Base64.URL_SAFE)
            Log.d("JWT", "Android Decoded URL_SAFE: $urlAndroidDecoded")
        } catch (e: Exception) {
            Log.d("JWT", "e: $e");
        }

        taskApp?.loginAsync(googleCredentials) { it ->
            if (it.isSuccess) {
                Log.v(
                    "AUTH",
                    "Successfully logged in to MongoDB Realm using Google OAuth."
                )
                Helpers().setLoginSuccesfoul(this, true)
                Helpers().setAuthProvider(this,"google")

                //TODO: 1 are limite setate in cont? daca nu are inseamna ca este un user now daca da inseamana ca este un user vechi
                checkifAccountIsNeeded(email, firstName)

            } else {
                hideProgressDialog()
                onLoginFailed("Nu s-a putut crea contul,${it.error}")
                Log.e(
                    "AUTH",
                    "Failed to log in to MongoDB Realm: ", it.error
                )
            }
        }

    }

The above is my latest attempt using auth code instead of a token ID.
Any help will be greatly appreciated.

A: The instructions in https://www.mongodb.com/docs/realm/sdk/java/examples/authenticate-users/#google-user mentions that you should pass getIdToken() when using GoogleAuthType.ID_TOKEN, but seems like you are passing the serverAuthCode when using the token id approach.


text:
Q: stream_set_timeout not working for ssh2_exec in PHP I am having trouble when try to set timeout for my ssh2_exec connection in PHP, so that when there is something wrong when running the command, it will release the executing thread and will not jam the whole web site. I have tried stream_set_timeout($stream,$seconds) but it seems not to work as expected.
Is there any ideas on this?
//run specified command (ssh)
    function runCMD($cmd){
        if (!($stream = ssh2_exec($this->conn, $cmd )))
        {
            echo "fail: unable to execute command\n";
            fclose($stream);
            return ERROR_SSH_EXEC_COMM;
        }

        sleep(1);
        stream_set_timeout($stream,5);//>>not work
        stream_set_blocking($stream, true);
        $res = stream_get_contents($stream);

        return $res;
    }

A: For anyone wondering how to set the timeout, there's a default_socket_timeout variable in php.ini that can be used to set the timeout for any socket-based connections in your current session.
You can check it by simply running
$timeStart = time();
ini_set("default_socket_timeout", 5);
$ssh = ssh2_connect('123.123.123.123');
echo (time() - $timeStart), PHP_EOL;

A: Here's how you could do that with phpseclib, a pure PHP SSH2 implementation:
<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

$ssh->setTimeout(5);
echo $ssh->exec('whatever');
?>

If you want to execute subsequent commands after that one you'll need to do $ssh->reset().

A: AFAIK, There are no true 'timeout' implementations in the php ssh2 specs.
The only solution that I have found for this problem can be found in this post here:
PHP ssh2_connect() Implement A Timeout


text:
Q: Why does Environment.NewLine not work on .net label? I have a solution to this little problem, but I'm trying to get my head around what is happening.
I have a website with a label:
  <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

And on Page_load I have:
 protected void Page_Load(object sender, EventArgs e)
    {
         Label1.Text = "It is now: " + Environment.NewLine + DateTime.Now.ToShortTimeString();
    }

Why does this not produce a new line / carriage return?
I have a solution but I'm just trying to grasp what is going on and why this doesn't work.

A: A line break in html is
:
Label1.Text = "It is now:
" + DateTime.Now.ToShortTimeString();


text:
Q: new aptana 3/titanium studio new project glitch Hello I recently noticed like 2 days ago that every time I create a new php , rails or any new project for that matter, I create the project successfully but after like 5 seconds of creating the project there is a [master] and a * next to it. For example a project I created before normally in the project explorer is fuel_intro, but now if I create a new project I have something like *fuel_project[master]. I have been trying to fix this problem for 2 days now. It is annoying because my files are in red color like if it was a bundle.So does anyone know why I am getting this?

A: This has to do with the GIT repository it creates internally.
Therefore, you have a version control on your own computer and that does actually make sense. (always use version control).
Not sure how you could disable this, but you could actually go along with it, and just commit the files you have changed. Once committed it will not be red anymore.
If you go to the menu and select preferences. Type there git and see what options you have. Good luck!

A: Topener's reply covered the reason.  Just want to add that if you want to turn off the git decorations, you could go to Preferences > General > Appearance > Labor Decorations and uncheck Git Decorator.


text:
Q: Undefined Array position when using big callback function So, our professor asked to make a brute force Traveling Salesman in JavaScript, this is the permutation algorithm i'm using:
function heapPermute(A, callback){
  var n = A.length;
  var c = [];
  var i = 0;

  for(i = 0; i < n; i++){
    c[i] = 0;
  }

  callback(A);

  i = 0;
  while(i < n){
    if(c[i] < i){
      if(i % 2){
        swap(A, c[i], i);
      }else{
        swap(A, 0, i);
      }
      callback(A);
      c[i]++;
      i = 0;
    }else{
      c[i] = 0;
      i++;
    }
  }
}

And call it like the following:
heapPermute(ArrayOfIndex, function(input){
    console.log(input);
});

console output with ArrayOfIndex = [1,2,3]
Array [ 0, 1, 2 ]
Array [ 1, 0, 2 ]
Array [ 2, 0, 1 ]
Array [ 0, 2, 1 ]
Array [ 1, 2, 0 ]
Array [ 2, 1, 0 ]

Thing is, when i use simple callback functions like console.log() the code runs with no problem and console logs all permutations, but if i try to do use the indexes to calculate the best route, i get Undefined when accessing the array positions.
bestDistance = Number.MAX_SAFE_INTEGER;
distMatrix = //Matrix read from .json;
bestRoute = [];

function checkIfBestRoute(route){

  console.log(route);   //this prints an Array with 2 undefined positions

  //distMatrix is global
  var distance = distMatrix[route[route.length - 1]][route[0]];    //Undefined route[0]

  for(var i = 0; i < route.length - 1; i++){
    distance += distMatrix[route[i]][route[i + 1]];
  }

  if(distance < bestDistance){
    bestDistance = distance;
    bestRoute = route.splice(0);
  }
}

heapPermute(ArrayOfIndex, checkIfBestRoute);    //Undefined route[0] trace

Console output when calling the function like the block above with ArrayOfIndex = [0, 1, 2, 3]
Array [ 0, 1, 2, 3 ]
Array [ undefined, undefined ]
TypeError: route[0] is undefined


text:
Q: Multiple Comparisons Adjustment for Sample Size in R I'm trying to compute a sample size for a study that has 5 groups. Aside from computing Cohen's f for the overall ANOVA, how can I compute a sample size for each group that adjusts for pairwise post-hoc comparisons, a la Tukey?  Is there a function in R that does this or would calculating Cohen's d and adjusting the alpha work here?

A: I think you're looking for a power analysis. Take a look at this blog. Specifically, you might use the pwr.anova.test function in R.


text:
Q: Pandas: tz_convert using apply returns object rather than datetime I have a dataframe indexed by timestamps in UTC, along with 2 columns specifying the time zone and daylight savings offsets in minutes from UTC:
                           time_zone  daylight_saving
END_DATE
2017-06-02 00:00:00+00:00          0               60
2017-06-02 01:00:00+00:00          0               60
2017-06-02 02:00:00+00:00          0               60
2017-06-02 03:00:00+00:00          0               60
2017-06-02 04:00:00+00:00          0               60

I'm attempting to convert the timestamps to the local timezone by using pytz.FixedOffset. Using a static offset works fine, I get a datetime with the appropriate timezone:
In [51]: df.tz_convert(pytz.FixedOffset(120))[['time_zone','daylight_saving']].head()
Out[51]:
                           time_zone  daylight_saving
END_DATE
2017-06-02 02:00:00+02:00          0               60
2017-06-02 03:00:00+02:00          0               60
2017-06-02 04:00:00+02:00          0               60
2017-06-02 05:00:00+02:00          0               60
2017-06-02 06:00:00+02:00          0               60

In [52]: df.tz_convert(pytz.FixedOffset(120))[['time_zone','daylight_saving']].head().index
Out[52]:
DatetimeIndex(['2017-06-02 02:00:00+02:00', '2017-06-02 03:00:00+02:00',
               '2017-06-02 04:00:00+02:00', '2017-06-02 05:00:00+02:00',
               '2017-06-02 06:00:00+02:00'],
              dtype='datetime64[ns, pytz.FixedOffset(120)]', name='END_DATE', freq=None)

In order to do this using the offset columns, however, I need to use the apply method:
In [63]: r_df.apply(lambda r:
r['END_DATE'].tz_convert(pytz.FixedOffset(r['time_zone'] +
r['daylight_saving'])), axis=1).head()
Out[63]:
0    2017-06-02 01:00:00+01:00
1    2017-06-02 02:00:00+01:00
2    2017-06-02 03:00:00+01:00
3    2017-06-02 04:00:00+01:00
4    2017-06-02 05:00:00+01:00
dtype: object

As you can see in the output, this returns an object series, not a datetime series as I expected.
If I try to convert it back using pd.to_datetime, I am forced to return it to UTC, defeating the purpose of applying the timezone.
Is there any way to convert this back to a dt while retaining the tz info?

A: I stumbled onto the same issue and reported it to the Pandas community, who redirected me to an older issue referencing the same problem. Sadly there is still no solution to the issue, but if you would like to track the issue you can check out:

*

*The issue I reported.

*The issue I was redirected to.

A: I encountered the same issue today in the exact same situation.
Found a workaraund by chaining the call to tz_convert with dt.tz_localize(tz=None).
# function to apply
def tz_func(x):
    return x.dt.tz_convert(x.name).dt.tz_localize(tz=None)
# group by timezone and transform with function
r_df.groupby("time_zone")["END_DATE"].transform(tz_func)

Then the resulting series will be of datetime type and not object, since having localized dates produces the pd.Series with type "object".


text:
Q: python - building a unique DB and counting the number of appearances Im reading a large file, where each row has 20 numbers.
I want to end up with a 2D-array, where each row will be a unique row from the file, and in addition for each row I will have the number of times it appeared in the file.
So I did this by building rowDB - a list of lists(where each sub-list is a 20 numbers row from the file), and another list that indicates how many times it appeared:
[uniq, idx] = is_unique(rowDB, new_row)
if (uniq):
   rowDB.append(new_row)
   num_of_occurances.append(1)
else:
   num_of_occurances[idx] += 1

I created this help-function:
Check if new_row is unique - i.e does not exist in rowDB.
Return uniq = True/False, and if False return also the index of the row in rowDB.
def is_unique(rowDB, new_row):
    for i in range(len(rowDB)):
        row_i = rowDB[i]
        equal = 1
        for j in range (len(row_i)):
            if (row_i[j] != new_row[j]):
                equal = 0
                break
        if (equal):
            return [False, i]
    return [True, 0]

However when the DB is large it takes lot of time. so My question is what is the most efficient way to perform this? maybe using numpy array instead of lists?
and if so, maybe there is a built in numpy function to check if a row is unique and if not to get the row index? how would you build this DB? Thanks!!!

A: You could probably use Counter for that, there are some good examples on the official documentation.

A: You may use tuple to save each line data, and build rowDB using OrderedDict, which maps line tuple to line number, then is_uniq is a simple and quick check as:
return new_row not in rowDB

is_uniq would be:
def is_uniq(rowDB, new_row):
    if new_row in rowDB:
         return False, rowDB[new_row]
    else:
         return True, 0


text:
Q: Prevent controller from running before HTTP request is fulfilled? $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
    if ($rootScope.carNameMap) {
        _import.stateEvent.changeTitle(toState, toParams, event);
    } else {
        _import.getCompanies.init().then(function(res){ //<-- promise
            _import.stateEvent.changeTitle(toState, toParams, event);
        });
    }
});

As you can see, in my $stateChangeStart I check if carNameMap was already created, if not I run a service that sends HTTP request, and returns a promise.
But when I have a remote db, my controller runs before http request ends.
How can I prevent controller from running before HTTP request is fulfilled?

A: You should check out the resolve functionallity that angularJs provides in the $routeProvider in the config blocks:
app.config(function ($routeProvider) {
  $routeProvider
    .when('/',
    {
      templateUrl: "app.html",
      controller: "AppCtrl"
      resolve: {
        foo: function ($q) {
            //your logic goes here, and then your controller will receive an "foo" parameter.
        }
      }
    }
  )
});


text:
Q: Extension .js files don't show up in Chrome debugger When I right click on the icon for my extension-in-development and click Inspect Popup (or when I click the icon and choose "Inspect Element") and look under the "Sources" tab, my .js file is nowhere to be seen - only a long list of inspect-able files like apitest, devtools, json_schema, etc. I can, however, find the code through the Elements tab by following the link in the .html file, but that doesn't bring to anywhere where I can actual debugging.
I've also loaded the "Hello, world" extension that Google's tutorial provides, and when I Inspect that one, its .js file is right there. I can't imagine what I've done differently from the tutorial example to cause this.
It's Chrome version 22.0.1229.94 run in a Linux VM. If there's any more information I should be providing, please let me know.

A: If I understand your question right,
Under the sources tab, there are two more tabs, one says Sources and the other says Content scripts. You need to click on the content scripts tab, and there you will find what you are looking for.

A: Type location.reload(true) in the console.
http://developer.chrome.com/extensions/tut_debugging.html

A: Okay So I figured it out, simply click on you extension icon, and a little dialog will pop up, then right click on it and click on inspect element. You can figure it out from there I reckon.  (My other answer would be good if it was a content script, but this is a popup script.)


text:
Q: $exceptionHandler to show error message on page What is the best solution to display error message on some element on HTML page?
Currently I have overriden $exceptionHandler to store error message to $rootScope.errorMessage and then on HTML page I'm using ng-show on div to show the content of the variable.
My div is located at top of the ng-view so it's not included to partials.
When error occurs the div is updated correctly but how can I reset it when user does some action, example ng-click in some partial.
I'm able to reset error message when navigating from page to another.

A: I think that there is probably quite a number of ways of doing this. You could define a $on message to listen for and then $emit 'said message' throughout code. Alternatively, you could play with listening for clicks on the body element, presuming nothing down the stack stops propagating the events.
For me it kinda depends on how big your app is.
hope this helps


text:
Q: How to force BIND 9.16 to resign my zones after editing zone file I'm using BIND 9.16 new dnssec-policy feature on my zones, following the guide to enable DNSSEC. Everything worked like a charm.
Now, I need to add another record to one of my zones, but after editing the zone file on /var/lib/bind/db.mydomain.com and using:
rndc reload
systemctl restart bind9

my .key file Kmydomain.com.xxxx.key is not being updated and on the logs, I see messages with the old serial for the zone (signed) and the new serial for the zone (unsigned).
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (unsigned): loaded serial 2021100801
...
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): loaded serial 2021100607 (DNSSEC signed)
...
Oct  8 13:07:04 bind named[622]: all zones loaded
Oct  8 13:07:04 bind named[622]: running
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): receive_secure_serial: unchanged
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): sending notifies (serial 2021100607)
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): reconfiguring zone keys
...
Oct  8 13:07:04 bind named[622]: zone mydomain.com/IN (signed): next key event: 08-Oct-2021 17:59:00.636

Reading the docs, I can't find references to a manual step to ask BIND to resign my zone, and I would like to know how to proceed.
My zone for the domain on /etc/bind/named.conf.local is
zone "mydomain.com" in {
    type master;
    file "/var/lib/bind/db.mydomain.com";
    allow-transfer { 123.123.123.123; };
    also-notify { 123.123.123.123; };
    dnssec-policy default;
};

A: In the end I used the "nuclear" option of removing the K* files for mydomain.com from /var/cache/bind/
rm -f /var/cache/bind/Kmydomain.com.*

Followed by restarting BIND
rndc reload
systemctl restart bind9

I had to generate a new DS record and update it on my parent DNS server, but I could not wait any longer.
If you know how to properly ask BIND to generate new (key/private/state) files when editing zone files I really would like to know.


text:
Q: Uninstall ClickOnce application with PowerShell? Is it possible to uninstall a click once client app using windows powershell?
Get-WmiObject Win32_Product -Filter "name='xxxx'"
When I use above, click once application doesn't show up. But it works with other apps. (Getting everything without filter also doesn't contain the click once application. But its visible in add/remove program UI).
Please help.
Thanks in advance.

A: read this:
http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/51a44139-2477-4ebb-8567-9189063cf340/
EDIT after comment:
$InstalledApplicationNotMSI = Get-ChildItem HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall | foreach-object {Get-ItemProperty $_.PsPath}

$UninstallString = $InstalledApplicationNotMSI | ? { $_.displayname -eq "YourAppicationDisplayName" } | select uninstallstring

cmd /c $UninstallString.UninstallString

the problem is that is not an Silent unistallation.
You have to add code for sendkey() TAB + ENTER to made it silently.

A: Here is a simple PowerShell script which uninstall the ClickOnce app (where DisplayName = your app process name]) and handles the UI:
$InstalledApplicationNotMSI = Get-ChildItem HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall | foreach-object {Get-ItemProperty $_.PsPath}
$UninstallString = $InstalledApplicationNotMSI | ? { $_.displayname -match "[your app process name]" } | select UninstallString
$wshell = new-object -com wscript.shell
$selectedUninstallString = $UninstallString.UninstallString
$wshell.run("cmd /c $selectedUninstallString")
Start-Sleep 5
$wshell.sendkeys("`"OK`"~")


text:
Q: Humanoid:MoveTo() doesn't work | Roblox LUA So i'm trying to make a little bot that moves to a point in the map
Here is my code :
local character = script.Parent
local humanoid = character.Humanoid
local testpoint = character.Parent.Points["End Part 2"].Position

humanoid:MoveTo(testpoint)
humanoid.MoveToFinished:Connect(function()
    print("Reached Dest")
end)

when i launch the game, the dummy model doesn't move at all (even if WalkToPoint have been correctly set)
and then after a few seconds the message Reached Dest prints in the console but the humanoid hasn't move.
I have no idea why this happend, could you please help me.
Thank you so much.

A: There are a few things that you might want to consider:
The first is that you need to make sure that all of the parts in the model that the humanoid is in are unanchored, because otherwise it will not move even though it will trigger "MoveToFinished" like it did for you.
The second is that there currently seems to be an issue with Roblox, as working with Vector3s that you have defined yourself in this situation can be near impossible because the humanoid will not move to the position, but rather about 5-10 studs away. I had this problem and this is how I fixed it. I hope this helps!

A:
humanoid:MoveTo(testpoint)

Aside from what I said below, testpoint is not set as a Vector, which ends up messing stuff up. A possible solution could be:
humanoid:MoveTo(Vector3.new(testpoint))

HOWEVER, You don't need to use MoveTo, I think you can use .Position just as easily, if you do this:
local character = script.Parent
local Torso = -- Get Torso somehow depending on your game rig
local pointToMove = character.Parent.Points["End Part 2"].Position
Torso.Position = Vector3.new(pointToMove)

A: I have seen problems before with trying to store an instances attribute in a variables. You should try:
local character = script.Parent
local humanoid = character.Humanoid
local testpoint = character.Parent.Points["End Part 2"]

humanoid:MoveTo(testpoint.Position)
humanoid.MoveToFinished:Connect(function()
    print("Reached Dest")
end)

Also please make sure you are getting the previous variables correctly like character and humanoid


text:
Q: Google Maps Services and Facebook Java version issue on Android Studio I'm getting this warning:
Warning:com/google/android/gms/maps/CameraUpdate.class(com/google/android/gms/maps:CameraUpdate.class): major version 51 is newer than 50, the highest major version supported by this compiler.

It seems Google Maps Services recommend me to compile with Java 1.7, but as per Facebook documentation, Facebook SDK should be compiled on Java 1.6.
What should I do: should I compile with 1.6 and ignore the warning; should I compile with 1.7 cause it will work flawless with Facebook SDK even the docs says 1.6;  or is there a way to compile Facebook SDK with 1.6 and the rest of the project with 1.7?


text:
Q: Splitting csv file of multiple objects over time by time-point Here I have an example file of multiple objects each measured at the same time-points (also ND.T represents each unique time point). I would like to split this file into separate files (using a python script) containing all objects unique to each time-point still containing the header.
Original file:
ID  ND.T    Time [s]    Position X [%s] Position Y [%s] Speed [%s]  Area [%s]   Width [%s]  MeanIntensity
1   1        3.87         417.57          11.46          0.06        339.48       14.1          245.65
1   2        8.72         417.37          11.68          0.04        342.61       14.15         239.34
1   3        13.39        417.57          11.66          0.04        344.17       14.3          239.48
2   1        3.87         439.01           6.59          0.02        342.61       11.66         204.47
2   2        8.72         438.97           6.65          0.007       342.61       10.7          197.96
2   3        13.39        438.94           6.66          0.03        345.74       11.03         214.74

Time_3.87.csv
ID  ND.T    Time [s]    Position X [%s] Position Y [%s] Speed [%s]  Area [%s]   Width [%s]  MeanIntensity
1   1        3.87         417.57          11.46          0.06        339.48       14.1          245.65
2   1        3.87         439.01           6.59          0.02        342.61       11.66         204.47

Time_8.72.csv
ID  ND.T    Time [s]    Position X [%s] Position Y [%s] Speed [%s]  Area [%s]   Width [%s]  MeanIntensity
1   2        8.72         417.37          11.68          0.04        342.61       14.15         239.34
2   2        8.72         438.97           6.65          0.007       342.61       10.7          197.96

Time_13.39.csv
ID  ND.T    Time [s]    Position X [%s] Position Y [%s] Speed [%s]  Area [%s]   Width [%s]  MeanIntensity
1   3        13.39        417.57          11.66          0.04        344.17       14.3          239.48
2   3        13.39        438.94           6.66          0.03        345.74       11.03         214.74

Example 2:
ID  ND.T    Time [s]    Position X [%s] Position Y [%s] Speed [%s]  Area [%s]   Width [%s]  MeanIntensity
1   1   3.87    417.57  11.46   0.06    339.48  14.1    245.65
1   2   8.72    417.37  11.68   0.04    342.61  14.15   239.34
1   3   13.39   417.57  11.66   0.04    344.17  14.3    239.48
1   4   18.1    417.73  11.71   0.04    337.92  14.14   225.17
1   5   22.81   417.83  11.89   0.03    344.17  14.64   233.3
1   6   27.48   417.69  11.83   0.02    345.74  14.23   238
1   7   32.16   417.65  11.94   0.03    345.74  14.71   230.75
2   1   3.87    439.01  6.59    0.02    342.61  11.66   204.47
2   2   8.72    438.97  6.65    0.007   342.61  10.7    197.96
2   3   13.39   438.94  6.66    0.03    345.74  11.03   214.74
2   4   18.1    438.9   6.53    0.04    342.61  10.46   202.9
2   5   22.81   438.97  6.7 0.02    342.61  10.3    194.32
2   6   27.48   438.89  6.71    0.006   350.43  11  219.41
2   7   32.16   438.87  6.74    0.05    348.87  10.36   219.58

A: You can use pandas to achieve this:
import pandas as pd
df = pd.read_csv(your_file)
df.groupby('Time [s]').apply(lambda x: x.to_csv(str(x.name) + '.csv'))

The above will load your csv using read_csv and then group on the Time [s] column and use this to name the file
You can see that the df is grouped on the Time [s]:
In [108]:
df.groupby('Time [s]').apply(lambda x: print(x))
   ID  ND.T  Time [s]  Position X [%s]  Position Y [%s]  Speed [%s]  \
0   1     1      3.87           417.57            11.46        0.06
3   2     1      3.87           439.01             6.59        0.02

   Area [%s]  Width [%s]  MeanIntensity
0     339.48       14.10         245.65
3     342.61       11.66         204.47
   ID  ND.T  Time [s]  Position X [%s]  Position Y [%s]  Speed [%s]  \
0   1     1      3.87           417.57            11.46        0.06
3   2     1      3.87           439.01             6.59        0.02

   Area [%s]  Width [%s]  MeanIntensity
0     339.48       14.10         245.65
3     342.61       11.66         204.47
   ID  ND.T  Time [s]  Position X [%s]  Position Y [%s]  Speed [%s]  \
1   1     2      8.72           417.37            11.68       0.040
4   2     2      8.72           438.97             6.65       0.007

   Area [%s]  Width [%s]  MeanIntensity
1     342.61       14.15         239.34
4     342.61       10.70         197.96
   ID  ND.T  Time [s]  Position X [%s]  Position Y [%s]  Speed [%s]  \
2   1     3     13.39           417.57            11.66        0.04
5   2     3     13.39           438.94             6.66        0.03

   Area [%s]  Width [%s]  MeanIntensity
2     344.17       14.30         239.48
5     345.74       11.03         214.74

Out[108]:
Empty DataFrame
Columns: []
Index: []

Here groupby will group on 'Time [s]' column, we then call apply to apply a lambda where we call the method to_csv on each grouping, we can access the group name using name attribute which is of dtype int so we cast to str and construct our csv name:
In [109]:
df.groupby('Time [s]').apply(lambda x: print(str(x.name) + '.csv'))

3.87.csv
8.72.csv
13.39.csv
Out[109]:
Empty DataFrame
Columns: []
Index: []


text:
Q: Angular 6 ng2-file-upload send list with file I have this piece of code in my Angular project and have used ng2-file-upload for uploading images.
export class Product {
    id: string;
    name: string;
    imageUrl: string;
    productCategoryId: string;
    shopId: string;
    productPropertyList: ProductProperty[] = [];
}
export class ProductProperty {
    propertyId: number;
    propertyName: string;
    productId: string;
    propertyValue: string;
}

When I try to send data with the file, the productPropertyList on server side is empty while it has data before sending.
initializeFileUploader(categoryId, shopId) {
    this.uploader = new FileUploader({
      url: this.baseUrl + 'users/' + this.authService.decodedToken.nameid + '/products/CreateProduct',
      additionalParameter: ['Url'],
      authToken: 'Bearer ' + localStorage.getItem('token'),
      isHTML5: true,
      allowedFileType: ['image'],
      autoUpload: false,
      removeAfterUpload: true,
      maxFileSize: 5 * 1024 * 1024
    });
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.uploader.onBuildItemForm = (item, form) => {
      console.log(this.product.productPropertyList);
      form.append('ProductCategoryId', categoryId);
      form.append('ShopId', shopId);
      form.append('Name', this.product.name);
      form.append('PropertyList', this.product.productPropertyList);
    };
  }

How can I send arrays?

A: You can JSON stringify it:
form.append('PropertyList',JSON.stringify(this.product.productPropertyList));


text:
Q: Handling Error in HTTPClient get method not working I am trying to catch error in HTTP get message in my service file.
Here is the script:
import { Injectable } from '@angular/core';
import { PortfolioEpicModel, PortfolioUpdateStatus } from '../models/portfolio-epic.model';
import { HttpClient, HttpErrorResponse, HttpParams} from '@angular/common/http'
import { config, Observable } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

refreshPortfolioEpicsList(id:number):Observable<PortfolioEpicModel[]>{
  this.baseUrl=this.conf.getSettings("apiUrl");
  return this.http.get<PortfolioEpicModel[]>(this.baseUrl+ "/api/pepics/"+ id.toString())
    .pipe(catchError(this.errorHandler));
}

errorHandler(error:HttpErrorResponse){
  console.info(error.message);
}

But the catchError call shows this error:

Argument of type '(error: HttpErrorResponse) => void' is not assignable to parameter of type '(err: any, caught: Observable<PortfolioEpicModel[]>) => ObservableInput'.
Type 'void' is not assignable to type 'ObservableInput'.ts(2345)

I didn't understand how to deal with it.
I am working in Angular 11.

A: You can use throwError from rxjs.
import { throwError } from 'rxjs';

errorHandler(error: HttpErrorResponse) {
  console.info(error.message);

  return throwError(error.message || "server error.");
}

Sample Solution with Success and Error Demo on StackBlitz

A: You're getting that error because the errorHandler function you're passing to the RxJS catchError operator requires either to return an Observable or to re-throw the error (like @Yong Shun has shown in his answer)
You can check the official documentation here for the catchError operator: https://rxjs.dev/api/operators/catchError


text:
Q: Solving a differential equation with only one variable So for some reason I'm blanking on solving a seemingly easy question:
$(8x + \cos(x))\mathrm dx + (4x^2 + 7\sin(x) + 1)\mathrm dy = 0$
Which I'm currently assuming is going to be solved using an integrating factor since as far as I can tell it isn't exact, linear, or homogenous (and I would need variables to separate for it to be separable).
Edit: there was a typo in the question, please ignore.

A: Write
$$
\frac{dy}{dx}=-\frac{8\,x + \cos x}{4\,x^2 + 7\sin x + 1}.
$$
Since there is no $y$ on the right hand side, all you have to do is to integrate with respect to $x$. However, the integral cannot be represented in terms of elementary functions. Are you sure there is not a $7$ in front of $\cos x$? (in which case the numerator would be the derivative of the denominator.)


text:
Q: Import of more than one App from Samsung App Store I tried to add some Apps to my Careers 2.0 profile.
I managed to add one App from the Samsung (bada) App Store. But when I try to add another one this always overwrites the first one.


text:
Q: Change of random variables
Let $X$ be a real-valued random variable with density function
  $$
f_X(x) = \begin{cases}
\frac{4}{15}x^3 & 1\leq x\leq 2 \\
0 & \text{otherwise.}
\end{cases}
$$
Find the density function of $Y =e^X$ and $Z= (X-2)^2$.

I am confused on how to tackle this problem. I know $\mathbb{P}\{Y\le y\} = \mathbb{P}\{e^X\le y\} = \mathbb{P}\{X\leq \ln y\}$.
However then I am lost on what to do.

A: We find the cdf $F_Y(y)$ of $Y$, by continuing on the path you were on. For $y$ between $e^1$ and $e^2$, we have
$$F_Y(y)=\Pr(Y\le y)=\Pr(e^X\le y)=\Pr(X\le \ln y)=\int_1^{\ln y} \frac{4}{15}x^3\,dx.\tag{1}$$
For the density function $f_Y(y)$ in the interval $[e^1,e^2]$ we want to differentiate the $F_Y(y)$ of (1). (The density will be $0$ outside this interval.)
Now we have two options: (i) Calculate the integral on the right of (1), and then differentiate or (ii) differentiate directly using the Fundamental Theorem of Calculus and the Chain Rule.
The path (i) is easy, for the integration gives no problem. I suggest also using path (ii), to  prepare for cases where the integration is not easy.

A: Consider the cumulative distribution function of $Y$ and $Z$, and use them (by differentiating) to get the probability density functions. For instance, for $x\in\mathbb{R}$,
$$
\begin{align*}
F_Y(x) &= \mathbb{P}\{Y \leq x\} = \mathbb{P}\{X \leq \ln x\} = \int_{-\infty}^{\ln x} f_X(t)dt \\
&= \begin{cases}
0 & x \leq e\\
1 & x \geq e^2\\
\int_{1}^{\ln x} \frac{4}{15}t^3 dt = \frac{\ln^4 x -1}{15} & \text{o.w.}
\end{cases}
\end{align*}
$$
so that
$$
f_Y(x) = F^\prime_Y(x) = \begin{cases}
\frac{4}{15}\frac{\ln^3 x}{x}& e\leq x \leq e^2\\
0 & \text{o.w.}
\end{cases}
$$

A: $F_Y(y)=P(Y \leq y) = P(X \leq \ln y) = \int_{-\infty}^{\ln y} f_X(x) dx$.
For $z <0$, $F_Z(z)=P(Z \leq z) =0$ as $Z \geq 0$. Thus, for $z \geq 0$
$F_Z(z)=P(Z \leq z) = P((X-2)^2 \leq z) = P(|X-2| \leq \sqrt{z}) = P( X-2 \leq \sqrt{z} \text{ and } -(X-2) \leq \sqrt{z}) = P(-\sqrt{z}+2 \leq X \leq  \sqrt{z}+2) = \int_{-\sqrt{z}+2}^{\sqrt{z}+2} f_X(x) dx$.
Now, the density of $Y$ is $f_Y(y) = F_Y'(y)$ and density of $Z$ is $f_Z(z) = F_Z'(z)$.


text:
Q: accessing table data within a table in a table I am trying to get specific contents of the second "datadisplaytable" is the Schedule type and Instructors name. The line below:
datadisplaytable = soup.find(class_='datadisplaytable').text

gets me the whole class which contains all other 'datadisplaytable's which I intend to loop through for the specific data that I need.
Using "Xpath" in selenium only gets me the contents of the selected path. and trying to use a for loop in selenium returns "WebElement not iterable'
Which brings me to the question,
How do I get the schedule type and Instructor.
catalog = https://prod-ssb-01.dccc.edu/PROD/bwckschd.p_disp_dyn_sched
term and subject is any.

A: Use find_elements_by_xpath ('<your xpath>) not  find_element_by_xpath. See the difference one is with s.
Remember find_elements return a list of web elements which you can loop through where as find_element return a single web element.


text:
Q: Print via terminal without usblp I need to print in an Epson TM-U220PD model M188D for receipts (without cups support), I used to write in a terminal [text] > /dev/lp0 but now usblp is deprecated. I can use this printer enabling the usblp kernel module, but this action disable cups.
There's other way to print, maybe using CUPS? How can I find the new path to the printer?

A: You can install it in CUPS as a raw device and then just lp -d Epson [textfile] (or possibly cat text | lp -d Epson) That's how I talk to my Eltron printers in EPL2.   In CUPS web interface it's under "Make: Raw", but in gnome-print it's "Choose Driver: Generic" then "Raw Queue".


text:
Q: How to modify the details of a debian package I am new to Ubuntu and would like to know if there's a way to modify or edit the details of a deb package. For example, I'm running the command:
sudo dpkg -I myPackage_amd64.deb and get several categories, such as Version, architecture, section, etc..
How can I remove or change the values of one or more of these categories?
Thanks very much.

A: The usual way to do this would be from a source tree. You would get a source tree by either downloading it or executing a command such as apt-get source some-package.
Once the source tree is downloaded, you would follow these steps:

*

*cd some-package*/debian

*nano control

*The control file holds information for the source tree and packages generated from the source. For the source tree, there are several fields including "Build-Depends", "Maintainer", "Section". For the package, there are fields such as "Architecture", "Depends", "Suggests", and "Description".

*nano changelog

*This is the version file that contains the changelog for this package. Simply modify the version number, or add your own section above it with your own version number.

*debuild -us -uc will re-build the package with the updated information

However, it's theoretically possible to do this by simply extracting the Debian package. (Note, I did not test this).

*

*ar x SomePackage.deb

*tar -xzf control.tar.gz

*nano control and edit the information

*tar -czf control.tar.gz conffiles control md5sums postinst postrm preinst prerm

*ar r SomePackage.deb control.tar.gz

*rm control.tar.gz data.tar.gz debian-binary conffiles control md5sums postinst postrm preinst prerm


text:
Q: React array not Updating after 1st click I am rendering and selecting a few cards in a component and adding them to an array using a context hook. 1st click is not connecting at all and accessing the context array by calling another component is returning empty value. Someone help a little. please
`import React, { useContext, useState } from 'react';
import { Link, useLoaderData } from 'react-router-dom';
import { CountryContext } from '../../../Context/CountryContext';

import Country from './Country';

const Countries = () => {
const allCountries = useLoaderData()
// const [selectedCountries, setSelectedCountries] = useState([]);
const [showAll, setShowAll] = useState(false);
const { selectedCountries, setSelectedCountries } = useContext(CountryContext)

// const handleCountryClick = (country) => {
//     const name = country.name.common;
//     console.log(name);
//     setSelectedCountries(prevCountries => {
//         if (prevCountries && prevCountries.includes(name)) {
//             return prevCountries.filter(c => c !== name);
//         } else {
//             return prevCountries ? [...prevCountries, name] : [name];
//         }
//     });
//     console.log(selectedCountries)
// };

// const handleCountryClick = (country) => {
//     const name = country.name.common;
//     console.log(name);
//     if (selectedCountries && selectedCountries.includes(name)) {
//         setSelectedCountries(selectedCountries.filter(c => c !== name));
//     } else {
//         console.log(selectedCountries);
//         setSelectedCountries(selectedCountries ? [...selectedCountries, name] : [name]);
//         // setSelectedCountries([...selectedCountries, name]);
//         console.log(selectedCountries);
//     }
// };

const handleCountryClick = (country) => {
    const name = country.name.common;
    console.log(name);
    if (selectedCountries.includes(name)) {
        setSelectedCountries(selectedCountries.filter(c => c !== name));
    } else {
        setSelectedCountries([...selectedCountries, name]);
        console.log(selectedCountries);
    }
};

const specificCountries = [
    "Canada",
    "Australia",
    "Germany",
    "United States",
    "United Kingdom",
    "New Zealand"
];

const filteredCountries = allCountries.filter(
    country => specificCountries.includes(country.name.common)
);

return (

Which Country Do you want to go?

            {
                showAll
                    ? allCountries.map(country => (
                        <Country
                            key={country.ccn3}
                            country={country}
                            selected={selectedCountries.includes(country)}
                            onClick={() => handleCountryClick(country)}
                        ></Country>
                    )) :
                    filteredCountries.map(country => (
                        <Country
                            key={country.ccn3}
                            country={country}
                            selected={selectedCountries.includes(country)}
                            onClick={() => handleCountryClick(country)}
                        ></Country>
                    ))
                //   allCountries.slice(0, showAll ? allCountries.length : 6).map(country => <Country>
  </Country>)
            }

        <button
            className='btn btn-primary my-16'
            onClick={() => setShowAll(!showAll)}
        >
            {showAll ? "Show Less" : "Show All"}
        </button>
        <button className='btn btn-primary my-16'><Link>Continu</Link></button>

);

};

export default Countries;`

console sog see click event work but not updated the array


text:
Q: Samsung Battery Life Extender - limit battery charging to 80% under Ubuntu Some of you may have used Easy Settings app that's provided by Samsung for Windows OS. Similar Samsung's tool for Linux OS distributions isn't available.
I missed Battery Life Extender function the most: I don't want my battery to be unnecessarily fully charged when I don't often use laptop while on battery for long periods of time.
How does one activate / deactivate Battery Life Extender under Ubuntu OS?

A: This was tested and validated to work on Ubuntu 12.04 x64 - 14.04 x64 and Linux Mint 16 x64 - 17.3 x64 and Samsung NP300E5Z laptop.
Essentially, we need to change content of /sys/devices/platform/samsung/battery_life_extender file to 1 or 0.
To turn on Battery Life Extender (run command from bash console):
sudo tee /sys/devices/platform/samsung/battery_life_extender <<<1
To turn off Battery Life Extender (run command from bash console):
sudo tee /sys/devices/platform/samsung/battery_life_extender <<<0
You may also use text editor, I used Sublime Text once.
There also seem to exist one or more aliases of above mentioned file, one being: /sys/bus/platform/devices/samsung/battery_life_extender


text:
Q: how can import android.support.v7.app.Appcompatactivity in android studio? I'm new in coding.
I used this import android.support.v7.app.Appcompatactivity
 for mainactivity.java but I received a red error:

cannot resolve symbol v7

I did invalidate caches restart too but that didn't work. If I run this code without that line, my app runs on Android 5.1.1 but doesn't work on galaxy j6 What's that line for?
My android studio version is 3.5.0.21,
I can show my error in a screenshot for more detail too:

package com.example.bmi;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.support.v7.app.Appcompatactivity

public class MainActivity extends AppCompatActivity {

    private EditText height;
    private EditText weight;
    private TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        height = (EditText) findViewById(R.id.height);
        weight = (EditText) findViewById(R.id.weight);
        result = (TextView) findViewById(R.id.result);
    }

    public void calculateBMI(View v) {
        String heightStr = height.getText().toString();
        String weightStr = weight.getText().toString();

        if (heightStr != null && !"".equals(heightStr)
                && weightStr != null  &&  !"".equals(weightStr)) {
            float heightValue = Float.parseFloat(heightStr) / 100;
            float weightValue = Float.parseFloat(weightStr);

            float bmi = weightValue / (heightValue * heightValue);

            displayBMI(bmi);
        }
    }

    private void displayBMI(float bmi) {
        String bmiLabel = "";

        if (Float.compare(bmi, 15f) <= 0) {
            bmiLabel = getString(R.string.very_severely_underweight);
        } else if (Float.compare(bmi,  15f) > 0  &&  Float.compare(bmi, 16f) <= 0) {
            bmiLabel = getString(R.string.severely_underweight);
        } else if (Float.compare(bmi, 16f) > 0  &&  Float.compare(bmi, 18.5f) <= 0) {
            bmiLabel = getString(R.string.underweight);
        } else if (Float.compare(bmi, 18.5f) > 0  &&  Float.compare(bmi, 25f) <= 0) {
            bmiLabel = getString(R.string.normal);
        } else if (Float.compare(bmi, 25f) > 0  &&  Float.compare(bmi, 30f) <= 0) {
            bmiLabel = getString(R.string.overweight);
        } else if (Float.compare(bmi, 30f) > 0  &&  Float.compare(bmi, 35f) <= 0) {
            bmiLabel = getString(R.string.obese_class_i);
        } else if (Float.compare(bmi, 35f) > 0  &&  Float.compare(bmi, 40f) <= 0) {
            bmiLabel = getString(R.string.obese_class_ii);
        } else {
            bmiLabel = getString(R.string.obese_class_iii);
        }

        bmiLabel = bmi + "\n\n" + bmiLabel;
        result.setText(bmiLabel);
    }
}

and my build.gradle code is
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.bmi"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    //noinspection GradlePath
    implementation files('SdkManager\\extras\\android\\support\\v7\\appcompat\\libs and select android-support-v7-appcompat')
}

A: Replacing

import android.support.v7.app.Appcompatactivity;

with

import androidx.appcompat.app.AppCompatActivity;

will work since v7 is no longer supported. You cannot use them at the same time.

A: These are support libraries to made some new features backward compatible. Google moved the support libraries from the android.support packages to androidx. You can't use both, which is why you are getting the error message.
It's encouraged to migrate to androidx. So, you should be fine removing v7 package.
What OS is your j6? What error message are you getting?


text:
Q: Android data synchronization from device sqlite to server In my application, I have two data management sources, one through web services and another standby in SQLite database in the device itself. In this, I want to add the feature to transfer the data from the device to server and from server to device if the web services available. Please suggest what would be the best way to perform this implementation.

A: Virgil Dobjanschi, author of the official Twitter app for Android, describes designing such data handling in his Google I/O 2010 presentation on Android REST client applications.


text:
Q: Python. Окончание ввода Подскажите, как задать окончание ввода данных в Python при нажатии Enter?
Например цикл, при каждом обращении запрашивает данные, при нажатии Enter - выход из цикла?
Спасибо

A: Например, так:
while True:
    data = input()
    if not data:
        break
    print(data)

Используется тот факт, что пустая строка в Python считается как False, а не пустая как True.


text:
Q: Problem with boolean variable in email validation program I am trying to create an email validation program without using the regex library. In one of my functions, I want to return a Boolean to check if there is an @ sign in the email address and also if it is in a valid position (the @ sign cannot be one of the first three characters of the string). However I am having problems with it because every time I run the program by entering in an email address with the @ sign in an invalid position, it keeps telling me that the email is valid. Please help!
valid = checkEmail(email); //function call

if(valid == true)
  cout << "Your email is valid!" << endl;

else
  cout << "Your email is invalid!" << endl;

bool checkEmail(string email)
{
  int counter;
  int length;
  bool firstThree; //checks to make sure @ is not in the first three chars

  counter = 0;
  length = email.length();
  firstThree = false;

  for(int i = 0; i < length; i++)
  {
    if(email[i] == '@')
      counter++;
  }

 for(int y = 0; y < length; y++)
 {
   if(email[0] == '@' || email[1] == '@' || email[2] == '@')
      firstThree = true;

   else
       firstThree = false;

 }

 cout << "\n" << counter << endl; //check to see if counter works

 if(counter != 1 && firstThree == true)
   return false;

 else
   return true;
}

A: I guess you need to define the function bool checkEmail(string email) at the begining of the program. Basically flip if else and the function definition.
bool checkEmail(string email)
{
  int counter;
  int length;
  bool firstThree; //checks to make sure @ is not in the first three chars

  counter = 0;
  length = email.length();
  firstThree = false;

  for(int i = 0; i < length; i++)
  {
    if(email[i] == '@')
      counter++;
  }

 for(int y = 0; y < length; y++)
 {
   if(email[0] == '@' || email[1] == '@' || email[2] == '@')
      firstThree = true;

   else
       firstThree = false;

 }

valid = checkEmail(email); //function call

if(valid == true)
  cout << "Your email is valid!" << endl;

else
  cout << "Your email is invalid!" << endl;

A: There seem to be a lot of beginner mistakes here, so I suggest learning the basics of programming and c++ first and like others suggested, use a debugger. Here are some of the mistakes:
Function definition
c++ is not like other common languages in the sense that functions need to be defined before they can be used. This means that you either need to move your checkEmail function above the function call, or create a separate definition above the function call like:
bool checkemail(string email);

as an exmaple.
Incorrect if-statement logic; Unnecessary for loop:
I'm assuming that based on how emails are formatted, you want the checkEmail function to return false if it doesn't match the correct formatting, and based on what your function currently does, that means that it will return false if the first three characters are @ or if there isn't exactly one @ symbol in the email. However, you used a && operator, which signifies and, meaning it will return true even when you don't want it to (much like how @Yastanub stated in his first comment). Better yet, that entire logic and if statement can be simplified greatly using std::string::find with a while loop and a vector (similar to this method):
vector<size_t> posVec;
size_t pos = email.find('@', 0); //note that this can be an int instead of size_t, but it can cause stack overflow with bigger numbers
while(pos != string::npos){
    posVec.push_back(pos);
    pos = email.find('@', pos+1);
}
switch(posVec.size()){
    //if there is only one @ symbol found
    case 1:
        bool firstThree = false;
        for(int i = 0; i <= 2; i++)
            //if there is only one @ but it's in the first 3 positions, the email isn't valid
            if(posVec[0] == i)
                firstThree = true;
        return !firstThree;
    //otherwise the email doesn't work
    default:
        return false;
}

Remember to include the required libraries in order for this part to work:
#include <string>
#include <vector>

This also eliminates the second for loop in your function that is useless because the variable y is not being used, and the counter that was being used for testing
Another note
Using if (valid == true) is unnecessary as well. You can just use if (valid) because of how booleans work with if-statements.


text:
Q: django: how to access only first error message in form.errors? I have a model called Users and I have a form for that model called UsersForm. In my views.py, I created a version of UsersForm, like so
form = UsersForm()
if reqest.method == POST:
    form = UsersForm(request.POST)
    if form.is_valid():
        form.save()
    c = {}
    c.update(csrf(request))
    c.update({'form':form})
    return render_to_response('home_page.html', c)

Now, my home_page.html is this:
<html>
    <body>

    <form method="post" action="">{% csrf_token %}
        {{ form }}
    <input type="submit" value="Register"/>
    </form>

    {% if form.errors %}
        {% for field in form %}
            <p> {{field.errors}} </p>
        {% endfor %}
    {% endif %}
    </body>
</html>

So, what I want is, I want to display only the first error in {{ field.errors}}.
What I was thinking was something like:
    {% if form.errors %}
        {% for field in form %}
            <p> {{field.errors}} </p> {{ break}}
        {% endfor %}
    {% endif %}

but there is no break in the django template language, right? I also tried thinking about using {% for field in form|slice:":1" %} but that wouldn't work either. Anyone know how to do this?

A: You can index lists in a django template by using the dot notation:
{{ field.errors.0 }}

Be sure to check that there is at least 1 error before doing that though, or you will get an Index out of range error.

A: Take the template tag route.
Here's a sample template tag:
from django.template.defaulttags import register

@register.filter(name='show_error')
def show_error(dictionary):
    try:
        return dictionary.values()[0][0]
    except (TypeError,IndexError,AttributeError):
        return 'tip: try again'

And use it in your template like so:
{% if form.errors %}{{ form.errors|show_error }}</span>{% endif %}


text:
Q: A website hosted on the 1.0.0.0/8 subnet, somewhere on the Internet? Background
I'm attempting to demonstrate, using a real-world example, of why someone would not want to configure their internal network on the 1.0.0.0/8 subnet.  Obviously it's because this is not designated as private address space.
As of 2010, ARIN has apparently allocated 1.0.0.0/8 to APNIC (the Asia-Pacific NIC), who seems to have begun assigning addresses in that subnet, though not in 1.1.0.0/16, 1.0.0.0/16, and others (because these addresses are so polluted by bad network configurations all around the Internet).
My Question
My question is this: I'd like to find a website that responds on this subnet somewhere and use it as a counter-example, demonstrating to a non-technical user its inaccessibility from an internal network configured on 1.0.0.0/8.  Other than writing a program to sniff all ~16 million hosts, looking for a response on port 80, does anyone know of a directory I can use, or even better yet, does anyone know of a site that's configured on this subnet?
WHOIS seems to be too general of a search for me at this point...

A: I don't know of any live sites in this range, but you do not need a counterexample -- You need RFC 1918.
Print it (possibly several times) and use the hardcopy to bludgeon the person who wants to violate it until they understand the error of their ways.

A: Since it specifically mentions 1.0.0.0 , you could quote them -
If you are using public IP addresses that have not been allocated by IANA or your ISP, then you may be using the IP network ID of another organization on the Internet. This is known as illegal or overlapping IP addressing. If you are using overlapping public addresses, then you cannot reach the Internet resources of the overlapping addresses. For example, if you use 1.0.0.0 with the subnet mask of 255.0.0.0, then you cannot reach any Internet resources of the organization that is using the 1.0.0.0 network.
You can also exclude specific IP addresses from the configured range. Excluded addresses are not allocated to private network hosts.
From http://technet.microsoft.com/en-us/library/cc783033(WS.10).aspx
Emphasis is mine, because the word illegal might scare them.

A: whois -h whois.apnic.net -- "-T inetnum -m 1.0.0.0/8" | less

Just produced 10005 lines of output, which is the first-level allocations under that netblock.  There are 566 allocations.  A few are in Australia, so might yield English-language web-pages and so might have more of a psychological impact in your re-education efforts?

A: If they use 1.0.0.0/8 and I go and join your network via WiFi or VPN, my iPhone will get confused and explode:

And your work does not want to buy me a new iPhone because they made mine explode. They're expensive.

A: I don't know any websites in the 1/8 range, but I do have my home dsl address in the 2/8 range:
$ host 2.0.232.240
240.232.0.2.in-addr.arpa domain name pointer ANantes-256-1-229-240.w2-0.abo.wanadoo.fr.

Wanadoo is the old french name of the ISP "Orange". They got the 2.0.0.0/12 pool:
$ whois 2.0.232.240

inetnum:        2.0.232.0 - 2.0.232.255
netname:        IP2000-ADSL-BAS
descr:          BSNAN256 Nantes Bloc 2

% Information related to '2.0.0.0/12AS3215'

route:          2.0.0.0/12
descr:          France Telecom Orange
origin:         AS3215

As this pool is used for adsl customers, I don't think a lot of website are hosted in that range.


text:
Q: How do I get the latest linux kernel, and why would I want to do that in the first place? I'm running 3.10-3-686-pae, and I think I would like to upgrade to 3.12 just so I can learn more about how it all works. My computer runs pretty well considering how old it is. I have been learning to use Linux for a little over two months.

A: You might find this article a bit educational to answer the 'why' portion of your question. As for 'how?' That sort of depends on your particular flavour of linux. And compiling a custom kernel can get pretty involved. For me, the most educational experience came from following Gentoo's guide on the subject.

A: How to get the latest kernel?  Goto kernel.org and download the "mainline" tar.xz file.
Make sure you have plenty of hard drive space.
wget https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.18.3.tar.xz
I normally use opensuse, but you may need to make adjustments to the process for your distribution.
decompress the kernel.
says you put it in /usr/src/kernel
goto to that folder.
cd /usr/src/kernel
make localmodconfig
make -j 8 bzImage
make -j 8 modules
make -j 8 modules_install
make -j 8 install

yast bootloader
select the new kernel version and set it active.
reboot and it is active.

A: Linux is highly modular and therefore the kernel is more commonly discussed as a lot can be done with it. For example, you could take the kernel, patch it up with lots of fixes, tweak other settings, strip out everything you won't need, and then replace your original kernel with your final product, and it will run just fine.

A: You don't need to do it in the first place, actually. Set up the latest( not provided by your distro) versions of development toolchain, and only then start to compile! It will save you alot of time and many errors and warnings just won't appear at all. Use Git sources from kernel.org - and go ahead!


text:
Q: Convert string into JsonObject type in c# I have a class Product with following properties:
public class Product
{
    public string id  { get; set; }
    public JsonObject details { get; set; }
}

An example of data in details field sent using POST request is:
 {
   "id": "1",
   "type": "icecream",
   "name": "Vanilla Cone",
   "image":
         {
           "url": "img/01.png",
           "width": 200,
           "height": 200
         }
 }

I am writing unit test for this class and methods. So earlier I put this structure in a string like :
details = "\{ \"id\":\"1\", \"type\": \"icecream\"\}, "

So now it is giving me an error that it cannot convert string type to jsonObject. Is there a way to convert such string into JsonObject?

A: you can use this code to convert a json string to your class
JsonObject jsonObj=System.Text.Json.JsonSerializer.Deserialize<JsonObject>(json);

Product product = new Product {id=(string) jsonObj["id"], details=jsonObj};

jsonObj.Remove("id");

UPDATE
if you are using array
    var jsonArray = JsonNode.Parse(json).AsArray();
    List<Product> products = new List<Product>();

    foreach (JsonObject jsonObj in jsonArray)
    {
        products.Add(new Product { id = (string)jsonObj["id"], details = jsonObj });

        jsonObj.Remove("id");
    }

A: string json = @"{
              "id": "1",
              "type": "icecream",
              "name": "Vanilla Cone",
              "image":
                  {
                    "url": "img/01.png",
                    "width": 200,
                    "height": 200
                   }
                }";

 JObject o = JObject.Parse(json);


text:
Q: PHP Carbon - Create a date in future relative to current time Imagine we have the day (of week) and the time of an event ( that is in the future ) :
$day = "Wednesday";
$time = "13:00";

And we want to create a Carbon date for that, but it has to be relative to current time :
$carbon = new Carbon();

For example if $carbon is Tuesday, 2017-01-17 09:00,
the $event date that we create should be Wednesday, 2017-01-18 13:00
In other words, the $event is a date that is taking place in the next 7 days. We don't have it's year, month and other data, but we do know it's day of week and the time.

A: you should be able to use something like:
Carbon::parse('next ' . $day)

and you can also throw the $time part in there somewhere too but can't remember exactly how right now.


text:
Q: google.cloud.bigquery python. How to get the bytes processed by query I am using Google BigQuery in my python code to fetch and insert data into tables. I would like to know the bytes processed by my queries. Is there a way to do that? I am currently using google.cloud.bigquery in python2.
Thanks.

A: In version 0.28.0 you can use either dry_run or get the results after the job is done, like so:
import google.cloud.bigquery as bq
import os

os.environ['GOOGLE_APPLICATION_CREDENTIALS']='path/to/your/secrets.json'
bc = bq.Client()
job_config = bq.QueryJobConfig()
job_config.dry_run = True

query = """your query"""
query_job = bc.query(query, job_config)
print "Total bytes this query will process: {}".format(
    query_job.total_bytes_processed)

# this approach is after you run the job without ``dry_run``
import time
query = """your query"""
query_job = bc.query(query)
while(query_job.done() != True):
    time.sleep(1)
print "Total bytes processed: {}".format(
    query_job.total_bytes_processed)


text:
Q: Location leaking between vue-test-utils tests I am trying to create everything fresh for each tests, for example creating localVue in each test, however, the location seems to be leaking between unit tests. I am using vue-test-utils and jest with vue-router. The way I work around it is to explicitly navigate to '/' at the beginning of each test. Is it inevitable, or is there a way to isolate the tests from each other?

A: Yes, because you are running tests in an environment with window on the global, any changes to window or its properties affect future tests running in the same scope. The best approach is to reset any properties that you're altering in your source code before each test.


text:
Q: Desktop computer rebooting after ~3 hours My desktop computer, less than a year old, has started rebooting automatically (as if power was suddenly lost and immediately restored), after ~3 hours of running.
After the first reboot in ~3 hours, it reboots repeatedly every 5-10 minutes at random.
If kept shut-down for a while, it then works for ~3 hours again before starting to reboot.
I thought this was a CPU overheating issue, but I monitored temperature, and it is 140F at worst (when CPU is highly taxed), and usually much cooler than that.
This is a Intel Haswell Core i5 processor with 4 GB Corsair RAM and a Corsair SSD and power supply, and no discrete GPU.
What could be the problem?
Thanks!

A: Well there are 5 (or even more) possible reasons that might cause this issue.

*

*CPU Overheat. After some temperature our computer tries to keep the temperature down by restarting or shuting down your computer. Since you said that CPU operating at max at 60C, you should check your BIOS Settings for missconfigured values on Temperature Alerts.

*Virus There are some viruses that causes your System to Restart after some specific actions. You can try cleaning your Computer with CCleaner, or some other Cleaning and AntiMalware software to ensure that your problem IS NOT any virus.

*Power deficiency. This occurs when there isn't enough power to keep electricity flowing in your motherboard, or the power supply becomes faulty.

*Faulty Motherboard. Malfunctioning capacitors on a Motherboard can create a wide range of issues. It is even possible for capacitors to fail due to a bad Power Source. A leaking capacitor is a very easy visual check. Open your case and take a look at the Motherboard. If you see a leaking capacitor (Google it), then replacement of the Motherboard is necessary. Be sure to check if your system is still under warranty before spending your money.

*BIOS. Finally, the last and often trickiest to troubleshoot source of reboot problems: your computer's BIOS. If there is a problem in your BIOS, or sometimes even in the firmware for one of the other pieces of hardware installed in your machine, it could cause an instability and lead to one of those automatic restarts. Especially if the problem is in the Advanced Configuration and Power Interface (ACPI) portion. The good news is that these problems are much less common than they used to be in the bad old days. But it never hurts to check with your computer manufacturer to see if there's an updated BIOS available.

Ref: Previous Experience and Dis


text:
Q: using powershell .sql query output is saving column name in .txt or .sql file Can anyone suggest me how to get rid of column names in the output file after executing the .sql file using powershell. I'm using the following method to achieve this
invoke-sqlcmd -inputfile C:\users\userbackup.sql -serverinstance DBATest -database Test | out-file C:\outputuser.sql

In the output file outputuser.sql ....i want to see only the rows without the column names.
Please help me on this.
thanks in advance

A: I know this is an old thread. Thought of sharing so that it helps others.
The below command works:
invoke-sqlcmd -inputfile C:\users\userbackup.sql -serverinstance DBATest -database Test | Format-Table -HideTableHeaders -Wrap| out-file C:\outputuser.sql


text:
Q: jquery with index based radio button selected value help I have following generated code and tried to retrive the radio button value or checked from below html generated code
HTML code generated :::
    <input type="radio"      name="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionnaire.value" id="SetUpTest_mergedServiceSets_0__cdaQuestionnaireresponses_0__questionnaire_valueY" value="Y" class="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionInputRadio" onchange="javascript:dataModified();"/> Yes

    <input type="radio" name="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionnaire.value" id="SetUpTest_mergedServiceSets_0__cdaQuestionnaireresponses_0__questionnaire_valueN" value="N" class="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionInputRadio" onchange="javascript:dataModified();"/> No

Jquery1.6.1 used :
var questionInputRadio = $(".mergedServiceSets[" + i + "].cdaQuestionnaireresponses[" + j + "].questionInputRadio");

where i and j are passed dynamically .
or
alert("questionInputRadio===" + $(".mergedServiceSets[0].cdaQuestionnaireresponses[0].questionInputRadio").val());

Actual results ::: undefined is displaying when i see in alert box .
It never works for index based classes or ids in jquery . please help

A: You need to escape [, ] and . in your selector.  Something like:
$(".mergedServiceSets\\[" + i + "\\]\\.cdaQuestionnaireresponses\\[" + j + "\\]\\.questionInputRadio");

Edit:  I'm actually not sure if those characters are even technically valid.


text:
Q: Getting relativePath and then diving deeper I have a package structure like
A
|_B
|_C
  |_D
    |_"myFile.txt"
myMain.java

In my main i want to do something like
Path currentRelativePath = Paths.get("");

Which gives me the current relative path to where my Main() is located. Something along the lines of /home/myprojects/project1/src/ How do I amend the above to get me the relative path all the way down to the level of myFile.txt?
I have tried things like:
 Path currentRelativePath = Paths.get("" + "/B/C/D/");

and
 Path currentRelativePath = Paths.get("","B/C/D/");

and
 Path currentRelativePath = Paths.get("");
 Path finalPath = Paths.get(currentRelativePath.toString(),"/B/C/D/");

But in each case it only gets the "/B/C/D/" portion and not the beginning of the path.

A: //Gets from the current working directory a path to B/C/D
Path path = Paths.get("B/C/D");
//String equal to "B/C/D"
path.toString();
//String equal to "/home/myprojects/project1/src/B/C/D"
path.toAbsolutePath().toString();

I think you are confusing relative and absolute paths. /home/myprojects/project1/src/ is an absolute path, not as you say in your question "the current relative path"


text:
Q: In my apple account I am not getting Certificates, Identifiers & Profiles option.provisioning profile error in xcode8 I am having valid certificate which will expire next year.When creating app i am getting Failed to create provisioning profile and No profiles for 'com.codewithsuchi.WarGame' were found.I checked my account in xcode preferences ,but no provision profile.

A: Did you finished your enrollment to the Apple Developer Program? It seems that you didn't finish some final steps. In your second screenshot it is obvious that you have to do some things here -> To continue your enrollment, complete your purchase now!
You should select this link and do the remaining stuff. Then it should work.


text:
Q: Have a firefox extension recognise a tel: tag and hangle it? I'm developing a click-to-dial tool, and would like to pass all tel: links in firefox to my extension, which will then run click to dial
so
Call this customer

should silently be passed to my extension to deal with and not ask the user which external application they wish to launch
This is primarily for Mac users although it should ideally be a cross-platform solution (so handled within the JavaScript rather than using any external applications)
Any suggestions where to look/what to Google?

A: How protocol URLs are handled is something that's determined by the operating system. You can see more details in this article.
What you'll want to do is run a content script on each page to detect tel: links and register a click handler on them. This click handler could perform the action you want, then return false to prevent any further action being taken.

A: I solved this by writing and registering my own protocol handler

*

*Mike's blog gives a helpful walkthrough

*Mozillazine explains what you're doing


text:
Q: How to fix Sys.ArgumentTypeException: Object of type 'Object' cannot be converted to type 'Function' I'm getting below error with my JavaScript function.
Uncaught Sys.ArgumentTypeException: Sys.ArgumentTypeException: Object of type 'Object' cannot be converted to type 'Function'.
Parameter name: handler

Script Manager
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
</asp:ScriptManager>

JavaScript

I can remove above error by adding ScriptMode="Release" to my Script Manager. but it deos not solve my problem. I have a gridview on JavaScript and i'm trying to get modified values from textbox in gridview. but always it gave me the old value. not modified value.
By adding ScriptMode="Release" to my Script Manager hide the error. but my problem is not fixed.
I wish to know why i'm getting this error and proper way to fix it.

A: The remove_endRequest accepts function that you want to remove from the list of handlers for endRequest Event. So the code you provided has invalid parameter because call of $(document).ready() returns the jQuery "wrapper" object instead of handler function.
If you want to call code after the end of async postback you should use add_endRequest and remove $(document).ready since it is not tied to the async postback events.

And when you don't need handle endRequest event unsubscribe myEndRequestHandler as follows:
Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(myEndRequestHandler);


text:
Q: Spring Security Https - Error when try to login with https I want to switch from http to https when user clicks on login/registration page (/user/add) and keep https session till logout.
Homepage is available without https.
My code in security.xml:
<http auto-config="true">
    <intercept-url pattern="/home*" access="ROLE_USER" />
    <intercept-url pattern="/user/add*" access="ROLE_USER" requires-channel="https"/>
    <form-login login-page="/user/add" default-target-url="/" authentication-failure-url="/user/add" />

    <port-mappings>
        <port-mapping http="8080" https="8181"/>
    </port-mappings>

</http>

I am using Glassfish 4.0, Spring MVC and Spring Security 3.0
When I am clicking on button to page /user/add, I get this Error:
ERR_TOO_MANY_REDIRECTS

Any suggestions?

A: You get too many redirects because you set you login page to "/user/add" (of course, it is not a page - you should set this address to a real login page). However, when the user gets to this address he is blocked, because the line before you define "/user/add*" as secured resource that needs to be authenticated. to the authentication fails, and then the user is redirected to "/user/add", because this is defined as the 'authentication-failure-url'.
This is the explanation.
Hope that helps :-)
PS if you want to see an example how to do the thing you want, have a look here (search for "form-login")


text:
Q: What kind of integral or analysis is capable of dealing with cantor's function? According to Lebesgue's characterization of Riemann integrable functions (see: http://www.math.ru.nl/~mueger/Lebesgue.pdf)
cantor funciton on $[0,1]$ (https://en.wikipedia.org/wiki/Cantor_function) is riemann integrable, and since it's bounded. They should be equal. However, since $f$ (the cantor function) is singular on $[0,1]$, $f'=0$ almost everywhere. Thus remmann and lebesgue both equal to $0$.
So both lebesgue and riemann integralbe can not deal with cantor's function or Weierstrass function on $[0,1]$(https://en.wikipedia.org/wiki/Weierstrass_function).
My question was what kind of analysis techniques can be used to deal with cantor funciton, or even Weierstrass function?


text:
Q: How to convert an array of objects to string and insert into sql using php? Currently I've got a list of array of sizes. I want the size to have quantity stock for each sizes.
Each object(of size and stock) will be inside an array and insert into sql.
class Item
        {
            public $size;
            public $stock;
        }
        $sizeArr = array("S", "M", "L", "XL");
        $arrObject = [];
        foreach ($sizeArr as $i) {
            $tempItem = new Item();
            $tempItem->size = $i;
            $tempItem->stock = 0;
            serialize($tempItem);
            array_push($arrObject,$tempItem);
        }

        echo implode(" ",$arrObject); //Object of class Item could not be converted to string
        //$sql = "INSERT INTO itemstock (itemName, description ,imgLinkArr, sizingAndStock, createddate) VALUES ('$itemname', '$textToStore', '$imageuri', '$sizing', '$date');";
        //mysqli_query($conn, $sql);

Here, I got an error saying Object of class Item could not be converted to string. How can I convert the array of objects to string and insert to SQL?

A: In here you are converting an object of class into the string. First, you need to convert that object into an array and then convert it into the string. See the following example :
<?php
class Item
    {
        public $size;
        public $stock;
    }
    $sizeArr = array("S", "M", "L", "XL");
    $arrObject = [];
    foreach ($sizeArr as $i) {
        $tempItem = new Item();
        $tempItem->size = $i;
        $tempItem->stock = 0;
        serialize($tempItem);
        $tempItemArray = (array) $tempItem;
        array_push($arrObject,$tempItemArray);
    }

    $final_val = '';
    foreach($arrObject as $ao) {
        $final_val .= implode(" ",$ao).",";
    }
    echo $final_val;
?>


text:
Q: Responsive Website not working with Media Queries in Css I am running a small website on Joomla and cannot get the responsiveness to work. I am running media queries for the screen sizes and making adjustments as needed, but cannot get them to adjust for anything under 760px wide.
I've checked all four of my media queries and cannot find a solution. I'm sure it's something simple, but I cannot find it. I do
/* Note: Design for a width of 768px */

@media (min-width: 768px) and (max-width: 959px) {
.main, #jf-footer .main-inner1 {
width: 768px;
}}

/* Note: Design for a width of 480px */

@media (min-width: 480px) and (max-width: 767px) {
.main, #jf-footer .main-inner1 {
width: 444px;
}}

/* Note: Design for a width of 320px */

@media (min-width: 320px) and (max-width: 767px){
.main, #jf-footer .main-inner1 {
width: 316px;
}}

I expect the main DIV to scale for 768px, 480px and 320px, but cannot get it to scale properly.
The website is located at:
https://crafted-development.com
My Css is located at:
https://www.crafted-development.com/templates/jf_calla-exteriors/css/template.css

A: You need to close the media tag also at the end with "}"
Also, instead of media, try adding "@media only screen and"
Example::
/* Note: Design for a width of 320px */

    @media only screen and (min-width: 320px) and (max-width: 767px){
      .main, #jf-footer .main-inner1 {
        width: 316px;
      }
    }

Also, the meta tag is necessary
<meta name="viewport" content="width=device-width, initial-scale=1">

A: Use this css
     @media only screen and (min-device-width: 768px) and (max-device-width: 959px) {
    .main, #jf-footer .main-inner1 {
    width: 768px !important;
    }
    }

    @media only screen and (min-device-width: 480px) and (max-device-width: 767px) {
    .main, #jf-footer .main-inner1 {
    width: 444px !important;
    }
}

    @media only screen and (min-device-width: 320px) and (max-device-width: 479px)
    {
    .main, #jf-footer .main-inner1 {
    width: 316px !important;
    }
}

A: This turned out to be the solution: Thank you guys!
/* Note: Design for a width of 320px */

@media only screen and (min-width: 320px) and (max-width: 767px){
  .main, #jf-footer .main-inner1 {
    width: 316px;
  }
}