text:
Q: Can I remap an ECU using CAN bus? I am thinking to use something like this to connect an Arduino to a motorbike ECU: http://www.skpang.co.uk/catalog/arduino-canbus-shield-with-usd-card-holder-p-706.html
I never do something like this, and I would know if using CAN bus I can only read some diagnostic parameter in the ECU or if I can also remap some ECU parameters.
Can you help me to understand this thing?

A: Via CAN you can primarily read messages transferred between different control modules in the vehicle. Many of these messages conform to a manufacturer-independent standard and can be taken as well-known or documented.
However, there are also manufacturer-specific messages which are usually not documented for access by the public. Messages controlling the configuration of the ECU and other modules are most likely of this kind, regarded as private to the manufacturer.
Therefore, messages for configuration of the control modules will mostly only be documented by someone who figured them out via reverse-engineering.
Reading and interpreting messages sent regularily on the bus should not be too difficult, as far as the messages are documented or can be analyzed easily. Those configuration messages will be hard to get hold of, probably impossible given hobbyist's means and tools.

A: No, you can not unless you know the specific diagnostic protocol implementation for this bike (usually KWP2000 or UDS), which may or may not support the ECU re flashing.
CAN is just the communication protocol. To do so, you would need to know the seed generation algorithm for security sessions access and then be able to send new data to the ECU. If you had all this information, you would then be able to reflash or remap the ECU. Why would you want to do this anyway?


text:
Q: Inserting a JS object into $http service I am trying to insert an object formatted like this:
$scope.newObj = {1: "N/A", 2: "KO", 3: "OK", 4: "OK", 5: "OK", 15: "N/A", 19: "OK"}

I tried using the following for loop:
var objt = $scope.newObject;
      console.log($scope.newObject[0]) // undefined
for(i=0;i<$scope.newObj.length;i++)
{
   $http.post("insert?etat="+$scope.newObject[0]+"&id="+Object.keys(objt))
}

But it doesn't seem to work. I am getting undefined everywhere.  Does anyone have an idea on how to retrieve the data from that object row by row then insert the values to the service?

A: newObj is an object rather than a array. You have tried to use it like a  array. So just a iteration code needs to modify:
Use the following code:
var objt = $scope.newObject;
for(var key in objt)
{
   $http.post("insert?etat="+objt[key]+"&id="+key)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python global variable empty in function So I've got a couple global variables: directory_name and file_list
They're defined at the top and then I give them values in main. I need their values in a function called checkDirectory(blocknum). If I print their values before I call the function, they're correct, but in the function they are empty. This is some of the code:
file_list = []
directory_name = ""

def checkDirectory(blocknum):
    global directory_name
    global file_list
    directory = tokenize(open(directory_name + '/' + file_list[blocknum], 'r').read())

main():
    try:
        directory_name = sys.argv[1]
        if not os.path.exists(directory_name):
            print("This is not a working directory.")
            return
    except:
        directory_name = os.getcwd()

    files = os.listdir(directory_name)
    file_list = sorted(files, key=lambda x: int((x.split("."))[1].strip()))
    ....
    checkDirectory(26)

This is a basic 100 line script, and I can pass in the variables but I'll have to do that for three or four functions which will be recursive, so I'd rather not have to do it every time.

A: You are shadowing directory_name and file_list in your main function. Since those variables are not known in that scope, they get created locally. In order to operate on the global variables, you need to declare them global in your main() as well:
file_list = []
directory_name = ""

def checkDirectory(blocknum):
    global directory_name
    global file_list
    directory = tokenize(open(directory_name + '/' + file_list[blocknum], 'r').read())

main():
    global directory_name
    global file_list
    ...

Please remember that, as mentioned in the comments, using globals is not good practice and can lead to bad code in the long run (in terms of unreadable/unmaintainable/buggy).


text:
Q: CodeBuild Windows Container Contents AWS Provides curated environment images:
> aws codebuild list-curated-environment-images --region us-west-2
...
"name": "aws/codebuild/windows-base:1.0",
...
"name": "aws/codebuild/standard:1.0",
...

The contents of the UBUNTU images can be determined from the git repo but there's nothing about the WINDOWS_SERVER images in the repo.
Where can we find information about the contents of the WINDOWS_SERVER platform images?

A: Unfortunately, the Dockerfile for Windows build image is not public. You can introspect the running container to look for clues or check what is already installed.


text:
Q: JPA entity classes are not discovered automatically with Gradle I'm new to Gradle. I'm trying to run some tests but they fail with messages showing that the entity classes are not mapped. When I explicitly map the classes in persistence.xml everything works fine. I did some research and found that adding theses lines to the build script would solve the problem:
sourceSets.main.output.resourcesDir = sourceSets.main.output.classesDir
sourceSets.test.output.resourcesDir = sourceSets.test.output.classesDir

but it simply didn't work for me. I still get the errors if I don't specify the classes in the deployment descriptor.
What could be wrong?
UPDATE
My project structure:

My persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="bd">
        <class>br.desenvolvimento.teste.modelo.Cliente</class>
        <class>br.desenvolvimento.teste.modelo.Banco</class>
        <class>br.desenvolvimento.teste.modelo.AgenciaBancaria</class>
        <class>br.desenvolvimento.teste.modelo.ContaBancaria</class>
        <class>br.desenvolvimento.teste.modelo.Filho</class>
        <class>br.desenvolvimento.teste.modelo.Projeto</class>
        <class>br.desenvolvimento.teste.modelo.Telefone</class>

        <properties>
            <property name="hibernate.show_sql" value="false" />
        </properties>
    </persistence-unit>
</persistence>

A: Which Gradle version do you use? If it is 5.x, you need to update your lines like the following:
sourceSets.main.output.resourcesDir = sourceSets.main.java.outputDir
sourceSets.test.output.resourcesDir = sourceSets.test.java.outputDir

Your sourceSets.main.output.classesDir is deprecated on Gradle 4.x and withdrawed on Gradle 5.x.
In my case, a portion of build.gradle is the following:
sourceSets {
  java {
    main {
      output.resourcesDir = java.outputDir
    }
  }
}

See: SourceSetOutput - Gradle DSL Version 5.5 https://docs.gradle.org/current/dsl/org.gradle.api.tasks.SourceSetOutput.html

A: I had the same problem and adding the
sourceSets.test.output.resourcesDir = sourceSets.test.output.classesDir

line fixed the problem for me (only this line needed). So thank you for your tip :)
I have a same project structure as yours so I don't know why this not works for you.


text:
Q: How to store value, received in delegate class, inside external one? There is a BLEManager class, that is responsible for scanning, connecting, and receiving data from Bluetooth Low Energy (BLE) devices. Looks like that:
class BLEManager: ObservableObject, OtherProtocols {
    private var myCentral: CBCentralManager!
    @Published var data = 0.0

    override init() {
        super.init()

        myCentral = CBCentralManager(delegate: self, queue: nil)
        myCentral.delegate = self
    }

    // ...some functions that scan, establish connection, etc.

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        // here I receive raw value, handle it and get a data to work with

        data = 10.0 // imagine it's the data received from BLE device
    }
}

Right now the "data to work with" is stored inside this class. I'd like to move this data in such a way, so the current class (BLEManager) is responsible for the BLE logic only, and data is stored together with other user data.
Is it possible in Swift?
P.s. I'm pretty new to Swift. Have experience in JS.
EDITED
In the current case, BLEmanager receives data from one specific peripheral. The data represents a human weight, to be clear. Other than that, there is a struct with human biometric data (age, height, gender). At the end of the day, biometric data + data from the device (weight) are closely related and are used in the same calculations.
RESULT
I was able to implement the Cristik's approach. The only difference that in my case the subsription happens in a View's .onAppear() modifier and not on class init, as he described. Had troubles with passing a publisher to the class.

A: If you plan to connect to a single device, I would keep this very simple, and let BLEManager pass this data to a delegate as it comes in. The delegate would then be responsible for deciding what to do with the data. Swift by Sundell has a nice introduction to delegates if you're not familiar with the pattern.
You'd make a separate object, a "DataManager" or whatever you'd like to call it, and it would be the delegate to the BLEManager (and would own the BLEManager). Whenever new data comes in, call methods like bleManager(_:didReceiveWeight:) or bleManager(_:didReceiveBiometricData:).
This will split up the process of getting data from the device from managing that data and performing computations, which I think is a worthy goal.
If this is a "real" project, and you're just starting, I highly recommend this pattern. It's well understood, there are dozens of blog posts about it going back many years. It's easy to understand and implement. The only pattern that's even easier to implement is to post Notifications, from BLEManager.
On the other hand, if this is more of an exploration, and you want to jump into the deep-end and the future of Swift (and limit yourself to iOS 15), you could also look at AsyncStream to emit new values as they occur into an AsyncSequence. That eventually will likely be the "Swifty" way to do this. But it's a much steeper learning curve, and the tools are not all fully developed yet, and no one really knows how to use it yet (not even Apple; it's just too new). If getting in on the ground floor of technology excites you, it's an area that everyone is exploring right now.
But if you just want this thing to work, or you want to focus on learning Swift right now rather than learning "the future of Swift," I'd use a delegate.

A:
I'd like to move this data in such a way, so the current class (BLEManager) is responsible for the BLE logic only, and data is stored together with other user data

This is a good mindset, as currently your BLEManager breaks the Single Responsibility Principle, i.e. has multiple responsibilities. The ObservedObject part is a SwiftUI specific thing, so it makes sense to be extracted out of that class.
Now, implementation-wise, one first step that you could make, is to transform the data property to a publisher. This will allow clients to connect to the data stream, and allows you to circulate the publisher instead of the BLEManager class, in the rest of your app.
import Combine

class BLEManager: OtherProtocols {
    // you can use `Error` instead of `Never` if you also want to
    // report errors which make the stream come to an end
    var dataPublisher: AnyPublisher<Int, Never> { _dataPublisher.eraseToAnyPublisher() }

    private var myCentral: CBCentralManager!

    // hiding/encapsulating the true nature of the publisher
    private var _dataPublisher = PassthroughSubject<Int, Never>()

    // ...

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        _dataPublisher.send(10.0) // imagine it's the data received from BLE device
    }

This way anyone who's interested in receiving BLE data simply subscribes to that publisher.
Now, on the receiving side, assuming that you also need an ObservableObject for your SwiftUI view, you can write something along of the following:
class ViewModel: ObservableObject {
    @Published var data: Int = 0

    init(dataPublisher: AnyPublisher<Int, Never>) {
        // automatically updates `data` when new values arrive
        dataPublisher.assign(to: &$data)
    }
}

