text:
Q: Oracle ManagedDataAccess via Nuget - The provider did not return a ProviderManifestToken string I got a fresh machine, with just Visual Studio 2015 and the latest .Net Framework, cloned a repository that accesses a remote Oracle 11g Database using  Entity and Oracle.ManagedDataAccess from Nuget, this project does work in other machines,
I tested the remote connection using SqlDeveloper, and verified the port access with telnet and even created a simple and local Oracle Database to exclude any network related error
To confirm the error i created a simple Console Project following a Oracle Article and still got the same error
Exception : The provider did not return a ProviderManifestToken string.
InnerException :     ORA-01017: invalid username/password; logon denied
I do not have any Oracle Client installed, and as far as i can tell i do not need any because i am using Nuget
And yes, i am extremelly sure of the user and password, as said above, the connection works when using SqlDeveloper
Oracle ManagedDataAccess Nuget
Oracle Article
Full StackTrace
"data source=OracleDS;user id=PUBLICO;password=PUBLICO;min pool size=1;max pool size=1;Incr Pool Size=1 ----- System.Data.Entity.Core.ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> Oracle.ManagedDataAccess.Client.OracleException: ORA-01017: invalid username/password; logon denied
   em OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, CriteriaCtx criteriaCtx, String affinityInstanceName, Boolean bForceMatch)
   em OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, CriteriaCtx criteriaCtx, String affinityInstanceName, Boolean bForceMatch)
   em OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword, CriteriaCtx criteriaCtx)
   em Oracle.ManagedDataAccess.Client.OracleConnection.Open()
   em Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices.GetDbProviderManifestToken(DbConnection connection)
   em System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
   em System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
   em System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   em System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
   em System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   em System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   em System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   em System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   em System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   em System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   em System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   em System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   em System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
   em BemaHybrid.Library.EntityFramework.DbContextExtended.AdquireUsuarioSenhaBaseadoUsuarioPublico() na D:\\Projetos\\hybrid.cliente\\BemaHybrid.Library.EntityFramework\\DbContextExtended.cs:linha 42"

UPDATE
Found this question that nailed the answer, a windows Registry settings that encrypted the password, in this question you can find the way to disabled on the registry or in the application config if you need
Solution


text:
Q: Trouble Understanding How to Pass a String in C++ Could somebody possibly breakdown the proper way to pass a string to a function, have that function put it into a vector and another function print contents of the vector? I'm sure there are tons of duplicates and I have looked at them all(mostly) and still have not been able to apply any of it to this problem, or at least it seems that way to me.
#include <cstdio>
#include <string>
#include <vector>

using namespace std;

static vector<string> added_messages;
static void addMessage(string message);
static void displayMessages();

int main()
{
    string message = "Testing 1 2 3";
    addMessage(message);
    //printf("%s\n", message);
    return 0;
}

void addMessage(string s)
{
    added_messages.push_back(s);
    //printf("%s\n", s);
}

void displayMessages()
{
    if (added_messages.size() != 0) {
        for (string i : added_messages)
            printf("%s\n", i);
    }
    added_messages.clear();
}

It mostly prints out garbage:4÷/4⌠/
I'm fairly new to C++ and coming from Java, I just can't figure this out. Thanks.

A: Get in the habit of declaring string parameters as const reference.
Instead of this:
void addMessage(string s)
{
    ...
}

This:
void addMessage(const string& s)
{
    ...
}

Not only does this avoid making a copy of the string, it also lets you pass string instances as well as string literals and char* variables that point to strings.  That is, the above enables all of the following:
addMessage("Foobar");

const char* psz = <some other string>
addMessage(psz);

std::string s = "A string";
addMessage(s);

And then to print the string correctly with printf, use the .c_str() member function to get the pointer address of the contents.
Instead of this:
printf("%s\n", s);

This:
printf("%s\n", s.c_str());

And it goes without saying that cout is preferred over printf:
cout << s << endl;

Putting it altogether:
static vector<string> added_messages;
static void addMessage(const string& message);
static void displayMessages();

int main()
{
    string message = "Testing 1 2 3";
    const char* psz = "Yet, another messsage);

    addMessage(message);
    addMessage("Another Message as a string literal);
    addMessage(psz);

    // sample printf statements
    printf("%s\n", message.c_str());
    printf("%s\n", psz);

    // sample cout statements - notice it can handle both pointers and string instances
    cout << message << endl;
    cout << psz << endl;
    cout << "Hello World" << endl;

    return 0;
}

void addMessage(const string& s)
{
    added_messages.push_back(s);
    printf("%s\n", s.c_str());
}

void displayMessages()
{
    for (const string& i : added_messages)
    {
        printf("%s\n", i.c_str());
    }

    added_messages.clear();
}

A: You can't use printf("%s") on string() object - this is the reason you are having the garbage in the output. "%s" expects C string, ie a pointer to char ended with a zero byte.
If you need to print a string() object, use c_str() method to get a C string representation, ie in your case i.c_str(). C++ is mixing C concepts with C++ concepts, so be aware. Use iostream header and std::cout << i to output your object is a C++ way.
About argument passing. In your example, you are doing it okay, but keep in mind that in your case you are doing it by value, ie a copy of the object is created. More efficient is passing by reference.

A: This should work:
for(std::size_t i = 0; i < added_messages.size(); i++)
    printf("%s\n",added_messages[i].c_str());

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get ssl certificate to work with my django app I have purchased an ssl certificate and installed it on my ubuntu apache2 server as directed by the issuer.  I then then added the following to /etc/apache2/sites-available/ssl-[mysite]:
<VirtualHost *:443>
    ServerAdmin [me]@[mysite]
    ServerName  www.[mysite]
    ServerAlias [mysite]

    # Indexes + Directory Root.
    # DirectoryIndex index.html index.htm index.php
    DocumentRoot [mysite htdocs]

    SSLEngine On
    SSLCertificateFile /etc/apache2/ssl/[mysite].crt
    SSLCertificateKeyFile /etc/apache2/ssl/[mysite].key
    SSLCertificateChainFile /etc/apache2/ssl/sf_bundle.crt

    WSGIScriptAlias /[myapp] /[myapp location]

</VirtualHost>

The ssl certificate is working like a dream for my base url, giving my the green lock symbol, but when I go to my app directory the lock symbol has a big red cross over it and I get this worrying message:

Your connection to [mysite] is encrypted with 256-bit encryption.
  However, this page includes other resources which are not secure.
  These resources can be viewed by others while in transit, and can be
  modified by an attacker to change the behavior of the page.

This obviously will scare away practically anyone, is this an issue with Django or with my apache config or what?
I have know idea where to start with this, so suggestions are welcomed

A: This warning means that you even though you are redirecting to an HTTPS link you are sending parts of your page over plain HTTP.
You should make sure that everything is over HTTPS to avoid this warning and pottential vulnerability.
I can't give you any hints on how to fix this since you haven't said much on your application and I don't know the apache2 configuration but hopefully you now have a starting point to see what to fix.
Usually you will see this warning on sites that have advertisments or embedded images


text:
Q: Decay channels of the Higgs Boson in Large Hadron Collider particle production I attach a diagram of 4 of the (many) possible decay channels produced by the Higgs boson, and I have read that 57 % of the time, we find a bottom quark, antibottom quark pair resulting from this decay.
This question results from my earlier question and the answers I received.
Resonances and Particles
My question is: are the decay products produced totally probabilistic or can we "tune" an accelerator to increase the probability of a particular decay channel occuring?
My knowledge of particle physics is very limited, but I am guessing that, at higher energy levels this "tuning" (my apologies for the terminology) is less likely.

A:
are the decay products produced totally probabilistic or can we "tune" an
  accelerator to increase the probability of a particular decay channel occuring?

Once a particle is produced, it decays completely independently of its production.
The only dependence on production occurs when, for instance, a particle is produced in an entangled state and decays to a CP eigenstate; similarly, sometimes time dependence is also affected.
Also, the production affects the polarization for particles with spin, and this in turn affects the decay angular distribution (but not branching fractions).


text:
Q: Remove all inline styles but one specific one I have seen posts such as remove all inline styles and remove all classes but one but I am looking for something else.
Say my element has got an inline style like so:

How would I go about removing all setted styles, but a specific one?
I can't use .removeAttr("style") nor can I use .attr("style", ""). What I could do, is get the value that I want, extract it, remove all styles and the add the style again:
var el = $("element"),
    elL = el.css("left");

el.removeAttr("style").css("left", elL);

But this would cause some flickering. I want a clean, straight solution!

A: Instead of that you can override the css style that you want to remove....!! with
$.css();


text:
Q: How to solve syntaxError in GraphQL? I have the following syntax error:

throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start,
  "Expected ".concat(kind, ", found ").concat(getTokenDesc(token)));

and this is my schema:
app.use('/graphql', graphqlHTTP({
    schema: buildSchema('type RootQuery{' +
        'events: [String!]!' +
        '}' +
        'type RootMutation{' +
        'createEvent(name: String): String' +
        '}' +
        'schema{' +
        'query: RootQuery' +
        'mutation: RootMutation' +
        '}'),
    rootValue: {
        events: () =>{
            return ['Hello1','Hello2','Hello3'];
        },
        createEvent: (args)=>{
            const eventName = args.name;
            return eventName;
        }

    },
    graphiql: true,
}));

I'm trying for hours to understand where in the schema syntax I was wrong, and I can't find it.

A: I was missing a few commas.
This is the working code:
app.use('/graphql', graphqlHTTP({
    schema: buildSchema('type RootQuery{' +
        'events: [String!]!' +
        '},' +
        'type RootMutation{' +
        'createEvent(name: String): String' +
        '},' +
        'schema{' +
        'query: RootQuery,' +
        'mutation: RootMutation' +
        '}'),
    rootValue: {
        events: () =>{
            return ['Hello1','Hello2','Hello3'];
        },
        createEvent: (args)=>{
            const eventName = args.name;
            return eventName;
        }
    },
    graphiql: true
}));


