text:
Q: How to load a react component from express app.js? I just included express sessions in my application. I am setting req.session.user=user in my server.js. I am also sending it to my /welcome route, which represents my homepage. I am currently using react router to show my components on the client side as the user navigates. However, after implementing express sessions, I want to express /welcome route to load my WelcomeUser component with the information about the user available through req.session.user object. My main motive is to send the express req.session.user to the WelcomeUser component, so I can create a profile page for my user. I was looking for solutions and I found the use of fetchAPI to get the data from an express route. A workaround is to have a different route like /getsession in my server.js and fetch the session from that URL in componentDidMount lifecycle method, but I don't know if it's the most optimal way to do this. The following are the relevant part of my code.
This is the express route that that is similar to my react-router route that I am using to show my component. In other words, /welcome route in my react router calls callback(null, WelcomeUser) to show the component.
app.get('/welcome', function (req, res, next) {
  if(!req.session.user){
            res.status(401).send();
  }else{
          console.log("********THIS IS THE USER SESSION*******   : "+ req.session.user);
          // res.status(200).send( "We are here" );
          res.status(200).render( './WelcomeUser.js' );
  }
});

The following is my react router:
   component: Base,
      childRoutes: [
        {
          path: '/',
          component: HomePage
        },
        {
          path: '/welcome',
                  getComponent: (location, callback) => {

              if (*some_login_mechanism_to_identify_if_user_is_loggedin*){
                       callback(null, WelcomeUser);
                    }
              else
                    {
                      callback(null, HomePage);
                    }
                 }
        }, ***morecode***

The following is my local authentication. You can see I am setting req.session.user=user; here I am using passport local strategy for this one.
function(req, email, password, done) {
    process.nextTick(function() {
      if(!req.user) {
        User.findOne({'local.email': email}, function(err, user) {
        if(err) {
          console.error(err);
          return done(err);
          }
        if(user) {

          return done(null, false, {errMsg: 'email already exists'});
        }
        else {
            var newUser = new User();
            newUser.username = req.body.username;
            newUser.email = email;
            newUser.password = password;
            req.session.user=newUser;
            newUser.save(function(err) {
              if(err) {
                if(err.message == 'User validation failed') {
                return done(null, false, {errMsg: 'Please fill all fields'});
                }
                return done(err);
                }
              return done(null, newUser);
            });
          }
      });
    }

The following is one of my social authentication routes:
function(req, accessToken, refreshToken, profile, done) {
    process.nextTick(function() {
      if(!req.user) {//confirm that user not loggedin

        User.findOne({'social.google.id': profile.id }, function(err, user) {
          if (err) {
            console.error('There was an error accessing the dbase', err.message);
            return done(err);
            }
          if (user) {
                          req.session.user=user;

              return done(null, user);
            }
          else {
              var newUser = new User();
         // variables to set my user information from profile variable
              req.session.user=newUser;
              newUser.save(function(err) {
                  if (err) {
                    console.error(err);
                    return done(err);
                  }
                  return done(null, newUser);
              });
            }
          }
        );
      }

All of these codes are present in their separate files. For example, login is present in the local-login file and social login is present in the google-login file. The following is my code to redirect to the /welcome route after authenticating my user.
app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  function(req, res) {
   res.redirect('/welcome'); // this was loading the component from the react router, before I added app.get('/welcome') route in my server.js
  });

This code was working fine before I had my app.get(/welcome) route in my server.js. After adding the app.get(/welcome) in my server.js, it seems like express is overriding my /welcome route result from react router and only showing "we are here" (I commented it out in my express welcome route) in the homepage.


text:
Q: Fragment Pagination - Replacing Touch Handler I'm trying to build an app with many tabs (like many iPhone apps), using the fragments navigation inside tabs. I'm using Support V4 lib.
So the framework is:
TabActivity->FragmentActivity->Fragments
In the fragment activity, the app will call this method to replace a new fragment:
public void updateFragment(Fragment fragment) {

    final FragmentTransaction transaction = fragmentManager
            .beginTransaction();
    transaction.replace(R.id.fragment_layout, fragment, nTag);
    transaction.addToBackStack(null);
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    transaction.commit();
}

... and in the new fragment I also ask the root view to handle the OnTouchEvent:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View root = inflater.inflate(R.layout.fragment_shopfilter, container,
            false);
    root.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    return root;
}

The previous fragment still gets the touch event, how do I make only the new fragment get the touch event?

A: You're registering the fragment as the handler of that event, therefore if you want it to not get the touch event, you have to unregister. You can use root.setOnTouchListener(null); to unset it before setting a new one.

A: My code is working, I just made a mistake.
In new fragment listview adapter, app will start a new empty fragment. But I forgot it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: response.sendRedirect not working between Java and AngularJS I am trying to set up a login page for my website, however at the moment I am stuck on the sendRedirect method, as it doesn't appear to load a new page when required.
My login page is a .jsp file that passes the username and password information via AngularJS $scope to the servlet, which contains the following code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    System.out.println("Redirecting...");
    response.sendRedirect("https://www.youtube.com/");
    return;
}

The System.out.println("Redirecting..."); works, however it does not redirect to the URL provided, no matter what that is. I have read other advice which mentioned to add the return; line, and I have tried other URLs specific to my project (e.g. index.jsp, \index.jsp, etc.), however none of these have made a difference and it still does not work.
Would window.location be a more suitable approach for this? What code should I be modifying here?

A: So I've made the webpage finally redirect correctly and I'm posting this just in case someone else stumbles upon the same issue.
As mentioned in previous comments, the response should be sent from the Java servlet to AngularJS, I have made the redirection occur as follows in my logincontroller.js file:
var app = angular.module('myApp', []);

function LoginController($scope, $http, $window)
{
    $scope.login = function()
    {
        $http({
            url: 'login',
            method: 'POST',
            data:
            {
                'username': $scope.username,
                'password': $scope.password
            }
            }).success(function(data, status, headers, config) {
                alert("SUCCESS! Data: " + data);
                $scope.details = data;
                $window.location.href = "home.jsp"; //This line redirects.
            }).error(function(data, status, headers, config) {
                alert('ERROR!');
        });
    };
};


text:
Q: Why am I getting, "cannot find table 0"? At program startup, I'm creating a SQL Server CE table if it doesn't exist, and adding a record to it:
if (dbconn.isValidTable("hhs_settings") == -1) // <-- (IOW, it's *not* a valid table)
{
    DBUtils.CreateSettingsTable();
    AppSettings.WriteSettingsVal("beltprinter", "None");
}

public static void CreateSettingsTable()
{
    try
    {
        string sqlddl =
            "create table hhs_settings (setting_id int identity (1,1) Primary key,  setting_name varchar(40) not null, setting_value(63) varchar not null)";
        dbconn.DBCommand(sqlddl, false);
    }
    catch (SqlCeException sqlcex)
    {
        MessageBox.Show("sqlcex - CreateSettingsTable " + sqlcex.Message);
    }
    catch (Exception ex)
    {
        MessageBox.Show("CreateSettingsTable " + ex.Message);
    }
}

...but then when I open a form that reads from the table:
lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");

...it fails with "cannot find table 0"
public static string ReadSettingsVal(string settingName)
{
    string retVal = string.Empty;
    string sqldml = string.Format("select setting_value from hhs_settings where setting_name = {0}", " + settingName + ");
    // There should only be one value returned, but using the existing getDataSet() method for now...
    DataSet dsSettingVal = frmCentral.dbconn.getDataSet(sqldml);
    foreach (DataRow row in dsSettingVal.Tables[0].Rows)
    {
        if (retVal == string.Empty)
        {
            retVal = row["setting_value"].ToString();
        }
    }
    return retVal;
}

Am I missing a step here, so that the table (hhs_settings) is not being created? Or...???
UPDATE
I'm still getting the same err msg even after changing all of the goofily formatted strings so that they are now:
string sqldml = string.Format("insert into hhs_settings (setting_name, setting_value) values('{0}', '{1}')", settingName, settingVal);
string sqlqry = string.Format("select setting_value from hhs_settings where setting_name = '{0}'", settingName);

And, I'm still seeing the msg "about to create hhs_settings" even though, presumably, the createtable sql was already good:
string sqlddl =
    "create table hhs_settings (setting_id int identity (1,1) Primary key,  setting_name varchar(40) not null, setting_value(63) varchar not null)";

...and so, the table should have been created (which should have made the isValidTable() method return something other than -1 (the value it returns when the table is not found).
UPDATE 2
It helped (it works now) when I changed my ddl to:
string sqlddl =
        "create table hhs_settings (setting_id int identity (1,1) Primary key,  setting_name nvarchar(40) not null, setting_value nvarchar(63) not null)";

A: string.Format("select setting_value from hhs_settings where setting_name = {0}", " + settingName + ");

The result of it is
select setting_value from hhs_settings where setting_name =  + settingName +

what is obviously not a correct SQL. You need to use something like this
string.Format("select setting_value from hhs_settings where setting_name = '{0}'", settingName);

(also note quotation marks around the parameter placeholder)
but it much more better if you use parameters instead of generating SQL with all identifiers embedded

A: If you are using stored procedures, check out the name of the passing queries in it. It should exactly match with the front end and backend.


text:
Q: WiX installer registry keys get removed at shutdown/restart Here is my xml file for WiX
https://github.com/Vaei/ue4cleaner/blob/master/UE4Cleaner/UE4CleanerInstaller.xml
The registry keys get installed and everything works beautifully until restarting the computer, then they get removed. If I do a bad shutdown (hold the power button or press reset on the case) it will remain.

A: The dirty shutdown scenario suggests to me that you have some running processes that are deleting the registry data when windows tells them to shutdown.  I don't think this is an installer problem at all.


text:
Q: Built in python hash table implementation Is there a  built in implementation of hash table in python which finds the key based on value in O(c) time (c - constant). I guess dictionaries in python finds the key just by iterating through the values.

A: Python's dict is a hash-table (see this StackOverflow answer)
And from Python wiki:

Python's dictionary implementation reduces the average complexity of dictionary lookups to O(1) by requiring that key objects provide a "hash" function


text:
Q: Restrict Input similar to Instagram Username Field I'm trying to restrict my username input field to be like that of Instagram's username field where it allows A-Z a-z and . and 0-9. I've tried a few regex JS examples but just can't get it to this point.
<label for="username">Username</label>
<input class="form-control" id="username" type="text" name="username">

This is what I have currently, can anyone help?

A: Can you post your Regex? There are a few ways to do validation of an input, but for something not too crazy like what you are requesting, I bet we can land on a solid Regex structure.
Just on my phone here, so not able to test super well but I am thinking something simple like:
[a-zA-Z\d\.]+


text:
Q: Set "hints" for function name I'm trying to declare function named hints and it does not work.
function hints() {
    alert("E");
}

<select id = "cbTipo" onchange="hints();">
    <option value = 0>1</option>
    <option value = 1>2</option>
</select>

Is it a reserved word?

A: Make sure to surround your JS code with script tags.

<select id = "cbTipo" onchange="hints();">
    <option value = 0>1</option>
    <option value = 1>2</option>
</select>

<script>
function hints() {
    alert("E");
}
</script>

A: Javascript reserverd words: https://www.w3schools.com/jS/js_reserved.asp
'Hints' - is not the reserved word


text:
Q: Feeding nullable data from BigQuery into Tensorflow Transform We're trying to build a pipeline that takes data from BigQuery, runs through TensorFlow Transform, before training in TensorFlow.
The pipeline is up and running, but we're having difficulty with null values in BigQuery.
We're using Beam to load from BigQuery:
    raw_data = (pipeline
                | '{}_read_from_bq'.format(step) >> beam.io.Read(
                    beam.io.BigQuerySource(query=source_query,
                                           use_standard_sql=True,
                                           )))

I'm playing with the dataset metadata, trying FixedLenFeature and VarLenFeature for various columns:
    # Categorical feature schema
    categorical_features = {
        column_name: tf.io.FixedLenFeature([], tf.string) for column_name in categorical_columns
    }
    raw_data_schema.update(categorical_features)

    # Numerical feature schema
    numerical_features = {
        column_name: tf.io.VarLenFeature(tf.float32) for column_name in numerical_columns
    }
    raw_data_schema.update(numerical_features)

    # Create dataset_metadata given raw_data_schema
    raw_metadata = dataset_metadata.DatasetMetadata(
        schema_utils.schema_from_feature_spec(raw_data_schema))

As expected, if you try and feed a BigQuery NULL into a FixedLenFeature, it breaks.
However, when I try to feed strings or integers a VarLenFeature, it breaks too. This seems to be because VarLenFeature expects a list, but BigQuerySource gives a Python primitive. The exact point where it breaks is here (error is from when I tried with an integer):
File "/usr/local/lib/python3.7/site-packages/tensorflow_transform/impl_helper.py", line 157, in <listcomp>
indices = [range(len(value)) for value in values]
TypeError: object of type 'int' has no len()
[while running 'train_transform/AnalyzeDataset/ApplySavedModel[Phase0]/ApplySavedModel/ApplySavedModel']

When I try VarLenFeature with my string inputs, e.g. "UK", the output is a SparseTensor like this:
SparseTensorValue(indices=[(0, 0), (0, 1)], values=['U', 'K'], dense_shape=(1, 2))

So it seems like I need to be passing a list into VarLenFeature for this to work, but BigQuerySource does not do this by default.
Is there a simple way of achieving this? Or am I totally missing the mark on reading nullable columns from BigQuery?
Thank you very much in advance!

A: You might need to handle NULL(missing) values by yourself. For numerical columns, you could replace NULLs with mean or median. For categorical columns (STRING), you could use some default value like an empty STRING or a new value as a missing value indicator.
I'm not very familiar with VarLenFeature, but you can probably replace NULLs (NULL imputation) in the source_query. Something like:
IFNULL(col, col_mean) AS col_imputed
The downside is that you will have to calculate col_mean first using sql and fill it here as a constant. Another thing is you will need to remember this mean and apply the same mean in prediction as it's not part of tf.transform (your graph).
Bigquery itself has BQML as an ML platform. They do support TRANSFORM and automatic imputation. Maybe you could also take a look :)


text:
Q: How do you set an 'active' class in React and CSS? I have navigation in my React app. However I would like the colour of navigation to change if on that page.
Heres my code Ive added an active className to the items.
        <Link to='/'>

Gatsby's

        </Link>
        <Link to='/drink'>

Drink

        </Link>
        <Link to='/food'>

Food

        </Link>
        <Link to='contact'>

Contact

        </Link>

The navigation links currently have a background of black. I want the colour to change to lets say red.
P.S I'm using standard CSS for styles.

A: Light/Fast way to do this would be to change the class at the parent DOM element of these <Link> elements... from there the CSS would do what it works best.
Assuming these <Link> ... </Link> tags are enclosed inside a  ...  tag, which is the parent DOM element.
{ (onThePage) ?  ...  :  ...  }

Try this else share MVCE if you get stuck so that it serves as a good example for others looking for help

A: There is actually a property of activeClassName in NavLink of react router.
It goes like this
Import { NavLink } from 'react-router-dom`
...

<NavLink exact activeClassName="your_active_css_classname" className="normal_css">Link name </NavLink>

Don't forget to add exact. Read more here: https://reacttraining.com/react-router/web/api/NavLink


text:
Q: SQL Coldfusion - eliminate the word THE when searching for duplicate names I have a process that creates a list of possible duplicate companies.  The problem is that "The ABC Company, Inc." and "ABC Company, Inc." both in Dallas, TX are probably duplicates but I won't find them with my criteria. I've eliminated the first 4 characters if they are "the " but I also need to check for the right 5 characters if they are " Inc.".
I have a view that creates a column thename.  The prefix "the " has been stripped;
    SELECT     CASE WHEN LEFT(name, 4) = 'The ' THEN RIGHT(name, (len(name) - 4)) ELSE name END AS thename, CASE WHEN CHARINDEX(' ', ltrim(rtrim(Name)))
                          = 0 THEN ltrim(Name) WHEN CHARINDEX(' ', ltrim(Name)) = 1 THEN ltrim('b') ELSE SUBSTRING(ltrim(Name) + ' x', 1, CHARINDEX(' ', ltrim(Name))) END AS subname,
                          CHARINDEX(' ', LTRIM(Name)) AS wordcheck, Name, Address_Line_1, City AS Company_City, State AS Company_State, Zip, Area_Code, Phone, Status_Flag, ID,
                          Not_Dupe_Flag, DUNS, Temp_Check_Dupes_Flag, Parent_Company_Number, Special_Display,
                          CASE WHEN c.parent_company_number = 0 THEN c.id ELSE c.parent_company_number END AS parent
    FROM         dbo.Companies AS c

Then I use that view in my query to look for duplicates;
        <cfquery name="qResults" datasource="#request.dsnlive#" timeout="200">
            SELECT b.ID,
            Thename,
            substring(TheName,1,(CHARINDEX(' ',TheNAME,1))) as subName,
            name,
            b.address_line_1,
            b.zip,
            b.company_state,
            b.company_city,
            b.area_code,
            b.phone,
            b.Special_Display,
            isnull(not_dupe_flag,'False') as not_dupe_flag,
            isnull(Temp_Check_Dupes_Flag,'False') as Temp_Check_Dupes_Flag,
            b.id as bID,
            b.duns
            FROM dbo.vw_Comp_Details_withFirstWord as b
            WHERE isnull(b.status_flag,'') != 'D'
            and b.ID <> #arguments.CompNum#
                and isnull(b.Temp_Check_Dupes_Flag,'False') = 'False'
            <cfif arguments.IncludeDunsOnly eq 0>
                <cfif arguments.FirstWord>
                    AND b.subName = '#arguments.CompanySubName#'
                <cfelse>
                    AND (substring(dbo.KeepAlphaNumCharacters(Thename),1,#val(arguments.WordLength)#) = substring('#arguments.CompanyName#',1,#val(arguments.WordLength)#)
                    or differnce(soundex(Thename),soundex('#arguments.CompanyName#')) > 2)
                </cfif>
                AND (
                ( company_city = '#arguments.City#'
                 AND Isnull(company_city, '') > '' )
                 AND ( b.parent != #val(arguments.Parent)#
                     AND Isnull(b.parent, '0') > 0 )
                     )
                <cfif arguments.IncludeDuns>
                AND (
                ( REPLACE(LTRIM(REPLACE(b.duns, '0', ' ')), ' ', '0') = '#val(arguments.Duns)#'
                 AND REPLACE(LTRIM(REPLACE(b.duns, '0', ' ')), ' ', '0') > ' '
                 AND #val(arguments.Duns)# > 0 )
                    or  REPLACE(LTRIM(REPLACE(b.duns, '0', ' ')), ' ', '0') = ' '
                    )
                </cfif>

            <cfelse>
                and (REPLACE(LTRIM(REPLACE(b.duns, '0', ' ')), ' ', '0') = '#val(arguments.Duns)#')
            </cfif>

        </cfquery>

Now I need to add code to strip the suffix " Inc." but I can't seem to come up with the logic to end up with a column that contains the name without the prefix "The " and the suffix " Inc."

A: I will like to share my question from some days ago. This was made in Postgres but Im sure you can find an equivalent for split string into rows for your rdbms.
What you do is split the string and remove the offending string like The or Inc
SQL Fiddle Demo
| ID |   token |
|----|---------|
|  1 |     The |
|  1 |     ABC |
|  1 | Company |
|  1 |    Inc. |
|  2 |     ABC |
|  2 | Company |
|  2 |    Inc. |
|  3 |     ABC |
|  3 | Company |

Then you go the other way and join the remaining strings together  postgres use string_agg() MSsql use XML PATH, etc

A: Many possible ways to do this. Consider if you want to have a fulltext index won the field which can then search for similar names and eliminate noise words like the. Or you can use an SSIS package to do fuzzy matching (this would also help with abbreviations vice spelling the whole word out). Or you can use Data Quality Services which is probably your best bet.
https://msdn.microsoft.com/en-us/library/ff877917.aspx


text:
Q:  works locally until I upload to apache server I have built a page with an  tag to display another page. When testing locally everything works as intended until I upload it to my apache2 server. I've never had this issue before. I have pulled older versions of this page that I know have worked before and they no longer work on the new software(switched from arch to Ubuntu server). Below is the code I used for the .
<iframe src="IP_Adress_Here" style="height:100%; max-height:3000px; border-radius: 12px;" width="100%" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>

A: Just for anyone interested, the issue was that the wrapping page is being served up on HTTPS but the iframe content was on HTTP and the browser's security model blocked the loading of the iframe content (shows quietly as an error in the console)


text:
Q: PHP cURL POST Request won't send? I'm trying to update a mySQL database with cURL and PHP, but the values that are supposed to be sent by the post aren't inserted into the database. I don't get any errors and cURL is enabled according to phpinfo(). Here is my script:
<?php

  $data = [
    'email' => 'jsnow@got.com',
    'token' => '58938539'
  ];

$string = http_build_query($data);
$ch = curl_init("http://www.econcentre.com/receiver.php");

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_exec($ch);
curl_close($ch);

?>

And here's the receiver script:
<?php
   require 'includes/db.php';  // Database connection. Connects with no errors raised

   if(isset($_POST['email']) AND isset($_POST['token'])) {
     $email = $_POST['email'];
     $token = $_POST['token'];

     $q = "INSERT INTO reset_tokens(email, token)";
     $q .= " VALUES(?, ?)";
     $stmt = $pdo->prepare($q);
     $test = $stmt->execute([$email, $token]);
 }

?>

A: Looks like you are missing HTTP Auth for http://www.econcentre.com/receiver.php.
You should include the HTTP Auth in the cURL request:
<?php

$data = [
    'email' => 'jsnow@got.com',
    'token' => '58938539'
];
$username = "auth-user";
$password = "auth-pwd";

$string = http_build_query($data);
$ch = curl_init("http://www.econcentre.com/receiver.php");

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
curl_close($ch);

?>


text:
Q: Database gets connected via DB client but not via Datasource explorer in eclipse I am experiencing an weird issue.
we have a DB2 database that gets connected using DB client like Db-visualizer etc but it does not get connected when tried using datasource explorer in eclipse.
Doing so , I get an error stating : Error opening socket to server
Error Code : -4499
SQL State :
As anyone faced this error or has any solution to this ?


text:
Q: Discrete Math on Induction proofs Show by induction that the following formulas hold for
$$
  \sum_{i=1}^n i^3
= \frac{n^2(n+1)^2}{4}
$$
Not sure how to go about this problem. Can someone help please?  Thanks

A: The base case:
$$\sum_{i=1}^1 i^3 = 1^3 = \frac{1^2 2^2}{4}.$$
Now suppose that the result holds for all $k \leq n$. Then
\begin{align}
   \sum_{i=1}^{n+1} i^3
&= \sum_{i=1}^n i^3 + (n+1)^3 \\
&= \frac{n^2 (n+1)^2}{4} + (n+1)^3 \\
&= (n+1)^2 \left( \frac{n^2 }{4} + (n+1) \right) \\
&= \frac{(n+1)^2}{4}(n^2 + 4n + 4) \\
&= \frac{(n+1)^2}{4}(n+2)^2 \\
&= \frac{(n+1)^2(n+2)^2}{4}.
\end{align}


text:
Q: O que é Mineração de Dados? Bom, o título diz tudo:

O que é Mineração de Dados?

A: Mineração de dados ou do inglês Data Mining
Desde que a informação passou a ser tão importante para a tomada de decisão os dados passaram a ser armazenados em grandes escalas. E com o volume de dados armazenados crescendo diariamente, começou a aparecer o questionamento. O que fazer com tantos dados armazenados? As técnicas tradicionais de exploração de dados não são mais adequadas para tratar a grande maioria dos repositórios. Com a finalidade de responder a esta questão, foi proposta, no final da década de 80, a Mineração de
Dados, do inglês Data Mining.
A Mineração de Dados é uma das tecnologias mais promissoras da atualidade. Um dos fatores deste sucesso é o fato de dezenas, e muitas vezes centenas de milhões de reais serem gastos pelas companhias na coleta dos dados e, no entanto, nenhuma informação útil é identificada. Em seu trabalho, Han (2006) em seu livro refere-se a essa situação como "rico em dados, pobre em informação". Além da iniciativa privada, o setor público e o terceiro setor (ONGt's) também podem se beneficiar com a Mineração de Dados.
Mineração de dados não é apenas usado pelo Bitcoin, mas Segundo Witten e Bramer podem ser utilizados em algumas das áreas de forma satisfatória, como:

*

*Retenção de clientes: identificação de perfis para determinados
produtos, venda cruzada;

*Bancos: identificar padrões para auxiliar no gerenciamento de
relacionamento com o cliente;

*Cartão de Crédito: identificar segmentos de mercado, identificar
padrões de rotatividade;

*Cobrança: detecção de fraudes;

*Telemarketing: acesso facilitado aos dados do cliente;

*Medicina: indicação de diagnósticos mais precisos;

*Segurança: na detecção de atividades terroristas e criminais;

*Tomada de Decisão: filtrar as informações relevantes, fornecer
indicadores de probabilidade.

*Um supermercado melhore a disposição de seus produtos nas
prateleiras, através do padrão de consumo de seus clientes;

Mas mineração de dados funciona na prática?
A mineração de dados é utilizado em grandes quantidades de dados e usa análises matemática para derivar anomalias, padrões e correlações, captando apenas o que é relevante, através de uma educação prévia da ferramenta. As empresas utilizam esta tecnologia para suportar a tomada de decisões e proporcionar vantagens estratégicas. Usando uma ampla variedade de técnicas, você pode utilizar estas informações para aumentar as receitas, reduzir custos, melhorar o relacionamento com os clientes, reduzir riscos e entre outros.
O mais importante para qualquer projeto que decida usar a mineração de dados é definir claramente qual será o problema solucionado.
Segundo o site do SAS Institute

Mineração de dados é definido como uma disciplina combinada,
  representa uma variedade de métodos ou técnicas utilizadas em
  diferentes capacidades analíticas que abordam uma gama de necessidades
  organizacionais, respondem diferentes tipos de perguntas e usam
  diferentes níveis de regras para se chegar a uma decisão.

E ainda definem várias tipo de modelagem, como: Modelagem descritiva, Modelagem preditiva e Modelagem prescritiva.
Um dos padrões mais difundidos para se trabalhar com mineração de dados é o CRISP-DM (Cross-Industry Standard Processo of Data Mining), devido à vasta literatura disponível e por atualmente ser considerado o padrão de maior aceitação, segundo HAN (2006).
Como afirma Olson et al. (2008) em seu livro, o processo CRISP-DM consiste de seis fases organizadas de maneira cíclica, conforme mostra a figura abaixo. Além disto, apesar de ser composto por fases, o fluxo não é unidirecional, podendo ir e voltar entre as fases.

As fases do processo CRISP-DM, são:

*

*Entendimento dos Negócios: Nessa etapa, o foco é entender qual o
objetivo que se deseja atingir com a mineração de dados. O
entendimento do negócio irá ajudar nas próximas etapas.

*Entendimento dos Dados: As fontes fornecedoras dos dados podem vir
de diversos locais e possuírem diversos formatos. Segundo Olson et
al, após definir os objetivos, é necessário conhecer os dados
visando: Descrever de forma clara o problema; Identificar os dados
relevantes para o problema em questão; Certificar-se de que as
variáveis relevantes para o projeto não são interdependentes.
Normalmente as técnicas de agrupamento e de exploração visual também
são utilizadas nesta etapa.

*Preparação dos Dados: Devido às diversas origens possíveis, é comum que os dados não estejam preparados para que os métodos de Mineração de Dados sejam aplicados diretamente. Dependendo da qualidade desses dados, algumas ações podem ser necessárias. Este processo de limpeza dos dados geralmente envolve filtrar, combinar e preencher valores vazios.

*Modelagem: É nesta fase que as técnicas (algoritmos) de mineração serão aplicadas. A escolha da(s) técnica(s) depende dos objetivos desejados.
Mineração de Dados: Conceitos, Tarefas, Métodos e Ferramentas 5

*Avaliação: Considerada uma fase crítica do processo de mineração, nesta etapa é necessária a participação de especialistas nos dados, conhecedores do negócio e tomadores de decisão. Diversas ferramentas gráficas são utilizadas para a visualização e análise dos resultados (modelos). Testes e validações, visando obter a confiabilidade nos modelos, devem ser executados (cross validation, suplied test set, use training set, percentage split) e indicadores para auxiliar a análise dos resultados precisam ser obtidos (matriz de confusão, índice de correção
e incorreção de instâncias mineradas, estatística kappa, erro médio absoluto, erro relativo médio, precisão, F-measure, dentre outros).

*Distribuição: Após executado o modelo com os dados reais e completos é necessário que os envolvidos conheçam os resultados.

Obs.: Resposta baseada nos livros citados. Todos o conhecimento
  repassados tem como base as afirmações e conhecimento dos altores
  sobre tema


text:
Q: Technical challenge: Limit of von-Mises distribution approximates normal. How to take the limit? Background:
In psychophysics or the study of ant navigation it's important to represent random variables on a circle. The most popular distribution for doing so is the von-Mises distribution (the wrapped Gaussian is too messy to work with). This is the von-Mises distribution for a random variable on a circle, $\theta \in [-\pi,\pi)$:
\begin{align}
p(\theta;\mu,\kappa) = \frac{e^{\kappa cos(\theta - \mu)}}{\int_{-\pi}^\pi e^{\kappa cos(\theta)} \text{d}\theta} = \frac{e^{\kappa cos(\theta - \mu)}}{2 I_0(\kappa)}  ,
\end{align}
where $\kappa$ is the concentration parameter (have the inverse variance $\kappa \sim \sigma^{-2}$ in mind), $\mu$ the mean and the normalisation can be expressed in terms of the modified Bessel function of the first kind, $I_0(\kappa)$.
Problem statement:
Wikipedia (https://en.wikipedia.org/wiki/Von_Mises_distribution) claims that
\begin{align}
\lim_{\kappa \rightarrow \infty} p(\theta;\mu,\kappa) = \text{Normal}(\theta; \mu, \kappa^{-1/2}).
\end{align}
(The limit is not a rigorous mathematical limit but more a physicist-way of saying: expand the expression and throw higher-order terms away).
It makes sense: If the distribution is highly concentrated, we can forget about the circularity and just approximate the von-Mises as normal. Mathematically it makes intuitive sense, too. The argument of the exponential ranges between $\pm \kappa$, being 0 always at $\theta = \pm \pi/2$. At the same time, the normalisation constant grows large such that the whole distribution is essentially divided by a very large number and tends to zero everywhere except around it's mode. Around the mode, the cosine can be approximated by $\cos(\epsilon) = 1- \epsilon^2/2$, yielding a nice normal distribution. Despite this, I find it incredibly hard to show this! Can anyone help me with this technical challenge?
My (unsuccessful) approach:
I've tried to use Taylor expansion for the cosine and the following series representations (http://mhtlab.uwaterloo.ca/courses/me755/web_chap4.pdf) of the Bessel function for large $\kappa$:
\begin{align}
I_0(\kappa) = \sum_{n}^\infty \frac{(\kappa/2)^{2n}}{n!\Gamma(n+1)} \approx \frac{e^\kappa}{\sqrt{2\pi \kappa}}(1 + \frac{1}{8\kappa} + \mathcal{O}(\kappa^{-2})),
\end{align}
however, it didn't get me anywhere. Does anyone have any ideas how to attack this problem? Any help is much appreciated!

A: I'm not entirely sure how rigorous this is so check over my work carefully.
From the pdf $\frac{e^{\kappa\cos(x-\mu)}}{2\pi I_0(\kappa)}$
You already got that $I_0(\kappa)= \frac{e^{\kappa}}{\sqrt{2 \pi \kappa}}(1+\frac{1}{8\kappa})$
In the limit only angles close to the mean will be significant therefore you can assume that $x-\mu$ is small.
For small $z$ we have $cos(z)=1-\frac{z^2}{2}$
Substitute the approximations for $cos(x)$ and $I(\kappa)$ into the pdf to get
$ \frac{1}{2\pi I_0(\kappa)} e^{\kappa \left(1-\frac{(x-\mu)^2}{2}\right)}$
$ \frac{1}{2\pi \frac{e^{\kappa}}{\sqrt{2 \pi \kappa}}(1+\frac{1}{8\kappa})} e^{\kappa \left(1-\frac{(x-\mu)^2}{2}\right)}$
Expanding out the exponent in the numerator and canceling $e^{\kappa}$ terms gives:
$ \frac{1}{2\pi \frac{1}{\sqrt{2 \pi \kappa}}(1+\frac{1}{8\kappa})} e^{ \left(\frac{\kappa(x-\mu)^2}{2}\right)}$
Neglecting the $\frac{1}{8\kappa}$ term in the denominator and tidying up the constants gives you
$ \frac{1}{\sqrt{\frac{2 \pi}{\kappa}}} e^{ \left(\frac{\kappa(x-\mu)^2}{2}\right)}$
Which is a normal distribution

A: Thanks Hugh, you got me onto the right path!
Comparing two values $x_d,x_D$ at distances $d$ and $D$ from the mean and $d < D$, the ratio of pdf's approaches zero quickly as I let $\kappa$ grow:
\begin{align}
\frac{p(x_D)}{p(x_d)} = e^{\kappa (\cos(D) - \cos(d)} \equiv e^{- \kappa \epsilon },
\end{align}
where $\epsilon := \cos(d) - \cos(D) > 0$. Suppose $\cos(y) \approx 1 - \frac{y^2}{2}$ is a valid approximation for $y=d$ but not for $y=D$. Then, I choose $\kappa \sim \epsilon^{-1}$ to ensure that the approximated pdf is only significantly different from zero where $d$ is small enough to taylor-expand the cosine to the quadratic order, as you suggested.
I am aware of the fact that this might not be a rigorous mathematical proof but it suffices for my application. Thanks again for your help!


text:
Q: How to Restore backup from external drive to itunes or iphone in Windows 8? I back my iPhone up to My Windows 8. Since I don't have much space on my C: Drive, I moved my iTunes backup folder to an external drive (mklink/J "%APPDATA%\Apple Computer\MobileSync\Backup" "J:\Backup"), and then created a symlink from the normal backup folder to the location on the external drive where that particular backup folder is located.
Now, there are two problems I've noticed with this. Firstly, when I connect my device and look in iTunes, it says "Latest Backup: Your iPhone has never been backed up to this computer" – even though it has been backed up (although to an external drive). The worse part is that the "Restore Backup..." button is grayed out, not allowing me to restore my iPhone from the backup.
Another thing I should mention is that when I go to iTunes > Preferences > Devices, I don't see my iPhone backup in the list.
So, how do I restore my iPhone from my backup external drive in my windows 8.. Please help

A: iTunes doesn't work with symlinks very well. Try to copy the backup of your device back to "~\MobileSync\Backup" folder. Your backup is a folder in "Backup" folder with 40 random chars in name (device UDID).
After copying the backup, restart iTunes. It should now see the backup and allow you to restore it.


text:
Q: Optaplanner add computerroom restriction it's my first post here and I'm posting for my team of learning Java programmer for an school project. So we aren't good programmer.
how can I add a constraint to make the Optaplanner move the lectures into a specific room type.
For example I want to move the lecture "Programming" into a computerroom and the lecture "Math" in a normal room. But with my constraint it declares the hard constraints but doesn't move the lectures in their room. This should be a negative constraint. So the negative score for this hard constraint is shown, but it still won't be resolved/moved.
Here's the constraint:
rule "computerroom"
    when
       $room : Room($computerroom : computerroom)
       $course : Course(computerroom == $computerroom)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end

We added a new variable to the class Room, that look like:
package org.optaplanner.examples.curriculumcourse.domain;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.optaplanner.examples.common.domain.AbstractPersistable;

@XStreamAlias("Room")
public class Room extends AbstractPersistable {

    private String code;
    private int capacity;
    private boolean computerroom;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public boolean getComputerroom() {
        return computerroom;
    }

    public void setComputerroom(boolean computerroom) {
        this.computerroom = computerroom;
    }

    public int getCapacity() {
        return capacity;
    }

    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }

    public String getLabel() {
        return code;
    }

    @Override
    public String toString() {
        return code + " {C" + capacity + "}";
    }

}

So have u got an advise for us?
Another little thing: the Optaplanner gets a lot of data to work with:
How can we increase the maximun seconds spend for resolving? Because we tried other values over 1152 but it does't work.
It's only a little question, the constraint is more important, but we would be happy to get the program running!
Greets
SEP2014

A: That score rule isn't checking anything that is "planning variable" (= a variable that changes during solving). So it's static, it can never have a different score than with what it starts out with.
Consider this instead:
rule "computerroom"
  when
    // If there's a room which has no computer
    $r : Room(hasComputer == false)
    // And we're putting a course which needs a computer in that room
    $course : Course(needsComputer == true, room == $r)
  then
    scoreHolder.addHardConstraintMatch(kcontext, -1);
end

The important thing here is Course(..., room == $r). That room is a planning variable: it changes during planning.
Note: this one doesn't punish courses that don't need a computer if they use a computer room (but that's easily changed).
Same rule, but written shorter and more efficiently:
rule "computerroom"
  when
    $course : Course(needsComputer == true, room != null, room.hasComputer == false)
  then
    scoreHolder.addHardConstraintMatch(kcontext, -1);
end


text:
Q: Fatal error with NuSoap 1.94 with PHP 5.2.17 making a soap client call I'm getting an error message when making a call to an xBase++ based web server that is acting as a web service (not using WSDL) when trying to make a soapclient call to it using NuSoap 1.94 with PHP 5.2.17.  This exact same code works with NuSOAP 1.94 on PHP 4.  Any ideas or help would be appreciated!
Note (I had to remove the https:// part of the addresses from the error message below - I was getting an error posting saying I needed 10 reputation to post 2 links or more)
Thanks,
Salar

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'xxx.xxx.com:55055' : failed to load external entity "xxx.xxx.com:55055" in /hsphere/local/home/xxx/xxx.com/phpinvent/inc/functions/xmsg.php:34 Stack trace: #0 /hsphere/local/home/xxx/xxx.com/phpinvent/inc/functions/xmsg.php(34): SoapClient->SoapClient('https://xxx.xxx...') #1 /hsphere/local/home/xxx/xxx.com/phpinvent/xmsgtest.php(15): XMsg('LOGIN', Array) #2 {main} thrown in /hsphere/local/home/xxx/xxx.com/phpinvent/inc/functions/xmsg.php on line 34

Here's the code of my test page, and the xmsg function:
<?php
ini_set('display_errors', 'On');
ini_set('default_socket_timeout', 300);
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// include configuration
require_once('inc/config.php');
require_once('inc/nusoap/nusoap.php'); // include the NuSOAP classes

$xmsg_param[0][0] = "userid";
$xmsg_param[0][1] = "TEST";
$xmsg_param[1][0] = "password";
$xmsg_param[1][1] = "TEST";

$result = XMsg("LOGIN", $xmsg_param);
echo("
resulttxt: ".$result['xmsg_resulttxt']);
echo("
Sessionid: ".$result['sessionid']);

?>

<?php
// XMsg *************************************************************************
// This function is used to send a message through the robust, connectionless message system
function XMsg($xm_type, $xm_parameters, $xm_target = XMSG_DEFAULT_GATEWAY, $xm_mode = XMSG_DEFAULT_MODE)
{
    // Parameters:
    // xm_type - C - mandatory – type of message being sent
    // xm_parameters - A - optional - 2 dimensional array of name/value pairs that will be sent to the target with the message
    // xm_target - C - optional - target - currently supports only URLs of AutoMate agents - defaults to gateway
    // xm_mode - C - optional - tokens that allow for modification of the message - currently defaults to #SOAP# to send via SOAP
    // Returns:
    // xm_result - A - array of name/value pairs returned from the target in same format as xm_target
    $xm_SOAPagent   = '';       // SOAP Envelope Object - Request
    $xm_SOAPresult  = '';       // SOAP Envelope Object - Response
    $xm_SOAPclass   = '';
    $xm_retrynum    = 0;        // Number of retries attempted
    $xm_retry       = true;     // Continue retrying?
    $xm_result      = Array();  // Array of results returned by XMsg
    $xm_numparams   = 0;        // Number of parameters passed to XMsg
    $xm_I           = 0;        // FOR Loop Counter
    // Initialize Parameters
    $xm_parameters  = (gettype($xm_parameters) == "array" ? $xm_parameters : array());

    // check if mandatory parameters are passed
    // xm_type must be character and not empty
    if (gettype($xm_type)=="string" && !empty($xm_type)) {
       switch($xm_mode)
       {
          case "SOAP":
              // open SOAP envelope and initialize
              echo("calling xm_target: ".$xm_target."
");
              $soapclient = new soapclient($xm_target);

              $soapparam = array();

              // create and pass xmsg structure - NOTE: this section is specialized to PHP
              $soapparam['xmsg_id'] = '';
              $soapparam['xmsg_source'] = '';
              $soapparam['xmsg_target'] = $xm_target;
              $soapparam['xmsg_session'] = $_SESSION['SESSIONID'];
              $soapparam['xmsg_userid'] = $_SESSION['USERID'];
              $soapparam['xmsg_websessid'] = session_id();
              $soapparam['xmsg_ip'] = $_SERVER['REMOTE_ADDR'];
              $soapparam['xmsg_status'] = 'SENT';
              $soapparam['xmsg_type'] = $xm_type;
              $soapparam['xmsg_result'] = '';
              $soapparam['xmsg_resulttxt'] = '';
              $soapparam['xmsg_date'] = date("m/d/y");
              $soapparam['xmsg_time'] = date("H:i:s");
              $soapparam['xmsg_datereceive'] = '';
              $soapparam['xmsg_timereceive'] = '';
              $soapparam['xmsg_dateresponse'] = '';
              $soapparam['xmsg_timeresponse'] = '';

              // count parameters and add to SOAP Envelope
              $xm_numparams = count($xm_parameters);
              for ($xm_I = 0; $xm_I < $xm_numparams; $xm_I++) {
                  echo("setting soapparam[".$xm_parameters[$xm_I][0]."] to :".$xm_parameters[$xm_I][1]);
                  $soapparam[$xm_parameters[$xm_I][0]] = $xm_parameters[$xm_I][1];
              }

              // SOAP retry loop start - retry until xm_retry is false - set to false when call succeeds or max # retries exceeded
              do {

                 // run remote SOAP call for RemoteCall as specified in
                 $xm_result = $soapclient->call('XMsg',$soapparam);
                 // check for fault
                 echo ("Fault: ".$xm_result['FAULT']."
");
                 echo ("1 Faultcode: ".$xm_result['faultcode']."
");
                 if (empty($xm_result['faultcode'])) {
                     echo('
'.'
' . htmlspecialchars($soapclient->response, ENT_QUOTES) . '
');
                     echo('
'.'
' . htmlspecialchars($soapclient->debug_str, ENT_QUOTES) . '
');
                    $xm_retry  = false;
                    // update status / response date / time
                    $xm_result['xmsg_status'] = "RECEIVED";
                    $xm_result['xmsg_dateresponse'] = date("m/d/y");
                    $xm_result['xmsg_timeresponse'] = date("H:i:s");
                 } else {
                     echo("2 faultcode: ".$xm_result['faultcode']);
                 }
                 // SOAP Call retry handling
                 if ($xm_retry) {
                    // increase the SOAP comm retry counter to count the number of retries made
                    $xm_retrynum++;
                    // check if the maximum number of retries has been reached
                    if ($xm_retrynum <= XMSG_NUMRETRY) {
                       sleep(XMSG_RETRYDELAY); // delay for set number of seconds
                    } else {
                       $xm_retry = false;
                    }
                 }
              } while ($xm_retry);
            break;
        default:
          // no other message type handling currently
        }
    }
}

return $xm_result;
// XMsg *************************************************************************

A: This is quite simple. Your web server can't see the location the WSDL is hosted at. Can you hit the location if you copy the WSDL url and paste it into your browser? You should check that the URL you are using is correct, and whether your web server can even see that location. If not you will need to remedy that before it will work.


text:
Q: How to directly upload a jar file to nexus repository using maven without pom file or settings.xml file? Context : I do not have UI access to Nexus Repository but I have access to Jenkins configured with access to nexus repository. I have a shaded jar in my git repository which needs to be directly uploaded to nexus repository using maven without pom.xml or settings.xml file.
Problem : How to upload a jar in git repo to nexus repository using Jenkins with maven plugin ?
I tried searching for this specific usecase and was not able to find a solution.

A: You can create a Jenkins Job to clone git repository [Source Code Management] where the required jar is present and configure Jenkins Job Build stage with below maven command [Execute Shell] :
mvn deploy:deploy-file \
    -DgroupId=com.example.test \
    -DartifactId=test-module \
    -Dversion=1.0.0 \
    -DgeneratePom=true \
    -Dpackaging=jar \
    -DrepositoryId=sample-rel \
    -Durl=http://nexus.private.net/Your_Nexus_Repository_Path \
    -Dfile=./PATH_TO_JAR_FILE

(edit: multi-line for legibility)

A: The deploy:deploy-file solution above still requires a settings.xml file. The login credentials will be retrieved from the setting.xml "servers" section using the ID specified in the repositoryId parameter.  There isn't any way that I know of to deploy using Maven without a settings.xml file. But you can specify a custom settings.xml file with "mvn -s some/path/settings.xml".
Alternatively, you could use a Jenkins plugin to do the deploy:  https://help.sonatype.com/integrations/nexus-and-continuous-integration/nexus-platform-plugin-for-jenkins#NexusPlatformPluginforJenkins-RepositoryManager3Integration


text:
Q: Position absolute doesn't work correctly in Chrome when is contained in a relative span I have a problem related to Chrome Browser.
My html contains a lot of span tags, some spans have the position: relative css property because it contains a div with position: absolute.The div have to be on the bottom-left of the span.
It works fine, but when the span starts in a new line there is a problem: the div.arrow is positioned in a wrong way (look images and code). (if you prefer: JSFiddle)

.selected {
  position: relative;
  border-bottom: 2px solid red;
  padding-bottom: 2px;
}

.arrow {
  position:absolute;
  left: 0;
  bottom: 0;
  width: 0;
  height: 0;
  border-left: 0 solid transparent;
  border-right: 4px solid transparent;
  border-bottom-width: 4px;
  border-bottom-style: solid;
  border-bottom-color: red;
}
foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar

foobar foobar foobar foobar foobar foobar foobar foobar

To reproduce the issue, you have to resize your window like the attached image:

The expected behaviour should be:

Do you have any ideas to solve this problem? Thanks!

A: Consider a background instead to avoid the issue of position:absolute and you won't need any extra element or pseudo element. Note that div inside span is invalid

.selected {
  padding-bottom: 4px;
  background:
    /* The arrow*/
    linear-gradient(to bottom left,transparent 49.5%,red 50%) bottom 2px left 0/4px 4px,
    /* The line*/
    linear-gradient(red,red) bottom/100% 2px,
    /* Backgroudn color */
    lightblue;
  background-repeat:no-repeat;
}
foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar

A: Just add display: inline-block; to your .selected class.


text:
Q: CRC32 in C# fails I was trying to implement my own CRC32 function in C#. I saw an elegant solution in JS here JavaScript CRC32
So I came up with this:
internal static class Crc32
    {
        internal static long CalculateCrc32(string str)
        {
            long[] crcTable = Crc32.MakeCrcTable();
            long crc = 0 ^ (-1);

            for (int i = 0; i < str.Length; i++)
            {
                char c = str[i];
                crc = (crc >> 8) ^ crcTable[(crc ^ c) & 0xFF];
            }

            return ~crc; //(crc ^ (-1)) >> 0;
        }

        internal static long[] MakeCrcTable()
        {
            long c;
            long[] crcTable = new long[256];
            for (int n = 0; n < 256; n++)
            {
                c = n;
                for (int k = 0; k < 8; k++)
                {
                    var res = c & 1;
                    c = (res == 1) ? (0xEDB88320 ^ (c >> 1)) : (c >> 1);
                }
                crcTable[n] = c;
            }

            return crcTable;
        }
    }

The problem is that my solution does not return the same result. Console.WriteLine(Crc32.CalculateCrc32("l")); results in 1762050814 while the JS function produces 2517025534. The JS result is also the correct one. What am I doing wrong?

A: The problem here is that you are using the wrong datatype. I'm not familiar with the CRC32 algorithm so I googled to find http://sanity-free.org/12/crc32_implementation_in_csharp.html as a reference implementation.
the first thing I noticed is that they are using uint instead of long. This makes sense as I'd assume the 32 in CRC32 means that it would return a 32 bit number. long is a 64 bit signed int.
If you change all the long for uint then we nearly get a working program. The only line that won't work is c=n because it can't implicitly convert an int (n) to a uint (c). However since we know n is always going to be a positive integer we can just change n to be of type uint as well.
This leaves me with:
internal static uint CalculateCrc32(string str)
{
    uint[] crcTable = Crc32.MakeCrcTable();
    uint crc = 0xffffffff;
    for (int i = 0; i < str.Length; i++)
    {
        char c = str[i];
        crc = (crc >> 8) ^ crcTable[(crc ^ c) & 0xFF];
    }

    return ~crc; //(crc ^ (-1)) >> 0;
}

internal static uint[] MakeCrcTable()
{
    uint c;
    uint[] crcTable = new uint[256];
    for (uint n = 0; n < 256; n++)
    {
        c = n;
        for (int k = 0; k < 8; k++)
        {
            var res = c & 1;
            c = (res == 1) ? (0xEDB88320 ^ (c >> 1)) : (c >> 1);
        }
        crcTable[n] = c;
    }

    return crcTable;
}

With this code Console.WriteLine(Crc32.CalculateCrc32("l")); displays 2517025534 as expected.


text:
Q: Working with Permission Attribute I'm probably just getting the concept wrong, but still i thought I should ask:
I'm trying to find the specific permissions needed to create a new local user group in Win2008. I went over the System.DirectoryServices.AccountManagement namespace and declared the permissions needed:
[SecurityPermissionAttribute(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
[DirectoryServicesPermissionAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
[DirectoryServicesPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]

I expected to get an exception when one of these permissions will be denied (i.e. when entering the method). Instead I still get UnauthorizedAccessException when calling the principal Save method.
What am I missing here? I'm looking for an answer more in regards to using the permissions attributes, than a solution to this specific issue.
Thanks.

A: You are referring to security attributes here which are part of the Code access security in .Net.  This will not address your issue.
You are receiving an Unauthorized access exception because the identity of your application (the user account who is running the process and/or currently impersonated) does not have access rights to call the .Save method which is trying to affect the domain.
You need a user account who has been given privileges to modify the active directory in the given domain/forest you are attempting to access in order to make your application work.
I'm sure you can understand that the ability to modify the active directory is considered a privileged operation.


text:
Q: Can I Use TypeScript instead of JavaScript for Minecraft Bedrock Edition modding? When looking at the Minecraft Bedrock Edition scripting API I noticed it uses JavaScript and I was wondering if I could use TypeScript instead. When I looked it up online I didn't really find a straight answer if I could (I know TypeScript is a superset of JavaScript by Microsoft and that Minecraft Bedrock Edition is also by Microsoft but I want to be 100% sure I can use TypeScript before I dive in and learn it) which is why I'm asking here.

A: No, you cannot. JavaScript and TypeScript are fundamentally the same syntax-wise though, and since it's just an API it's pretty much the same. So technically no but keep in mind it's mostly sticking to a.register("e"); a.e(5,2);

A: You can use TypeScript according to this article: https://medium.com/free-code-camp/how-to-mod-minecraft-without-java-f076ddaec01c. There is even a written and video tutorial.


text:
Q: Hyperlink a field by extracting or selecting the leading 2 or 3 digit number from alphanum field resultScreenshot of xls and image folder

I have a folder containing 2 items: INDEX.xlsx and a folder called MAPS with 109 pdf's called Fire_1.pdf thru Fire_109.pdf.
 In the INDEX.xlsx are fields with street name and MAPPAGE (C2). A street can be found on more than one page. Therefore C2 can contain any of the following entries: (The map has 4 quadrants A-D, but that doesn't matter for this purpose)
5A shows the street is found on 5.pdf
27C shows the street is found on 27.pdf
105A shows the street is found on 105.pdf
5A,4B shows most of the street is found on 5.pdf
104B,105A shows most of the street is found on 104.pdf
I'm hoping a formula can find only the first number 1-109 and fetch the pdf from the MAPS folder. *Afterthought- Would they be easier to select if I added hyphens?  5-A, 27-C, 105-A?*
MAPS\Fire_5.pdf
MAPS\Fire_27.pdf
MAPS\Fire_105.pdf
MAPS\Fire_5.pdf
MAPS\Fire_104.pdf

snippets and experiments include:
 This actually chooses the map number correctly
 =LOOKUP(99^99,--
 ("0"&MID(C2,MIN(SEARCH({0,1,2,3,4,5,6,7,8,9},C2&"0123456789")),ROW($1:$10000))))

Then I try to plug it in here in place of the Substitute clause
 =Hyperlink( ".\" & "MAPS" & "\" Substitute(C2," ", "") & ".pdf", C2)

 =HYPERLYNK(".\" & "MAPS" & LOOKUP(99^99,-
("0"&MID(C2,MIN(SEARCH({0,1,2,3,4,5,6,7,8,9},C2&"0123456789")),ROW($1:$10000))))
& ".pdf",C2)

=HYPERLYNK("W:\ArcMap_Projects_0713\FireBook\Maps\" & LOOKUP(1, -
MID(C2,MIN(FIND({0,1,2,3,4,5,6,7,8,9},C2&"0123456789")),ROW(INDIRECT("1:"&LEN(C2
))))) &".pdf")


text:
Q: How to change image folders with mod_rewrite? At my webpage I have links to images like this:
img/123456765/mypicture.jpg (<img src="img/123456765/mypicture.jpg" />)
img/2534/anotherpicture.jpg

where number folder is lastmodified time of image file in seconds e.g. strtotime(filemtime(mypicture.jpg)). They are virtual paths for browser cache refreshing, not real paths.
I'd like apache to automatically change those links to urls like these:
img/mypicture.jpg
img/anotherpicture.jpg

Basically,I'd like to eliminate that number folder in image path.
Mod_rewrite instructions I'm trying to construct look like this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^img/([a-zA-Z0-9-_]+)/\.(jpg|jpeg|gif|bmp|png)$ img/ [L]

I'm new to mod_rewrite so I'm not sure if these instructions are correct. Can anyone correct me if I'm wrong here? I'd appreciate it! Thanks!

A: You're on the right track, but you want something like this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^img/[a-zA-Z0-9-_]+/(.*\.(jpg|jpeg|gif|bmp|png))$ img/$1 [L]

The regex ^img/[a-zA-Z0-9-_]+/(.*\.(jpg|jpeg|gif|bmp|png))$ has a backreference ($1) to the match .*\.(jpg|jpeg|gif|bmp|png), essentially anything after the string of numbers and letters after the "img/". This will rewrite:
img/123456765/mypicture.jpg to img/mypicture.jpg
img/2534/anotherpicture.jpg to img/anotherpicture.jpg


text:
Q: Euler-summability of a convergent sequence and its limit In the book Finite Markov Chains by John G.Kemeny and J.Laurie Snell, the authors introduce the following concept of Euler-summability of a sequence:

Having a sequence $(s_n)_{n \geq 0},$ we introduce its sequence of averages $(u_n)_{n \geq 0},$ where for each $n \geq 0,$ $u_n = \sum \limits_{i=0}^n {n \choose i} k^{n-i} (1-k)^i s_i$ for some number $k$ such that $0 < k < 1.$ If the sequence $(u_n)_{n \geq 0}$ converges to a limit $u,$ then we say that sequence $(s_n)_{n \geq 0}$ is Euler-summable to $u$*.

Then the authors mention, that if the sequence $(s_n)_{n \geq 0}$ converges to a limit $s$, then it's also Euler-summable to $s,$ i.e. its sequence of averages $(u_n)_{n \geq 0}$ converges to $s$ as well.
I was trying to prove it using the $\varepsilon$-approach, similar to the one used in Convergence of series implies convergence of Cesaro Mean, but I failed. If someone could give me any hint on how to do it or simply proved it, I would much appreciate it.


text:
Q: Let $A,B,C$ be sets such that $\mathcal{P}(A) \cup \mathcal{P}(B) = \mathcal{P}(C)$. Then either $A=C$ or $B=C$. Let $A,B,C$ be sets such that $\mathcal{P}(A) \cup \mathcal{P}(B) = \mathcal{P}(C)$. Then either $A=C$ or $B=C$.
I just need a little direction with this. I know that since $\mathcal{P}(A) \cup \mathcal{P}(B)$, then $(x\in \mathcal{P}(A)) \lor (x\in \mathcal{P}(B))$ and also $[\mathcal{P}(A) \cup \mathcal{P}(B) = \mathcal{P}(C)] \Rightarrow [(\mathcal{P}(A) \cup \mathcal{P}(B))\subseteq \mathcal{P}(C)] \land[\mathcal{P}(C)\subseteq (\mathcal{P}(A) \cup \mathcal{P}(B))]$,
but I honestly have no idea what to do with this information. Should I break the union down into truth statements like so: $\mathcal{P}(A) \cup \mathcal{P}(B)\Rightarrow (x\in \mathcal{P}(A)) \lor (x\in \mathcal{P}(B))$?
Any direction would be greatly appreciated!


text:
Q: Number of solutions of $x_1 + 2x_2 + 3x_3 + \cdots + n x_n = p$
Given a non-negative integer $p$. What is the number of solutions of $x_1+2x_2+3x_3 + \cdots + nx_n = p$, where the $x_i$'s are non-negative integers.

Can we answer this by using number of solutions of $x_1+x_2+x_3 + \cdots + x_m = q$ for any $m,q$?

A: The number of nonnegative integer solutions of $x_1 + 2 x_2 + \cdots + n x_n = p$, where $p \geq 0$, is the coefficient of $t^p$ in the following generating function [JDL]
$$\prod_{k=1}^n \frac{1}{1-t^k} = \frac{1}{(1-t) (1-t^2) \cdots (1-t^n)}$$

[JDL] Jesús A. De Loera, The Many Aspects of Counting Lattice Points in Polytopes.

A: The number of solutions of $x_1+2x_2+ \cdots +nx_n=p$ is given by the coefficient of $x^{p}$ in
\begin{eqnarray*}
\frac{1}{(1-x)(1-x^2) \cdots (1-x^n) }
\end{eqnarray*}
The number of solutions of $x_1+x_2+ \cdots +x_m=q$ is given by the coefficient of $x^{q}$ in
\begin{eqnarray*}
\frac{1}{(1-x)^m }
\end{eqnarray*}
So the answer to your question is no.


text:
Q: Can't boot from NVME SSD after data migration I used the Data Migration tool by Samsung to clone the content (Windows boot drive) of a Samsung SSD 850 Pro to a Samsung SSD 950 Pro. But I can't boot from it now.
Motherboard: GA-Z170X-Gaming-7 with F8 Bios version
Windows 10 Pro (1803)
Bios mode is UEFI
Drive partition is GPT
If I select the 950 Pro as boot device I get the following message

Reboot and Select proper Boot device
  or Insert Boot Media in selected Boot device and press a key

If I look into Diskmgmt.msc the drive is offline with the following message:

This disk is offline, because it has a signature collision with another disk that is online.

I tried to unplug the old drive (850 Pro), but I still can't boot from the new SSD. Installing the Samsung NVME driver also didn't changed something. The device is still using the Intel driver. Samsung Magician can't correctly detect the device (sure, it's offline). I can set it to online mode to access the data, but I can't boot correctly from it.
It seems the boot sector is faulty. Do I have to reinstall Windows completely or can I get the cloned drive to work?

A: Now I fixed it myself. I believe the main reason was that after the clone process the PC booted with two bootable disks, which had the same id in the GPT (through the clone tool). These were the steps I did to get it running:

*

*delete partition of the new drive with diskpart

*clone the drive

*shutdown of the pc and unplug of the old drive

*reboot and have fun

Here are the commands for diskpart:

*

*enter diskpart in a new command line (cmd)

*list disk

*select disk x

*list partition

*select partition x

*delete partition
I think you could also set a new unique id with diskpart instead of the above (or afterwards). Here are the commands again:

*

*enter diskpart in a new command line (cmd)

*list disk

*select disk x

*uniqueid disk to see the current id

*set a new id with uniqueid disk ID=xxx (take old one and modify it a bit)


text:
Q: How can I extend Node's stream I'm trying to create a method for Readable Stream, but after trying just a little bit, I ran out of ideas to how.
import * as stream from 'stream'
//yields Property 'asdasas' does not exists on type 'Readable'
stream.Readable.prototype.asdasas
//yields asdas does not exists on type 'typeof Readable'
stream.Readable.asdas

Can someone give me a solution and explain why the errors happened? Thanks

A:
explain why the errors happened

The first rule of migrating from JavaScript to TypeScript:
Declare what you use.
https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html
Here Readable doesn't have the member you are looking for. If you want to add it, you need to declare it. Something like :
interface Readable {
  asdfasdfasdf: any;
}

A: I managed to extend them. The behaviour wasn't as unusual as I thought (I still would appreciate an explanation on the difference of "type 'Readable'" and "type 'typeof Readable'". The code:
import * as stream from 'stream'

class mod_Readable extends stream.Readable {
    pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T {
        //whatever
        return super.pipe(destination, options)
    }
}


text:
Q: Explanation of the calc_delta_mine function I am currently reading "Linux Kernel Development" by Robert Love, and I got a few questions about the CFS.
My question is how  calc_delta_mine calculates :
delta_exec_weighted= (delta_exec * weight)/lw->weight
I guess it is done by two steps :

*

*calculation the (delta_exec * 1024)  :
 if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
 tmp = (u64)delta_exec * scale_load_down(weight);
   else
 tmp = (u64)delta_exec;

*calculate the /lw->weight ( or * lw->inv_weight ) :
  if (!lw->inv_weight) {
  unsigned long w = scale_load_down(lw->weight);
  if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
            lw->inv_weight = 1;
    else if (unlikely(!w))
            lw->inv_weight = WMULT_CONST;
    else
            lw->inv_weight = WMULT_CONST / w;
 }

 /*
  * Check whether we'd overflow the 64-bit multiplication:
  */
 if (unlikely(tmp > WMULT_CONST))
         tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
                 WMULT_SHIFT/2);
 else
         tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);

 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);

The SRR (Shift right and round) macro is defined via :
    #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))

And  the other MACROS are defined :
    #if BITS_PER_LONG == 32
    # define WMULT_CONST    (~0UL)
    #else
    # define WMULT_CONST    (1UL << 32)
    #endif
    #define WMULT_SHIFT     32

Can someone please explain how exactly the SRR works and how does this check the 64-bit multiplication overflow?
And please explain the definition of the MACROS in this function((~0UL) ,(1UL << 32))?

A: The code you posted is basically doing calculations using 32.32 fixed-point arithmetic, where a single 64-bit quantity holds the integer part of the number in the high 32 bits, and the decimal part of the number in the low 32 bits (so, for example, 1.5 is 0x0000000180000000 in this system). WMULT_CONST is thus an approximation of 1.0 (using a value that can fit in a long for platform efficiency considerations), and so dividing WMULT_CONST by w computes 1/w as a 32.32 value.
Note that multiplying two 32.32 values together as integers produces a result that is 232 times too large; thus, WMULT_SHIFT (=32) is the right shift value needed to normalize the result of multiplying two 32.32 values together back down to 32.32.
The necessity of using this improved precision for scheduling purposes is explained in a comment in sched/sched.h:
/*
 * Increase resolution of nice-level calculations for 64-bit architectures.
 * The extra resolution improves shares distribution and load balancing of
 * low-weight task groups (eg. nice +19 on an autogroup), deeper taskgroup
 * hierarchies, especially on larger systems. This is not a user-visible change
 * and does not change the user-interface for setting shares/weights.
 *
 * We increase resolution only if we have enough bits to allow this increased
 * resolution (i.e. BITS_PER_LONG > 32). The costs for increasing resolution
 * when BITS_PER_LONG <= 32 are pretty high and the returns do not justify the
 * increased costs.
 */

As for SRR, mathematically, it computes the rounded result of x / 2y.
To round the result of a division x/q you can calculate x + q/2 floor-divided by q; this is what SRR does by calculating x + 2y-1 floor-divided by 2y.


text:
Q: I can't assign from pointer to pointer to derived class and pointer to pointer to base class?
Possible Duplicate:
Conversion between Derived** to Base**

I'm getting back into C++ after several years of mostly Python, and am hitting up against a strongly-typed wall. I think I have a good handle on basic polymorphism and type-casting between pointers of base and derived classes (e.g. Can a pointer of a derived class be type cast to the pointer of its base class?), but here's a stumper: why can't I assign a pointer to a pointer to a derived class to a p-to-p to it's base class?
For more context (and perhaps tips on doing this less pythonishly), here's a reduced version of what I'm trying to do. I want to have a list of pointers to objects (derived from a single class) and a string identifying them (i.e. a map<string, obj*>). A set of components will then pass a list of identifying strings and locations to store a pointer to the corresponding object (i.e. a map<string, obj**>). I should then be able to find the appropriate object by its string id, and fill in the appropriate pointer for subsequent use by the component.
Simplified code to do this is
#include <map>
#include <string>
using namespace std;

class base
{
};

class derived: public base
{

};

typedef map<string, base**> BasePtrDict;
typedef map<string, base*> BaseDict;

int main(int argc, char* argv[])
{
    base b1, b2;
    derived d;
    derived* d_ptr;

    BaseDict base_dict;
    base_dict["b1"] = &b1;
    base_dict.insert(make_pair("b2",&b2)); // alternate syntax
    base_dict["d"]= &d;

    BasePtrDict ptr_dict;
    ptr_dict["d"] = &d_ptr;

    for (auto b = ptr_dict.begin(); b != ptr_dict.end(); b++)
        *(b->second) = base_dict[b->first];

    return 0;
}

This runs into a compile error at ptr_dict["d"] = &d_ptr;. Why? In the C++ paradigm, what should I be doing? Do I really need to do ugly (unsafe?) reinterpret_cast<base>() everywhere?

A: You're losing the necessary information to be able to cast a base * to a derived *.
Consider the case where derived inherits from multiple base classes, so a cast needs to adjust the pointer value.  Then derived *pd = static_cast<derived *>(pb) for a pointer-to-base pb will automatically apply the pointer adjustment.
However derived *pd; base **ppb = &pd; *ppb = *pb will fail to apply the pointer adjustment, so this cannot be legal.
What you should be doing is:
base *b_ptr;
... // existing code
derived *d_ptr = static_cast<derived *>(b_ptr);

A: Consider what would be enabled if it were permitted to treat a derived** as a base**:
class base
{
};

class derived: public base
{
public:
    int boom;
}

void light_the_fuse( base** pb)
{
    *pb = new base;
}

int main()
{
    derived* pd = NULL;

    light_the_fuse( &pd);

    pd->boom = 42;  // uh oh, `pd` points to a `class base`...

    return 0;
}

A: In order to do a child-to-base conversion the types need to be related. For derived** to base** this implies that derived* is a child of base* which is clearly not true as they're orthogonal pointer types (that happen to point to related classes).
You should be able to solve this with a static_cast rather than reinterpret_cast though:
ptr_dict["d"] = &static_cast<base*&>(d_ptr);

A: The direct cast derived* to base* is ok, but that's not what you're attempting. You're attempting to do derived** to base**, which isn't an implicit cast. That aside, may I ask why? I'd even go ahead and ask whether you actually need pointers, but double pointers?

A: It will be much simpler to replace
derived* d_ptr;

with
base* d_ptr;

and use a cast anytime when you may need to apply the exact type of d_ptr but of course the principles of object orientation say that such a case should be quite rare.

A: This is almost similar to Why do I need a reinterpret_cast to convert Fred ** const to void ** const?
Pointer to two different object types are basically incompatible. But, there are exceptions

*

*Derived* to Base*... Derived and Base are related and therefore, conversion is allowed (after typecasting to Base*, the pointer would actually be pointing to an object of Base type

*T* to void* - allowed (see the link above)

but there is no reason why D** should be allowed to be converted to B**, because B* and D* are essentially different types.

A: You cannot and should not assign a Derived** to a Base** because it is unsafe.  If the cast was permitted, then it would allow Derived* to point to types that are not Dervied types.  Consider the following:
class Base {};
class Derived: public Base {};
class Other: public Base {};

...

Derived derived;
Derived* derived_p   = &derived;   // derived_p points to derived.
Derived** derived_pp = &derived_p; // derived_p points to derived.
                                   // derived_pp points to derived_p.
Base** base_pp = derived_pp;       // derived_p points to derived.
                                   // base_pp points to derived_p.

Other other;
Other* other_p = &other;           // other_p points to other.

*bpp = op;                         // base_pp points to derived_p.
                                   // derived_p points to other.

If the above code was valid, it would allow Derived* derived = new Other().
Unfortunately, I am not exactly sure what is trying to be accomplished, so I cannot provide an alternative solution.


text:
Q: apache does not pass request to Django (404 not found) I have a custom 404 page setup for the site, which works fine, like this:
when I hit mysite.com/fdsafsadfdsa which doesn't exist, the custom 404 page shows up.
However if I add a urlencoded '/' which is '%2f' at the end of url, mysite.com/fdsafsadfdsa%2f, and this gives me the apache 404 not found.
it looks like apache decided to handle this 404 itself instead of passing down to Django
Anybody has idea why this is happening?

A: Turns out it's a issue in Apache/Nginx. And somebody submit this issue to Django project before, see here: https://code.djangoproject.com/ticket/15718
and quote from the ticket, there's a workaround:

After investigation I've found that the 2nd issue (404 error directly from apache) is not related to django and can be avoided by adding "AllowEncodedSlashes On" into apache config. Unfortunately apache replaces %2f with / itself, so the behavior is exactly the same as in simple http server provided by django. In Apache 2.2.18 (which is not released yet, i guess), AllowEncodedSlashes allows value NoDecode. With the value NoDecode, such URLs are accepted, but encoded slashes are not decoded but left in their encoded state. Meanwhile I'm using the workaround

request_uri = force_unicode(environ.get('REQUEST_URI', u'/'))
    if u'?' in request_uri:
        path_info,query = request_uri.split('?',1)
    else:
        path_info,query = request_uri,''

instead of original
path_info = force_unicode(environ.get('PATH_INFO', u'/'))

in core/handlers/wsgi.py


text:
Q: How to check spring boot post API if it is available in the database **Controller**
package com.example.curd.curdtesting.controller;

import com.example.curd.curdtesting.entity.Book;
import com.example.curd.curdtesting.service.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class Controller {
    @Autowired
    BookServiceImpl bookService;

    @PostMapping("/addProducts")
    public List<Book> addProducts(@RequestBody List<Book> book) {
        return bookService.insertBook(book);
    }
}

**Entity class**
package com.example.curd.curdtesting.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table
public class Book {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    private String description;

}

**Service class**

package com.example.curd.curdtesting.service;

import com.example.curd.curdtesting.entity.Book;
import com.example.curd.curdtesting.repository.BookRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookServiceImpl {
    @Autowired
    BookRepo bookRepo;

     public List<Book> insertBook(List<Book> book) {

       return bookRepo.saveAll(book);
    }
}

**Repository**

package com.example.curd.curdtesting.repository;
import com.example.curd.curdtesting.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface BookRepo extends JpaRepository<Book, Integer> {
    public List<Book> findBookByName(String name);
}

Once the item is received from user in json format. I want to check if the book with same name is already in my database if so, i want to output duplicate no possible. As I receive book object from json but how to check in service layer if the book with the name is present in database. Can anyone please help me as I am new to spring boot.

A: Your service layer is the place to set your business rules and you can do as follow :

*

*Create a custom exception to handle your logic, for example : RecordExistsException

*Create a RestControllerAdvice to handle your exception. In this class, you can return the message thrown by your exception.

*Check if your record exists and throw a RecordExistsException when your
findBookByName(String name) returns an already existing book.

The service class will look something like this:
@Service
public class BookServiceImpl {
    @Autowired
    BookRepo bookRepo;

     public List<Book> insertBook(Book book) {
       if(!bookRepo.findByName(book.getName()).isEmpty()) {
           throw new RecordExistsException("The book " + book.getName() + " already exists !!!")
       }
       return bookRepo.saveAll(book);
    }
}


text:
Q: How to get multiple specific values from a key in a JSON Object So right now I am trying to get information from the logged in user through Facebook graph api.
{"id":"10202628284866677","name":"Rohit Tigga","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/10202628284866677\/","picture":{"data":{"is_silhouette":false,"url":"https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-xta1\/v\/t1.0-1\/p200x200\/10438582_10202555461926149_8285465463541146116_n.jpg?oh=283ec503c6eb051aad077366155c621d&oe=55E6E24B&__gda__=1445616180_3110e5bf89e9f3050fe623b86d47618b"}},"friends":{"data":[{"name":"Arthur Shir","id":"10153237510764181"},{"name":"Kanye East","id":"1454465268197338"}],"paging":{"next":"https:\/\/graph.facebook.com\/v2.3\/10202628284866677\/friends?access_token=CAAWKvUHZCc2sBAHDCZCfL1dHLcrrMoqNxHJSXun5vm1iJQlMxaF43ZCTvIj4Oo4sHeRstTEACDpDz45wLj9FwXBXkoqxPyBQvjcQKY4ZCPgEqhcPdyPb3JepOA1KCADTt2ZBIO8NRX8QKdrlvSWxxgEfSH6SY94nUsLZBRslP8OjJ9r9DYm6kih8GwJ7la0w30KbZAi3AFNOUx1FDU9Y38S&limit=25&offset=25&__after_id=enc_AdB7OPjfCizP7TWz68NToMvADpaegj9bV3w8g22S1dgcGTiHSRUC2xQr2uhJDdQczRtmkKPQS9fzh0Fq7LgWLZAsu"},"summary":{"total_count":1289}}}

I was able to get the id, name, profile_pic_url
GraphRequest request = GraphRequest.newMeRequest(
                                loginResult.getAccessToken(),
                                new GraphRequest.GraphJSONObjectCallback() {
                                    @Override
                                    public void onCompleted(
                                            JSONObject object,
                                            GraphResponse response) {
                                        // Application code
                                        response.getError();
                                        //Here's what you got
                                        Log.e("JSON:", object.toString());

                                        //Find out how to store all user friends efficiently

                                        try {
                                            user_id=object.getString("id");
                                            name=object.getString("name");
                                            profile=object.getString("link");
                                            profile_pic_url = object.getString("picture");
                                            friends = object.getString("friends");

                                            JSONObject pic_object1= (JSONObject) new JSONTokener(profile_pic_url).nextValue();
                                            JSONObject pic_object2 = pic_object1.getJSONObject("data");
                                            profile_pic_url = (String) pic_object2.get("url");

I am more specifically trying to get the ID of each facebook friend from the logged in user. It is from this portion which I have as a string now.
 {"data":[{"name":"Arthur Shir","id":"10153237510764181"},{"name":"Kanye East","id":"1454465268197338"}],"paging":{"next":"https:\/\/graph.facebook.com\/v2.3\/10202628284866677\/friends?access_token=CAAWKvUHZCc2sBAHDCZCfL1dHLcrrMoqNxHJSXun5vm1iJQlMxaF43ZCTvIj4Oo4sHeRstTEACDpDz45wLj9FwXBXkoqxPyBQvjcQKY4ZCPgEqhcPdyPb3JepOA1KCADTt2ZBIO8NRX8QKdrlvSWxxgEfSH6SY94nUsLZBRslP8OjJ9r9DYm6kih8GwJ7la0w30KbZAi3AFNOUx1FDU9Y38S&limit=25&offset=25&__after_id=enc_AdB7OPjfCizP7TWz68NToMvADpaegj9bV3w8g22S1dgcGTiHSRUC2xQr2uhJDdQczRtmkKPQS9fzh0Fq7LgWLZAsu"},"summary":{"total_count":1289}}

I am trying to iterate through the JSON Object and store every id in an array.
But I have been unsuccessful in my attempts.
I am looking at this, yet no luck :/
How to iterate over a JSONObject?
How can I iterate JSONObject to get individual items
How should I go about doing this?

A: Your goal is to retrieve the ids from the following json string:
{"data":[{"name":"Arthur Shir","id":"10153237510764181"},{"name":"Kanye East","id":"1454465268197338"}],"paging":{"next":"https:\/\/graph.facebook.com\/v2.3\/10202628284866677\/friends?access_token=CAAWKvUHZCc2sBAHDCZCfL1dHLcrrMoqNxHJSXun5vm1iJQlMxaF43ZCTvIj4Oo4sHeRstTEACDpDz45wLj9FwXBXkoqxPyBQvjcQKY4ZCPgEqhcPdyPb3JepOA1KCADTt2ZBIO8NRX8QKdrlvSWxxgEfSH6SY94nUsLZBRslP8OjJ9r9DYm6kih8GwJ7la0w30KbZAi3AFNOUx1FDU9Y38S&limit=25&offset=25&__after_id=enc_AdB7OPjfCizP7TWz68NToMvADpaegj9bV3w8g22S1dgcGTiHSRUC2xQr2uhJDdQczRtmkKPQS9fzh0Fq7LgWLZAsu"},"summary":{"total_count":1289}}

In that case, you can try the following code:
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray friends = jsonObject.getJSONArray("data");
for (int index=0; index<friends.length(); ++index){
        JSONObject currentFriend = friends.getJSONObject(index);
        String id = currentFriend.getString("id");
}

A: You should be able to grab the JSONArray "data" from the JSON like this
JSONArray array = object.getJSONArray("data");

for(int i = 0; i < array.length; i++) {
    JSONObject object = (JSONObject) array.get(i);

    String id = object.get("id");
    //and so on
}


text:
Q: How to add a image button for cancel in form MVC I try to add a cancel button in MVC form besides submit button which is also image button. The code is :
<input type="image" src="../../Images/SUBMIT_bttn1.gif" alt="Submit" />
<a href='<%= Html.ActionLink("EditPage", "Home")%>'>

But it gives Error :
Server Error in '/' Application. HTTP Error 400 - Bad Request

What is the problem? Thanks.

A: This is because HTML.ActionLink will create the  tag. You need Url.Action which just create a link the following should work.
<a href='<%= Url.Action("EditPage", "Home")%>'>


text:
Q: Is it possible to use Integrated Windows Auth when Server isn't on the domain? Our production web servers ARE NOT part of the domain, but we'd like people to be able to log in automatically since they are logged into the domain on their PC.
Is there anyway to get the browser (IE7+) to send the appropriate information to the server (IIS6) so I can retrieve the ServerVariables["AUTH_USER"] or ServerVariables["LOGON_USER"]?
I presume the answer is no since if I set the security for windows auth to "on" and anonymous access to "off", then the server wouldn't know what do do with any user information for a domain which it has no knowledge of.  I just want to know for sure before I give the SSO team a "not possible" answer.

A: I have implemented IWA for one of my projects and I am afraid the answer is NO, you can't use it when the server is in other domain.
IIS won't be able to communicate to the server through IWA in this case.


text:
Q: How to change CVPixelBuffer data format I convert UIImage to CVPixelBuffer for the CoreML, but I want change the RGB pixel, like R/1.5, G/2, B/2.5.
I can read the pixel data by using assumingMemoryBound(to : UInt8.self),but
how can I modify the pixel data in CVPixelBuffer?

A: Why do you want to do this in the CVPixelBuffer? Core ML can automatically do this for you as part of the model.
When you convert your model to Core ML you can specify an image_scale preprocessing option.
In your case it looks like you want different scales for each color channel, which you can do by adding a scaling layer to the model. See the following Jupyter notebook for an example: https://github.com/apple/coremltools/blob/master/examples/Image_preprocessing_per_channel_scale.ipynb


text:
Q: sending form data to text file in PHP on live server gives a permission denied error I'm creating a simple registration form in PHP. When I send form data to text file in PHP on local server it's working well but on live server its giving me a permission denied.
This is my register.php
<?php
$name = $_POST['Name'];
$email = $_POST['Email'];
$phone = $_POST['Place'];
$msg = $_POST['Message'];

$fp = fopen("formdata.txt", "a");
$savestring ="First Name= " .$name. " Email id=" .$email. " Phone Number= ".$phone." Message= ".$msg.'/n';
fwrite($fp, $savestring);
fclose($fp);?>

This is my form :

<form action="register.php" method="post">
  <input type="text" Name="Name" placeholder="NAME" required="">
  <input type="email" Name="Email" placeholder="EMAIL" required="">
  <input type="text" Name="Phone Number" placeholder="PHONE NUMBER" required="">
  <input type="text" Name="Place" placeholder="PLACE" required="">
  <textarea name="Message" placeholder="PROJECT DETAILS" required=""></textarea>

  <button type="submit">SEND MESSAGE</button>

</form>

This is working on local server but error is showing on live:
Warning: fopen(formdata.txt) [function.fopen]: failed to open stream: Permission denied in D:\INETPUB\VHOSTS\something.com\register.php on line 7

Warning: fwrite(): supplied argument is not a valid stream resource in D:\INETPUB\VHOSTS\something.com\register.php on line 9

Warning: fclose(): supplied argument is not a valid stream resource in D:\INETPUB\VHOSTS\something.com\register.php on line 10

A: Assuming the PHP user is called www-data, you have to give www-data writing permissions for the file formdata.txt. One way to achieve this is to set the owner to www-data via chown www-data fordata.txt and change the permissions for the file to 644 (write permissions for owner, reading permission for everyone else) with chmod 644 formdata.txt.
Then your script should work just fine.


text:
Q: How to generate lighter/darker color with PHP? I have a hex value of some color, for example #202010.
How to generate a new color which is either lighter or darker given in percent  (ie. 20% darker) in PHP?

A: Torkil Johnsen's answer is based on fixed step which doesn't manipulate only brightness but also slightly changes the hue. Frxstrem's method has flaws too as Torkil Johnsen noted.
I've taken this approach from a Github comment and improved the code. It works perfectly for any case.
/**
 * Increases or decreases the brightness of a color by a percentage of the current brightness.
 *
 * @param   string  $hexCode        Supported formats: `#FFF`, `#FFFFFF`, `FFF`, `FFFFFF`
 * @param   float   $adjustPercent  A number between -1 and 1. E.g. 0.3 = 30% lighter; -0.4 = 40% darker.
 *
 * @return  string
 *
 * @author  maliayas
 */
function adjustBrightness($hexCode, $adjustPercent) {
    $hexCode = ltrim($hexCode, '#');

    if (strlen($hexCode) == 3) {
        $hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
    }

    $hexCode = array_map('hexdec', str_split($hexCode, 2));

    foreach ($hexCode as & $color) {
        $adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
        $adjustAmount = ceil($adjustableLimit * $adjustPercent);

        $color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
    }

    return '#' . implode($hexCode);
}

Here is an example result:

A: I was interested in this, but my question was how do I add a opacity to a colour?
I wanted a colour to fade, not made lighter.  i found this:
http://www.gidnetwork.com/b-135.html
and it worked great- code posted from original site for SO readers.
function color_blend_by_opacity( $foreground, $opacity, $background=null )
{
    static $colors_rgb=array(); // stores colour values already passed through the hexdec() functions below.
    $foreground = str_replace('#','',$foreground);
    if( is_null($background) )
        $background = 'FFFFFF'; // default background.

    $pattern = '~^[a-f0-9]{6,6}$~i'; // accept only valid hexadecimal colour values.
    if( !@preg_match($pattern, $foreground)  or  !@preg_match($pattern, $background) )
    {
        trigger_error( "Invalid hexadecimal colour value(s) found", E_USER_WARNING );
        return false;
    }

    $opacity = intval( $opacity ); // validate opacity data/number.
    if( $opacity>100  || $opacity<0 )
    {
        trigger_error( "Opacity percentage error, valid numbers are between 0 - 100", E_USER_WARNING );
        return false;
    }

    if( $opacity==100 )    // $transparency == 0
        return strtoupper( $foreground );
    if( $opacity==0 )    // $transparency == 100
        return strtoupper( $background );
    // calculate $transparency value.
    $transparency = 100-$opacity;

    if( !isset($colors_rgb[$foreground]) )
    { // do this only ONCE per script, for each unique colour.
        $f = array(  'r'=>hexdec($foreground[0].$foreground[1]),
                     'g'=>hexdec($foreground[2].$foreground[3]),
                     'b'=>hexdec($foreground[4].$foreground[5])    );
        $colors_rgb[$foreground] = $f;
    }
    else
    { // if this function is used 100 times in a script, this block is run 99 times.  Efficient.
        $f = $colors_rgb[$foreground];
    }

    if( !isset($colors_rgb[$background]) )
    { // do this only ONCE per script, for each unique colour.
        $b = array(  'r'=>hexdec($background[0].$background[1]),
                     'g'=>hexdec($background[2].$background[3]),
                     'b'=>hexdec($background[4].$background[5])    );
        $colors_rgb[$background] = $b;
    }
    else
    { // if this FUNCTION is used 100 times in a SCRIPT, this block will run 99 times.  Efficient.
        $b = $colors_rgb[$background];
    }

    $add = array(    'r'=>( $b['r']-$f['r'] ) / 100,
                     'g'=>( $b['g']-$f['g'] ) / 100,
                     'b'=>( $b['b']-$f['b'] ) / 100    );

    $f['r'] += intval( $add['r'] * $transparency );
    $f['g'] += intval( $add['g'] * $transparency );
    $f['b'] += intval( $add['b'] * $transparency );

    return sprintf( '%02X%02X%02X', $f['r'], $f['g'], $f['b'] );
}

A: If you want a simple implementation and you don't care that much about the values being specifically above 50% lightness (or whatever your threshold), you can use my solution for lighter colors:
$color = sprintf('#%06X', mt_rand(0xFFFFFF / 1.5, 0xFFFFFF));

The idea is to generate a random color in the higher part of the palette. You can adjust the results to be more or less dark by changing the "1.5" value:

*

*larger will expand the palette into darker colors

*smaller will curb it to lighter colors

You can do the same for darker colors by setting the starting point of the random function to "0x000000" and dividing the end limit:
$color = sprintf('#%06X', mt_rand(0x000000, 0xFFFFFF / 1.5));

I know this is not a precise but it works for me.

A: The answers are wrong.
Using RGB model is a conceptual error.
You need to transform the color from RGB (or Hex form) into HSL.
That is Hue, Saturation, Lightness.
Once you convert it from RGB into HSL, to lighten up the color you simply adjust the L value (lightness) by 10%. Then once you are done you convert back from HSL to RGB and you are done.
Voila!
RGB to HSV in PHP

A: Here's an example:
<?php
$color = '#aabbcc'; // The color we'll use

Extract the colors. I'd prefer to use regular expressions, though there are probably other more efficient ways too.
if(!preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i', $color, $parts))
  die("Not a value color");

Now we have red in $parts[1], green in $parts[2] and blue in $parts[3]. Now, let's convert them from hexadecimal to integers:
$out = ""; // Prepare to fill with the results
for($i = 1; $i <= 3; $i++) {
  $parts[$i] = hexdec($parts[$i]);

Then we'll decrease them by 20 %:
  $parts[$i] = round($parts[$i] * 80/100); // 80/100 = 80%, i.e. 20% darker
  // Increase or decrease it to fit your needs

Now, we'll turn them back into hexadecimal and add them to our output string
  $out .= str_pad(dechex($parts[$i]), 2, '0', STR_PAD_LEFT);
}

Then just add a "#" to the beginning of the string, and that's it!

A: https://github.com/mikeemoo/ColorJizz-PHP allows to convert to HSL, change lightness component and convert back to RGB.

A: Adjusting colour by percent, as in the example given by Frxstrem, is not ideal.
If your colour is black (0,0,0 in RGB), you will be multiplying by zero, which will not yield any change at all. If your colour is dark gray (for instance 2,2,2 in RGB), you will have to lighten by 50% to just move up to (3,3,3). On the other hand, if you have an RGB colour of (100,100,100), the adjustment of 50% will move you up to (150,150,150), which is a much bigger change in comparison.
A much better solution would be to adjust by step/number (0-255) instead of by percent, for instance like this (PHP code):
Edit 2014-01-06: Cleaned up the code a bit.
function adjustBrightness($hex, $steps) {
    // Steps should be between -255 and 255. Negative = darker, positive = lighter
    $steps = max(-255, min(255, $steps));

    // Normalize into a six character long hex string
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
    }

    // Split into three parts: R, G and B
    $color_parts = str_split($hex, 2);
    $return = '#';

    foreach ($color_parts as $color) {
        $color   = hexdec($color); // Convert to decimal
        $color   = max(0,min(255,$color + $steps)); // Adjust color
        $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
    }

    return $return;
}