If you don't use SwiftUI (I assumed you do, due to the ObservableObject conformance), then you can sink to the same publisher in order to receive the data.

Either SwiftUI, or UIKit, once you have a BLEManager instantiated somewhere, you can hide it from the rest of the app, and still provide the means to subscribe to the BLE data, by circulating the publisher. This also helps with the separation of concerns in the rest of the app.


text:
Q: modulus remainder different from java and php I'm trying to implement two methods in PHP and JAVA that return a common integer and have the same output.
internal parameters match but when it comes to modular division, it fails.
My numbers are stored as int.
In PHP i have this result

1192581159 % 100000000 = 85278720

In Java i have this result

1192581159 % 100000000 = 92581159

LATER_EDIT_WHILE_POSTING_QUESTION i think 1192581159 is bigger that PHP_MAX_INT , a possible solution is to treat it as a string and apply substrings in order to get correct result from Java

A: solution is described here
Modulus PHP Problem
my approach was to treat 1192581159 as a string and substring the result needed for my calculations
    $bigint = (string)$bigint;
    $bigint = substr($bigint,-$returnDigits);
    // $returnDigits is the same as the last
    // x numbers from the end of my "string"


text:
Q: How does +elemental damage work? Does +element damage items increase damage of spells or just add elemental damage to the attack of the weapon it's on?
For example, I have a poison damage focused Outlander and was wondering if +poison gems in my weapon would increase DPS.

A: Elemental gems only affect the weapon they are in, by adding flat damage, and that would increase the DPS of that particular weapon but not of anything else (e.g. other weapons or skills).  If you find any enchant that says +% to all poison damage, that would apply to everything.  Most of those tend to be for armor, not weapons though.
If you look under arcane stats you can get an idea of what stats apply per weapon and which ones apply for all attack.  For example, elemental damage % bonus is listed as a global stat, as are things like execute chance and critical chance.  However, elemental flat damage and attack speed are listed under each separate weapon (hand).


text:
Q: Wordpress Force Post to select category i am using WordPress post to build post.is there any plugin or some function that warn be when i  don't select a category for the post.its a headache ever time i post a category i miss some time as there is a lot of post to be made in the category after some time see those post in uncategory its a great headache.
add_theme_support('menus');

**
**> the above code is nothing because stack over flow doesn't allow me to

post my question as it say standard low.**

**
thanks in advance.
hope i could find one suitable answer

A: hah.. its so funny but you can try as below in your functions.php file
function force_post_categ_init()
{
  wp_enqueue_script('jquery');
}
function force_post_categ()
{
  echo "<script type='text/javascript'>\n";
  echo "
  jQuery('#publish').click(function()
  {
    var cats = jQuery('[id^=\"taxonomy\"]')
      .find('.selectit')
      .find('input');
    category_selected=false;
    for (counter=0; counter<cats.length; counter++)
    {
        if (cats.get(counter).checked==true)
        {
            category_selected=true;
            break;
        }
    }
    if(category_selected==false)
    {
      alert('You have not selected any category for the post. Please select post category.');
      setTimeout(\"jQuery('#ajax-loading').css('visibility', 'hidden');\", 100);
      jQuery('[id^=\"taxonomy\"]').find('.tabs-panel').css('background', '#F96');
      setTimeout(\"jQuery('#publish').removeClass('button-primary-disabled');\", 100);
      return false;
    }
  });
  ";
   echo "</script>\n";
}
add_action('admin_init', 'force_post_categ_init');
add_action('edit_form_advanced', 'force_post_categ');

NOte:- javascript must be enable to run this

A: I would suggest using a jQuery object to read the real value of the input since the page can be loaded with a checked value and then an input can be un-checked and saved. This uses the jQuery object .is('checked') method:
function force_post_categ()
{
    $custom_js = <<<CUSTOM_JS
    <script type='text/javascript'>
    jQuery('#publish').click(function()
    {

      var cats = jQuery('[id^="taxonomy"]').find('.selectit').find('input');
      category_selected = false;

      $.each(cats, function(key,value){
          if ( $(this).is(':checked') == true ) {
            category_selected = true;
            return false;
          }
      });

      if (category_selected == false)
      {
        alert('You have not selected any metro or country for the post. Please select a metro.');
        setTimeout("jQuery('#ajax-loading').css('visibility', 'hidden');", 100);
        jQuery('[id^="taxonomy"]').find('.tabs-panel').css('background', '#F96');
        setTimeout("jQuery('#publish').removeClass('button-primary-disabled');", 100);
        return false;
      }
    });
    </script>
CUSTOM_JS;

    echo $custom_js;
}


text:
Q: Nomes das tabelas no Hibernate são criadas com letras minúsculas Estou tentando transformar a seguinte Entidade em uma tabela no Postgre usando Hibernate
@Entity
@Table(name="Usuarios")
public class Usuario implements Serializable { ... }

o problema é que quando a tabela é criada, o nome dela é criada com todos os caracteres em minúsculo.
estou usando uma classe como helper para configurar:
        Properties props = new Properties();

        props.put("hibernate.temp.use_jdbc_metadata_defaults", "false");
        props.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        props.put("hibernate.connection.driver_class", "org.postgresql.Driver");
        props.put("hibernate.provider_class", "org.hibernate.connection.C3P0ConnectionProvider");
        props.put("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
        props.put("hibernate.current_session_context_class", "thread");
        props.put("hibernate.hbm2ddl.auto", "create");
        props.put("hibernate.show_sql", "true");
        props.put("spring.jpa.hibernate.naming.physical-strategy", "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");

        URI dbUri = new URI("postgres://*user*:*senha*@localhost:5432/*bd*");

        String username = dbUri.getUserInfo().split(":")[0];
        String password = dbUri.getUserInfo().split(":")[1];
        String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

        props.put("hibernate.connection.url", dbUrl);
        props.put("hibernate.connection.username", username);
        props.put("hibernate.connection.password", password);

        props.put("c3p0.min_size", 5);
        props.put("c3p0.max_size", 15);
        props.put("c3p0.timeout", 300);
        props.put("c3p0.acquire_increment", 1);
        props.put("c3p0.max_statements", 50);
        props.put("c3p0.idle_test_period", 3000);

        cfg.addProperties(props);

        sessionFactory = cfg.buildSessionFactory();

A: Acredito que esse "problema" não seja com o Hibernate, mas sim do PostgreSQL. Por padrão o PostgreSQL converte tudo para minúsculo internamente.
Você pode ver mais aqui:
https://stackoverflow.com/questions/13409094/why-does-postgresql-default-everything-to-lower-case
Você até consegue criar tabelas no PostgreSQL com maiúsculo, mas tem que colocar aspas:
createdb "Usuarios"


text:
Q: Handling DateTime DbNull in mvc label using ?? operator I am trying to handle dbnull using the ?? operator.  I know I can test for dbnull using == equal operator.  But I would like to shorten the code with ?? operator.  Here is what I have so far but not working:
@Html.Label(Model.CustomerDate.ToString() ?? "", new { id = "CustomerDate" })

But it is not working.  Model.CustomerDate is a DateTime? type.  I have searched and found no results specific to above scenario.  Any help would be appreciated.
Update #1
I tried the following as suggested by Joel below:
@Html.Label(Model.CustomerDate.ToString(), new { id = "CustomerDate" })
This did not work since the field is a DateTime?.  I receive the error "Object reference not set to an instance of an object." I have to handle null, dbnull and a valid datetime value.
Update #2
I was able to figure out a working solution thanks to Joel's answer below:
Note: You have to have a space in the double quotes after the ?? section below, if not it will not render the control when null:
@Html.Label(Model.CustomerDate?.ToString() ?? " ", new { id = "CustomerDate" })

A: DBNull is not the same as a C# null, and does not work with the null-coalescing ?? operator like that. You have compare with DBNull.Value.
Aside from that, DBNull.ToString() will already produce an empty string, such that you should be able to simply remove the null-coalescing operation like this:
@Html.Label(Model.CustomerDate.ToString(), new { id = "CustomerDate" })

That will give you the empty string you want if you have null, or create a string from the DateTime value if you don't, using the format for the current culture of the process (usually the server default, but in an ASP.Net context you can sometimes set things to infer from the browser).
If you also need to handle a Nullable type, you can do this:
@Html.Label(Model.CustomerDate?.ToString() ?? "", new {id = "CustomerDate"})


text:
Q: Why does regression use least "squares" instead of least "absolute values"? Linear regression uses summation of least squares to find the best fit. Why? I fully understand that we do not want to use actual residuals, otherwise, positive and negative numbers may cancel out each other. Then, why don't we use absolute values? Sorry if this sounds like a duplicate question. I did see many explanations but did not see an easy-to-understand answer. For example, some said that squares made calculation easier. How come?
Your insight is highly appreciated!

A: $$\min_{a,b}\sum_{k=1}^n(ax_k+b-y_k)^2$$ has a simple analytical solution.
$$\min_{a,b}\sum_{k=1}^n|ax_k+b-y_k|$$ is difficult.
One of reasons is that the absolute value is not differentiable.

A: As mentioned by others, the least-squares problem is much easier to solve. But there's another important reason: assuming IID Gaussian noise, the least-squares solution is the Maximum-Likelihood estimate.

A: It is easy to minimize the error when it is given by the least squares. Consider the following: there given points $(x_k,y_k), \ k=1,\ldots,n $ and you want to find $a,b$ constants such that $y \approx ax+b$. What does $y\approx ax+b$ mean? E.g. $E(a,b):=\sum_{k=1}^n (y_k-ax_k-b)^2$ is minimal in $a,b$. Now
\begin{align*}
\frac{\partial}{\partial a} E(a,b) &= -2\sum_{k=1}^n (y_k-ax_k-b)x_k = 0\\ \frac{\partial}{\partial b} E(a,b) &= -2\sum_{k=1}^n (y_k-ax_k-b) = 0
\end{align*}
The solution is given as the solution to
$$ \begin{bmatrix}1 & \frac1n\sum_{k=1}^n x_k \\ \frac1n\sum_{k=1}^n x_k & \frac1n\sum_{k=1}^n x_k^2 \end{bmatrix}\begin{bmatrix} b \\ a \end{bmatrix} = \begin{bmatrix} \frac1n\sum_{k=1}^n y_k \\ \frac1n\sum_{k=1}^n x_ky_k \end{bmatrix} $$
it can be shown that this is indeed a minimum by looking at Hessian of $E(a,b)$.

A: In actuality least absolute value methods of regression is sometimes used, but there are a few reasons why least squares is more popular.
1) In calculus, when trying to solve an optimization problems (which is what regression is, minimizing error) we take the derivative to find the points where it is equal to 0. When differentiating, absolute value signs are a nightmare and create a kind of piecewise function whereas squares are far simpler to differentiate, especially due to their non-linearity.
2) Least squares regression lines are more efficient (they don't require as great of a number of samples to get a good estimate of the true regression line for the population).
But in all honesty, least squares is more common because it ended up that way. There are many good arguments as to why in many scenarios least absolute value is better, including the fact that least squares regression is far more sensitive to outliers.
This is shown in this example.
Sourced from: https://demonstrations.wolfram.com/ComparingLeastSquaresFitAndLeastAbsoluteDeviationsFit/

A: In addition to the previous answers, I want to highlight the differences in the solutions obtained when optimizing each of the two objective functions.
In particular, if we look at the response variable $y$ conditioned on the explanatory variables $\mathbf{x}$, that is $y | \mathbf{x}$,
the algorithm estimates

*

*the mean of response values, in the case of squared differences;

*the median of the response values, in the case of of absolute differences.

By replacing the absolute value with a tilted absolute value loss function,
we obtain quantile regression.
The figures below exemplify the differences in solutions for the two methods (these images were taken from this assignment, see §2):

The same resource provides some motivating examples for using quantile regression:

*

*A device manufacturer may wish to know what are the 10% and 90% quantiles for some feature of the production process,
  so as to tailor the process to cover 80% of the devices produced.

*For risk management and regulatory reporting purposes, a bank may need to estimate a lower bound on the changes in the value of its portfolio which will hold with high probability.

A: One can think of a set of $n$ observations as being an $n$-dimensional vector. We then have the Euclidean norm $\sqrt {\sum (y_i-\hat y_i)^2}$. Since minimizing the square root of a value is the same as minimizing the value (for positive numbers), it's simpler to talk of finding the least squares, rather than finding least root mean square.
Using  $\sum (y_i-\hat y_i)^2$ over $\sqrt {\sum (y_i-\hat y_i)^2}$ has further advantages, such as that we can split $\sum y_i^2$ into the "explained" part $\sum (y_i-\hat y_i)^2$ and the "unexplained" part $\sum y_i^2-\sum (y_i-\hat y_i)^2$.
Once we have the Euclidean norm, many questions can be answered by looking at the geometry of the space. For instance, if we take the set of points obtained by $\hat y = mx+b$, this is a plane in the space. Finding the least squares means finding the point on this plane closest to the observation vector, which can be obtained simply by looking at the hyperplane perpendicular to that plane that goes through the observation vector, and seeing what point it intersects the plane, which is a simple linear algebra problem.


text:
Q: Navbar that changes div contents all in one page So to be quick and to the point, I'm attempting to create a small vertical menu on the left side of my screen where when you click on an item in the list, it changes all the contents of a div to the right of it, the 'content' section but without changing the physical html file.  Meaning, I'd like to keep it all as one document and do it with JavaScript as I've seen used before.
Here's a 'mock-up' of what I'd like to do:

EDIT/UPDATE
Alright so I've found a solution that works, but I've got 2 things I want to change with it and I'm not sure how.
          function toggle_visibility(id) {
                 var e = document.getElementById(id);
                 if(e.style.display == 'block')
                        e.style.display = 'none';
                 else
                        e.style.display = 'block';
            }

I want to add the following:

*

*Only one can display at a time

*Some sort of 'slide' animation for
changing 'screens'

Here's an example currently on how the links work:
Testing

testing for page 2

A: Vanilla JavaScript is good enough for this

document.querySelectorAll('nav a')
  .forEach(e => e.addEventListener('click', _ => change(e.dataset.id)))

function change(n) {
  let panels = document.querySelectorAll('main div')
  panels.forEach(p => p.classList.remove('active'))
  panels[n - 1].classList.add('active')
}
.container {
  display: flex;
}
nav {
  display: flex;
  flex-direction: column;
  margin-right: 50px;
  background-color: seagreen;
  cursor: pointer;
}
nav a {
  padding: 10px;
}
nav a:hover {
  background-color: gold;
  display: block;
}
main div {
  display: none;
  padding: 20px;
}
.active {
  display: block;
}

    Item 1
    Item 2
    Item 3

Item 1 Content

Item 2 Content

Item 3 Content


text:
Q: gridview default sortexpression Has anyone managed to extend a GridView with default sorting?
This seems pretty trivial to me but i can't get it done.
The idea is to add a property DefaultSortExpression to a Server Control that inherits GridView.

*

*Calling Sort() performs an additional select, we don't want that.

*Setting this.SelectArguments.SortExpression seems to get it's value set after i do so that doesn't work either. (Unless there's some magical event i didn't try yet).

I want to be able to set the SortExpression before the GridView does it's databinding.

A: protected override DataSourceSelectArguments CreateDataSourceSelectArguments()
        {
            DataSourceSelectArguments dsa = base.CreateDataSourceSelectArguments();

            // dsa.SortExpression = "my field";

           return dsa;
}


text:
Q: ¿Cómo quitar el espacio al seleccionar un item del autocomplete jquery UI? Buenas tardes quisiera saber como puedo quitar el espacio que sale al seleccionar con la tecla tab un elemento del autocomplete cuando lo selecciono.Gracias de antemano.
Observación: El Json contiene espacios en el campo NUMERO_PROYECTO, quizás por ello carga el autocomplete con espacios como podría eliminar ese espacio.
archivo.json
{"data":[{"NUMERO_PROYECTO":"103438    ","NOMBRE_PROYECTO":"DIST__DS-CANVIA- SWF-AGILE CO","ALIAS":null,"GERENTE_PROYECTO":null,"INICIO_PLANIFICADO":null,"TERMINO_PLANIFICADO":null,"BU":null,"LINIA":null,"ESTADO":null,"TIPO":null},{"NUMERO_PROYECTO":"101495    ","NOMBRE_PROYECTO":"SLIN__DS-CANVIA-SWF-AGILE","ALIAS":null,"GERENTE_PROYECTO":null,"INICIO_PLANIFICADO":null,"TERMINO_PLANIFICADO":null,"BU":null,"LINIA":null,"ESTADO":null,"TIPO":null},{"NUMERO_PROYECTO":"100959    ","NOMBRE_PROYECTO":"PROY__DS-CANVIA-TESTING INT","ALIAS":null,"GERENTE_PROYECTO":null,"INICIO_PLANIFICADO":null,"TERMINO_PLANIFICADO":null,"BU":null,"LINIA":null,"ESTADO":null,"TIPO":null},{"NUMERO_PROYECTO":"103569    ","NOMBRE_PROYECTO":"DIST_DS-CANVIA-SOP FUNC SIST","ALIAS":null,"GERENTE_PROYECTO":null,"INICIO_PLANIFICADO":null,"TERMINO_PLANIFICADO":null,"BU":null,"LINIA":null,"ESTADO":null,"TIPO":null},{"NUMERO_PROYECTO":"103045    ","NOMBRE_PROYECTO":"DIST__DS-CANVIA-SERV SWF","ALIAS":null,"GERENTE_PROYECTO":null,"INICIO_PLANIFICADO":null,"TERMINO_PLANIFICADO":null,"BU":null,"LINIA":null,"ESTADO":null,"TIPO":null}]}

Autocomplete.js
$("#IdProyecto").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: root + '/Sigeri/ObtenerProyectos',
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.NUMERO_PROYECTO, value: item.NUMERO_PROYECTO };
                    }))

                }
            })
        },
        messages: {
            noResults: "No results found.",
            results: function (count) {
                return count + (count > 1 ? ' results' : ' result ') + ' found';
            }
        }
    });