text:
Q: Woocommerce Product Ordering Drop-down box disappears for no reason On my website the product ordering drop-down box disappeared after I changed any option or went to a new page.
After fiddling around I went the the file woocommerce/includes/wc-template-fuctions.php and changed
function woocommerce_catalog_ordering() {
    if ( ! wc_get_loop_prop( 'is_paginated' ) || ! woocommerce_products_will_display() ) {
        return;
    }

to
function woocommerce_catalog_ordering() {
    if ( ! wc_get_loop_prop( 'is_paginated' ) || ! woocommerce_products_will_display() ) {
        echo 'test';
        return;
    }

And this has fixed the problem entirely. Now I'm not one to look a gift horse in the mouth, but I would really like to know why this has solved the issue because I've tried lots of other things and I can't figure out why this should work.
Notes:

*

*I have to print actual words

*If I print html the text will appear and replace the dropdown box

*removing the return breaks this fix


text:
Q: testing that an actor has received a specific message I'm new to Akka and actors model, and I'm struggling while trying to test an actor.
From the Akka documentation you could create a simple actor that bounds itself to a local port and listens to incoming connections with the following code:
class Server extends Actor {

  import Tcp._
  import context.system

  IO(Tcp) ! Bind(self, new InetSocketAddress("localhost", 12345))

  def receive = {
    case b @ Bound(localAddress) =>
      // do some logging or setup ...

    // rest omitted for brevity
  }

}

I'd like to write a test that creates a Server actor and then verifies that the actor has received the Bound message from IO(Tcp). I guess this is possible but I think I'm missing something. My understanding of expectMsg is that this is applied to an actor that is sending a message to the actor you're testing, receiving something back and asserting on that something it has received. Can I actually check what an actor I created has received?

A: This test would be testing if Akka IO works/that you are using the API correctly and could remove your actor from the equation and instead use a TestProbe.
It could be a good idea to separate the setup/register logic from constructing your actor instance. This way you could test:

*

*that your setup code is correct using a TestProbe verifying that you get a Bound message

*Send your actor the same messages that IO would send to it and verify that it behaves correctly


text:
Q: Asp.net path removed I have a web site hosted on Network Solutions and it runs fine there. I'm trying to set up a test site on an old local server running Windows Server 2003. On that server the pages loaded from the menu on the site master drop on the root path. In other words the site is posted at {server}/{site name}/default.aspx. That loads. When I click on a menu to load the login page, for instance it points to {server}/login.aspx. The site name is no longer there. Both sites are .Net 4.0
Below is the CSS for the menu (the image no longer displays, as well) and the html to create the menu. What am I missing?
Greg
#mainNav ul {
margin: 0;
padding: 0;
list-style: none;
background: url(/App_Themes/Blue/Images/bg_nav.png) repeat-x left top;
float: left;
border-bottom: 1px solid #000;
width: 100%;
}

Home

Login

Register

Resources

Services

Contact Us

Legal

About

A: Root/relative paths - your links above point to root (while you are expecting your root to be site_name..its not)

*

*if you want site_name to be app root, set it as such (virtual application) in IIS

*if you want a quick fix for the links, remove the / prefix so they are all in the same "relative location"...unsure if this is truly "quick" though because that means "all links"...and beware code that needs/references "root"

A: Assuming you are using Asp.net webforms, use of <asp:HyperLink> can be a solution to your problem.

                <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default.aspx">Home</asp:HyperLink>
                <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/MemberLogin.aspx">Login</asp:HyperLink>
                <asp:HyperLink ID="HyperLink3" runat="server" NavigateUrl="~/Register.aspx">Register</asp:HyperLink>
                <asp:HyperLink ID="HyperLink4" runat="server" NavigateUrl="~/Resources1.aspx">Resources</asp:HyperLink>
                <asp:HyperLink ID="HyperLink5" runat="server" NavigateUrl="~/Services.aspx">Services</asp:HyperLink>
                <asp:HyperLink ID="HyperLink6" runat="server" NavigateUrl="~/ContactNew.aspx">Contact Us</asp:HyperLink>
                <asp:HyperLink ID="HyperLink7" runat="server" NavigateUrl="~/Legal.aspx">Legal</asp:HyperLink>
                <asp:HyperLink ID="HyperLink8" runat="server" NavigateUrl="~/About.aspx">About</asp:HyperLink>


text:
Q: Why am I getting a Segmentation fault in Node.js? I have this function right here:
function createInsta(email, userid) {
  if (!fs.existsSync('users/' + email + '/' + userid)) {
    fs.mkdir('users/' + email + '/' + userid)
    fs.writeFileSync(('users/' + email + '/' + userid +  '/instagram.json'), fs.readFileSync("data/data.json", "utf-8"))
    console.log("insta folder created");
  }
  console.log("Initializing Data")
  var data = fs.readFileSync('users/' + email + '/' + userid +  '/instagram.json', "utf-8")
  data = JSON.parse(data);
  var result;
  request(("https://instagram.com/" + userid + "/?__a=1"), function(error, response, body) {
    var res = JSON.parse(body);
    result = res.user.followed_by.count
    if (error) {
      console.log(err)
    }
  })
  while (result === undefined) {
    deasync.sleep(100)
  }
  data.STARTING_COUNTS[0].DAY = result;
  data.STARTING_COUNTS[0].WEEK = result;
  data.STARTING_COUNTS[0].MONTH = result;

}

right after the console prints outs Initializing Data, the console says Segmentation fault
I have no clue why this is, my code does not seem like anything could cause such an error.
Any pointers? Thanks

A: As promised (pardon the pun), here is getting started into converting your code into Promise / await.
This is kind of a start of making your code into using promises, there is more error checking needed etc, but I've deliberately done as little to the code for now too show changes, and we can refactor as we go on.
eg. all that fs.existsSync etc, want's making into promises, so we can get rid of all the sync stuff.  Your node.js App will love you for it.
Later, we can do more.  Promise's built into browser/node are fine, but I also find a Promise lib can make things easier, I would suggest  bluebird -> http://bluebirdjs.com/docs/getting-started.html It might be worth having a good read there too, bluebird has some useful utility functions like promisify that will make your fs.func's easier.
So I think this should do for now, and we'll do another refactor later.

//lets mark this function as async..
async function createInsta(email, userid) {
  return new Promise(function (resolve, reject) {
    if (!fs.existsSync('users/' + email + '/' + userid)) {
      fs.mkdir('users/' + email + '/' + userid)
      fs.writeFileSync(('users/' + email + '/' + userid +  '/instagram.json'), fs.readFileSync("data/data.json", "utf-8"))
      console.log("insta folder created");
    }
    console.log("Initializing Data")
    var data = fs.readFileSync('users/' + email + '/' + userid +  '/instagram.json', "utf-8")
    data = JSON.parse(data);
    request(("https://instagram.com/" + userid + "/?__a=1"), function(error, response, body) {
      if (error) {
        console.log(err)
        return reject(error);
      }
      var res = JSON.parse(body);
      var result = res.user.followed_by.count
      data.STARTING_COUNTS[0].DAY = result;
      data.STARTING_COUNTS[0].WEEK = result;
      data.STARTING_COUNTS[0].MONTH = result;
      resolve(data); //i'm assuming data is what your wanting to return
    })
  });
}

//to be able to use await our function also needs to be async
async function run() {
 var data = await createInsta('bob@bob.com');
}

A: Ok, lets refactor our last post.
There was only one reason we use the new Promise() constructor, and that was because the request is Async.  In fact I made a slight mistake really as some errors won't be handled in the correct way.  What I should have done is move the new Promise() to just before the request.
Now one great thing about Promises is that error's will propagate down the chain, in our example so far we have a console.log() inside our request object.  What would be nice is that all un-handled errors are handled in one place.  In this example the run() function seems a nice place.
If you now look at your createInsta function you would think it's using all sync function, but in fact apart from existsSync everything else is async.  Like mentioned in the comments, existSync really wants removing anyway,. Instead just create the directory and catch the error in a try catch, or even better make a utility function say called tryMkDir, that does this (promise based of course).. :)
One last note, await / async is a pretty new javascript, I think it's ES7, and I don't believe it's yet even finalised. But you can use it now, by using something like Babel.

//lets make a Promise based request.
//There is an NPM module that would do this and more
//but this is a good example of making existing callback
//functions into a Promise.

async function promRequest(url) {
  return new Promise(function(resolve, reject) {
    request(url, function(error, response, body) {
      if (error) return reject(error);
      //promises can only return one thing
      //so use an object literal to return more
      resolve({
        response:response,
        body: body
      });
    });
  });
}

//lets also promisify some Node stuff.
var Promise = require('bluebird');

//there is a promisifyall, but I like to be
//specific about what I promisify.
var fsWriteFile = Promise.promisify(fs.writeFile),
    fsReadFile = Promise.promisify(fs.readFile),
    fsMkdir = Promise.promisify(fs.mkdir);

//because promRequest is already a promise
//we can now get rid of the new Promise contructor here.
//The only part of this function that is now async
//is existsSync, the exists() in node is depreciated
//due to potential race conditions, really this
//should be altered to just try and create dirctory
//and catch error if exists.
async function createInsta(email, userid) {
  if (!fs.existsSync('users/' + email + '/' + userid)) {
    await fsMkdir('users/' + email + '/' + userid);
    await fsWriteFile(('users/' + email + '/' + userid +  '/instagram.json'), await fsReadFile("data/data.json", "utf-8"));
    console.log("insta folder created");
  }
  console.log("Initializing Data")
  var data = await fsReadFile('users/' + email + '/' + userid +  '/instagram.json', "utf-8")
  data = JSON.parse(data);
  var res = JSON.parse(
    await promRequest("https://instagram.com/" + userid + "/?__a=1").body);
  var result = res.user.followed_by.count
  data.STARTING_COUNTS[0].DAY = result;
  data.STARTING_COUNTS[0].WEEK = result;
  data.STARTING_COUNTS[0].MONTH = result;
  return data;
}

//to be able to use await our function also needs to be async
async function run() {
  //lets catch all unahandled errors here.
  try {
    var data = await createInsta('bob@bob.com');
  } catch (e) {
    //fantasic any error's can now be logged
    //eg. fsMkdir might have failed and it's still
    //going to be logged here..
    console.log(e);
  }
}


text:
Q: How to find the smallest value that meets multiple criteria I want to find a number that (with an input of 2 numbers) is a multiple of the biggest one while being a multiple of the smallest one if you add or subtract the GCD of both numbers. In other words:
val%max(x,y)==0 and ((val-gdc(x,y))%min(x,y)==0 or (val+gdc(x,y))%min(x,y)==0)

For example: if I have 4 and 7, the value would be 7 as it is a multiple of 7 and if you add 1 (which is the gcd of 7 and 4) it becomes 8, which is a multiple of 4
I need a solution that doesn't make use of loops if possible, as my solution does work but is quite slow with big numbers:
from math import gcd
x,y=map(int,input().split())
def fun(x,y):
    big=max(x,y)
    small=min(x,y)
    d=gcd(x,y)
    val=big
    while (val+d)%small!=0 and (val-d)%small!=0:
        val+=big
    return val
val=fun(x,y)
print(val)

A: Here's a solution that doesn't use loops. I've benchmarked it against numbers with up to 10 thousand digits, and its still running in subsecond times.
from math import gcd

def solve(n, m):
    n, m = max(n, m), min(n, m)
    d = gcd(n, m)
    p, q = n//d, m//d

    a = pow( p, -1, q)
    b = pow(-p, -1, q)

    return n * min(a, b)

It will give a different (but still correct) solution in rare circumstances- returning 0 instead n (the bigger number) when both are valid solutions.


text:
Q: R.java auto generation problem I am trying to implement MJAndroid. There R.java is getting generated on its own. I want to delete the auto generated one and either create my own or overwrite the existing one. Its not allowing me to do so. What should I do?

A:
There R.java is getting generated on its own. I want to delete the auto generated one and either create my own or overwrite the existing one. Its not allowing me to do so.

AFAIK, that is not possible. Whatever problem you think you are solving this way can hopefully be solved in some other way.


text:
Q: Spring MVC @EnableWebMvc Bean config I´m trying to configure a Bean to be used in a Spring MVC Controller app using the @Bean annotation.
As far as I know, the @Bean annotation is equivalent to the  tag in XML configuration. What I am doing is the following:
The class with the configuration
@Configuration
public class ContextConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

But when trying to autowire myBean in an MVC Controller it fails.
The bean injection
@Controller
public class HomeController {

    @Autowired
    private MyBean myBean;

    @RequestMapping({"/", "/home"})
    public ModelAndView home (ModelAndView model) {
        model.setViewName("home");
        return model;
    }
}

The error is:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.validation.ValidatorFactory com.proeza.sgs.controller.HomeController.factory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.validation.ValidatorFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.validation.ValidatorFactory com.proeza.sgs.controller.HomeController.factory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.validation.ValidatorFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.validation.ValidatorFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 24 more

Final comments

*

*There are other beans configured via annotation (@Bean), that are being injected without problem.

*The MyBean class is not implementing nor extending anything.

*The configuration location is declared in the web.xml
Conf:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.myapp.config</param-value>
</context-param>

The ContextConfig class is in that package
Any idea why is this happening?

A: The exception is not related to the MyBean class. The exception says:
No qualifying bean of type [javax.validation.ValidatorFactory] found for dependency

Spring failed to inject javax.validation.ValidatorFactory to the HomeController class. Check that configuration for ValidatorFactory class.

A: Thanks for the response Ilya.
You´re right, the stack I pasted was not the correct one. The cause was that to simplify, I gave the example with MyBean and I forgot to rename it in the stack.
The problem has been solved. The real name of MyBean is MessageResolver and what was happening was that I already had another method called messageResolver inside the ContextConfig class, used to create a bean for Thymeleaf. The difference is that mine does not receive parameters and the other receives a MessageSource, BUT...Reading the Spring docmentation I found this:
Spring Doc Quote:

2.2.6. Customizing bean naming
By default, JavaConfig uses a @Bean method's name as the name of the
  resulting bean. This functionality can be overridden, however, using
  the BeanNamingStrategy extension point.

Spring @Bean doc
So, the problem is that the bean was not being created because it was being overrided its definition.
The error disappears just renaming the messageResolver method.
Thanks again. Regards!


text:
Q: Skip maven deploy for one module I have a multi-module maven project. Parent pom looks like this:
<project>
    ...
    <packaging>pom</packaging>
    <modules>
        <module>common</module>
        <module>a</module>
        <module>b</module>
    </modules>
</project>

common builds a jar, which is added as dependency in the other modules, like this:
<dependency>
    <groupId>my.project</groupId>
    <artifactId>common</artifactId>
    <version>${module.common.version}</version>
</dependency>

Modules a and b are Spring Boot projects having the spotify docker plugin.
I need to be able to run mvn deploy in order to get the spotify plugin push the docker image.
mvn install works fine, which builds the docker images. But in order to push them, when I run mvn deploy, it throws error for the common module:

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy
  (default-deploy) on project common: Deployment failed: repository
  element was not specified in the POM inside distributionManagement
  element or in -DaltDeploymentRepository=id::layout::url parameter

Searching for this error, this answer suggests adding the repository url in the distributionManagement section. But I don't want to deploy common. I just want to build it, so it gets injected as dependency in the other modules and deploy those other modules. How can I do that?
I tried to deploy only a and b using this command, but it gives the same error for common:
mvn clean \
   -DdockerRegistryHost=123.dkr.ecr.us-west-1.amazonaws.com/test1 \
   --projects a,b \
   --also-make \
   deploy

A: You can accomplish what you want by configuring the maven-deploy-plugin.
Try adding the following to your parent pom:
<build>
    ...
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>3.0.0-M1</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    ...
 </build>

or add -Dmaven.deploy.skip=true to your command line.


text:
Q: Uncaught TypeError: Cannot read property 'connection' of undefined at file:///android_asset/www/app.js:1 I don't know where the error is and how to remove it. I'm new to sencha touch and phonegap.
here is my app.js file
// DO NOT DELETE - this directive is required for Sencha Cmd packages to work.
//@require @packageOverrides
//
    Ext.Loader.setPath({
    'Ext': 'touch/src'
});
//
Ext.application({
name: 'appointMeDr',

requires: [
'Ext.MessageBox','Ext.device.Connection','appointMeDr.SessionInfo',
'Ext.data.proxy.LocalStorage','Ext.data.proxy.LocalStorage'
],

views: [
'Main','homePage.Home','viewsTab.FindDrTab','viewsTab.SettingTab',
'profile.user_profile','userAppointment.PatientAppointment',
'doctorViews.MainDr','doctorViews.drAppointment.DrAppointment','doctorViews.doctorProfile.BlockPatient',
'doctorViews.tabViews.DrProfileTab',
'MyPicker','Utils',
'signUp.UserSignUp','signUp.SignUp',
'guardianView.GuardianPatient','guardianView.guardianProfile.GuardianProfile','guardianView.MainGuardian',
'attendant.MainAttendant','attendant.tabViews.AttendantProfileTab','HealthyTips'

],
models:[
'SearchDr','fixedAppointment','Patient','Login','user','DoctorModel','AppointmentModel','Guardian','DoctorDetail',
'doctorAppointment','Attendant','HealthyTipModel'
],
stores:[
'SearchDocResults','AppointmentResults','Patients','Users','OfflineUser','Doctors','Guardians','DoctorDetailsStore',
'doctorAppointments','AttendantStore','BlockPatients','TimeSlots','HealthyTips'
],
controllers: [
'LoginController','MainController','DoctorController','UserSignUp','AppointmentController','AttendantController',
'GuardianController'

],

icon: {
    '57': 'resources/icons/Icon.png',
    '72': 'resources/icons/Icon~ipad.png',
    '114': 'resources/icons/Icon@2x.png',
    '144': 'resources/icons/Icon~ipad@2x.png'
},

isIconPrecomposed: true,

startupImage: {
    '320x460': 'resources/startup/320x460.jpg',
    '640x920': 'resources/startup/640x920.png',
    '768x1004': 'resources/startup/768x1004.png',
    '748x1024': 'resources/startup/748x1024.png',
    '1536x2008': 'resources/startup/1536x2008.png',
    '1496x2048': 'resources/startup/1496x2048.png'
},

launch: function() {
    // Destroy the #appLoadingIndicator element
   // Ext.fly('appLoadingIndicator').destroy();
Ext.Viewport.add(Ext.create('appointMeDr.view.homePage.Home'));
    // Initialize the main view
   // Ext.Viewport.add(Ext.create('appointMeDr.view.Main'));
},

onUpdated: function() {
    Ext.Msg.confirm(
        "Application Update",
        "This application has just successfully been updated to the latest version. Reload now?",
        function(buttonId) {
            if (buttonId === 'yes') {
                window.location.reload();
            }
        }
    );
}

});

A: We don't know what you want to do, but I try something :
I think you call connection.type property before "deviceready" event.
From phonegap doc :

This is a very important event that every Cordova application should
  use.
Cordova consists of two code bases: native and JavaScript. While the
  native code is loading, a custom loading image is displayed. However,
  JavaScript is only loaded once the DOM loads. This means your web
  application could, potentially, call a Cordova JavaScript function
  before it is loaded.
The Cordova deviceready event fires once Cordova has fully loaded.
  After the device has fired, you can safely make calls to Cordova
  function.

So try this :
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
    checkConnection();
}