Muestro la siguiente imagen

A: Podrías aplicarle trim a item.NUMERO_PROYECTO y así evitar que la opción aparezca con espacios.
Ejemplo
response($.map(data, function (item) {
  let num = item.NUMERO_PROYECTO.trim();
  return {label: num, value: num};
}));


text:
Q: curl xpost with jquery I have a problem with a JQuery ajax request, cannot figure out what I am doing wrong.
When I send a curl on the command line it is working fine:
curl -XPOST http://127.0.0.1:3000/bridge/heatingCircuits/hc1/temperatureRoomManual -d '{"value":20}' -H 'Content-Type: application/json'

But with JQuery Ajax it is not working:
$.ajax({
    url: "http://127.0.0.1:3000/bridge/heatingCircuits/hc1/temperatureRoomManual",
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    data: '{"value":20}',
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function(){
        alert("Cannot get data");
    }
});

I got the following Error Response:
net::ERR_CONNECTION_REFUSED

A: did you try ? :
$.ajax({
    url: "http://127.0.0.1:3000/bridge/heatingCircuits/hc1/temperatureRoomManual",
    type: 'POST',
    dataType: 'json',
    //contentType: 'application/json',
    data: {value:20},
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function(){
        alert("Cannot get data");
    }
});


text:
Q: How to get score to get updated and display on screen? When player touches coin score gets updated and displayed the score gets overlapped e.g. 1,2,3 etc making unclear to see the score. I am trying to get it so the previous score disappears and only the new one is shown.
def main():  #my main loop
    running = True
    clock = pygame.time.Clock()  # A clock to limit the frame rate.
    score = (1)
    score = str(score)

myfont = pygame.font.SysFont('OpenSans', 30)
textsurface = myfont.render('Level ONE:   Greenland', False, (0, 0, 0))
background.blit(textsurface,(500,10))

textsurface = myfont.render('Score:', False, (0, 0, 0))
background.blit(textsurface,(10,10))

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    player_hit_list = pygame.sprite.spritecollide(player, coin_list,True)
        for coin in player_hit_list:
             textsurface = myfont.render(score, False, (0, 0, 0))
             background.blit(textsurface,(90,10))
             score = str(int(score)+ 1))

    sprites.update()
    screen.blit(background, (0, 0))
    sprites.draw(screen)  # Draws all of the sprites onto the screen
    clock.tick(60)  # Limit the frame rate to 60 FPS.
    pygame.display.update()

I except on the top left it shows Score: 1 and when the coin is touched it get updated e.g. Score:

A: Using the PyGame surface subsurface() function, copy the part of the background that is directly under the core, probably adding a bit extra to handle more digits in the core.
Then to update the score, erase the existing score by writing that section of the background, then paint the text bitmap.
Something like:
# rectangle around score
under_score_rect = [ 90, 10,  100,  40 ]
# copy of background that's under the score
under_score_background = background.subsurface( under_score_rect ).copy()

...