function checkConnection() {
    var networkState = navigator.network.connection.type;
    ...
}

EDIT : now we have more information, I think this answer is useless for you :/

A: After 2 days of hard work i solved it by myself.Remove all warnings even if "",""(comma generates it) and thats it. Problem solved :)
happy coding


text:
Q: Inserting New Column in MYSQL taking too long We have a huge database and inserting a new column is taking too long. Anyway to speed up things?

A: Unfortunately, there's probably not much you can do. When inserting a new column, MySQL makes a copy of the table and inserts the new data there. You may find it faster to do
CREATE TABLE new_table LIKE old_table;
ALTER TABLE new_table ADD COLUMN (column definition);
INSERT INTO new_table(old columns) SELECT * FROM old_table;
RENAME table old_table TO tmp, new_table TO old_table;
DROP TABLE tmp;

This hasn't been my experience, but I've heard others have had success. You could also try disabling indices on new_table before the insert and re-enabling later. Note that in this case, you need to be careful not to lose any data which may be inserted into old_table during the transition.
Alternatively, if your concern is impacting users during the change, check out pt-online-schema-change which makes clever use of triggers to execute ALTER TABLE statements while keeping the table being modified available. (Note that this won't speed up the process however.)

A: There are four main things that you can do to make this faster:

*

*If using innodb_file_per_table the original table may be highly fragmented in the filesystem, so you can try defragmenting it first.

*Make the buffer pool as big as sensible, so more of the data, particularly the secondary indexes, fits in it.

*Make innodb_io_capacity high enough, perhaps higher than usual, so that insert buffer merging and flushing of modified pages will happen more quickly. Requires MySQL 5.1 with InnoDB plugin or 5.5 and later.

*MySQL 5.1 with InnoDB plugin and MySQL 5.5 and later support fast alter table. One of the things that makes a lot faster is adding or rebuilding indexes that are both not unique and not in a foreign key. So you can do this:
A. ALTER TABLE ADD your column, DROP your non-unique indexes that aren't in FKs.
B. ALTER TABLE ADD back your non-unique, non-FK indexes.
This should provide these benefits:
a. Less use of the buffer pool during step A because the buffer pool will only need to hold some of the indexes, the ones that are unique or in FKs. Indexes are randomly updated during this step so performance becomes much worse if they don't fully fit in the buffer pool. So more chance of your rebuild staying fast.
b. The fast alter table rebuilds the index by sorting the entries then building the index. This is faster and also produces an index with a higher page fill factor, so it'll be smaller and faster to start with.
The main disadvantage is that this is in two steps and after the first one you won't have some indexes that may be required for good performance. If that is a problem you can try the copy to a new table approach, using just the unique and FK indexes at first for the new table, then adding the non-unique ones later.
It's only in MySQL 5.6 but the feature request in http://bugs.mysql.com/bug.php?id=59214 increases the speed with which insert buffer changes are flushed to disk and limits how much space it can take in the buffer pool. This can be a performance limit for big jobs. the insert buffer is used to cache changes to secondary index pages.
We know that this is still frustratingly slow sometimes and that a true online alter table is very highly desirable
This is my personal opinion. For an official Oracle view, contact an Oracle public relations person.
James Day, MySQL Senior Principal Support Engineer, Oracle

A: usually new line insert means that there are many indexes.. so I would suggest reconsidering indexing.

A: Michael's solution may speed things up a bit, but perhaps you should have a look at the database and try to break the big table into smaller ones. Take a look at this: link. Normalizing your database tables may save you loads of time in the future.


text:
Q: Can't connect to MongoDb externally Some information:

*

*The port is indeed open(i can bind it to apache2, for example, and access it externally)

*I've tried setting the bind_up parameter to 0.0.0.0, to my localip, etc

*I can access it through my local IP(192.167.10.xxx)

*I didn't isntall mongo with apt-get, just downloaded it and ran mongod

I've spent a lot of time searching and trying different things, anyone has a idea on what could be causing it?
Mongo runnning
edit:
Mongo options: [initandlisten] options: { config: "config.conf", net: { bindIp: "0.0.0.0", port: 8008 }, security: { authorization: "enabled" }, storage: { dbPath: "/home/defense/mongo/data" } }
When i try to connect:
[thread1] Failed to connect to 146.164.x.xxx:8008, in(checking socket for error after poll), reason: Connection refused
Port check(also I used to connect to MySql using that same port):
Port 8008 is open on 146.164.x.xxx.
Any ideas?


text:
Q: Unit test for OS patching process in RHEL As a part of my automation framework, I am using ansible to perform the OS patching to my host machines. Before executing this proccess in production, I need to write a unit test to verifiy that, the task:
yum update

is finishing successfully.
I am trying to get the number of packages that will be updated and compare it, after, with the number of packages that has been updated (using this command: yum history.
What is the best way?

Note: the test will run beforehand on a similar testing machine (RHEL 7)


text:
Q: Does the word rudimentary has any negative connotation? I am a non native (Indian) English speaker and I used the phrase "feature X is rudimentary" as matter of fact in a American office setting (chat;slack). Can it be construed in a negative manner ? i.e aggressive or accusatory?

A: I wouldn't call it complimentary, but it could be simply factual.

"Hey, I developed this prototype. It's still rudimentary, but you can see how a final product should work."

In that sentence, the state of the product is simply rudimentary, and it is neither a good nor bad thing. It simply is.
The negative connotation would come across in a dismissive tone. If the person worked really hard and thought that the feature was production-worthy, calling it "rudimentary" is slapping down their hard work. It could even be insulting if it's unfairly called "rudimentary," i.e. it may not be perfect, but it's hardly an incipient effort.


text: Q: Doesn't include signing certificate in xcode8.1 it is working fine in xcode7.2 on same machine. here I am not using automatic code signing. when i select Provisioning profile tab manually it shows error Provisioning profile doesn't include signing certificate.Also Removed provising profile,certificate from machine and redownload still it's not working and also remove derived data from xcode.but results are same.


text:
Q: Batch - Using findstr to read a file entry and output if it is less than a variable I'm trying to read a text file using findstr to output only specific characters based on whether the value is less than my predefined number value. Here is a line from the text file that i am trying to read:
BW6556 *NULL* 1 6 1406922741 1407046596 1415081796 0 845292618 3 3 5 5 0 8 1024

BW6657 *NULL* 1 6 1408817016 1408817016 1416852216 0 193816666 2 2 5 5 0 0 1024

I need an expression that looks at the above line and does the following:

*

*looks at the long number on each line that starts at character 41 and ends on character 50

*If that number is GREATER THAN 1 and LESS THAN my variable number %expirydate% then write out characters 1-7 to a new file.

*Does the same thing on every line in the text file!

Any ideas?

A: That cannot be done with FINDSTR. First off, FINDSTR cannot numerically compare numbers. Second, FINDSTR cannot return a substring from a line.
It can be solved using FOR /F to parse the space delimited list of values. Note that this solution is not based on character position.
EDIT: Major rewrite to handle possibility of number larger than 2147483647. Also, my original code failed if it had zeros in the middle of the number
This solution assumes all lines have 10 digits in the 7th token (position 41). I enclose the values in quotes within the IF comparison to force it to do a text comparison instead of a numeric comparison. This will work properly as long as all values have exactly 10 digits.
set "num=0000000000%expirydate%"
set "num=%num:~-10%"
for /f "usebackq tokens=1,7" %%A in ("test.txt") do (
  if "%%C" gtr "0000000001" if "%%C" lss "%expirydate%" (echo %%A )
)

A: If I look at your example and take character 41 to 50 from the first line it gives me: "141508179", but that string is ten characters long; "1415081796" and it doesn't look like a date.
Here you have a VBScript which extracts numbers bigger than 200000000 and places them in a new file.
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Temp\input.txt", ForReading)
Do While objFile.AtEndOfStream <> True
    strLine = objFile.ReadLine
    extractednr = Mid(strLine,41,9)
    If (extractednr > 200000000) Then
        strContents = strContents & extractednr & vbCrLf
    End If
Loop
objFile.Close

Set objFile = objFSO.CreateTextFile("C:\Temp\output.txt", true)
objFile.WriteLine strContents
objFile.Close

A: There are many questions..You want the number BEFORE or AFTER spaces are cleared?Are you sure that the these are exact end and start charaters ? What can be max value of the numbers ? Can it be more than 2147483647 - the max integer value?If it is - can be a string comparison be executed instead?
@echo off

set /a variable=2147483647
set "val_file=number.txt"
set "new_file=new.txt"

break>"%new_file%"
setlocal enableDelayedExpansion
for /f "useback delims=" %%# in ("%val_file%") do (
    set "line=%%#"
    set line=!line:~40,10!
    set /a number=!line: =!
    rem echo !number! !variable!
    if !number! GTR 1 if !number! LSS !variable! (echo(!number!)>>"%new_file%"

)


text:
Q: Scipy Optimize Pandas Dataframe I have a dataframe like so:
ID | size | p1 | p2 | ... |p10| quantity | o1| o2|...|o10|
p1 to p10 and o1 to o10 are float32 values. Size is a string. For one ID there can be 1 or more sizes. For every size there is one row p1..p10 but only 1 row of o1..o10 for every ID whether it contains 1 or more sizes.
I have 10 linear equations like so:
f1 = [(p1S1*qS1)+(p1S2*qS2)+...+(p1Sn*qSn)] + o1
f2 = [(p2S1*qS1)+(p2S2*qS2)+...+(p2Sn*qSn)] + o2
.
.
f10 = [(p10S1*qS1)+(p10S2*qS2)+...+(p10Sn*qSn)] + o10

Where p1S1 is p1 of size 1, qSn : quantity of size 1. Bounds for q are either -q<solution<0 or 0<solution<q depending on whether q is negative or positive.
I want to solve for q in order to maximize (C is constant):
F = max(C, f1, f2,...,f10)
I've looked into the documentation of scipy.optimize.minimize but I don't fully understand how to pass data in. Please help!


text:
Q: Homebrew Export Settings Looking for a way to export my homebrew and homebrew cask installations (everything from 'brew list' and 'brew cask list')
I'd like to be able to export them to a file that I can then put on any new machine, and run some sort of install that will install them automatically.
Basically using something like a package.json for package management.

A: This is exactly what homebrew-bundle does.


text:
Q: Cannot select css selector I am running into an issue where I cannot select the correct CSS selector.  I think the website itself is causing the issue.  Any ideas why it isn't selecting correctly?
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests, time

driver = webdriver.Firefox(executable_path="geckodriver")
driver.get("https://www.okcc.online/")
driver.maximize_window()
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='rod-menu-button']"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@id='rodDocTypeTxt']"))).send_keys('MTG')
wait.until(EC.element_to_be_clickable((By.XPATH, "//ul[@id='ui-id-1']//li//div"))).click()