def drawScore( score, screen, background_img ):
    global score_font
    textsurface = score_font.render( score, False, (0, 0, 0) )
    screen.blit( background_img, ( 90, 10 ) )
    screen.blit( textsurface, ( 90,10 ) )

...

drawScore( score, window, under_score_background )


text:
Q: My Calendar Plugin - add output directly in template file I am using the latest version of the My Calendar plugin by Joe Dolson with the latest version of WP. I want to output an events list in a particular place in my code, but I can't seem to find any way to do this. The only thing I've found regarding output is by using shortcodes in the post/page.
I guess theoretically I could add a new sidebar widget and then add the templates that way. Then put the sidebar where I want in the code, but this poses two problems:
1. It's a hassle
2. I don't want my clients to be able to move or change this. I'd like to have it set and stay that way.
I'm having some trouble finding the answers to this question. It seems like it would be possible, because most plugins I've used have an option to add output directly in the template code, but I can't seem to find the answer.
Thanks in advance!

A: You can use the function do_shortcode in your template to output the content generated by the shortcode that My Calendar provides for listing events.
For an example, to show a list of upcoming events use something like:
<?php echo do_shortcode('[my_calendar_upcoming before="3" after="3" type="event" fallback="No events coming up!" category="General" template="{title} {date}" order="asc" skip="0"]'); ?>

Take note of the use of single quotes for the function and double quotes for the shortcode attributes.


text:
Q: WCF doesn't find client configuration I have a WCF service on server B. Then on the machine A is the client, which is a Windows service. In a separate dll stands all the business logic for this service. So my proxy for the WCF is on that side. I have 2 app.config (client side only) : 1 for the service and another one in the dll. So I tried (for test purpose) puting the servicemodel config section in both. Both still, it doesn't work, it says that it can't find the endpoint with that name and for that contract...
What I'm trying to do here is modify the configuration programatically. Here' the code in the business layer dll :
Dim ep As New EndpointAddress(New Uri(ConfigurationManager.AppSettings(nomServeurCible)), _
                                    EndpointIdentity.CreateDnsIdentity(ConfigurationManager.AppSettings("Identity_" & nomServeurCible)))

    serviceCible = New ServiceProxy.ExecOperClient("wsHttp", ep)

And here is a sample of the config file :
<add key="TEST1" value="http://TEST1:8000/MySpacePerso/ExecOperService"/>
<add key="TEST1_CertificateSerialNumber" value="10 hj 6y 7b 00 01 32 12 01 21"/>
<add key="Identity_TEST1" value="TEST1"/>

<system.serviceModel>
<client>
  <endpoint address="http://SERV_NAME:8000/CSSTQDA/ExecOperService" binding="wsHttpBinding"
            behaviorConfiguration="myClientBehavior"
            bindingConfiguration="MybindingCon" contract="ExecOper.Service.IExecOper"
            name="wsHttp">
    <identity>
      <dns value="SERV_CERT_NAME"/>
    </identity>
  </endpoint>
</client>
<bindings>
  <wsHttpBinding>
    <binding name="MybindingCon">
      <security mode="Message">
        <message clientCredentialType="UserName" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>

<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceTraitementBehavior">
      <serviceMetadata httpGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="myClientBehavior">
      <clientCredentials>
        <serviceCertificate>
          <authentication certificateValidationMode="ChainTrust" revocationMode="NoCheck"/>
        </serviceCertificate>
      </clientCredentials>
    </behavior>
  </endpointBehaviors>
</behaviors>

A: Well, it turns out it was just a matter of ConfigurationName tag in my proxy class...  Sorry :-) It didn't have the correct namespace for my contract. The fully qualified name must match the one in the app.config.


text:
Q: Failed to install Ubuntu 22.04 desktop many times My laptop is Asus X541U 4GB RAM, 1TB HDD, 2GHZ Intel i3 6th gen CPU. In the grub menu I get the Try Ubuntu or install option. I highlight this option and choose the E keyword to get a command line and set "nomodeset", but still I get the tcp crb error and then failed to install live CD installer and then  many more  messages.

I used Rufus 3.19 to create a bootable USB and chose GPT format then. I have done this 7-8 times, but I still got the same issue every time.

A: Have a look here, Arsalan:
How can I install 22.04 onto Asus K541UA laptop
I ran into a very similar problem end got it solved.
Good luck.


text:
Q: Resetting the time part of a timestamp in Java In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ?
In T-SQL, this query will do to achieve the same, but I don't know how to do this in Java.
SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';

A: You can go Date->Calendar->set->Date:
Date date = new Date();                      // timestamp now
Calendar cal = Calendar.getInstance();       // get calendar instance
cal.setTime(date);                           // set cal to date
cal.set(Calendar.HOUR_OF_DAY, 0);            // set hour to midnight
cal.set(Calendar.MINUTE, 0);                 // set minute in hour
cal.set(Calendar.SECOND, 0);                 // set second in minute
cal.set(Calendar.MILLISECOND, 0);            // set millis in second
Date zeroedDate = cal.getTime();             // actually computes the new Date

I love Java dates.
Note that if you're using actual java.sql.Timestamps, they have an extra nanos field.  Calendar of course, knows nothing of nanos so will blindly ignore it and effectively drop it when creating the zeroedDate at the end, which you could then use to create a new Timetamp object.
I should also note that Calendar is not thread-safe, so don't go thinking you can make that a static single cal instance called from multiple threads to avoid creating new Calendar instances.

A: Assuming your "timestamp" is a java.util.Date, which is represented as the number of milliseconds since the beginning of the epoch (Jan 1, 1970), you can perform the following arithmetic:
public static Date stripTimePortion(Date timestamp) {
    long msInDay = 1000 * 60 * 60 * 24; // Number of milliseconds in a day
    long msPortion = timestamp.getTime() % msInDay;
    return new Date(timestamp.getTime() - msPortion);
}

A: I prefer this solution:
GregorianCalendar now = new GregorianCalendar();
GregorianCalendar calendar = new GregorianCalendar(
              now.get(GregorianCalendar.YEAR), now.get(GregorianCalendar.MONTH),
              now.get(GregorianCalendar.DAY_OF_MONTH));

A: Do this
import org.apache.commons.lang.time.DateUtils;

Date myDate = new Date();
System.out.println(myDate);
System.out.println(DateUtils.truncate(myDate, Calendar.DATE));

and the output is
Wed Mar 19 14:16:47 PDT 2014
Wed Mar 19 00:00:00 PDT 2014

A: If you're using commons lang you can call DateUtils.truncate. Here's the javadoc documentation.
It does the same thing @Alex Miller said to do.

A: Since I don't do much DateTime manipulation, this might not be the best way to do it. I would spawn a Calendar and use the Date as source. Then set hours, minutes and seconds to 0 and convert back to Date. Would be nice to see a better way, though.

A: Using Calendar.set() would certanly be "by the book" solution, but you might also use java.sql.Date:
java.util.Date originalDate = new java.util.Date();
java.sql.Date wantedDate = new java.sql.Date(originalDate.getTime());

That would do exactly what you want since:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

Since java.sql.Date extends java.util.Date, you can freely use it as such. Be aware that wantedDate.getTime() will retrieve original timestamp though - that's why you don't want to create another java.util.Date from java.sql.Date!

A: Find below a solution which employs Joda Time and supports time zones.
So, you will obtain the current date and time (into currentDate and currentTime) or some date and time you inform (into informedDate and informedTime) in the currently configured timezone in the JVM.
The code below also informs if the informed date/time is in future (variable schedulable).
Please notice that Joda Time does not support leap seconds. So, you can be some 26 or 27 seconds off the true value. This probably will only be solved in the next 50 years, when the accumulated error will be closer to 1 min and people will start to care about it.
See also: https://en.wikipedia.org/wiki/Leap_second
/**
 * This class splits the current date/time (now!) and an informed date/time into their components:
 * <lu>
 *
schedulable: if the informed date/time is in the present (now!) or in future.

 *
informedDate: the date (only) part of the informed date/time

 *
informedTime: the time (only) part of the informed date/time

 *
currentDate: the date (only) part of the current date/time (now!)

 *
currentTime: the time (only) part of the current date/time (now!)

 * </lu>
 */
public class ScheduleDateTime {
    public final boolean schedulable;
    public final long millis;
    public final java.util.Date informedDate;
    public final java.util.Date informedTime;
    public final java.util.Date currentDate;
    public final java.util.Date currentTime;

    public ScheduleDateTime(long millis) {
        final long now = System.currentTimeMillis();
        this.schedulable = (millis > -1L) && (millis >= now);

        final TimeZoneUtils tz = new TimeZoneUtils();

        final java.util.Date          dmillis   = new java.util.Date( (millis > -1L) ? millis : now );
        final java.time.ZonedDateTime zdtmillis = java.time.ZonedDateTime.ofInstant(dmillis.toInstant(), java.time.ZoneId.systemDefault());
        final java.util.Date          zdmillis  = java.util.Date.from(tz.tzdate(zdtmillis));
        final java.util.Date          ztmillis  = new java.util.Date(tz.tztime(zdtmillis));

        final java.util.Date          dnow   = new java.util.Date(now);
        final java.time.ZonedDateTime zdtnow = java.time.ZonedDateTime.ofInstant(dnow.toInstant(), java.time.ZoneId.systemDefault());
        final java.util.Date          zdnow  = java.util.Date.from(tz.tzdate(zdtnow));
        final java.util.Date          ztnow  = new java.util.Date(tz.tztime(zdtnow));

        this.millis       = millis;
        this.informedDate = zdmillis;
        this.informedTime = ztmillis;
        this.currentDate  = zdnow;
        this.currentTime  = ztnow;
    }
}

public class TimeZoneUtils {

    public java.time.Instant tzdate() {
        final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();
        return tzdate(zdtime);
    }
    public java.time.Instant tzdate(java.time.ZonedDateTime zdtime) {
        final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);
        final java.time.Instant instant = zddate.toInstant();
        return instant;
    }

    public long tztime() {
        final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();
        return tztime(zdtime);
     }
    public long tztime(java.time.ZonedDateTime zdtime) {
        final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);
        final long millis = zddate.until(zdtime, java.time.temporal.ChronoUnit.MILLIS);
        return millis;
    }
}