driver.find_element_by_xpath('//*[@id="rod-date-toggle"]').click()

driver.find_element_by_xpath('//*[@id="rodFromDateTxt"]').send_keys('4/1/2020')
driver.find_element_by_xpath('//*[@id="rodToDateTxt"]').send_keys('4/20/2020')

search_button = driver.find_element_by_xpath('//*[@id="rod-submit-search"]').click()

time.sleep(2)

pdf = driver.find_elements_by_css_selector("icon pdf-icon")

print(len(pdf))

When I run this, it returns a count of 0, where it should return a count of 50 if I am selecting the CSS correctly on this site.
Ultimately I want to iterate through all of these items, and download the pdf that returns..but I cannot even get the dang thing to be recognized.

A: This will select all elements with compound class icon pdf-icon
driver.find_elements_by_css_selector(".icon.pdf-icon")

This will select all div tags with compound class icon pdf-icon
driver.find_elements_by_css_selector("div.icon.pdf-icon")

More information about css selectors
https://www.w3schools.com/cssref/css_selectors.asp

A: Try div.icon.pdf-icon.
That is what is suggested here: Locating Elements


text:
Q: Guard fails on Windows 7 with Runtime Error Running
$bundle exec guard

with
ruby 1.9.3p327 (2012-11-10) [i386-mingw32]
Rails 3.2.11
Guard version 1.6.1

fails on Windows 7 64bit, for me with:
17:49:03 - INFO - Guard uses Notifu to send notifications.
17:49:03 - INFO - Guard uses TerminalTitle to send notifications.
C:/Ruby193/lib/ruby/gems/1.9.1/gems/pry-0.9.11.3-x86-mingw32/lib/pry/command_set
.rb:216:in `alias_command': Command: `help` not found (RuntimeError)
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard/interacto
r.rb:135:in `block in create_command_aliases'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard/interacto
r.rb:134:in `each'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard/interacto
r.rb:134:in `create_command_aliases'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard/interacto
r.rb:95:in `initialize'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard.rb:161:in
 `new'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard.rb:161:in
 `setup_interactor'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard.rb:82:in
`setup'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard.rb:183:in
 `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/lib/guard/cli.rb:11
0:in `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/thor-0.16.0/lib/thor/task.rb:27
:in `run'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/thor-0.16.0/lib/thor/invocation
.rb:120:in `invoke_task'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/thor-0.16.0/lib/thor.rb:275:in
`dispatch'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/thor-0.16.0/lib/thor/base.rb:42
5:in `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/guard-1.6.1/bin/guard:6:in `<to
p (required)>'
        from C:/Ruby193/bin/guard:23:in `load'
        from C:/Ruby193/bin/guard:23:in `<main>'

Do I need to start notifu in a specific way? What am I missing?

A: RKing has filed an issue at Guard and linked your question to it. It looks like this is either a problem with the latest Pry or Guard doesn't use the Pry API right.
Two things comes to mind to work around the issue:

*

*Disable the interactor
Since Pry is only used in the interactor, you can diable it when starting Guard and you should have the Guard plugins working at least:

$ bundle exec guard -i

*Find the last working Pry version
I think you should get it running with an older version of Pry, the question is which version has introduced the incompatibility. You can use a fixed Pry version by specify the version in your Gemfile and run bundler:
In your Gemfile:

gem 'pry', '0.9.11.2'

Then run bundler in the console:

$ bundle update

If it still doesn't work, just use a lower version. Please try 0.9.11.2, 0.9.11.1, 0.9.11 and 0.9.10.
If you have found a working version, please report it to the linked Guard issue at GitHub.


text:
Q: How to order the parameters passed on a form_tag path? I'm passing some params trough the form_tag but it's not passing them as I want it, on the actual view I have params[:id] with :id being '225907' (a specific number) but after I execute the form_tag, it truncates that params[:id] and changes it to the name of the action => params[:id]='save_path'
Inside the form_tag it's stated a Cita (Meeting) with all the parameters it needs to save for a meeting, all of that is Ok as it is passed into a hash through the params path as an element, but there's another element called Id which should have a numeric value that identifies my users, then the form_tag passes it wrong:
Parameters:

{"utf8"=>"✓",
  "authenticity_token"=>"bQu90nWiFQdn8GTwZH4xedyZiLhhTUCT5DjLUOqgfB2aiju3V7EFbRMI4LwLJNzIsVAOiryJ1+fHjfDCaP6thw==",
  "cita"=>{"fecha"=>"2019/08/26", "requiere"=>"false",
  "matricula"=>"214876", "cve_empleado"=>"91985", "id_centro"=>"",
  "id_facultad"=>"", "tipo"=>"1", "area"=>"", "especialidad"=>"",
  "experto"=>"", "tema"=>"9", "subtema"=>"92", "orientacion"=>"67",
  "problema"=>"", "materia"=>"", "asesor"=>"", "nota"=>"fgnfhfgh",
  "ciclo"=>"2370"}, "checkboxReq2"=>"on", "optionsCheckboxes2"=>"1",
  "id"=>"save_path"}

Form:
 <%= form_tag(guardar_tutoria_path, method: :post) do |f| %>
        <input type="hidden" name="cita[fecha]" value="{{cita.fecha}}">
        <input type="hidden" name="cita[requiere]" value="{{cita.requiere}}">
        <input type="hidden" name="cita[matricula]" value="{{cita.matricula}}">
        <input type="hidden" name="cita[cve_empleado]" value="{{cita.cve_empleado}}">
        <input type="hidden" name="cita[id_centro]" value="{{cita.id_centro}}">
        <input type="hidden" name="cita[id_facultad]" value="{{cita.id_facultad}}">
        <input type="hidden" name="cita[tipo]" value="{{cita.tipo}}">
        <input type="hidden" name="cita[area]" value="{{cita.area}}">
        <input type="hidden" name="cita[especialidad]" value="{{cita.especialidad}}">
        <input type="hidden" name="cita[experto]" value="{{cita.experto}}">
        <input type="hidden" name="cita[tema]" value="{{cita.tema}}">
        <input type="hidden" name="cita[subtema]" value="{{cita.subtema}}">
        <input type="hidden" name="cita[orientacion]" value="{{cita.orientacion}}">
        <input type="hidden" name="cita[problema]" value="{{cita.problema}}">
        <input type="hidden" name="cita[materia]" value="{{cita.materia}}">
        <input type="hidden" name="cita[asesor]" value="{{cita.asesor}}">
        <input type="hidden" name="cita[nota]" value="{{cita.nota}}">

The expected result should have the Id with the user's Id not with the name of the action:
Parameters:

{"utf8"=>"✓", "authenticity_token"=>"bQu90nWiFQdn8GTwZH4xedyZiLhhTUCT5DjLUOqgfB2aiju3V7EFbRMI4LwLJNzIsVAOiryJ1+fHjfDCaP6thw==",
  "cita"=>{"fecha"=>"2019/08/26", "requiere"=>"false",
  "matricula"=>"214876", "cve_empleado"=>"91985", "id_centro"=>"",
  "id_facultad"=>"", "tipo"=>"1", "area"=>"", "especialidad"=>"",
  "experto"=>"", "tema"=>"9", "subtema"=>"92", "orientacion"=>"67",
  "problema"=>"", "materia"=>"", "asesor"=>"", "nota"=>"fgnfhfgh",
  "ciclo"=>"2370"}, "checkboxReq2"=>"on", "optionsCheckboxes2"=>"1",
  "id"=>"225907"}

What am I doing wrong?

A: On my route I added the Id to the path and all of it is working now:
post '/follow_up/save_meeting/:id', to: 'tutoring/follow_up#save_meeting', as: :save_meeting


text:
Q: Laravel Paginator's "append" generates different key for array Using Laravel 5.5 with PHP 7.0, trying to create and append some queries to pagination following the docs.
https://laravel.com/docs/5.5/pagination#displaying-pagination-results
However with some queries which have multiple values, rendered links have different keys.
Simplest reproducing code is:
>>> User::query()->paginate(30)->appends(['query' => ['foo', 'bar', 'baz']])->nextPageUrl()
=> "http://homestead.app?query%5B0%5D=foo&query%5B1%5D=bar&query%5B2%5D=baz&page=2"
# expecting "http://homestead.app?query%5B%5D=foo&query%5B%5D=bar&query%5B2%5D=baz&page=2"

In other words, the next url of /user?page=1&query[]=1&query[]=2 should be:
/user?page=2&query[]=1&query[]=2
but actually
/user?page=2&query[0]=1&query[1]=2
What is wrong in my code?


text:
Q: htaccess redirect directory except for ipad and iphone I want to redirect all url's from
domain.com/incoming-dir/   to domain.com/direct-dir/
I use the following for this:
RewriteEngine On
RewriteRule ^/?incoming-dir/(.*)  direct-dir/$1 [R=301,L]

But now I want to build in an exception.
The redirect should not happen for an iPhone and iPad.
What should be added for this exception?

A: You should check first with %{HTTP_USER_AGENT} and exclude what you want from next rule
 RewriteEngine On
 RewriteCond %{HTTP_USER_AGENT} !^.*(iPhone|iPad).*$  [NC]
 RewriteRule ^incoming-dir/(.*)  direct-dir/$1 [R=301,L]


text:
Q: Jenkins groovy init script for sonarqube configuration I am trying to set sonarqube settings in Jenkins system property using groovy init script but I am getting below error. Can somebody help me to resolve this?
Error
+++++

groovy.lang.GroovyRuntimeException: Could not find matching constructor for:
hudson.plugins.sonar.SonarInstallation(java.lang.String, java.lang.String,
java.lang.String, hudson.plugins.sonar.model.TriggersConfig,
java.lang.String)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1732)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1532)

This is the script that I am using
import hudson.model.*
import jenkins.model.*
import hudson.plugins.sonar.SonarGlobalConfiguration
import hudson.plugins.sonar.*
import hudson.plugins.sonar.model.TriggersConfig
import hudson.tools.*

def inst = Jenkins.getInstance()

println "--> Configuring SonarQube"

SonarGlobalConfiguration global = Hudson.instance.getDescriptorByType(SonarGlobalConfiguration.class)

def sonar_inst = new SonarInstallation(
    "SonarQ",
    "http://localhost:9000",
    "yy", // Token
    new TriggersConfig(),
    ""
)

// Only add ADOP Sonar if it does not exist - do not overwrite existing config
def sonar_installations = sonar_conf.getInstallations()
def sonar_inst_exists = false
sonar_installations.each {
    installation = (SonarInstallation) it
    if (sonar_inst.getName() == installation.getName()) {
        sonar_inst_exists = true
        println("Found existing installation: " + installation.getName())
    }
}

if (!sonar_inst_exists) {
    sonar_installations += sonar_inst
    sonar_conf.setInstallations((SonarInstallation[]) sonar_installations)
    sonar_conf.save()
}

A: You missed some parameters. SonarInstallation constructor needs 7 parameters, not 5:
@DataBoundConstructor
public SonarInstallation(String name,
  String serverUrl, String serverAuthenticationToken,
  String mojoVersion, String additionalProperties, TriggersConfig triggers,
  String additionalAnalysisProperties) {
  this.name = name;
  this.serverUrl = serverUrl;
  this.serverAuthenticationToken = serverAuthenticationToken;
  this.additionalAnalysisProperties = additionalAnalysisProperties;
  this.mojoVersion = mojoVersion;
  this.additionalProperties = additionalProperties;
  this.triggers = triggers;
}


text:
Q: Does FFMPEG support RTSP authentication? Such as...
rtsp://user:pass@x.x.x.x/VideoString

A: ffmpeg supports RTSP authentication. I think you might be missing quotes covering RTSP URL.
Examples
Not working:
ffmpeg -i rtsp://user:pass@x.x.x.x/VideoString

Working:
ffmpeg -i "rtsp://user:pass@x.x.x.x/VideoString"

A: Yea Im having problems with this too. It seems Digest authentication is missing. there are a few mailing list comments about adding it in. see http://web.archiveorange.com/archive/v/yR2T4nBtThzJs27hqDLb but nothing conclusive.
Please be aware that HTTP basic authentication is passed in the URL string as in your example but digest is md5 encoded and passed as a separate element in the HTTP request.
also the http://www.live555.com/ library does support http/digest authentication, i have tested, it works.
to test conectivity use the testProgs in live555
live/testProgs/openRTSP -4 -u admin admin -w 1280 -h 720 -f 20 rtsp://192.168.0.2/defaultPrimary?streamType=u > testmovie.mp4

A: Yes, ffmpeg does support RTSP authentication using the ffplay command.
Try using the ffplay command instead:
ffplay rtsp://user:pass@x.x.x.x/VideoString

This works for me.
source (adapted from the commands used to authenticate ftp and others using the same syntax):
ffmpeg.org

A: After digging a lot with ffmpeg I found that long urls with authorization fail in ffmpeg while working good with VLC.
Url lenght with auth should be less than 140.
So 139 chars worked while 140 failed with method SETUP failed: 401 Unauthorized
P.S.
After digging in Source code I found https://github.com/FFmpeg/FFmpeg/blob/415f907ce8dcca87c9e7cfdc954b92df399d3d80/libavformat/rtsp.h#L423
Looks like it is 128 char for url without password.

A: It has been quite q while, not sure what's the story back in 11, but yes, ffmpeg now support so.
ffmpeg -i rtsp://user:pass@x.x.x.x/VideoString
works.

A: What I found was that you should use single quotes ' instead of double quotes " as recommended in the solution given by @AmitSharma.
And the reason for this, is that if the password contains any special characters you might get weird errors as the shell might interpret them as it wants. I tried to escape these characters first, which seemed to solve the problem with the shell, but now for some weird reason ffmpeg didn't read the password correctly anymore... So the only way for me to get it to work was to use single quotes instead, as that tells the shell (bash in my case) to not interpret anything between the quotes.
Solution by @AmitSharma
ffmpeg -i "rtsp://user:pass@x.x.x.x/VideoString"

Solution with single quotes
ffmpeg -i 'rtsp://user:password!@x.x.x.x/VideoString'

A: FFmpeg appears to support Digest authentication, at least as of this March 25, 2010 commit:
https://github.com/FFmpeg/FFmpeg/commit/855e7732c6bcc7d52cd0863407a721c2bf00fcf1
The logic implementing the digest computation is mostly in this file:
https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/httpauth.c
According to this changelog, that made it into the version 0.6 release:

*

*HTTP Digest authentication

A: I spent whole weekend on it (ffmpeg 07/07/2014) and can say -NO! Perhaps ffmpeg has RTSP codes for digest/auth, but they do not work there.  I always got 401 error from IP camera with digest/auth and good work with basic/auth.
VLC with live555 works well with any authentication.


text:
Q: (Two hyphens != n-dash) even out of math mode I am not trying to do this in math mode, and yet a pair of consecutive hyphens
\documentclass{article}
\begin{document}
\sffamily\bfseries\itshape
How are you?\\
{\emph --Bob}
\end{document}

are not converted to an n-dash. Why?

A: The correct usage of \emph is \emph{Bob}. The command takes an argument!
So with the following MWE
\documentclass{article}
\begin{document}
\sffamily\bfseries\itshape
How are you?\\
{\emph --Bob} --test --\emph{Bob} \emph{--Bob}
\end{document}

you get what you want:


text:
Q: Mostrar resultado de consulta Firestore en React Typescript
Estoy en construccion (y aprendisaje) de una aplicacion web en React con Typescript, utilizando Firestore de Firebase para el manejo de datos.
Tengo problemas (dado mi escaso nivel de conocimiento y experiencia) en traer los datos desde Firestore y volcarlos para su utilizacion a traves de react.
Necesito que la constante userData2 me lleve todos los datos del usuario y pueda pasarlo como tal a traves de las props.
He aqui  mi codigo:
"InitGame.tsx"
import { Component } from "react";
import Config from "./Config";
import { auth, dbAuth } from "./Firebase";
import { collection, query, where, onSnapshot } from "firebase/firestore";

const q = query(collection(dbAuth, "auth"), where("emailId", "==", `${auth.currentUser?.email}`));
const userData2 = onSnapshot(q, (querySnapshot) => {
  const datosUsuario: any[] = [];
      querySnapshot.forEach((doc) => {
      datosUsuario.push(doc.data().firstName);
      datosUsuario.push(doc.data().creditosDisponibles);
  });
  console.log(datosUsuario);
  return datosUsuario;
});

    interface InitGameProps {
      socket: any;
      usuario: any;
    }

    interface InitGameState {
      isEmpty: boolean;
      name: string | undefined;
      submitted: boolean;
      usuario: any;
    }

    class InitGame extends Component<InitGameProps, InitGameState> {

      constructor(props: InitGameProps) {
        super(props);
        this.state = { isEmpty:false, name:"Juancito", submitted:true, usuario:userData2
    };
        console.log(this.state);
    }

      render() {
          return <Config socket={this.props.socket} name={this.state.name} />;
        }
    }

    export default InitGame;

Si hago console.log veo los resultados (linea 13 de InitGame.tsx), tal como quisiera, pero no logro que los mismos se muestren en el parametro "usuario" (Linea 34 de InitGame.tsx) y solo muestra lo que parece ser una funcion.

React version 17.0.2
Firebase version 9.6.4
Typescript version 4.5.5
Gracias desde ya.


text:
Q: Magento 2, certification exam Can any one please share links for the

study material for magento 2 certification exam (dump)

I know many questions related to this is asked before many times. But all those question are not satisfactory, and as we know day by day era is changing, with positive vibes, I want to know is something get update regarding magento2. Hope some body can help me for the same.
I HAVE REFERED THESE LINKS AS WELL
For Developer Certification: Fundamentals of Magento 2 Development
For Frontend Certification: Core Principles of Theming in Magento 2
except these if any information is updated regarding this. I am glad to thank for the participation of that guy who help me for the same.
Thank you.

A: Update 2018-04-30:
Magento U has now released three Magento 2 certifications. There's also a Frontend Developer Certification under work that should be available within several months, and I've heard rumor of a JS Certification a year or two down the road. You can view all certifications on the Magento U website.
Study guides for each certification can be requested here: Download A Free Magento Study Guide
The available M2 certifications are:
Magento 2 Certified Solution Specialist: "Magento 2 Certified Solution Specialists have demonstrated a thorough understanding of how to leverage Magento 2 functionality to satisfy ecommerce business goals according to best practices."
Magento 2 Certified Professional Developer: "Magento 2 Certified Professional Developers have demonstrated a deep understanding of how to customize Magento 2 source code in accordance with Magento best practices." This is targeted at backend developers with 1.5+ years experience with Magento 2.
Magento 2 Certified Associate Developer: "This exam is for a developer who is beginning their career as a Magento Developer and is designed to validate the student's skills and knowledge of Magento 2 in the areas of: UI modifications, database changes, admin modifications, customizations, catalog and checkout structure, and functionality changes."
Upcoming: Magento 2 Certified Frontend Developer

Original Answer:
There is no Magento 2 certification exam yet, so there are no resources for studying/training for the M2 certification exam. Anything saying otherwise, as of this writing, is lying.
The latest rumors I've heard are that M2 certification will be coming sometime after the release of Magento 2.2. It's likely M2 certification will be released in late 2017 or early 2018.
See also: Certification and training - Magento 1 vs Magento 2

A: You can get sample study guide from below link, Which is written by Joseph Maxwell and he is one of the first to have taken and passed the Certified Developer exam
It has 177 pages full of helpful and informative content. This not only makes you a better developer, but will help you pass the test.
https://swiftotter.com/technical/certifications/magento-2-certified-developer-study-guide

A: There are 3 certifications:

*

*MAGENTO 2 CERTIFIED SOLUTION SPECIALIST https://u.magento.com/certified-magento2-solution-specialist#.WtnrBnVuZhE

*MAGENTO 2 CERTIFIED PROFESSIONAL DEVELOPER https://u.magento.com/magento-2-certified-professional-developer#.WtnrCHVuZhE

*MAGENTO 2 CERTIFIED ASSOCIATE DEVELOPER EXAM https://u.magento.com/magento-2-certified-associate-developer-exam#.WtnrC3VuZhE

A: You can try Magento questions dump with this link. I had follow and pass exam with that questions dump 70% correct.

A: I practiced here https://m2professional.dev, but real expirince was  more reliable on the final exam.

A: Latest study guide certifications:updated [21 August 2020]:

*

*[AD0-E700]: Adobe Certified Expert Magento Commerce Business Practitioner Details

*[AD0-E701]: Adobe Certified Expert-Magento Commerce Front-End Developer Details

*[AD0-E702]: Adobe Certified Professional—Magento Commerce Developer Details

*[AD0-E703]: Adobe Certified Expert - Magento Commerce Developer Details

*[AD0-E704]: Adobe Certified Master Magento Commerce Architect Details

*[AD0-E705]: Adobe Certified Expert-Magento Commerce JavaScript Developer Details

*[AD0-E706]: Adobe Certified Expert-Magento Commerce Cloud Developer [available since June 2018] Details

*[Adobe AD0-E707] Adobe Certified Expert Magento Commerce Order Management Developer Details


text:
Q: Docker Java Application failing at obtaining input from console I am trying to create a docker image for my java application. At startup this application needs to be given a password (currently via console).
I tried several methods of obtaining input however they have all failed. Is this a limitation of docker and if so is there a workaround?
For this snippet:
Console console = System.console();
if(console == null){
    System.out.println("console is null!!");
} else {
    System.out.println("Input password: ");
    char[] password = console.readPassword("Pass: ");
}

System.console() is returning null.
For this snippet:
    System.out.println("Creating InputStreamReader");
    InputStreamReader s = new InputStreamReader(System.in);
    System.out.println("Creating BufferedReader");
    BufferedReader r = new BufferedReader(s);
    System.out.println("Input password: ");
    String password = r.readLine();
    System.out.println("Password: "+password);

the input is automatically skipped, (resulting in the String password to be null) with the program continuing execution as if there was no input requested. (password is null)
For this snippet:
Scanner s = new Scanner(System.in);
System.out.println("Input password: ");
String password = s.next();

I get
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at com.docker.test.DockerTest.testScanner(DockerTest.java:49)
    etc...

I am running the program from within my image using docker run test/plaintest1
my dockerfile is as follows
FROM centos
RUN yum install -y java-1.7.0-openjdk
ADD DockerTest.jar /opt/ssm
ENTRYPOINT ["java","-jar","/opt/ssm/DockerTest.jar"]
CMD [""]

A: Solved it.
By running the command using the -i and -t parameters you can be allowed to enter the password. using all 3 methods.
so basically docker run -i -t <imagename> <params>

A: I was struggling with this yesterday for most of the day. The problem seemed to have been a broken base image supplied by the official CentOS repo. If you look on your base image you will notice that /opt/java exists on the base image. That's the clue that you have the broken image. Simply pull the latest image with "docker pull centos" and you'll be back in action. They must have fixed it sometime last night. You'll notice the hash of the image has changed even though it shows that the image was uploaded 2 weeks ago. Someone is trying to hide their tracks! Haha. Your Dockerfile is fine.
Regards
Wynand


text:
Q: Difference between "saw you" and "have seen you" What is the difference between the two statements?

*

*I saw you recently

*I have seen you recently

Are both the statements correct? If correct, then why?
Explain the difference between specified timing and unspecified timing with examples.

A: Grammatically, they are written correctly. However, each has a different meaning.
The first one is Past Tense. That means the action of the person seeing you started and ended before now, which is some specific time in the past. The adverb recently tells to what extent the person saw you. The adverb is modifying the verb saw to mean "not long ago."
http://www.merriam-webster.com/dictionary/recently
The other sentence uses the Present Perfect Tense, which can mean two things, an action that started and ended at no definite time in the past OR an action that started in the past and continues up to now. I'm sure for your sentence, it means an action that started and ended at no definite time in the past.
You see, the Past Tense has a definite time in the past. For example, the person saw you at exactly 2 o'clock yesterday afternoon; with the other, there is no definite time. You may wonder why is that important about what time in the past?
Watch...
Speaker: The police are looking for Jim. I think he's in trouble.
Alex: Wow! I saw him yesterday at the gym. [a specific time]
Carol: I have seen him at the library, but I forget when. [no specific time can be determined]

A: Well both are correct, i mean they grammatically are. The first statement is a generalised way of implying that the process of 'seeing' happened sometimes in the past, while the second one emphasises on a more recentness of the act of being 'seeing' in respect of the present.
For more clarification and understanding on this very subject, do look into the implications of a statement in Past Tense and that in a Present Perfect Tense in any book dealing with generative grammar. Hope I have been helpful to some extent. #Thank_You :)


text:
Q: Create a table from CSV columns in SQL Server without using a cursor Given a table:
|Name    | Hobbies                |
-----------------------------------
|Joe     | Eating,Running,Golf    |
|Dafydd  | Swimming,Coding,Gaming |

I would like to split these rows out to get:
|Name    | Hobby     |
----------------------
|Joe     | Eating    |
|Joe     | Running   |
|Joe     | Golf      |
|Dafydd  | Swimming  |
|Dafydd  | Coding    |
|Dafydd  | Gaming    |

I have completed this below (example is ready to run in SSMS), buy my solution uses a cursor which I think is ugly. Is there a better way of doing this? I am on SQL Server 2008 R2 if there is anything new which will help me.
Thanks
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Split]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].Split
go
CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces
  )

go

declare @inputtable table (
    name varchar(200) not null,
    hobbies varchar(200) not null
)

declare @outputtable table (
    name varchar(200) not null,
    hobby varchar(200) not null
)

insert into @inputtable values('Joe', 'Eating,Running,Golf')
insert into @inputtable values('Dafydd', 'Swimming,Coding,Gaming')

select * from @inputtable

declare inputcursor cursor for
select name, hobbies
from @inputtable

open inputcursor

declare @name varchar(255), @hobbiescsv varchar(255)
fetch next from inputcursor into @name, @hobbiescsv
while(@@FETCH_STATUS <> -1) begin

    insert into @outputtable
    select @name, splithobbies.s
    from dbo.split(',', @hobbiescsv) splithobbies

    fetch next from inputcursor into @name, @hobbiescsv
end
close inputcursor
deallocate inputcursor

select * from @outputtable

A: Use a string parsing function like the one found here. The key is to use CROSS APPLY to execute the function for each row in your base table.
CREATE FUNCTION [dbo].[fnParseStringTSQL] (@string NVARCHAR(MAX),@separator NCHAR(1))
RETURNS @parsedString TABLE (string NVARCHAR(MAX))
AS
BEGIN
   DECLARE @position int
   SET @position = 1
   SET @string = @string + @separator
   WHILE charindex(@separator,@string,@position) <> 0
      BEGIN
         INSERT into @parsedString
         SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position)
         SET @position = charindex(@separator,@string,@position) + 1
      END
     RETURN
END
go

declare @MyTable table (
    Name char(10),
    Hobbies varchar(100)
)

insert into @MyTable
    (Name, Hobbies)
    select 'Joe', 'Eating,Running,Golf'
    union all
    select 'Dafydd', 'Swimming,Coding,Gaming'

select t.Name, p.String
    from @mytable t
        cross apply dbo.fnParseStringTSQL(t.Hobbies, ',') p

DROP FUNCTION [dbo].[fnParseStringTSQL]

A: Create this function in your DB:
CREATE FUNCTION dbo.Split(@origString varchar(max), @Delimiter char(1))
returns @temptable TABLE (items varchar(max))
as
begin
    declare @idx int
    declare @split varchar(max)

    select @idx = 1
        if len(@origString )<1 or @origString is null  return

    while @idx!= 0
    begin
        set @idx = charindex(@Delimiter,@origString)
        if @idx!=0
            set @split= left(@origString,@idx - 1)
        else
            set @split= @origString

        if(len(@split)>0)
            insert into @temptable(Items) values(@split)

        set @origString= right(@origString,len(@origString) - @idx)
        if len(@origString) = 0 break
    end
return
end

and then simply call it in your Select statement and use cross apply to join to the function
Select t.Name,
       s.items as 'Hobby'
from dbo.MyTable as t
Cross Apply dbo.Split(t.Hobbies,',') as s

A: Just do the following:
select *
from @inputtable
outer apply dbo.split(',', hobbies) splithobbies

A: I generally prefer to use XML to split CSV list to table valued format. You can check this function:
CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN
   (
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM
      (
        SELECT x = CONVERT(XML, ''
          + REPLACE(@List, @Delimiter, '')
          + '').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );
GO

and the following article for more techniques showing how to do this. Then, you just need to use CROSS APPLY clause to apply the function.


text:
Q: Disabling of TCP SYN retransmission I am developing a client which connects to server through TCP. Servers are configured such that if one server is down, connection is set up with another server.
My requirement is that if TCP connection is not established with the 1st server within 2s, client needs to establish connection with the 2nd server.
Below is my observation based on testing-
TCP SYN message is sent by client to the 1st server to establish connection. Since 1st server is down, after 1s, TCP SYN retransmission is sent to the 1st server. After 2s(owing to processing and network delays), TCP SYN message is sent to the 2nd server by the client. So its taking 3s (1s + 2s) for the SYN message to be sent to the 2nd server, which is not what I wanted. I want the TCP SYN message to be sent to 2nd server within 2s.
In order to send TCP SYN message to the 2nd server within 2s, I want to avoid TCP SYN retransmission.
I tried setting net.ipv4.tcp_syn_retries=0 in /etc/sysctl.conf. But I get 1 TCP SYN retransmission.
So is there any way to disable TCP SYN retransmission from userspace without changing the kernel source?

A:
My requirement is that if TCP connection is not established with the 1st server within 2s, client needs to establish connection with the 2nd server.

In this case just do a connect with a timeout of 2 seconds at the client and if the connect does not succeed retry with the other server. Once you have closed the socket the kernel will stop trying to connect to the first server. This is much better and more independent from a specific platform than to fiddle with the built in reliability behavior and timing of TCP.


text:
Q: MutableList map extension function outputs immutable List I want to map all my items in MutableList into other items:
(0..10).toMutableList().map { 1 }

What I have after is just List
(0..10).toMutableList().map { 1 }.toMutableList() //ok

Is there any mapMutable method? Or maybe this is wrong?

A: There's mapTo which let's you specify where to map the values into:
val origList = (0..10).toMutableList()
val mappedList = origList.mapTo(mutableListOf()) { 1 }

A: Since map returns List and not MutableList, you have 2 choices:
val list = (0..10).map { 1 }.toMutableList()

or
val list: MutableList<Int> = mutableListOf()
(0..10).mapTo(list) { 1 }


text:
Q: Camel Salesforce Kafka Source Connector does not start I am trying to run the Camel Salesforce Kafka Source Connector version 1.0.x (LTS) and following the documentation as described on https://camel.apache.org/camel-kafka-connector/1.0.x/reference/connectors/camel-salesforce-source-kafka-source-connector.html all I need to do is to configure a bunch of camel.kamelet.salesforce-source.xxx properties which is exactly what I did.
Let's just assume that camel.kamelet.salesforce-source.clientId=xyz
When trying to run the connector it fails to start complaining that clientId is an unknown parameter:
Failed to resolve endpoint: salesforce://event/Case__e?clientId=xyz due to:
There are 1 parameters that couldn't be set on the endpoint.
Check the uri if the parameters are spelt correctly and that they are properties of the endpoint.
Unknown parameters=[{clientId=xyz}]

Running out of ideas I tried to configure a camel route myself and specified the clientId part of the salesforce endpoint. The issue was exactly the same. Running out of ideas I asked this question Unable to create camel salesforce endpoint and got a valid explanation for that behaviour: This type of settings should be done at component level not at endpoint level.
Digging further I checked that version 0.11.x (LTS) allows us to configure camel.component.salesforce.xxx properties as opposed to 1.0.x (LTS) which only has camel.kamelet.salesforce-source.xxx. In fact I was able to start the 0.11.x (LTS) connector.
Now it is hard to believe the migration from 0.11.x to 1.0.x was not fully tested and I am tempted to say I am missing some basic setup.
Can anyone bring some light in here?
Thank you in advance for your inputs.


text:
Q: Xamarin Forms Button pressed event for 3 seconds executes action or nothing I need to write a event behind a button, when i pressed it for 3 seconds a method must executes. If i released it before the 3 seconds, it doesnt do anything.
Any ideas?
Thanks!

A: Since Xamarin Forms 2.4, buttons have included Pressed and Released events.
Start a 3 second timer in the Pressed event. Cancel it in the Released event if it hasn't fired.


text:
Q: Writing data to sqlite xCode first of all I am from spain so sorry about my grammar. I am writing some data to a sqlite data base, here is my code:
@try {

    NSFileManager *fileMgr=[NSFileManager defaultManager];

    NSString *dbPath=[[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:@"capturas.sqlite"];
    BOOL succes=[fileMgr fileExistsAtPath:dbPath];
    if(!succes)
    {
        NSLog(@"Cannot locate database '%@'.",dbPath);
    }
    if (!(sqlite3_open([dbPath UTF8String], &dbcapturas)==SQLITE_OK)) {
        NSLog(@"An error has occured: %@",sqlite3_errmsg(dbcapturas));
    }

    //sqlite3_stmt *sqlStatement;
    NSString *asd=numero.text;
    NSString *insertStatement=[NSString stringWithFormat:@"INSERT INTO captura(key,tecnico, fecha,provincia,municipio,latitud,longitud,altura,familia,especie,numero,comentario)Values(\"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\")",asd,tecnico,fechaHora,tecnico,municipio,latitud,longitud,altura,tecnico,animal,asd,coment];
    char *error;
    if((sqlite3_exec(dbcapturas, [insertStatement UTF8String], NULL, NULL, &error))==SQLITE_OK)
    {
        NSLog(@"Person inserted.");
    }
    else
    {
        NSLog(@"Error: %s", error);
    }
} @catch (NSException *exception) {
    NSLog(@"fail");
}
@finally {

}

the first time I click on the save button I get:

2012-07-04 12:17:45.644 adasdasd[1783:f803] Person inserted.

and the second time I get :

2012-07-04 12:29:18.959 adasdasd[1840:f803] Error: column key is not unique

So my code should be ok but when I open the database its totally empty, any idea?

A: You have your SQLITE db file in your main bundle. All files in the main bundle are read-only. You need to copy the db to the Documents folder.
Try this out (from http://www.iphonedevsdk.com/forum/iphone-sdk-development/17262-sqlite-database-works-fine-on-simulator-but-is-readonly-on-device.html):
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@\"database_name.sql\"];
success = [fileManager fileExistsAtPath:writableDBPath];
// NSLog(@\"path : %@\", writableDBPath);
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@\"database_name.sql\"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success)
{
NSAssert1(0, @\"Failed to create writable database file with message '%@'.\", [error localizedDescription]);
}
}


text:
Q: How to return a future combinator with `&self` I have this piece of code using futures v0.1:
impl ArcService for (Box<MiddleWare<Request>>, Box<ArcService>) {
    fn call(&self, req: Request, res: Response) -> Box<Future<Item = Response, Error = Error>> {
        box self.0.call(req).and_then(move |req| self.1.call(req, res))
    }
}

pub trait ArcService: Send + Sync {
    fn call(&self, req: Request, res: Response) -> Box<Future<Item = Response, Error = Error>>;
}

pub trait MiddleWare<T>: Sync + Send {
    fn call<'a>(&'a self, param: T) -> Box<Future<Item = T, Error = Error> + 'a>;
}

type MiddleWareFuture<'a, I> = Box<Future<Item = I, Error = Error> + 'a>;

impl MiddleWare<Request> for Vec<Box<MiddleWare<Request>>> {
    fn call(&self, request: Request) -> MiddleWareFuture<Request> {
        self.iter()
            .fold(box Ok(request).into_future(), |request, middleware| {
                box request.and_then(move |req| middleware.call(req))
            })
    }
}

pub struct ArcRouter {
    routes: HashMap<Method, Box<ArcService>>,
}

// Service implementation
impl hyper::Server::Service for ArcRouter {
    type Response = Response;
    type Request = Request;
    type Error = hyper::Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn call(&self, req: Request) -> Box<Future<Item = Self::Response, Error = Self::Error>> {
        if let Some(routeMatch) = self.matchRoute(req.path(), req.method()) {
            let mut request: ArcRequest = req.into();
            request.paramsMap.insert(routeMatch.params);
            let response = routeMatch.handler //handler is ArcService
                    .call(request, ArcResponse::new())
                    .map(|res| res.into());
            return box response;
        }

        // TODO: this should be handled by a user defined 404 handler
        return box Ok(Response::new().with_status(StatusCode::NotFound)).into_future();
    }
}

Note the lifetime parameter on Middleware — it is used to avoid lifetime issues.
This does not compile because Box<Future<Item = Response, Error = Error>> is implicitly 'static and therefore causes lifetime issues. hyper::Server::Service requires a 'static Future
Here is an example that aptly describes my problem:
extern crate futures; // v0.1 (old)

use futures::{future, Future};

struct Example {
    age: i32,
}

// trait is defined in an external crate. You can't change it's definition
trait MakeFuture {
    fn make_a_future(&self) -> Box<Future<Item = i32, Error = ()>>;
}

impl MakeFuture for Example {
    fn make_a_future(&self) -> Box<Future<Item = i32, Error = ()>> {
        let f = future::ok(self).map(|ex| ex.age + 1);
        Box::new(f)
    }
}

playground link
which gives the lifetime error:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:16:28
   |
16 |         let f = future::ok(self).map(|ex| ex.age + 1);
   |                            ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 15:5...
  --> src/main.rs:15:5
   |
15 | /     fn make_a_future(&self) -> Box<Future<Item = i32, Error = ()>> {
16 | |         let f = future::ok(self).map(|ex| ex.age + 1);
17 | |         Box::new(f)
18 | |     }
   | |_____^
note: ...so that expression is assignable (expected &Example, found &Example)
  --> src/main.rs:16:28
   |
16 |         let f = future::ok(self).map(|ex| ex.age + 1);
   |                            ^^^^
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that expression is assignable (expected std::boxed::Box<futures::Future<Item=i32, Error=()> + 'static>, found std::boxed::Box<futures::Future<Item=i32, Error=()>>)
  --> src/main.rs:17:9
   |
17 |         Box::new(f)
   |         ^^^^^^^^^^^

Is there a way to get around this? I'm building with hyper::Service and using Rust v1.25.0 (nightly)

A:
How to return a future combinator with &self

You return a future that refers to self like this:
use futures::future::{self, FutureResult}; // 0.1.28

struct Example {
    age: i32,
}

impl Example {
    fn make_a_future(&self) -> FutureResult<&Example, ()> {
        future::ok(self)
    }
}

As discussed in the Tokio documentation on returning futures, the easiest stable solution to returning a complicated future is a impl Trait. Note that we assign an explicit lifetime to self and use that in the returned value (via + 'a):
use futures::{future, Future}; // 0.1.28

struct Example {
    age: i32,
}

impl Example {
    fn make_a_future<'a>(&'a self) -> impl Future<Item = i32, Error = ()> + 'a {
        future::ok(self).map(|ex| ex.age + 1)
    }
}

Your real question is "how can I lie to the compiler and attempt to introduce memory unsafety into my program?"
Box<SomeTrait + 'static> (or Box<SomeTrait> by itself) means that the trait object must not contain any references that do not last for the entire program. By definition, your Example struct has a shorter lifetime than that.
This has nothing to do with futures. This is a fundamental Rust concept.
There are many questions that ask the same thing in regards to threads, which have similar restrictions. A small sampling:

*

*Lifetime of variables passed to a new thread

*How do I use static lifetimes with threads?

*The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want

*Lifetime troubles sharing references between threads
Like in those cases, you are attempting to share a reference to a variable with something that may exist after the variable is destroyed. Languages such as C or C++ would let you do this, only to have your program crash at a seemingly random point in time in the future when that variable is accessed after being freed. The crash is the good case, by the way; information leaks or code execution is also possible.
Like the case for threads, you have to ensure that this doesn't happen. The easiest way is to move the variable into the future, not sharing it at all. Another option is to use something like an Arc around your variable, clone the Arc and hand the clone to the future.


text:
Q: Soma de todos os números inteiros dentro de uma List Tenho um metodo:
public static int soma(params int[] n)
        {
            int resultado = 0;

            for (int i = 0; i < n.Length; i++)
            {
                resultado += n[i];
            }

            return resultado;
        }

No meu console:
List<int> numeros = new List<int>();

Console.WriteLine("Digite um numero");
numeros.Add(int.Parse((Console.ReadLine())));

resultado = soma(numeros); //Gera erro de conversão de list Generics para int

Estou com a dúvida de como passar uma lista de parametros inteiros que o usuario digita para o metodo. E também como deixa o usuário parar de digitar para efetuar a soma.
Ex: ele vai digitando [1 2 3 4 5 6 8 9] e quer para e somar, não estou sabendo o comando para interromper.

A: dentro da função soma, meta a entrar uma variável do tipo List, e basta trocar esse 'for' por um 'foreach', ficara assim:
public static int soma(List<int> nomedalista){
                 int resultado = 0;
                 foreach(int x in nomedalista){
                        resultado+=x;
                 }
return resultado;
}