A: Here's a simple function with a main example:
import java.util.Calendar;
import java.util.Date;
public class Util {
/**
 * Returns an imprecise date/timestamp.
 * @param date
 * @return the timestamp with zeroized seconds/milliseconds
 */
public static Date getImpreciseDate(Date date) {
   Calendar cal = Calendar.getInstance(); // get calendar instance
   cal.setTime(date);// set cal to date
   cal.set(Calendar.SECOND, 0); // zeroize seconds
   cal.set(Calendar.MILLISECOND, 0);   // zeroize milliseconds
   return cal.getTime();
}

public static void main(String[] args){
   Date now = new Date();
   now.setTime(System.currentTimeMillis()); // set time to now
   System.out.println("Precise date:  " + Util.getImpreciseDate(now));
   System.out.println("Imprecise date:  " + Util.getImpreciseDate(now));
}
}

A: Just trying to put an answer for Java-8 , though answers using Calendar are valid too but lots of folks are not using that class anymore.
Refer SO Answers this & this to understand conversions between java.time.ZonedDateTime & java.sql.Timestamp
then you can simply truncate ZonedDateTime on days & reconvert back to Timestamp
Timestamp.valueOf(ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS).toLocalDateTime())


text:
Q: What is the breakdown of Happy Home Academy points? For the previous Animal Crossing games, people have published breakdowns of what assigns point values in Happy Home/Room Academy evaluations (e.g. here).
Is this information available for New Leaf?

A: I don't think so, but it would be safe to assume that they are very similar to the GCN and WW numbers. In general these sorts of things change very little from AC game to game, the changes seem only to be balancing tweaks.


text:
Q: How to use Gitlab CI generated artifact in an API call? I am using a Go microservice where I need to parse a Newman report. Currently, I am taking the Newman report from the local directory as follows:
jsonFile, err := os.Open("outputfile.json")
if err != nil {
    fmt.Println(err)
}

But I need to generate the report in Gitlab CI as follows:
  image:
    name: postman/newman
    entrypoint: [""]
  script:
    - echo "Generating newman report"
    - pwd
    - newman --version
    - newman run collection.json --reporters cli,json --reporter-json-export outputfile.json
  artifacts:
    paths:
      - outputfile.json

Is there any way I can use this report from GitLab CI (maybe using CURL) and take the report as an API-driven input, rather than taking it from the local directory?

A: Sure, you can use cURL without any problem.
Let's suppose you are in the organization ORG within the project PROJECT in the master branch and that your aforementioned defined job is called generate_newman.
You could download the last generated artifact as follows:
curl -L https://gitlab.com/ORG/PROJECT/-/jobs/artifacts/master/download?job=generate_newman


text:
Q: How to add image upload tag in Struts2 jquery grid plugin I am using struts2 jquery Grid plugin for the admin panel functionality for website.
In this plugin when i click add button it populate form using jquery dialog ui
So here i want to show my form that accepts file uploading & also i have written validation xml file for this form so i want this dialog should show validation errrors if user forgets to enter some information.
Thanks in advance.

A: You can try to use edittype:'file'. For the validation you can use editrules with custom: true and define your custom validation in custom_func.


text:
Q: Manually publish s3 folder to Cloud front I uploaded some files to my S3 bucket, how do I make them available in my Cloud front?
Any idea?

A: I think this 'getting started' article is what you need: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/GettingStarted.html
(make sure you correctly set permissions for S3 objects, otherwise CloudFront won't be able to access them)


text:
Q: MySQL, rank keywords separated by space I've a table with only one col, and contain free text, and each keyword separated by a space
TEXT
apple orange dog
apple banna cat

I want to have a result sth like
apple 2
orange 1
dog 1
banna 1
cat 1

Is it possible with just SQL?

A: Try this
create Function
Create FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN
    SET @index = CHARINDEX(@delimiter , @text)
    IF (@index = 0) AND (LEN(@text) > 0)
      BEGIN
        INSERT INTO @Strings VALUES (@text)
          BREAK
      END
    IF (@index > 1)
      BEGIN
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
        SET @text = RIGHT(@text, (LEN(@text) - @index))
      END
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END

Query
 declare @ColumnNameList VARCHAR(MAX)
select @ColumnNameList  = COALESCE(@ColumnNameList +' ' ,'') +column  from table
select @ColumnNameList
select value,count(value) as count from (select value from fn_split((select @ColumnNameList),' '))
Space_tbl group by value


text:
Q: Call Parent Pop-Up Jquery function from A child Pop-Up? I have a scenario:  (A) Parent Page => (B) Child Pop-up => (C)Child Pop-Up.
I am using window.parent.FunctionName(); for calling jquery's function from B to A, It's working fine.
But I am unable to call a function from C which is defined on B. I am using bpopup with MVC 3.


text:
Q: What does 'lay one's shoulder to ' mean? I came across the following paragraph when reading Jon Meecham's The Art of Power ( it's a excerpt from the epistle from Jefferson to John Page)

we have both been drawn from our natural passion for study & tranquility, by times which took from us the freedom of choice: times however which, planting a new world with the seeds of just government, will produce a remarkeable aera in the history of mankind. it was incumbent on those therefore who fell into them, to give up every favorite pursuit, and lay the shoulder to the work of the day.

I Googled the phrase but couldn't find matching expressions. The closest one it showed was 'put one's shoulder to the wheel', which means 'work hard at something', and it somehow fits the context herein. Therefore I was wondering if the phrase has fallen out of use or morphed into other forms?

A: It is like "lean into it." I would say it means push harder into your work. When you have hard work to do and you are struggling you need to "lean into it" which is how I would say it in today's English, but "lay one's shoulder to" something seems to be the same type of expression, but in an older English style.


text:
Q: How can I convert varchar to numeric in visual studio? Please help me,Im trying to do a fixed asset program in visual basic studio using sql server, Im stack in this.
I checked if my sql table data types match with the visual studio data types.
Public Class Equipos_de_Computacion
    Dim sql As String = ""

    Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click
        If (Me.txtCodigoInterno.Text = "") Then
            MsgBox("El campo idententificacion no puede estar vacio", MsgBoxStyle.Critical, "Atencion")
            Me.txtCodigoInterno.Select()
        Else
            Dim CodigoInterno As Integer
            Dim NumerodeSerie As Integer
            Dim NumerodeFactura As Integer
            Dim FechadeCompra As Date
            Dim Precio As Decimal
            Dim Acargode As String = ""
            Dim Estado As String = ""
            Dim Depreciacion As Decimal
            Dim Caracteristicas As String = ""

            CodigoInterno = Me.txtCodigoInterno.Text
            NumerodeSerie = Me.txtNumerodeSerie.Text
            NumerodeFactura = Me.txtNumerodeFactura.Text
            FechadeCompra = Me.DateTimePicker1.MinDate
            Precio = CDec(txtPrecio.Text)
            Acargode = Me.txtACargode.Text
            Estado = Me.txtEstado.Text
            Depreciacion = CDec(txtDepreciacion.Text)
            Caracteristicas = Me.txtCaracteristicas.Text

            cmd.CommandType = CommandType.Text
            cmd.Connection = conn

            sql = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion) "
            sql += "Values('" & CodigoInterno & "','" & NumerodeSerie & "','" & NumerodeFactura & "','" & FechadeCompra & "','" & CDec(Precio) & "','" & Acargode & "','" & Estado & "','" & Caracteristicas & "','" & CDec(Depreciacion) & ")"
            MsgBox(sql)
            cmd.CommandText = sql
            Try
                cmd.ExecuteNonQuery()
                MsgBox("Registro insertado correctamente")

            Catch ex As Exception

                If ex.ToString.Contains("duplicate") Then
                    MsgBox("El registro ya existe en la base de datos")
                Else
                    MsgBox(ex.ToString)
                End If
            End Try
        End If
    End Sub

it sends me converting varchar to numeric error.

A: Iam only able to insert integer numbers.With Cint
`Imports System.Data.SqlClient
Public Class Equipos_de_Computacion
    Dim sql As String = ""
Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click
    If (Me.txtCodigoInterno.Text = "") Then
        MsgBox("El campo idententificacion no puede estar vacio", MsgBoxStyle.Critical, "Atencion")
        Me.txtCodigoInterno.Select()
    Else
        Dim CodigoInterno As Integer
        Dim NumerodeSerie As Integer
        Dim NumerodeFactura As Integer
        Dim FechadeCompra As Date
        Dim Precio As Decimal
        Dim Acargode As String = ""
        Dim Estado As String = ""
        Dim Depreciacion As Decimal
        Dim Caracteristicas As String = ""

        CodigoInterno = CInt(Me.txtCodigoInterno.Text)
        NumerodeSerie = CInt(Me.txtNumerodeSerie.Text)
        NumerodeFactura = CInt(Me.txtNumerodeFactura.Text)
        FechadeCompra = CDate(Me.DateTimePicker1.Text)
        Precio = Me.nudPrecio.Value
        Acargode = Me.txtACargode.Text
        Estado = Me.txtEstado.Text
        Depreciacion = Me.NudDepreciacion.Value
        Caracteristicas = Me.txtCaracteristicas.Text

        cmd.CommandType = CommandType.Text
        cmd.Connection = conn

        sql = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion)"
        sql += "Values( '" & CodigoInterno & "' , '" & NumerodeSerie & "' , '" & NumerodeFactura & "' ,'" & FechadeCompra & "', '" & Precio & "' ,'" & Acargode & "','" & Estado & "','" & Caracteristicas & "','" & Depreciacion & "' )"
        MsgBox(sql)
        cmd.CommandText = sql
        Try
            cmd.ExecuteNonQuery()
            MsgBox("Registro insertado correctamente")

        Catch ex As Exception

            If ex.ToString.Contains("duplicate") Then
                MsgBox("El registro ya existe en la base de datos")
            Else
                MsgBox(ex.ToString)
            End If
        End Try
    End If
End Sub

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvEquiposdeComputacion.CellContentClick

End Sub

Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles btnMostrar.Click
    Dim DS As New DataSet
    Dim DA As New SqlDataAdapter("Select * from [Equipos de Computacion]", conn)
    DA.Fill(DS)

    dgvEquiposdeComputacion.DataSource = DS.Tables(0)
End Sub

Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged

End Sub

Private Sub BtnTotalDepreciacion_Click(sender As Object, e As EventArgs) Handles btnTotalDepreciacion.Click

    NudDepreciacion.Value = CDec(FormatNumber(nudPrecio.Value * 0.25, 2))

End Sub

Private Sub TxtPrecio_TextChanged(sender As Object, e As EventArgs)

End Sub

Private Sub txtPrecio_KeyPress(sender As Object, e As KeyPressEventArgs) Handles nudPrecio.KeyPress
    nudPrecio.DecimalPlaces = 2
End Sub

Private Sub txtPrecio_LostFocus(sender As Object, e As EventArgs)
    Dim VarMonedaDolares As Double
    VarMonedaDolares = nudPrecio.Value

    nudPrecio.Value = CDec(FormatCurrency(VarMonedaDolares, 2))
End Sub

End Class`


text:
Q: Implement interface using derived types of the types defined in the interface - why can't you do it? I have these interfaces:
public interface IService
{
    public interface IRequest { }

    void Do(IRequest request);
}

Why is this implementation incorrect?
public class Service : IService  //Error: CS0535
{
    public class Request : IService.IRequest { }

    public void Do(Request request) { }
}

A: This is because the interface requires a method with the signature Do(IRequest request) and you provide Do(Request request) in your implementation instead.
I think this will become clearer when we expand your example with the following code:
public class Request2 : IService.IRequest { }

And then we will try to perform the following:
var service = new Service();
var request = new Service.Request();
var request2 = new Request2();

service.Do(request); // OK
service.Do(request2); // Nope

Compare it with that:
IService service = AnyKindOfServiceResolver.Resolve<IService>();
var request = new Service.Request();
var request2 = new Request2();

service.Do(request); // OK
service.Do(request2); // OK

This difference is what makes your code unable to compile successfully. It also shows what is required of each class that is an implementation of the IService interface.
Edit: Looking at the comments section under your question, I can see that your concerns originate from a misunderstanding of the meaning of a nested interface. Think about your code like this:
public interface IService
{
    void Do(IRequest request);
}

public interface IRequest { }

Placing the definition of IRequest inside the body of IService does not "bind" the two to each other in any way other than inheritance of visibility (public in this case).
Edit 2: This is how you can achieve what you are trying to do:
public interface IService<TRequest> where TRequest : IRequest
{
    void Do(TRequest request);
}

public interface IRequest { }

public class Service1 : IService<Request1>
{
    public void Do(Request1 request) { }
}

public class Request1 : IRequest { }

Or if you really insist on having nested types (readability-- and complexity++):
public interface IService<TRequest> where TRequest : IService<TRequest>.IRequest
{
    public interface IRequest { }

    void Do(TRequest request);
}

public class Service : IService<Service.Request>
{
    public class Request : IService<Request>.IRequest { }

    public void Do(Request request) { }
}

A: It's not possible implement an interface by specifying derived types instead of the types that the interface defines.
Otherwise, a restriction not foreseen by the original meaning of the interface would be imposed.
All types defined in the interface must match exactly in their implementations (C#9 allows methods to return a more derived type, because that's safe).
Thanks to @canton7, @Tholdrim and @Mathias R. Jessen, for helping me come to this conclusion.


text:
Q: jquery keydown return false doesn't work on android chrome I have this input type="text" in my html that I'm assigning the keydown event to it using jquery as below:
$('#refNumber').keydown(function(e) {
    console("key code is " + e.keyCode);

    var val = $(this).val();
    if(val.length == 30) {
        if(e.keyCode == 8 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 9) {
            return true;
        }
        return false;
    }
});

now the event is fired because I can see the log in the console but the return false when the input's value reaches 30 characters does work when I user desktop browser or mobile firefox & ios chrome browser but it doesn't work on android mobile chrome


text:
Q: R: understanding the acf() function Studying autocorrelation using R I ran into a brief exposure by Ryan Sheehy named Autocorrelation in R. In this exposure, the topic and the use of the function acf() are nicely explained and it is illustrated how autocorrelations are in fact lagged correlations. Readers are instructed to run an example that shows that on their data set the result of the acf() function equals the correlation of the variable with its' lagged variable if a correction factor is applied. It works on their example, but in the example I had in mind in the box below, a difference remains.
x<-c(1,4,5,5,7,6,7,7)

## ac according to acf = 0.371
acf(x, plot=FALSE)

## ac from correlations with lagged variable (after correction for (n-1)/n) = 0.692
n<- length(x)
x_t0 <- x[-1]
x_t1 <- x[-n]
cor(x_t1, x_t0) * (n-1)/n

How?


text:
Q: Angular and Asp.Net, can't reference angular js from Script Directory Going over this tutorial. http://codewala.net/2014/05/28/learning-angularjs-with-examplespart-1/
I used nuget to get angular js (angularjs.html)
I replaced

with

This breaks even though the Scripts directory contains angular.js.
Complete code:
<!DOCTYPE html>

    <title>Hello world with AngularJS</title>

 {{helloWorldMessage}}

Error: Argument 'HelloWorldCtrl' is not a function, got undefined

A: The syntax you are using is often used in examples due to it's brevity but typically you see apps and controllers defined like this:
app = angular.module("myapp", []);

app.controller("HelloWorldCtrl", function($scope) {
    $scope.helloWorldMessage = "Hello World " + (new Date()).toDateString();
});

Then your HTML should be:

        {{helloWorldMessage}}

Without knowing what error you're getting it's hard to say why your code isn't working, but give the above a try and if there are still problems just comment and I'll help.
Good luck.

A: I'd recommend putting {{ 1 + 2 }} in your html just to verify Angular is loaded (if it works, it'll render as 3). If that doesn't work, it's a problem with your path. If it's not inside the same folder your html file is in, you might need                    src="../Scripts/angular.js"


text:
Q: How can I store references of non-serializable objects in Java? (Android) I'm experimenting some stuff with Java for Android.
I'm still new to Android programming and I haven't been using Java in A LOT, so I may be a little rusty.
So, here's the situation: I got an Activity that, each time you press a button, creates and starts a new CountDownTimer. If I close the activity, the CountDownTimers started before will still be running. I need a way to recover the references to the ContDownTimer instances from another Activity.
I thought about Serialization, but the abstract class CountDownTimer doesn't seem to implement Serializable. (I get an error while I try to deserialize the objects. Besides, since they ARE running, it means they still are on the heap, right? I only need a way to reference them. I'm a little bit confused on this whole topic of serialization, but that's not the point... or is it?)
Next attempt was going to be an Android Service, but they're even more confusing than Serialization and also look a little like an overkill, due to battery consumption and the fact that CountDownTimers (as far as I understood it) already run on a thread (or a process?) of their own. So I decided i would pay a visit here to see if I was heading in the right direction before starting to struggle with the world of Services.

A:
I need a way to recover the references to the ContDownTimer instances from another Activity.

Then they should not have been part of the first activity originally. Put them in some central storage location. That could be a singleton or a Service. Or, it could be that the answer is to dump CountDownTimer entirely and do something else. Since we do not know what you are trying to accomplish, it is difficult to provide you with good advice.

I thought about Serialization

That would not make much sense for a CountDownTimer.

Besides, since they ARE running, it means they still are on the heap, right?

As long as your process is around.

I'm a little bit confused on this whole topic of serialization

Serialization is for persisting objects to disk. That would not make much sense for a CountDownTimer.

due to battery consumption

A Service does not intrinsically consume any battery. How you use a service might.

the fact that CountDownTimers (as far as I understood it) already run on a thread (or a process?) of their own

No, they do not. They use the main application thread.

So I decided i would pay a visit here to see if I was heading in the right direction

We have no way of answering that, since we have no idea what you are trying to implement. While CountDownTimer might be part of a proper solution to your problem, it might not, let alone the rest of it.


text:
Q: Where can I store the Endpoint configuration when calling a WS from a DLL? I have a set of services, some of them will be Web Services, some will be stored in DLLs, and so on. I would like to create a framework so it is transparent for the caller if he is calling a WS, DLL or something else.
The problem is, if I add a Web Reference in my DLL project, once I add it as a reference in other project (say Project A) and start it, the configuration file  which will be used will be Project A's App.config, which has no information about the WebService endpoint and so on.
An easy way to solve it is copying the configuration section to Project A's App.config, but then the transparency would break.
Is there any other way to store it easily?
I could also create the endpoint programatically, but I would have to store all the info in the App.config information, so, at the end of the day, it would be the same as copying the config section....
This problem seems awkward, so maybe I am getting everything wrong.... Am I?

A: Just to let you know how I solved this problem:
It is possible to instantiate the proxy class passing only the binding and the EndpointAddress, this is what I've done:
client = new ContractClient(new NetMsmqBinding(NetMsmqSecurityMode.None), new EndpointAddress(new Uri(config.WebServiceAddress.Value)) );

Where config is an object which reads the App.config. (ConfigurationManager.GetSection for more information)


text:
Q: C#. Deserialization into same types depending on attribute I had been working with deserialization and got stucked.
There is my classes:
public class Parent
{
   public List<Child> child {get;set}
}

public class Child
{
   some properties
}

public class Child1 : Child
{
   some properties
}

public class Child2 : Child
{
   some properties
}

And I have xml:
<Parent>
   <Child AttribName="TypeOne">
   </Child>
   <Child AttribName="TypeTwo">
   </Child>
</Parent>

How can I use some [Xml] attributes to do this?
I need List<Child> (Child1 or Child2, depending on attrute AttribName) in Parent

A: XmlSerializer does not support discriminators based on an attribute; only the element name. So you could use XmlSerializer for this - but not your scenario:
<Parent>
   <ChildTypeOne>
   </ChildTypeOne>
   <ChildTypeTwo>
   </ChildTypeTwo>
</Parent>

Options:

*

*deserialize it manually

*transform the xml before deserialization

*simply change the xml format

A: In my case with strong xml format and very big files I have just one solution - custom serialization.

A: You can use custom xml reader like this:
public class CustomXmlReader : XmlTextReader
{
    public CustomXmlReader(string url) : base(url) { }

    public override string GetAttribute(string localName, string namespaceURI)
    {
        if (namespaceURI == "http://www.w3.org/2001/XMLSchema-instance" && localName == "type")
        {
            if (base.LocalName == "Child")
            {
                var attr = base.GetAttribute("AttribName");

                if (attr == "TypeOne")
                    return "Child1";
                if (attr == "TypeTwo")
                    return "Child2";
            }
        }
        return base.GetAttribute(localName, namespaceURI);
    }
}

Add attributes to base class:
[XmlInclude(typeof(Child1))]
[XmlInclude(typeof(Child2))]
public class Child

Example usage:
var xs = new XmlSerializer(typeof(Parent));

Parent parent;

using (var xmlReader = new CustomXmlReader("test.xml"))
    parent = (Parent)xs.Deserialize(xmlReader);


text:
Q: convert date format to diffrent date format like edm Im having field type java.util.date and from it im getting the value of to.string()
Sat Sep 14 00:00:00 IDT 2013 but I need to get it in different format which is EDM format
like 2013-09-12T14:00  .
There is simple way to do that?
Thanks!

A: Use SimpleDateFormat (a good tutorial is available here). Consider this example:
Date date = new Date();
System.out.println(date);

which outputs:

Mon Jun 24 21:46:22 BST 2013

To convert to EDM format, do the following:
String firstPartOfPattern = "yyyy-MM-dd";
String secondPartOfPattern = "HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(firstPartOfPattern);
SimpleDateFormat sdf2 = new SimpleDateFormat(secondPartOfPattern);
String formattedDate = sdf1.format(date) + "T" + sdf2.format(date);

formattedDate now has the following format:

2013-06-24T21:46:22

A: Edit: As mentioned you shouldn't use SimpleDateFormat anymore in Java 8+!
You can do also simplify the steps described by Sam:
String pattern = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String formattedDate = sdf.format(date);

A: tl;dr
myUtilDate.toInstant().toString()

2017-01-23T01:23:45.123Z

ISO 8601
Your desired format is defined in the ISO 8601 standard.
The java.time classes use ISO 8601 formats by default when parsing or generating strings.
java.time
Avoid using the outdated troublesome old date-time classes such as Date that are now legacy, supplanted by the java.time classes.
Convert your Date object to java.time by using new methods added to the old classes. The modern counterpart to Date is Instant for a moment on the timeline in UTC but with a finer resolution of nanoseconds rather than milliseconds.
Instant instant = myUtilDate.toInstant() ;

To generate your ISO 8601 string, simply call toString. The Z on the end is short for Zulu and means UTC.
String output = instant.toString() ;


text:
Q: Parsing a file containing filenames and ignoring entries with multiple dot characters? I have a file that contains a bunch of filenames, i.e.:
hello.txt
goodbye.py
test..pdf
n3w.world.file.text
...

I am trying to ignore all filenames with multiple dots.
Currently I am able to find all the filenames using:
import re
data = ['hello.txt', 'goodbye.py', 'test..pdf', 'n3w.world.file.text']
matches = re.findall('([\w].+)\.(\w+)', data)
print(matches)

However this prints out all the filenames. How can I modify this to just print out: hello.txt and goodbye.py?

A: Regex in this case is overkill. You can use str.count() function:
data = ['hello.txt', 'goodbye.py', 'test..pdf', 'n3w.world.file.text']

data = [w for w in data if w.count('.') < 2]
print(data)

Prints:
['hello.txt', 'goodbye.py']

A:    data = [i for i in data if '..' not in i]

You can use the above code


text:
Q: Service has a mocked service dependency which returns promise, struggling with testing I have three services. RequestAuthorizationService calls the OAuthAuthorizationDataService to get the credentials for token based authorization and the credentials will be stored in session storage by sessionStorageManagerService, so they are passed through.
The test subject is the call when sessionStorageManagerService.set() method gets the data. I want to be sure whether it is called.
I don't know what I'm doing wrong when I check whether the method called in the then block. The test is always saying that the method has not been called.
I went through a lot of articles here but I could not figure out what to do.
Thanks for any help in advance!
Here are the code:
requestAuthorizationService
(function () {
    'use strict';

    var serviceId = 'requestAuthorizationService';

    angular
        .module('dilib')
        .service(serviceId, requestAuthorizationService);

    requestAuthorizationService.$inject = ['$q', 'Restangular', 'cryptoService', 'OAuthAuthenticationDataService', 'sessionStorageManagerService'];

    function requestAuthorizationService($q, Restangular, cryptoService, OAuthAuthenticationDataService, sessionStorageManagerService) {

        //API
        var service = {

            requestAuthorization: requestAuthorization,
        }

        return service;

        /////////////////////////////////////////////////////////////////////

        function requestAuthorization(user) {

            var defer = $q.defer();

            var userLocal = undefined;

            if (typeof user === "undefined") {

                userLocal = {
                    username: 'visitor',
                    password: cryptoService.getMD5('qwe123')
                };
            } else {

                userLocal = user;

            }

            OAuthAuthenticationDataService.authenticate(userLocal).then(function (result) {

                //To be tested
                sessionStorageManagerService.set('authorizationData',
                {
                    token: result.access_token,
                    username: user.username
                });

                defer.resolve(userdata.username);

            }, function (msg) {

                defer.reject(msg);

            });

            return defer.promise;
        }

    }
})();

OAuthAuthenticationDataService
(function () {
    'use strict';

    var serviceId = 'OAuthAuthenticationDataService';

    angular
        .module('dilib')
        .service(serviceId, OAuthAuthenticationDataService);

    OAuthAuthenticationDataService.$inject = ['Restangular'];

    function OAuthAuthenticationDataService(Restangular) {

        var OAuthHttpHeader = {
            "Content-Type": 'application/x-www-form-urlencoded'
        };

        var oAuthEndpointResource = Restangular.all('/token');

        var service = {

            authenticate : authenticate

        }

        return service;

        function authenticate(user) {

            return oAuthEndpointResource.post('grant_type=password&username=' + user.username + '&password=' + user.password, {}, OAuthHttpHeader);

        }
    }
})();

sessionStorageManagerService
(function () {
    'use strict';

    var serviceId = 'sessionStorageManagerService';

    angular
        .module('dilib')
        .service(serviceId, sessionStorageManagerService);

    sessionStorageManagerService.$inject = ['localStorageService'];

    function sessionStorageManagerService(localStorageService) {

        var service = {

            get: get,
            set: set

        };

        return service;

        function set(key, val) {

            localStorageService.set(key, val);

        }

        function get(key) {

            return localStorageService.get(key);

        }

    }
})();

Test
describe('requestAuthorizationService', function () {

    var RestangularProvider,
        localStorageServiceProvider,
        cryptoServiceMockSvc,
        OAuthAuthenticationDataServiceMockSvc,
        sessionStorageManagerServiceMockSvc,
        requestAuthorizationService,
        $q,
        $rootScope;

    beforeEach(function () {

        angular.module('ngAnimate', []);
        angular.module('ngRoute', []);
        angular.module('dilib.layout', []);
        //angular.module('LocalStorageModule', []);
        angular.module('http-auth-interceptor', []);
        //angular.module('restangular', []);

    });

    beforeEach(function () {

        module('dilib', function (_RestangularProvider_, _localStorageServiceProvider_) {

            RestangularProvider = _RestangularProvider_;
            localStorageServiceProvider = _localStorageServiceProvider_;

        });

    });

    //beforeEach(inject());

    beforeEach(function () {

        module(function ($provide) {

            $provide.service('cryptoService', function () {
                this.getMD5 = jasmine.createSpy('getMD5').and.callFake(function (param) {

                    var returnVal;

                    if (param == 'qwe123') {

                        returnVal = '200820e3227815ed1756a6b531e7e0d2';
                    }

                    if (param == 'qwe321') {

                        returnVal = 'blabla';
                    }

                    return returnVal;
                });
            });

            $provide.service('OAuthAuthenticationDataService', function () {
                this.authenticate = jasmine.createSpy('authenticate').and.callFake(function (userObject) {

                    var defer = $q.defer();
                    defer.resolve({ access_token: '1234' });
                    return defer.promise;

                });
            });

            $provide.service('sessionStorageManagerService', function () {

                this.get = jasmine.createSpy('get').and.callFake(function(param) {
                    return param;
                });
                this.set = jasmine.createSpy('set').and.callFake(function(param) {
                    return param;
                });

            });

        });

    });

    beforeEach(inject(function (cryptoService,
                                OAuthAuthenticationDataService,
                                sessionStorageManagerService,
                                _requestAuthorizationService_,
                                _$q_,
                                _$rootScope_) {

        cryptoServiceMockSvc = cryptoService;
        OAuthAuthenticationDataServiceMockSvc = OAuthAuthenticationDataService;
        sessionStorageManagerServiceMockSvc = sessionStorageManagerService;
        requestAuthorizationService = _requestAuthorizationService_;
        $q = _$q_;
        $rootScope = _$rootScope_;

    }));

    describe('requestAuthorization method', function () {

        describe('OAuth authentication result will be passed through sessionStorageManager', function () {

            it('default value result will be passed through', function () {

                //try 1
                // OAuthAuthenticationDataServiceMockSvc.authenticate().then(function(result) {

                    // console.log('result', result);

                    // expect(sessionStorageManagerServiceMockSvc.set).toHaveBeenCalled();

                // });

                // $rootScope.$digest();

                //try 2
                // OAuthAuthenticationDataServiceMockSvc.authenticate();

                // expect(sessionStorageManagerServiceMockSvc.set).toHaveBeenCalled();

                // $rootScope.$digest();

            });

        });

    });

});

A: Authenticate has fake implementation, which does not call sessionStorageManagerService.
I do not see any sessionStorageManagerService.set call in your code.

A: I think this should help
var $scope;
var $q;
var deferred;
var sessionStorageManagerService;
var requestAuthorizationService;
var OAuthAuthenticationDataService;

/* Mock another required modules */

beforeEach(function() {
    angular.mock.module(function($provide) {
        sessionStorageManagerService = jasmine.createSpyObj('sessionStorageManagerService', ['set', 'get']);

        $provide.value('sessionStorageManagerService', sessionStorageManagerService);
    });
});

beforeEach(function() {
    angular.mock.module(function($provide) {
        OAuthAuthenticationDataService = jasmine.createSpyObj('OAuthAuthenticationDataService', ['authenticate']);

        $provide.value('OAuthAuthenticationDataService', OAuthAuthenticationDataService);
    });
});

beforeEach(function() {
    angular.mock.module(function($provide) {
        requestAuthorizationService = jasmine.createSpyObj('requestAuthorizationService', ['requestAuthorization']);

        $provide.value('requestAuthorizationService', requestAuthorizationService);
    });
});

beforeEach(inject(function(_$rootScope_, _$q_, _sessionStorageManagerService_, _requestAuthorizationService_, _OAuthAuthenticationDataService_) {
    $scope = _$rootScope_.$new();
    $q = _$q_;
    sessionStorageManagerService = _sessionStorageManagerService_;
    requestAuthorizationService = _requestAuthorizationService_;
    OAuthAuthenticationDataService = _OAuthAuthenticationDataService_;
    deferred = $q.defer();

requestAuthorization.requestAuthorization.and.returnValue(deferred.promise);
OAuthAuthenticationDataService.authenticate.and,returnValue(deferred.promise);

    $scope.$digest();
}));

it('', function() {
    var user = {};

    requestAuthorizationService.requestAuthorization(user);
    deferred.resolve({});
    $scope.$digest();

    expect(OAuthAuthenticationDataService.authenticate).toHaveBeenCalledWith(...);
    expect(sessionStorageManagerService.set).toHaveBeenCalledWith(...);
});

it('', function() {
    var user = {};

    requestAuthorizationService.requestAuthorization(user);
    deferred.reject({});
    $scope.$digest();

    expect(...);
});


text:
Q: Crashing R when calling `write.table` on particular data set The following consistently crashes my R session.
Tested on two machines, Ubuntu and Mac OS X with similar results on both.
Brief Description:
Calling write.table on a data.frame with factor column of all NA's.
The original data set is rather large, and I've managed to isolate the offending column and then create a similar vector, named PROBLEM_DATA below, which causes the same crash.
Interestingly, sometimes R crashes outright, othertimes it simply throws the following error:
Error in write.table(x, file, nrow(x), p, rnames, sep, eol, na, dec, as.integer(quote),  :
  'getCharCE' must be called on a CHARSXP

Any thoughts as to the cause of the crash or should it be submitted as a bug?
Offending data and call:
PROBLEM_DATA <- structure(114:116, .Label = c("String1", "String2", "String3", "String4", "String5", "String6",
                   "String7", "String8", "String9", "String10", "String11", "String12", "String13", "String14", "String15"), class = "factor")

# This will cause a crash
write.table(PROBLEM_DATA, file=path.expand("~/test.csv"))

# This will also crash
write.table(PROBLEM_DATA, file=path.expand("~/test.csv"), fileEncoding="UTF-8")

SESSION INFO OF EACH MACHINE
UBUNTU
R version 2.15.3 (2013-03-01)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C         LC_TIME=C            LC_COLLATE=C
 [5] LC_MONETARY=C        LC_MESSAGES=C        LC_PAPER=C           LC_NAME=C
 [9] LC_ADDRESS=C         LC_TELEPHONE=C       LC_MEASUREMENT=C     LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] gdata_2.12.0     ggplot2_0.9.3    stringr_0.6.1    RMySQL_0.9-3     DBI_0.2-5
[6] data.table_1.8.8

loaded via a namespace (and not attached):
 [1] MASS_7.3-23        RColorBrewer_1.0-5 colorspace_1.2-0   dichromat_1.2-4
 [5] digest_0.5.2       grid_2.15.3        gtable_0.1.1       gtools_2.7.0
 [9] labeling_0.1       munsell_0.4        plyr_1.7.1         proto_0.3-9.2
[13] reshape2_1.2.1     scales_0.2.3       tools_2.15.3

Mac OS X
R version 2.15.3 (2013-03-01)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

A: This is a nice reproducible bug and should be reported to R-devel or using bug.report(). FWIW on
> sessionInfo()
R version 3.0.0 Patched (2013-04-03 r62485)
Platform: x86_64-unknown-linux-gnu (64-bit)

If on Linux I configure R with CFLAGS="-g -O0" I can
R -d gdb
(gdb) break Rf_error
(gdb) run

then paste your lines above and end up at
> write.table(PROBLEM_DATA, file=path.expand("~/test.csv"))

Breakpoint 1, Rf_error (format=0x7ffff7a8f0f0 "'%s' must be called on a CHARSXP") at /home/mtmorgan/src/R-3-0-branch/src/main/errors.c:753
753     RCNTXT *c = R_GlobalContext;
(gdb) up 3
#3  0x00007ffff1b9bfb3 in EncodeElement2 (x=0x31ccf50, indx=113, quote=TRUE, qmethod=TRUE, buff=0x7fffffffbdc0, cdec=46 '.')
    at /home/mtmorgan/src/R-3-0-branch/src/library/utils/src/io.c:938
938     p0 = translateChar(STRING_ELT(x, indx));
(gdb) call Rf_PrintValue(x)
 [1] "String1"  "String2"  "String3"  "String4"  "String5"  "String6"
 [7] "String7"  "String8"  "String9"  "String10" "String11" "String12"
[13] "String13" "String14" "String15"
(gdb) p indx
$1 = 113

which shows R trying to print out the 114th element of the factor names -- clearly things have gone wrong because the factor has integer values beyond the length of its levels.

A: Not an answer, but a long commment:
PROBLEM_DATA <- structure(c(1:5,114:116), .Label = c("String1", "String2", "String3",'string4','str5','str6','str7'),class='factor')
Rgames> as.numeric(PROBLEM_DATA)
[1]   1   2   3   4   5 114 115 116
Rgames> as.numeric(as.character(PROBLEM_DATA))
[1] NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion
Rgames> levels(PROBLEM_DATA)
[1] "String1" "String2" "String3" "string4" "str5"    "str6"    "str7"
Rgames> write.table(PROBLEM_DATA, file=path.expand("~/ctest.csv"))
Error in write.table(x, file, nrow(x), p, rnames, sep, eol, na, dec, as.integer(quote),  :
  'getCharCE' must be called on a CHARSXP

ctest.csv contains:  (each line is a single cell so far as Excel is concerned)
x
1 "String1"
2 "String2"
3 "String3"
4 "string4"
5 "str5"
6

So you can see something going bad when there's a 'gap' in the levels' underlying numbering.  Hope this provides a clue to someone who understands factors a lot more than I do.


text:
Q: Twitter's Bootstrap collapse with manual control - div is not hidden I would like to use Twitter's Bootstrap collapse inside of each collapsible element. But it doesn't work as I expect - see the demo:

*

*when Search button is pressed it is OK, since manually controlled via javascript:
$("#myform").collapse('hide');
$("#search-results").collapse('show');

*when link show search form is clicked, I expect myform to be shown, but search-results to be hidden, but it doesn't happen.

A: You Can add this code to your ready function
 $("a").click(function(){
    $("#myform").collapse('show');
      $("#search-results").collapse('hide');
  });

Here is a working example : http://jsbin.com/upavon/1/edit
Thanks


text:
Q: Concatenate Multi index dataframes ,I'm trying to concatenate multiple resultant dataframes together from a function which I have called with tqdm process_map. Each df has one column, one index and 3 sub-indices. When I concat them, the inidces don't align as you can see below. This creates NaN which I would like to avoid.
cost_values = pd.concat(process_map(run_simulation_a0_b0_search, param_list, max_workers=4),axis=1)

                           0.01      10.00     0.01      10.00
0.01  Average distance  3.055864  0.423096       NaN       NaN
      Collisions        0.007313  0.000000       NaN       NaN
      Minimum distance  0.867630  0.332057       NaN       NaN
10.00 Average distance       NaN       NaN  0.445388  0.418373
      Collisions             NaN       NaN  0.000906  0.000000
      Minimum distance       NaN       NaN  0.280610  0.297080

Here are the 4 dfs printed before they are returned by the run_simulation_a0_b0_search function
                        0.01
0.01 Collisions        0.0073125
     Average distance    3.05586
     Minimum distance    0.86763

                           10.0
0.01 Collisions               0
     Average distance  0.423096
     Minimum distance  0.332057

                           0.01
10.0 Collisions        0.00090625
     Average distance    0.445388
     Minimum distance     0.28061

                           10.0
10.0 Collisions               0
     Average distance  0.418373
     Minimum distance   0.29708


text:
Q: How to join two table without foreignkey with refrence uf uid I am new to DRF I have seen few solution but didnt worked in my case: I have 2 model both have same userID I want to join both table , I have tried but it didnt worked. My modal class is :
class UserGPSFeed(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete = models.CASCADE
    )
    device = models.ForeignKey(
        'UserSensorDevice',
        on_delete = models.CASCADE,
        null=True
    )
    hardware_serial = models.CharField(max_length=255, null=True)
    fixok = models.BooleanField()

class UserSensorDevice(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    sensor_type = models.ForeignKey(
        'SensorDevice',
        on_delete=models.CASCADE
    )
    pseudonym = models.CharField(max_length=255)
    sensor_code = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

My serializer class
class UserGPSFeedSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserGPSFeed
        fields = '__all__'
        read_only_fields = ['id','created_at',]

class UserSensorDeviceWithParamSerializer(serializers.ModelSerializer):
    user = UserGPSFeedSerializer(many=False,read_only=True)
    class Meta:
        model = models.UserSensorDevice
        fields = '__all__'
        read_only_fields = ['id','created_at']

Views.py
class UserSensorDeviceParamListView(generics.ListAPIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = serializers.UserSensorDeviceWithParamSerializer
    queryset = models.UserSensorDevice.objects.filter(sensor_type=2)

    def get_queryset(self):
        return self.queryset.filter(user=self.request.user)

I want to get all user sensor device with parameter. as both have same foreign key. So is there any way to link these type of situation. Any help will be highly appreciated. Thanks!

A: I'm not quite sure about your goal but if you just want to include some data based on something you have in your current serializer you can try this
class UserSensorDeviceWithParamSerializer(serializers.ModelSerializer):
    user_gps = serializers.SerializerMethodField()

    def get_user_gps(self, obj):
        # you can do this
        return UserGPSFeed.objects.filter(user_id=obj.user_id)
        # OR if you prefer
        return UserGPSFeed.objects.filter(user=obj.user)
        # both are the same but using user_id may give a slightly faster performance

    class Meta:
        model = models.UserSensorDevice
        fields = '__all__'
        read_only_fields = ['id','created_at']

Note that, user_id is the name of the column created in your model when specifying a foreign key as it holds the id for the recored it points to
Update: regarding error Object of type UserGPSFeed is not JSON serializable it means that django failed to parse the result to json automaticlly because it's not a model instance but a queryset - sorry I forgot to handle that - so we need to use a serializer to do so, to serialize every object in the returned queryset.
Luckily you have already made this serializer, so we only need to pass the returned queryset to it, so we update get_user_gps() to be like this,
def get_user_gps(self, obj):
    user_gps_queryset = UserGPSFeed.objects.filter(user_id=obj.user_id)
    user_gps_serializer = UserGPSFeedSerializer(user_gps_queryset, many=True)
    return user_gps_serializer.data

The first example still valid of course if it will return one object


text:
Q: Convert Numeric Reference Character to actual character I have a text that needs to be converted into an actual character, we use swedish characters but the data that we received are encoded into Numerical Character like this: ö Ä å
which suppose to be converted into normal characters like ö, ä, å this respectively.
I tried to search here but no luck and there was one though however they use python library instead so I can't convert it to C#.
Do anyone has a sample code on how to convert it to a normal character?

A: WebUtility.HtmlDecode(string) method can do trick for you or you can also use HttpUtility.HtmlDecode(string) method Under Namespace System.Web.
var res1 = WebUtility.HtmlDecode("&#246");

OR
var res1 = HttpUtility.HtmlDecode("&#246");