text:
Q: C++ Passing Rvalue Reference to Functions That Takes Lvalue Reference When I was reading Effective Modern C++ by Scott Meyer about how std::forward function works, I got one question that I don't quite understand. Say if we have a function foo as follows:
template<typename T>
void foo(T&& fooParam)
{
    ...
    someFunc(std::forward<T>(fooParam));
}

In the book, Scott explains that the std::forward<T> could be implemented in the following way:
template<typename T>
T&& forward(typename remove_reference<T>::type& param)
{
    return static_cast<T&&>(param);
}

Suppose the argument passed to foo is an rvalue of type Widget. Then the std::forward function template would be initialized like this:
Widget&& forward(Widget& param)
{ return static_cast<Widget&&>(param); }

So my question is, when fooParam (which is of type Widget &&) passed to std::forward, how could the function that takes a parameter of type Widget& param match fooParam? I know fooParam itself is a lvalue. But its type is still rvalue reference (Widget &&) right? How could they match each other?
If a function which takes a parameter of lvalue reference type could be passed with a rvalue reference, then this function could do whatever it wants to even modify the passed in rvalue (like a temporary object). This doesn't make sense to me...

A: #include <iostream>
using std::cout;
using std::endl;

template<class T>
void my_print(T&& arg)
{
    my_print_impl(std::forward<T>(arg));
}
template<class T>
void my_print_impl(T& arg)
{
    cout << "lvalue reference" << endl;
}

template<class T>
void my_print_impl(T&& arg)
{
    cout << "rvalue reference" << endl;
}

int main()
{
    int i = 1;
    int & l_ref = i;
    int && r_ref = 1;
    my_print(l_ref);            //print lvalue reference
    my_print(r_ref);            //print lvalue reference
    my_print(std::move(l_ref)); //print rvalue reference
    my_print(1);                //print rvalue reference, 1 is a true rvalue
    system("pause");

    return 0;
}

As you say, r_ref is a lvalue reference, you should not make it to match as a rvalue reference.If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.


text:
Q: gradlew assembleDebug fails because of transformClassesWithJarMergingForDebug When i build my android application using "Build->Build Project" on android studio. it works fine. But when i run:
gradlew assembleDebug

from terminal. Build fails and prints this message:
* What went wrong:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/slf4j/impl/StaticLoggerBinder.class

What is the difference between two methods? How can i solve this problem because i have to create my .apk file using gradle scripts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set an Enum's numeric value Is there a way to set the underlying value of an enum (e.g. via reflection)?
And what will happen if there is no matching enum entry for the set value?
Bonus: What would be the implications for someone using the enum after it was set to an "invalid" value?
Thanks!
Edit: (Use-Case)
One use-case would be for testing purposes.
Assume you have a protocol with a message type field represented by a enum, transferred as a byte in the protocol.
Now what if I want to test some message type field values which are invalid, aka not defined and thus not part of the enum.
Bonus 2:
Hoiw would that cast look like if the enum type is dynamic as opposed to fixed. E.g. assume you get handed a enum type object and want to set its underlying value to 1.

A: I'll try to answer all of your questions
Given
public enum SomeEnum
{
    Bob,
    Blip
}

Is there a way to set the underlying value of an enum

Yes..
myEnum = (SomeEnum)1; ///  = Blip

And what will happen if there is no matching enum entry for the set
value?

Nothing...
myEnum = 3;

If(myEnum == SomeEnum.Bob)
   // never gets hit

What would be the implications for someone using the enum after it was
set to an "invalid" value?

Same as above
Consider
SomeEnum myEnum;

myEnum = (SomeEnum)1;
Console.WriteLine(myEnum);

myEnum = (SomeEnum)3;
Console.WriteLine(myEnum);

Output
Blip
3

Though you could imagine a situation where someone ranges checks an enum
var myEnum = (SomeEnum)3;

switch (myEnum)
{
    case SomeEnum.Bob:
       break;
    case SomeEnum.Blip:
       break;
    default:
       throw new ArgumentOutOfRangeException();
 }

In which case an exception will get thrown

Now what if I want to test some message type field values which are
invalid, aka not defined and thus not part of the enum.

you could use the Enum.IsDefined Method

Returns a Boolean telling whether a given integral value, or its name
as a string, exists in a specified enumeration.

Example
if(!Enum.IsDefined(SomeWeirdReflectedType, someValue))
  ...

How would that cast look like if the enum type is dynamic as opposed
to fixed

You can use Enum.ToObject convert an integer to an enum value at runtime

Converts a specified integer value to an enumeration member.

Example
var someEnumType = typeof(SomeEnum);

var asd = Enum.ToObject(someEnumType, 1);

Console.WriteLine(asd);
Console.WriteLine(asd.GetType());

Output
Blip
ConsoleApp1.Program+SomeEnum


text:
Q: Embedded Signing - Signing from My App I'm working on get the signing process on an iFrame to Embedded docusign on my app.
I have trying to work on this based on this tutorials:
Docusign Embedded Signing using template
https://developers.docusign.com/esign-rest-api/guides/features/embedding
Based on what I understood, if you want to embedded you have to create the "create the envelope on the fly". So you don't specify the templateId correct?
So what I don't fully get is, how I get the documentBase64 string value? I have to get it manually? Or docusing api has an endpoint that will return that?
Also I want to know, what happen to the custom fields I added to the template? I can't use them?
Right now this is the json I'm sending:
{{baseUrl}}/envelopes
{

  "emailSubject":"This is a custom email subjet, look at the doc.",

  "status":"sent",

  "templateId":"a0847413-35ac-48ed-9ed6-9b7f96019eda",

  "templateRoles":[
    {

      "email":"mauriciotaranto@email.com",

      "name":"Mauricio T",

      "clientUserId": "1234",

      "roleName":"Test",

      "routingOrder":"1",

       "tabs": {

        "textTabs": [

          {

            "tabLabel": "Custom",

            "value": "This is a custom value"

          },
           {
            "tabLabel": "NewCustom",
            "value": "Another custom value added using API"
        },
        {
            "tabLabel": "NewCustom1",
            "value": "Last custom value added using API"
        }

        ]

      }

    }

  ],

  }

And then I go to the recipient view to get the URL:
{{baseUrl}}/envelopes/{{envelopeId}}/views/recipient
{
    "returnUrl": "https://www.google.com.uy",
    "authenticationMethod": "None",
    "email": "mauriciotaranto@email.com",
    "userName": "Mauricio T",
    "clientUserId": "1234"
}

As far as I understood this way will not allow the user to sing the document.
Need to do it with the document instead.
Can you explain to me how this should work?
Thanks!
UPDATE:
Im manually parsing the bytes of the document to base64. and send this json:
"status":"sent",
"emailSubject":"Envelope with Embedded Signer",
"documents":[
   {
      "documentId":"1",
      "name":"contract.pdf",
      "documentBase64":bytes
   }
],
"recipients":{
   "signers":[
      {
         "email":"mauriciotaranto@hotmail.com",
         "name":"Mauricio T",
         "recipientId":"1",
         "clientUserId":"1234"
      }
   ]
}
}

I change the headers, add the accept: application/json and content-type: multipart/from-data
And this is the response I get:
{
    "errorCode": "ENVELOPE_IS_INCOMPLETE",
    "message": "The Envelope is not Complete. A Complete Envelope Requires Documents, Recipients, Tabs, and a Subject Line. Content-Type does not contain boundary parameter."
}

A: You can create envelopes in any way, either by using Templates or by passing base64 of document or both as well using Composite Template. When you send templates, then you already have added signers tabs on the document in the templates so you just need to populate the signer details like name and email in creating an envelope and/or pre-populate the DS Tabs value. But when you send document as base64,  then you need to tell DocuSign how to add DS Tabs on the document, either by using

*

*X and Y position of the tabs

*AnchorString

*PDF Field Transformation

Embedded Signing is a type of signing, to implement that you need to just add clientUserId in the signers details. This can be done in both ways either by using template or by passing document as base64 or both as well using Composite Template. Once you have an embedded signer by adding clientUserId then you need to generate signing URL as explained in your qs, by using Recipient View URL, as soon as URL is generated then you will open this URL in IFrame or on new tab.
In the link which you shared is having very small code snippet and it does not have complete example, check Complete Example, and you will see that they are adding DS Tabs on the document using X/Y position.


text:
Q: install php-mcrypt on Centos 6 I'm trying to install php-mcrypt on my Centos 6.0, 64 bit, php 5.3.3.
I'm using epel repo rpm -Uvh http://download.fedora.redhat.com/pub/epel/6/x86_64/epel-release-6-5.noarch.rpm, the last one.
But after I run yum install php-mcrypt I'm getting an error
   [root@CentOS-60-64-minimal ~]# yum install php-mcrypt
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: centos.kiewel-online.ch
 * epel: mirror.fraunhofer.de
 * extras: centos.kiewel-online.ch
 * rpmforge: ftp-stud.fht-esslingen.de
 * updates: centos.kiewel-online.ch
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php-mcrypt.x86_64 0:5.1.6-5.el5 will be installed
--> Processing Dependency: php-api = 20041225 for package: php-mcrypt-5.1.6-5.el5.x86_64
--> Processing Dependency: libmcrypt.so.4()(64bit) for package: php-mcrypt-5.1.6-5.el5.x                                     86_64
--> Running transaction check
---> Package libmcrypt.x86_64 0:2.5.7-5.el5 will be installed
---> Package php-mcrypt.x86_64 0:5.1.6-5.el5 will be installed
--> Processing Dependency: php-api = 20041225 for package: php-mcrypt-5.1.6-5.el5.x86_64
--> Finished Dependency Resolution
**Error:** Package: php-mcrypt-5.1.6-5.el5.x86_64 (epel)
           **Requires: php-api = 20041225**
           Installed: php-common-5.3.3-3.el6_1.3.x86_64 (@updates)
               php-api = 20090626
           Available: php-common-5.3.3-3.el6.x86_64 (base)
               php-api = 20090626
 You could try using --skip-broken to work around the problem

Why epel doesn't give last mcrypt for me? php-mcrypt-5.1.6-5.el5.x86_64 is not the latest version on the repo... What can I do?

A:
Package php-mcrypt.x86_64 0:5.1.6-5.el5 will be installed

Pay attention to the el5, it means that this package is pulling from the EL5 repo. Make sure that the epel-release-6-5.noarch.rpm has been installed successfully:
$ rpm -qa | grep epel
epel-release-6-5.noarch

and the mirrorlist (in /etc/yum.repos.d/epel.repo) point to the right path:
[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

(epel-6 instead of epel-5)

A: If anyone encounters this in future I did this:
Removed the previous EPEL install.
yum remove epel-release
Then install the latest version for CentOS 6.
$ cd /tmp
$ wget http://mirror-fpt-telecom.fpt.net/centos/6.6/extras/x86_64/Packages/epel-release-6-8.noarch.rpm
$ rpm -ivh epel-release-6-8.noarch.rpm
And from then on I just ran the yum install php-mcrypt command and php-mcrypt installed fine.

A: You can try this :
wget http://dag.wieers.com/rpm/packages/libmcrypt/libmcrypt-2.5.7-1.2.el6.rf.x86_64.rpm
wget http://dag.wieers.com/rpm/packages/libmcrypt/libmcrypt-devel-2.5.7-1.2.el6.rf.x86_64.rpm
rpm -Uvh libmcrypt-*.rpm
I use this for a long time without any problem.


text:
Q: SQL Server Kafka connector in standalone mode not loading data in kafka I am using JDBC source Kafka connector to dump data from the SQL Server to Kafka in standalone mode. I have downloaded the confluentinc-kafka-connect-jdbc-5.5.0.zip for the JDBC connector jars & copied all the jars at plugin.path. I am using the below worker & connector configuration.

*

*worker.peroperties
  value.converter=org.apache.kafka.connect.json.JsonConverter
  key.converter=org.apache.kafka.connect.json.JsonConverter
  bootstrap.servers=localhost:9092
  plugin.path=/home/kafka_2.12-2.5.0/connector/plugin/
  offset.storage.file.filename=file

*connector1.properties
  name=test12_connector
  connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
  connection.url=jdbc:sqlserver://host;databaseName=db;
  connection.user=user
  connection.password=password
  query=SELECT TOP 100 * FROM table;
  topic.prefix=test-
  mode=bulk

I am running connector in standalone mode using below command-
sh bin/connect-standalone.sh -daemon connector/worker.properties connector/connector1.properties

I am using the latest SQL Server JDBC driver & copied at the same plugin path.
Also, added same plugin.path in CLASSPATH.
But the issue I am facing that it is getting stuck at below lines in logs & not producing any data in the topic from the table (expected topic: test-table)
-logs
[2020-06-29 18:41:31,402] DEBUG Dialect SqlServerDatabaseDialect scored 100 against JDBC subprotocol 'sqlserver' and source 'jdbc:sqlserver://host:1433;databaseName=db;' (io.confluent.connect.jdbc.dialect.DatabaseDialects:127)
[2020-06-29 18:41:31,402] DEBUG Dialect SqliteDatabaseDialect scored 0 against JDBC subprotocol 'sqlserver' and source 'jdbc:sqlserver://host:1433;databaseName=db;' (io.confluent.connect.jdbc.dialect.DatabaseDialects:127)
[2020-06-29 18:41:31,402] DEBUG Dialect SybaseDatabaseDialect scored 100 against JDBC subprotocol 'sqlserver' and source 'jdbc:sqlserver://host:1433;databaseName=db;' (io.confluent.connect.jdbc.dialect.DatabaseDialects:127)
[2020-06-29 18:41:31,403] DEBUG Dialect VerticaDatabaseDialect scored 0 against JDBC subprotocol 'sqlserver' and source 'jdbc:sqlserver://host:1433;databaseName=db;' (io.confluent.connect.jdbc.dialect.DatabaseDialects:127)
[2020-06-29 18:41:31,403] DEBUG Using dialect SqlServerDatabaseDialect with score 100 against JDBC subprotocol 'sqlserver' and source 'jdbc:sqlserver://host:1433;databaseName=db;' (io.confluent.connect.jdbc.dialect.DatabaseDialects:133)

It is not even showing any error logs. I have changed the log level to TRACE but still, the connector is not showing any error & only shows the above logs.
Please help me out if I am missing anything.

A: I'd try to play with connector properties probably adding:
"tasks.max": "1",
"internal.key.converter.schemas.enable": "false",
"reporter.admin.bootstrap.servers": "localhost:9092",
"internal.value.converter.schemas.enable": "false",

It also seems that it hangs not getting connection to source SQL server, so either connection string is not right or it can't find the driver JAR file for this dialect.
Check the logs if JDBC SQL Server dialect driver is loaded.


text:
Q: How is SELinux loaded on boot? I understand that a configuration file is in:
/etc/selinux/config

But how is it processed at boot? How does SELinux start, is it a daemon? Which startup script starts SELinux?

A: SELinux policy is loaded by init in early boot. Init checks that SELinux is enabeld, after which it loads the policy and re-executes itself in correct security context.
Sources: RHEL4 documentation, Ubuntu Hardy, systemd


text:
Q: Calculate lateral drift when driving straight with 2D GPS data I have a set of GPS data in 2D. I want to calculate a 2D vector or function going straight through this set of data. When this vector/line is obtained I want to calculate the distances from the vector/line to each GPS data sample (90 degrees from the line) in order to determine how accurate the object with GPS have been moving straight.
I assume that the GPS measures without noise. The idea is illustrated in figure.
If anything is unclear about the question, please tell me!
Black: GPS data. Red: The most straight line through GPS data. Green distance from most straight line to GPS data sample.

A: You can try the formula about distance from point to a line
if your red line has equation ac + by + c = 0 (you can surely retrieve it by interpolation) and your "external point" has coordinates x0,y0.


text:
Q: How do I learn sensor data from knx group address for c#? static void Main(string[] args)
        {

            var connection = new KnxConnectionRouting();

            connection.Connect();
            connection.KnxEventDelegate += Event;
            connection.Action("1/0/1", false);
            Thread.Sleep(5000);

        }

        static void Event(string address, string state)
        {
            var connection = new KnxConnectionRouting();

            if (address == "1/0/1")
            {
                decimal temp = (decimal)connection.FromDataPoint("1.001", state);
                Console.WriteLine("New Event: device " + address + " has status " + temp);
                return;
            }

            Console.WriteLine("New Event: device " + address + " has status " + state);
        }

"state" variable returning from "Event" method returns null.temp value always gives zero result.
Any suggestion ?
I used KNXLib

A: So what datapoint type does your group address 1/0/1 actually have?
If it is supposed to be a sensor value, probably 9.001, or? I this case, change connection.FromDataPoint("1.001", state) to connection.FromDataPoint("9.001", state).
But then sending a boolean value to the same group address (connection.Action("1/0/1", false)) makes no sense.


text:
Q: Find user's online status I am using private_pub 1.0.3 gem which is build on top of faye and able to use it in my localhost. Now I want to implement functionality to check if user online status is online or offline using this gem.
I am totally new to web sockets and found private_pub really easy to configure it so implemented it.....but Now I am stuck in the above mentioned problem. So, please let me know what is the proper solution for it.
I found this tutorial http://www.ryanepp.com/blog/how-do-i-tell-if-a-user-is-online and I think that can solve my problem....I have configured redis server and tested it through console, it is all working.....Now all I want to do is to replace websocket-rails part of code with our own private_pub gem utilization.
UPDATE
I found these faye events:
bayeux.bind('disconnect', function(clientId) {
  // event listener logic
});

client.bind('transport:down', function() {
  // Fires when the connection is lost
});
client.bind('transport:up', function() {
  // Fires when the connection is established
});

But, how can I use and bind these events using private_pub gem
NEW-UPDATE
I have opened issue in github for faye-rails and private_pub gem, please visite them, I have done partial solution for problem, but that didn't fully solved my problem
private_pub issue 110
faye-rails issue 72
Thanks


text:
Q: How to keep browser window full screen after a location.replace? On intro screen, the user has the choice of full screen thru a button. Say user chooses so, and I want to keep that status when we transition to the real app loading a new document using location.replace (path). Is this possible? (It seems the default behavior is that after the location.replace, the window jumps back to the size it was before the user hit full screen, as if it never happened.)
Thank you for your time and attention.
EDIT 1 - The question might be misleading if you haven`t dealt with full screen programmatically before. I don't have a problem passing parameters if user chose full screen or not, etc., the problem is that the browser:
1) Just goes back to non-full when a new page is loaded, even if user had gone full, and that is annoying.
2) When I try the requestFullscreen API family on the SECOND page - if user chose full screen on first - the browser tells me that full screen has to be a) requested by the user, b) that request had to be 'recent' (one day I'll know how recent :D)
EDIT 1.1 - Some reading show my problem maybe that I am turning an ELEMENT into full screen view, not the browser. Once the old page is gone, so is the element with the full screen...
Any pointers there? Can I at user's command turn the browser into full screen, so maybe it stays so on new page?  I'm no expert on this, it seems :D

A: Whatever script you use to set fullscreen mode on the intro page, you could just call that again -- but conditionally -- on the "real" page. To remember that the user wants fullscreen, you can use Local Storage. So:
On the first page,
localStorage.setItem("fullScreenMode", "on");

Then on the second page,
let fullScreenMode = localStorage.getItem("fullScreenMode");
if(fullScreenMode == "on"){
  // Set second page to full screen here
}

Whenever the user resets the default behavior, you'd remember this new state by setting localStorage.fullScreenMode to "off" (or to "Starbuck" -- anything except "on").
Or you could wipe all your local storage properties with:
localStorage.clear();


text:
Q: Can not allowing space, equal sign, and quote inputs prevent php/SQL injection? I was just wondering that if you limit the user to only be able to input letters and numbers, would that fully protect you against injection?

A: That depends on how you define letters and numbers.  There are certain Unicode characters that can result in SQL injection.  This is sometimes called SQL Smuggling.

There are cases of SQL Injections leveraging the implicit conversion
  of Unicode homoglyphs from Unicode character string types (NCHAR,
  NVARCHAR) to character string types (CHAR, VARCHAR). A character such
  as ' (U+02BC) in NVARCHAR may slip through the escaping routine and
  get translated to ' (U+0027) in VARCHAR, which may result in an SQL
  Injection when such a string is used to build an SQL statement
  dynamically.
However, your validation is pretty strict (only characters from the
  Basic Latin Unicode block and Unicode whitespace characters) and I
  can't think of any case where this would fail.

https://security.stackexchange.com/a/54958
Having said that, prepared statements / parameterized queries offer the best protection against SQL injection.  If the allowable character set is expanded through a requirements change years down the road, the person doing the change may be unaware of the security implications of allowing additional characters.

A: For MySQL you can escape your string using mysql_real_escape_string() or so. Actually, if there is only something contains letters(A-Z) and digits (0-9) then it is okay. But the point is to have the right filter for each variable you are receiving from user.

A: *

*It makes no sense.

*It is useless.

Even if it worked it would be useless and wrong.
Dynamical SQL building should be never connected to whatever user input and its validation. There are rules of safe SQL creation already. That works for ANY data, not only artificially limited subset.
In a sanely designed application data storage layer should be separated from user input processing. And should be able to process any data, regardless of its source or developer's whims.


text:
Q: How to create a Hash if keys and values are separately provided? If keys and values are separately provided how can I make a Hash?
I'm doing it now like this.
h = Hash.new
values.each_with_index do |v, i|
  h[keys[i]] = v
end

But I think there is a better way to do it. Any suggestion?

A: Do as below :
Using Hash::[] :
Hash[keys.zip(values)]

or using Ruby2.1.0 Array#to_h :
keys.zip(values).to_h


text:
Q: Send FCM Notification to multiple users using their UID through cloud functions i have users Uid in an 'users' array as ['uid1','uid2'] now i will be sending notifications to these users in cloud function?
        exports.sendNotificationFromCr = functions.database.ref('/cr/{crUid}/notifications/{notificationid}/').onWrite(event => {

    const uid = ['uid1','uid2']; // some how i get this.
    // some work to send notifications
    // to all tokens of uid1 and uid2.
}

here is the database structure:
users/
   uid1/
      name:{name}
      FCM-key/
         token1:true
         token2:true
   uid2/
      ...
      FCM-key/
         token3:true

using ['uid1','uid2'] i want to send notification to all 3 tokens in my database. how to do that?

A: If you're using something like firebase. Then you would want to have a notifications database model, that has the userId, the notification title, body and perhaps image, also a seen flag (true or false).
You would then post notifications either from your clients or from your cloud server code into the database. One per client/notification. If you have thousands of users you would use some sort of server-side cronjob, to offload this so that it runs outside of say your client to server API.
On the clients, you would be listening for new rows in that model filtering on the userId and when they appear, display them to the client in your UI. Once the client has seen the notification you would mark it as seen on the client.
Without knowing what platforms, code base, DB you are using it's impossible to explain in code terms how this would be done.
There are various API's for IOS and Android and Firebase that resolve this.


text:
Q: Array with double parameters I am reading some book and I have encountered a piece of code that wasn't explained in the book, but has some part which is very confusing to me, bold part, and I want to know what is it about.
void Set::intersection(const Set& s1, const Set& s2)
{
    Set s;
    s.arrayA = new double[ s1.sizeA<s2.sizeA ? s1.sizeA : s2.sizeA];
    int i, j, k;
    while(i < s1.sizeA && j < s2.sizeA)
        if(s1.arrayA[i] < s2.arrayA[j])
            i++;
        else if (s1.arrayA[i] > s2.arrayA[j])
            j++;
        else
            s.arrayA[k++] = s1.arrayA[j++,i++]; // question is about this line

    s.sizeA= k;
    deleteA();
    copyA(s);
}

What does it do, and why is there two parameters inside the [] brackets? Thanks in advance.

A: Two parameter within brackets is expression using comma operator. Result of such expression is result of last item (j++, i++ gives i incremented by one, while j is also incremented by one).
So s.arrayA[i++] = s1.arrayA[j++,i++]; really can be converted to equal j++, s.arrayA[i++] = s1.arrayA[i++];
This code intersects to sets s1 and s2. It seems code suggests that arrays (that implement sets) are sorted.
Code is walking on s1.arrayA and s2.arrayA and if some element is present in both sets, than it places that element in s.arrayA.


text: Q: Brouwer fixed-point theorem on non-convex sets I read about the Brouwer fixed-point theorem in Wikipedia, and got confused about whether it holds when the domain of the function is non convex. On one hand, convexity is explicitly mentioned as a pre-condition. On the other hand, they say that it holds also for domains that are homeomorphic to a disc, and there may be such domains which are not convex (e.g. a concave quadrangle). So, what is the largest family of sets of $\mathbb{R}^n$ on which the BFPT holds?


text:
Q: Fantasy book where a young prince becomes a mage When I was younger (11-12 years old, so the early 2000s) I once read a story where a young boy, who may have been either a young prince or a squire of some sort, is recruited by a wizard and taken to a city to train as a mage.
I seem to remember him living in dorms with the other children at this school, until he gets into difficulty with another of the boys in the dorm. He is kicked out of the dorms and ends up living above a blacksmith shop (I think).
I remember it being the first book in a series of books of which there were about 3 out at the time. I think one of the stories was about the boy going to a tower to do something or other.
Does anyone have any idea what this book series is? I haven't been able to find it for years now but it was a story I really loved.

A: This is School of Wizardry, the first book in the "Circle of Magic" series by Debra Doyle and James D. Macdonald. Randal is indeed training as a squire when he is inspired to join Madoc, a visiting wizard, to become a mage. He does indeed get into an altercation with another student, although him moving out of the dorms is more of an offered choice than him being kicked out as I recall it. Here is the summary from Wikipedia of the first book:

The protagonist, Randal, a young boy preparing for knighthood at Castle Doun, leaves his old life behind and follows Madoc the Wayfarer, who takes him to study at the Schola Sorceriae in the city of Tarnsberg. He struggles with his studies, aided by an elder student, Nick, and comforted by a young orphan lutenist, the girl Lys. After he narrowly squeals through exams, the young and charismatic Master Laerg takes an interest in Randal, tutoring him in private; but his motives are less than honest.

The second book, The Secret of the Tower or Tournament and Tower, indeed has him traveling to the tower of a Master Balpesh to seek a boon from him as a result of the events of the first book.

You can find an excerpt on the author's website of the first chapter of the first six of the eight books in the series.


text:
Q: Use the root test to determine the radius of convergence Use the root test to determine the radius of convergence of
$\sum_{i=1}^\infty \frac{2x^n}{1+5^n}$
How to approach it? I know what the root test is about, but that $1+5^n$ in the denominator makes me somehow confused about usage of it.

A: It is:
$$\lim_{\color{red}n\to\infty} \left|\frac{2x^n}{1+5^n}\right|^{1/n}=\lim_{n\to\infty} \frac{2^{1/n}\cdot |x|}{5\cdot (1+\frac1{5^n})^{1/n}}=\frac{|x|}{5}<1 \Rightarrow |x|<5 \Rightarrow R=5.$$


text:
Q: Regular Expression for splitting string I am looking for regular expression to get the match as "HELLO" and "WORLD" separately when the input is any of the following:
"HELLO", "WORLD"
"HELL"O"", WORLD"
"HELL,O","WORLD"

I have tried few combination but none of them seem to work for all the scenarios.
I am looking to have my c# code perform something like this:
string pattern = Regex Pattern;
// input here could be any one of the strings given above
foreach (Match match in Regex.Matches(input, pattern))
{
   // first iteration would give me Hello
   // second iteration would give me World
}

A: If you only require it on Hello and World I suggest Sebastian's Answer.  It is a perfect approach to this.  If you really are putting other data in there, and don't want to capture Hello and World.
Here is another solution:
^([A-Z\"\,]+)[\"\,\s]+([A-Z\"\,]+)$
The only thing is, this will return HELLO and WORLD with the " and , in it.
Then it us up to you to do a replace " and , to nothing in the output strings.
Example:
//RegEx: ^([A-Z\"\,]+)[\"\,\s]+([A-Z\"\,]+)$
    string pattern = "^([A-Z\"\\,]+)[\"\\,\\s]+([A-Z\"\\,]+)$";
    System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(pattern);

    string MyInput;

    MyInput = "\"HELLO\",\"WORLD\"";
    MyInput = "\"HELL\"O\"\",WORLD\"";
    MyInput = "\"HELL,O\",\"WORLD\"";

    string First;
    string Second;

    if (Reg.IsMatch(MyInput))
    {
        string[] result;
        result = Reg.Split(MyInput);

        First = result[1].Replace("\"","").Replace(",","");
        Second = result[2].Replace("\"","").Replace(",","");
    }

First and Second would be Hello and World.
Hope this helps.  Let me know if you need any further help.

A: Try this:
Regex.Match(input, @"^WORLD|HELL[""|O|,]?O[""|O|,]$").Success

A: I always found it useful to use an online Regular Expression tester like this one http://www.gskinner.com/RegExr/.


text:
Q: Iterative MergeSort Time Complexity (Bottom-Up) I have a problem with finding the time-complexity.

*

*Firtly, speaking about the outer FOR in MergeSort, i think that the repetitions are (1+ Sumation(from i=1, to sizeOfArray)(2*i) = 1+(2+4+8+16+32+...+size) but i also think that i am very wrong.

*I also have a problem measuring the inside FOR-loop repetitions.

MergeSort(){     //Iterative Version (Bottom-Up)
            for(int currentSize = 1; currentSize < length; currentSize *= 2)        {
                for(int low = 0; low < length - currentSize; low += 2*currentSize){

                    int mid = low + currentSize - 1;
                    //min() is used here so if low is very close to the end of the array, high doesn't take outOfBoundries Value.
                    int high = Math.min(low + currentSize*2 -1, length - 1);

                }
            }

}
merge(int low, int middle, int high) {
            // Copy both parts into the helper array
            for (int i = low; i <= high; i++) {
                    helper[i] = arrayForMergeSort[i];
            }

            int i = low;
            int j = middle + 1;
            int k = low;
            // Copy the smallest values from either the left or the right side back
            // to the original array
            while (i <= middle && j <= high) {
                    if (helper[i] <= helper[j]) {

                            arrayForMergeSort[k] = helper[i];
                            i++;
                    } else {

                            arrayForMergeSort[k] = helper[j];
                            j++;
                    }
                    k++;
            }
            // Copy the rest of the left side of the array into the target array
            while (i <= middle) {
                    arrayForMergeSort[k] = helper[i];
                    k++;
                    i++;
            }

    }

A: For the outer loop, the number of iterations is ceil(log2(length)).
For the inner loop, the number of runs to be merged on each iteration is ceil(length / currentSize) or floor((length + currentSize - 1) / currentSize). If this is an even number, then the last run's size may be less than currentSize. If this is an odd number, then the last run has no run to merge with and also may be less than currrentSize. I'm not sure there's a way to calculate the total number of merge operations without using iteration to sum the merge operations per iteration.
In a "production" version of merge sort, a one time allocation of a working array the same (or 1/2) the size of the original array is done, and then the direction of merge (original to working or working to original is changed with each outer loop. If the program pre-caculates the number of outer iterations, and it is an odd number, then a pre-pass can be done to swap elements in place on the initial pass, so that an even number of merge passes are done, with the sorted data ending up in the original array.


text:
Q: Joomla 3.3.1 Opencart 1.5.5.1 Mijoshop 2.4.1 pages initiate very slow We've just started to use the latest version of Joomla and Opencart for our stores but we've noticed it takes forever to initiate.  Below is a link from Firebug showing the load time of the pages.  Does that first load seem unusual?  The 1st one is the URL I am trying to access within our site like "www.yoursite.com/blue-shoe".  Below the URL are more details, hosting, etc.
http://s1288.photobucket.com/user/dirkd9000/media/firebug-net_zpsb864e462.jpg.html
The pages take about 4-6 seconds to start but from there it loads very fast.  I am currently using most of the methods to boost speed of our pages such as removing product count, GZip, JCH Optimized and Joomla's Cache Plugin.  We are currently using Hostgator VPS lev 5 with 1.8 GB RANm CPU 2 cores and 1.4 TB bandwidth.  Maybe we need to upgrade or find a different host?
Google pagespeed website gives us a score on our pages that range 68-74 points.  Other sites such as gmetrix rate us very good too.  I'm thinking this could be a query issue on start up.  My boss is really breathing down my neck about this and I'm not sure what the issue is.  My hosting says everything is fine.
I know the images cause some delay but which is easy to fix but again I don't understand what the hang up is at the very beginning.  Thanks!


text:
Q: How to pass default messages from git to editor? Usually, when I do git commit or git rebase -i, a core.editor is started with default messages.
e.g.)
subject line

what happened

[ticket: X]
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
# modified:   lib/test.rb
#
~
~
".git/COMMIT_EDITMSG" 14L, 297C

In my environment, however, core.editor is started without any default messages (with blank).
My environment is below.

*

*Windows 8.1 Pro (64bit)

*Cygwin (mintty 2.1.5, x86_64-pc-cygwin)

*git version 2.5.3

A: Did you check the folder .git/hooks?
Default message is defined in their's script.
If there are no script, I guess, your core.editor will show without any default messages.
So, if your hooks is blank, use git init command on somewhere and then copy their's hooks's script to your blank hooks directory.
In addition, I guess this link also would be help you: GIt - Git Hooks
(I want to comment this, but my reputation level does not allow me to do it.)

A: You should use the commit.template option of git config. Follow these steps:

*

*Create a file on your system that contains the default text for your commit message. For example, use a command such as the following to create the file: echo "MY DEFAULT COMMIT MESSAGE IS...." > ~/.mygitmsg.txt

*If you want this default message to appear when you make a commit in all repositories on your system, at the command line type git config --global commit.template ~/.mygitmsg.txt. Otherwise, if you just want this to work for your current git repository, drop the --global switch, executing this command in the git repository for which you want it to be the default message.

If this doesn't work, perhaps there's a problem with your default text editor and git on Windows.


text:
Q: Export from Python to .xls I wanted to get output like this: Output
I am able write this code and its working fine. Being a beginner, I seek your criticism on this code. I feel its too lengthy.
1. If there is any short way, please let me know
2. Doubt:
I dont know why I am getting this error Exception: Unexpected data type <class 'numpy.int32'>, when i change this line values=[a*1., a*1.] to values=[a, a]. Why cant it export integers ? Similar logic works here:
for row, (name, value) in enumerate(zip(names, values)):
    sh.write(row, col, name);
    sh.write(row, col+1, value);

Main working code:
import numpy as np
import xlwt #THIS MAY BE GOOD
#from pandas import DataFrame

amin =2
amax=10
da = 2
names = ['amin', 'amax', 'da']
values = [amin, amax, da]

fname='EXPORTexample.xls'; sheetname = 'sheet 1'

book = xlwt.Workbook()
sh = book.add_sheet(sheetname)

col=0;
# FIRST WRITE THE VARIABLES AND THEIR VALUES INTO XLSX.
for row, (name, value) in enumerate(zip(names, values)):
    sh.write(row, col, name);
    sh.write(row, col+1, value);

t2 = np.arange(0.0, 5.0, 1)
amat= np.arange(amin,amax,da)

fn=np.zeros((np.shape(t2)[0],1))

col=3;
#row_eps =0;
#row_Dt += row_eps;

for a in amat:
    fn = a*t2

    names = ['eps_dot', 'Delta_t']
    values=[a*1., a*1.]
    #write specific a conditions on every data curve/set
    for row, (name, value) in enumerate(zip(names, values)):
        sh.write(row, col, name);
        sh.write(row, col+1, value);

    #write names such as strain, stress, d11s, d_dot, d11
    occ_rows = len(names)#no.of occupied rows.
    names = ['strain', 'stress', 'd11s', 'd_dot', 'd11']
    for cols,name in enumerate(names):
        sh.write(occ_rows+1, col+cols, name)

    ## WRITE actual numbers
    for rows, (strain_i,stress_i, d11s_i, d_dot_i, d11_i) in enumerate(zip(fn, t2, fn, t2, fn)):

        sh.write(occ_rows+1+rows+1, col, strain_i)
        sh.write(occ_rows+1+rows+1, col+1, stress_i)
        sh.write(occ_rows+1+rows+1, col+2, d11s_i)
        sh.write(occ_rows+1+rows+1, col+3, d_dot_i)
        sh.write(occ_rows+1+rows+1, col+4, d11_i)

    col+=6 #incremening column value to avoid overwriting and related error

book.save(fname)


text:
Q: How to estimate Leave One Out Cross Validation (LOOCV) in MATLAB? I want to make a leave 1 out cross validation (LOOCV) in MATLAB and I have two cells wherein I stored my data. My first cell Original{} is a 1x33 matrix with 1x7 in each. My second cell Predicted{} has the exact same amount of data as Original{}.
How can I make a for loop to take 1 subject out for testing, and 32 for training, 33 times?
I also want to know the R^2 (R-squared) of each of my cross validated values.
This is the code I tried to make:
%% cross validation Leave 1 out
for i = 1:33
    xcv = Predicted{1,i};
    ycv = Original{1,i};
    sse = 0;
    N = 33;
    for i = 1:7
        [train,test] = crossvalind('LeaveMOut',N,1);
        %crossval = xcv(train), ycv(train),xcv(test);
        sum = sse + sum ((crossval - ycv(test)).^2);
    end
end


text:
Q: firebase.json change public folder dynamically I have an angular7/ionic4 app with 2 environments for staging and prod.
I can do

ionic build
ionic build --prod

This publishes the app in different folders I have set in angular.json

dist/staging
dist/prod

I also have 2 projects in firebase and can deploy to each

firebase deploy -P staging
firebase deploy -P default

However in firebase.json I can only set one hosting folder from where to pick the files up to send to firebase:
"hosting": {
    "public": "dist/prod"
}

So despite being able to deploy to different projects I can't seem to set which folder to deploy from.
I want

firebase deploy -P default

to deploy files from dist/prod
and

firebase deploy -P staging

to deploy files from dist/staging
Can I change firebase.json (or .firebaserc) to set which folder to deploy from for each environment / project ?

A: Associate the sites with a local target so Firebase knows which code to deploy where.
$ firebase target:apply hosting  staging  staging_project_name
$ firebase target:apply hosting  prod  production_project_name

And then edit the configuration in the firebase.json file as follows:
{
  "hosting": [ {
      "target": "staging",
      "public": "dist/staging",
      "rewrites": [...]
    },
    {
      "target": "prod",
      "public": "dist/prod",
      "rewrites": [...]
    }
  ]
}

And then you can deploy as follows:
$ firebase deploy --only hosting:staging -P staging
$ firebase deploy --only hosting:prod -P default


text:
Q: How to expand UIButton frame in select mode? I have an small UIButton and set Background for select state by:
[button setBackgroundImage:[UIImage imageNamed:@"butBG.png"] forState:UIControlStateSelected];

butBG.png imageSize > button.frame.
And I want to expand UIButton.frame equal to imageSize when [button setSelected:YES];
After that back to origin Frame when [button setSelected:NO];
How can I do that? Thanks for your help in advance!

A: 1) check the button state on button click using btn.isSelected.
2) If btn.isSelected is true then set the button size similar to image size else set the button size which you want on normal state.

A: you could make a category for the button and override the setSelected method to change the frame size of the button depending on the state

A: You can listen to the state of your button and resize it when it changes
in viewDidLoad (or do the equivalent using the interface builder)
[button addTarget:self action:@selector(myButtonStateChanged:) forControlEvents:UIControlEventTouchDown];

[button addTarget:self action:@selector(myButtonStateChanged:) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel)];

create the method
- (IBAction)myButtonStateChanged:(UIButton *)sender {
  if (sender.selected) {
     sender.frame = BIG_SIZE_FRAME;
  }
  else {
     sender.frame = NORMAL_SIZE_FRAME;
  }

}

A: -(void)setButtonframe:(UIButton *)button
{
    if (button.selected)
    {
        [button setFrame:largeFrame];

    }
    else
    {
        [button setFrame:smallFrame];

    }
}

Call
[self setButtonframe:sender];
in the action of button click

A: GO for this...
- (IBAction)paymentBtnCliked:(id)sender {

if ([sender isSelected]) {
     // configure same object as per requirement
    [paymentBtn setSelected:NO];
}else{
     // configure same object as per requirement
     [paymentBtn setSelected:YES];

}
}


text:
Q: Write to a NameValueCollection I am trying to implement a simple construct where I first clear the NameValueCollection and the write new values to it. However at the moment I can't because it is read only. Is there a way to make it not read only or a walk around?
My Code:
NameValueCollection DataDictionary = ConfigurationManager.GetSection("dataDictionary") as NameValueCollection;
            DataDictionary.Clear();
            for (int i = 0; i < tableLayoutPanel2.RowCount; i++)
            {
                var T = tableLayoutPanel2.GetControlFromPosition(1, i);
                var T2 = tableLayoutPanel2.GetControlFromPosition(3, i);
                string key = T.Text;
                string value = T2.Text;
                DataDictionary.Add(key, value);
            }

A: Copy it in a new NameValueCollection:
var writableCollection = new NameValueCollection(DataDictionary);
writableCollection.Add(...);


text:
Q: CoerceValueCallback not called after ClearValue I have a CheckBox which I have extended to add a IsReadOnly property. The property has a Coerce callback, which will look up access rights for the current user, and return true, if the user does not have permissions:
private static object CoerceIsReadOnly(DependencyObject d, object baseValue)
    {
        var owner = (CheckBox)d;

        bool isReadOnly = (bool)baseValue;
        if (isReadOnly == false)
        {
            if (AccessControl.HasFullAccess(owner) == false)
            {
                return true; // If we do not have access, and read only is false, we coerce it to true
            }
        }

        return baseValue;
    }

Now I did some experiments to look at the different values:
XAML
<vc:CheckBox Content="AccessControl" x:Name="ChkBoxAccessControl" Margin="5" vc:AccessControl.OverrideAccessRights="NoAccess"/>

Code-behind
var defaultValue = CheckBox.IsReadOnlyProperty.GetMetadata(typeof(CheckBox)).DefaultValue; // False
var localValue = ChkBoxAccessControl.ReadLocalValue(CheckBox.IsReadOnlyProperty); // Unset (we didn't set a value in code or XAML)
var actualValue = ChkBoxAccessControl.GetValue(CheckBox.IsReadOnlyProperty); // True (coerced)

ChkBoxAccessControl.SetValue(CheckBox.IsReadOnlyProperty, false);
var localValue2 = ChkBoxAccessControl.ReadLocalValue(CheckBox.IsReadOnlyProperty); // False
var actualValue2 = ChkBoxAccessControl.GetValue(CheckBox.IsReadOnlyProperty); // True

ChkBoxAccessControl.ClearValue(CheckBox.IsReadOnlyProperty);
var localValue3 = ChkBoxAccessControl.ReadLocalValue(CheckBox.IsReadOnlyProperty); // Unser
var actualValue3 = ChkBoxAccessControl.GetValue(CheckBox.IsReadOnlyProperty); // false??? WTH...

So to my surprise, the last actualValue3 returns false.
Apparently when calling ClearValue, it does not call the coerce callback. Is this to be expected? Can anyone explain why this would be correct?

A:
Is this to be expected?

Yes, see this answer. When you clear the value, you get the default non-coerced one.
Also, actualValue isn't coerced in your example but actualValue2 is.
A dependency property stores and remembers the non-coerced value. You can read more about this here.


text:
Q: Can't deploy with capistrano from windows to centos I have Windows 7 64bit. I installed ruby200-x64 with official installer. I could successfully deploy with Capistrano one time, but now this kind of error appears all the time:
[deploy:update_code] exception while rolling back: Capistrano::ConnectionError, connection failed for: user@77.77.77.77 (TypeError: no implicit conversion of nil into String)

The remote server is running CentOS and is configured ok, because I can deploy to it from Xubuntu and Mac OS without any problems.
The deploy file looks like this:
set :application, "application_name"
set :repository, "git@bitbucket.org:username/application_name.git"
set :scm, :git
set :use_sudo, false
set :deploy_to, "/var/www/application_name/"

set :deploy_via, :remote_cache
set :copy_exclude, [".git", ".DS_Store", ".gitignore", ".gitmodules"]

server "user@77.77.77.77", :app

namespace :application do
  task :symlink, :roles => :app do
    run "if [ -d #{shared_path}/uploads ]; then ln -nfs #{shared_path}/uploads #{release_path}/wp-content/uploads; fi"
  end

  task :chmod_wp, :roles => :app do
    run "chmod -R 755 #{release_path}/.*"
    run "find #{release_path}/ -type f -exec chmod 644 {} \\;"
  end
end

after "deploy:create_symlink", "application:symlink", "application:chmod_wp"

Maybe someone has a slight idea what's the problem with deploying from Windows?


text:
Q: Pass variable list of arguments to docker as a file I have seen a few answers about this but noone do what I would like to do, as far as I can understand. Example
If my code is able to accept different calls like this:
app.py -hist

app.py -hist -yearIni 2018 -yearEnd 2019 -station 12341234

app.py -hist -dateIni 20-2-2018 -dateEnd 20-2-2019

And depending on what arguments it receives, it makes an API call or another.
What I want now is to dockerize this behaviour. So far I have only found Docker ARG and CMD as options, but if I understand them correctly, they do not allow to pass a file, like a yaml, specifying which arguments will appear. Instead, you are forced to somehow hard code in either Dockerfile or somewhere else the names and (possible) values of the arguments.
Since right now I have already 4-5 different combinations, and they may grow in the future, I would like to pass a file.yaml (or json or whatever other format) where I define what possible parameters can be used, and then my python code will decide whether or not those are valid parameters, and act based on that.
Pseudocode of possible yaml "schema":
predictions:
    city: "//str"
hist:
    yearIni: "//str"
    yearEnd: "//str"

    dateIni: "//str"
    dateEnd: "//str"

    station: "//str"

Is there any way to do this? To pass dynamic arguments to a python app that could work on its own with this behaviour, but now, inside docker?

A: Here's an example of how to pass arguments to docker-compose from cli
docker-compose build --build-arg app_env=production
docker-compose up


text: Q: Characterization of positive McLauren series? A non-negative real polynomial can always be written as $p_1(x)^2+p_2(x)^2$, (or something like this?), where $p_i$ are real polynomials. But can we say something like this for a positive McLauren series? For example they are always equal to $\sum c_ie^{a_ix}$ with a positive sequence $c_i$, and $a_i$ is real?


text:
Q: Ajax POST request sending undefined to Express I'm trying to send some data to be parsed. The script on the client side is the following:
function addURL(link) {
        console.log("Adding url...");
        $.ajax({
            type: "POST",
            url: location.protocol + "//" + location.host + "/shorturl/create",
            crossDomain: true,
            contentType: "application/json",
            data: JSON.stringify({url:link}),
            success: function(data){
                $("#shortenedURL").html(data.shortenedURL);
            },
            error: function(err){
                console.log("Ran into an error... " + err);
            }
        });
}

On my express app, on one of the routers, I've got:
router.post("/create", function(req, res){

console.log(req.body);
console.log(req.body.url);
var url = req.body.url; }

I get 'undefined', and then the 'Cannot get property 'url' of undefined'.
I can't figure out where I'm going wrong...

A: You need to use bodyParser:
app.js:
var bodyParser = require('body-parser')
  , app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));


text:
Q: Unable to create remote repository when using .xcworkspace Xcode 9 + GitHub I am using Xcode 9 (Beta) which has GitHub integrated into it.
Please note I have pod files (223 MB size !!) in the project, and I've also set up GitHub account in Xcode preferences.
When I don't have any pods installed, I am able to create remote repository on GitHub by opening the .xcodeproj file and following the below steps, however it doesn't work when I have pods installed (see below steps).
How could I get around this issue ?
Below are the steps I am following to create a remote repository on GitHub using Xcode 9 (Beta).
1. Open .xcworkspace file

2. Create Git Repository
Xcode > Source Control > Create Git Repositories

3. Creating remote repository on GitHub

Result

A: Private commits are enabled for paid users only. Try committing with public visibility and it should probably work.


text:
Q: What's the best way to handle a file upload in asp.net mvc? I'm having trouble getting an asp.net MVC 3 app to bind to a class that includes an uploaded file.
Here's my class:
public class PhotoAndCaption : IValidatableObject
{
    [Required]
    public HttpPostedFile ImageFile { get; set; }

    [Required]
    public string Caption { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        //make sure ImageFile is jpg image of proper size.
        yield return new ValidationResult("This shit ain't right!!!!");
    }
}

and here's the view:
@using(Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

<input type="file" id="ImageFile" name="ImageFile" />

@Html.TextBoxFor(m => m.Caption)

 <input type="submit" value="Upload File" />
}

What happens is that the Caption binds correctly but the ImageFile does not. I'd like to bind it to a class that implements IValidatableObject so I can neatly validate the uploaded image to make sure it's the right pixel dimensions and such. If not, I want to respond with a meaningful error message. Ideally I'd like to do all of the validation for the class in one place, so I can check the caption and any other fields I might add later in one place.
When I test this my Caption property binds correctly but the ImageFile does not.

A:
We have to use the HttpPostedFileBase class, rather than the
  HttpPostedFile because every Request, Response, HttpContext and all
  related ASP.NET intrinsic abstractions are one layer farther way in
  ASP.NET MVC

This is Scott Hanselman's MVC file upload example explanation, why we have to use HttpPostedFileBase instead of HttpPostedFile in MVC.

A: I changed the ImageFile property from HttpPostedFile to HttpPostedFileBase and it now works.


text:
Q: App closes shortly after launching in ios but android works fine? I am having a problem with ios when i launch the app, it shows the splash screen then the app just closes itself. While on android it works fine.

right now this is my config:

<preference name="ScrollEnabled" value="false" />
<preference name="android-minSdkVersion" value="16" />
<preference name="BackupWebStorage" value="none" />
<preference name="SplashMaintainAspectRatio" value="true" />
<preference name="FadeSplashScreenDuration" value="1000" />
<preference name="SplashShowOnlyFirstTime" value="false" />
<preference name="SplashScreen" value="screen" />
<preference name="ShowSplashScreenSpinner" value="false" />
<preference name="SplashScreenDelay" value="5000" />
<preference name="FadeSplashScreen" value="true" />
<preference name="orientation" value="portrait" />
<preference name="loadUrlTimeoutValue" value="60000" />

my plugin list is below:

cordova-plugin-camera 4.0.3 "Camera"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-facebook4 1.7.4 "Facebook Connect"
cordova-plugin-file 6.0.1 "File"
cordova-plugin-file-transfer 1.7.1 "File Transfer"
cordova-plugin-firebase 2.0.5 "Google Firebase Plugin"
cordova-plugin-geolocation 4.0.1 "Geolocation"
cordova-plugin-googleplus 5.3.2 "Google SignIn"
cordova-plugin-ionic-webview 1.2.1 "cordova-plugin-ionic-webview"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-whitelist 1.3.1 "Whitelist"
cordova-plugin-x-socialsharing 5.4.1 "SocialSharing"
es6-promise-plugin 4.2.2 "Promise"
ionic-plugin-keyboard 2.2.1 "Keyboard"
onesignal-cordova-plugin 2.4.3 "OneSignal Push Notifications"

my ionic info is below:

cli packages: (/usr/local/lib/node_modules)
@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:
cordova (Cordova CLI) : 7.1.0

local packages:
@ionic/app-scripts : 3.1.6
Cordova Platforms  : ios 4.1.0
Ionic Framework    : ionic-angular 3.9.2

System:
ios-deploy : 1.9.2
Node       : v6.12.0
npm        : 3.10.10
OS         : macOS High Sierra
Xcode      : Xcode 9.2 Build version 9C40b

Environment Variables:
ANDROID_HOME : not set

Misc:
backend : pro

I have also try using Cordova Platforms 4.4.0 and 4.5.1 but getting same problem.

A: Not being able to see your Config.xml, I can only speculate that you are attempting to use a permission that is being denied in Xcode, due to a missing permission string.
Are you using the Camera, Microphone, Photo library or Location services?
Typically XCode will output an error message on the log when the app crashes. In most instances that I've encountered, it's due to a missing plist.info string.
Here's a sample of my config.xml that includes the usage descriptions:
    <edit-config file="*-Info.plist" mode="overwrite" target="NSCameraUsageDescription">
        <string>To take photos.</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="overwrite" target="NSPhotoLibraryUsageDescription">
        <string>To choose photos.</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="overwrite" target="NSMicrophoneUsageDescription">
        <string>To record videos.</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="overwrite" target="Use for video and audio messages">
        <string>To record videos.</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="overwrite" target="NSLocationAlwaysUsageDescription">
        <string>We use your location for...</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="overwrite" target="NSLocationAlwaysAndWhenInUseUsageDescription">
        <string>We use your location for...</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="overwrite" target="NSLocationWhenInUseUsageDescription">
        <string>We use your location for...</string>
    </edit-config>

Add those to the bottom of your config.xml, below the  tag, and see what happens now.


text:
Q: bash awk filter value between values Morning all,
I'm not very familiar with awk or filtering out values from a particular file.
The particular value i would like to extract from the file between "\n"
\nGenerated password: password\n
Is there a site i could potentially have a look at to help with this?
I managed to extract the information i need but having a bit of a difficult time to remove \n from the beginning and end of the line.
What i attempted: awk -F'\n' 'print $1'
Snippet of the output:
time="2023-01-23T18:40:06+02:00" level=info msg="Browser will open URL in 5 seconds"
time="2023-01-23T18:40:06+02:00" level=info msg="message"
time="2023-01-23T18:40:06+02:00" level=info msg="Open this link manually in a browser tab if it does not open."
time="2023-01-23T18:40:18+02:00" level=info msg="File encrypted \"file.txt\" in file.zip.\nGenerated password: mypassword\n"

A: $ cat file
foo
Generated password: password
bar

$ awk '/^Generated password:/{printf "%s", $0}' file
-------8<------------------
Generated password: password

or to get only the value:
$ awk '/^Generated password:/{printf "%s", $NF}' file
-------8<------------------
password

A: Using sed:
sed -n '/Generated password: / { s/\\n\".*//; s/.*\\n//; p }' file


text:
Q: How to approach finding Big O /Time complexity of any algorithm All,
I have always found myself being doubtful when it comes to finding the complexity of a given code/algorithm. Ex.
FOR I=1 TO N
do J=1
WHILE J*J < I
do J=J+1

The above code has time complexity of Big Theta (N^(3/2)) . However, I don't understand how the answer is derived.
Can anyone please guide me to the steps for finding the complexity or any specific resource that can help me? Most of the times, I only find code with complexity N, lg N , N lg N and N^2

A: The approach is always the same: work out how many operations are being executed as a function of N, and then throw away low-order terms and constants.
So in your example above, the inner loop iterates approximately sqrt(I) times, so we have (approximately) sqrt(1) + sqrt(2) + sqrt(3) + ...  The result is a function whose highest-order term is N^(3/2).


text:
Q: Double wildcarding within a do block in Haskell Consider the following function which runs a command:
getGrepStdout :: IO String
getGrepStdOut = do let cmd' = "grep"
                       pattern' = "//"
                       options' = "-nR"
                       path' = "/path/to/file"
                       stdin' = ""
                       args' = [pattern', options', path']
                   (_, stdout', _) <- readProcessWithExitCode cmd' args' stdin'
                   return stdout'

Notice the second to last line which has a double _ wild card matching (within a do block). This seems to compile fine in my case, but I was wondering if it was problematic formally speaking?

A: No, there is no problem with having one or more _ in pattern matches, in do-blocks or otherwise. Why do you think there might be?

A: You should be fine (at least with GHC).
It's good to be worried, because if you were to use any other identifier this would blow up!
Prelude> :{
Prelude| do
Prelude|     (x,x) <- return (1,1)
Prelude|     return x
Prelude| :}

<interactive>:12:6:
    Conflicting definitions for 'x'
    Bound at: <interactive>:12:6
              <interactive>:12:8
    In a pattern binding in
         'do' block

The main thing is that this gets desugared to :
return (1,1) >>= \(x,x) -> return x

And lambda abstractions don't let you use the same local name twice. _ gets special treatment.

So for _, you're telling the compiler that you don't need whatever value's in there. And don't make any assumptions about the value.
In general you shouldn't be worrying about clobbering over your definitions in the same scope, Haskell won't really let you. Here's a related question about not being able to do things like :
plus a a = 2*a
plus a b = a + b

Which is actually pretty similar to this situation. _'s special treatment is needed.

A: Strictly speaking, _ isn't really any more of a wildcard pattern than x or arg. What it is, however, is a hole. That means that it can not only accept any value, but won't bind that value to any particular variable. Since _ doesn't bind the value at all, using it twice in the same function declaration is perfectly valid, both theoretically and pragmatically.


text:
Q: How can i remove "Sections" from url by url writing? I am working on vb.net application and i need to remove word "sections" from the url.
url: http://www.examplewebsite.com/sections/page.aspx
This is what i need to do by regular expression in web.config.

A: You can use the following rewrite rule in your web.config file:
<rewrite>
  <rules>
    <rule name="Hide sections">
      <match url="^(.+)$
      <action type="Rewrite" url="sections/{R:1}" />
    </rule>
  </rules>
</rewrite>


text:
Q: Eloquent lastInsertId I want to get 'loan_id' that was inserted in both tables.
With return $this->getConnection()->getPdo()->lastInsertId();
I suppose i should get at least last id (which is specified for this model as 'id' and autoincremented) but I don't receive it too. (just empty response)
Even better if I can get full object that was inserted in DB.
So, I wanted to catch an Exception if transaction fails and return error message in case of failure and $loan_id or saved Object in case of success. how to do it ?
<?php
namespace App\model;

use Illuminate\Database\Eloquent\Model as Eloquent;
//use Illuminate\Support\Facades\DB as DB;
use Illuminate\Support\Manager as Manager;
use Illuminate\Database\Capsule\Manager as DB;
use PDO;

class Loan extends Eloquent
{
    protected $table = 'loans';

    protected $primaryKey = 'id';

    public $timestamps = false;

    public function addLoan($amount, $instalments)
    {

        // Manager::connection()->getPdo()->beginTransaction();
        $this->getConnection()->transaction(function () use ($amount)
        {
            $loan_id = substr(uniqid(), -12);

            DB::table('loans')->insert([
                    'loan_id' => $loan_id,
                    'amount' => $amount,
                    'status' => 'requested'
                ]
            );

            DB::table('loan_instalment')->insert([
                    'loan_id' => $loan_id,
                    'principal' => 777.12,
                    'interest' => 333.12
                ]
            );

        });

        return $this->getConnection()->getPdo()->lastInsertId();
    }
}
?>

A: Instead of
$this->getConnection()->getPdo()->lastInsertId()

You can do this:
DB::table('table')->insert([...])->lastInsertId();

And catching an exception see: Laravel: Using try...catch with DB::transaction()


text:
Q: Can Spyder programmatically open a python file given its absolute path? I'm using inspect.getfile() to get the python file directory of some class of interest, and then I would ideally like to be able to open it semi-automatically. As it stands, I copy paste the directory into the open window and it takes some navigating.
Any thoughts?
Thanks!

A: Once you have the path to your file, you can use IPython magic command %edit path from the console or within a script in the following way:
from IPython import get_ipython

path = "C:/path/to/your/file.py"

ipython = get_ipython()

ipython.magic(f"%edit {path}")


text:
Q: Fundamental questions on CNN and MLP in general I have read a number of tutorials and online lectures (link1: https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/) and link2: the webtutorial: http://cs231n.github.io/convolutional-networks/#overview
 but none of them mention the rationale for selecting a particular design. How do we decide on the following design aspects?
In particular the following points are unclear to me and shall be extremely grateful if somebody could walk through the concepts that will help me to design any CNN architecture.
1) If the filter size is 5*5*3 then how come the number of filters, $K=12$? Shouldn't it be 3 -- one for each channel?
2) In the second link, there is a formula   -  $((W-F+2P)/S)+1$
where $W$ = width of the input image, $F$ = filter size. It is not clear what is the purpose of this formula
3) Is there a rule of thumb/formula for deciding on the number of layers, number of filters, filter size, number of fully connected layers?  Or is it purely on the basis of trial and error?
4) Can somebody please explain the intuition and the rationale for designing a CNN architecture for this example -- considering a binary classification problem. For an input RGB image of size 500*500*3, how would you design the architecture -- how many layers, number of filters, size of the filter, how much is the stride, etc.

A: *

*I'm not sure where you found the $5 \times 5 \times 3$. Maybe it's the size of the input image. In that case the input image does have 3 channels, but we can select how many filters we want the layer to have arbitrarily. Let's say we select $K=12$ filters. Then the output of this layer will have $12$ filters. This way, the next layer will see $12$ channels as its input.

*This formula is used to calculate the number of parameters a convolutional layer will have.

*No unfortunately there is no such rule of the thumb. Also the well established state-of-the-art networks don't follow any sort of architecture (e.g. see inception, resnet, vgg. They are all very different architecturally). If you want to create your own I'd suggest taking an established network (e.g. ResNet-50 and tweaking it out a bit).

*Same as before. One thing you could try to do is follow the pretty basic scheme of [conv (+relu) -> conv (+relu) -> max pool] repeat this 2-3 times -> flatten -> fc (+relu) -> dropout -> fc (2 neurons and softmax activation). This, is a decent model which doesn't take much memory and runs relatively fast (compared to more complex CNNs), but can't reach state of the art performance. If you want better results stick with fine-tuning a pre-trained state-of-the-art model.


text:
Q: How to insert homepage and current page in breadcrumbs? I'm working on breadcrumbs for a client's website, and I'm asking myself if homepage has to be in its code.
So, is it better to do :
With link to homepage and current

        Accueil

    >

        Annonces

    >

        Categorie

        Produit

Without link to homepage and current page
Accueil >

        Annonces

    >

        Category

Produit

You can try this codes with Google Structured Data Testing Tool (http://www.google.com/webmasters/tools/richsnippets) and you will see that homepage is not rendered with my first example.
So, what's the best solution ? How do you do for your sites ?
Thanks !

A: For seo it's better without that links because you would have two links for the home page and  the other link is for the same page you are in...


text:
Q: ORA-01403: no data found during online table redefinition in oracle
ORA-01403: no data found during online table redefinition in oracle
  when trying to convert basicfile lob to securefile lob.

Steps followed:

*

*Created table T1 with basicfile lob (stored in tablespace ts1) having primary key on number field.

*Loaded the table T1 with data.

*Created interim table T2 with same structure as T1 (lobs being Securefile stored in tablespace ts2)

*Perform Online redefinition (with copy_indexes => 0) to convert T1 to
securefile lob.

*ORA-01403: no data found in copy_table_dependents.
I have tried setting copy_indexes --> 1 which does not result in any error
SQL> @online_redef.sql   sf sf basic_table sf_table sf/sf@cdb1_pdb1 'sys/knl_test7@cdb1_pdb1 as sysdba' 'tbsbas.dbf' 'tbsinter.dbf'
SQL> SET FEEDBACK 1
SQL> SET NUMWIDTH 10
SQL> SET LINESIZE 80
SQL> SET TRIMSPOOL ON
SQL> SET TAB OFF
SQL> SET PAGESIZE 100
SQL>
SQL> SHOW CON_NAME

CON_NAME
------------------------------
CDB1_PDB1
SQL>
SQL>
SQL> -- Create a new user
SQL> DROP USER &1 CASCADE;
old   1: DROP USER &1 CASCADE
new   1: DROP USER sf CASCADE
DROP USER sf CASCADE
        *
ERROR at line 1:
ORA-01918: user 'SF' does not exist

SQL> CREATE USER &1 IDENTIFIED BY &2;
old   1: CREATE USER &1 IDENTIFIED BY &2
new   1: CREATE USER sf IDENTIFIED BY sf

User created.

SQL>
SQL> -- Grant privileges
SQL> GRANT EXECUTE ANY PROCEDURE TO &1;
old   1: GRANT EXECUTE ANY PROCEDURE TO &1
new   1: GRANT EXECUTE ANY PROCEDURE TO sf

Grant succeeded.

SQL> GRANT CONNECT, RESOURCE, CREATE SESSION TO &1;
old   1: GRANT CONNECT, RESOURCE, CREATE SESSION TO &1
new   1: GRANT CONNECT, RESOURCE, CREATE SESSION TO sf

Grant succeeded.

SQL> GRANT CREATE TABLESPACE, ALTER TABLESPACE, UNLIMITED TABLESPACE, DROP TABLESPACE TO &1;
old   1: GRANT CREATE TABLESPACE, ALTER TABLESPACE, UNLIMITED TABLESPACE, DROP TABLESPACE TO &1
new   1: GRANT CREATE TABLESPACE, ALTER TABLESPACE, UNLIMITED TABLESPACE, DROP TABLESPACE TO sf

Grant succeeded.

SQL> GRANT SELECT ANY SEQUENCE TO &1;
old   1: GRANT SELECT ANY SEQUENCE TO &1
new   1: GRANT SELECT ANY SEQUENCE TO sf

Grant succeeded.

SQL>
SQL>
SQL> -- Connect as user
SQL> CONNECT &5
Connected.
SQL>
SQL>
SQL> -- Create tablespace for storage of BasicFiles
SQL> DROP TABLESPACE &3 INCLUDING CONTENTS AND DATAFILES;
old   1: DROP TABLESPACE &3 INCLUDING CONTENTS AND DATAFILES
new   1: DROP TABLESPACE basic_table INCLUDING CONTENTS AND DATAFILES
DROP TABLESPACE basic_table INCLUDING CONTENTS AND DATAFILES
*
ERROR at line 1:
ORA-00959: tablespace 'BASIC_TABLE' does not exist

SQL> CREATE TABLESPACE &3
2      DATAFILE '&7'
3      SIZE 256M REUSE
4      EXTENT MANAGEMENT LOCAL
5      UNIFORM SIZE 4M
6      SEGMENT SPACE MANAGEMENT AUTO;
old   1: CREATE TABLESPACE &3
new   1: CREATE TABLESPACE basic_table
old   2:     DATAFILE '&7'
new   2:     DATAFILE 'tbsbas.dbf'

Tablespace created.

SQL>
SQL>
SQL> -- Create tablespace for storage of interim table.
SQL> DROP TABLESPACE &4 INCLUDING CONTENTS AND DATAFILES;
old   1: DROP TABLESPACE &4 INCLUDING CONTENTS AND DATAFILES
new   1: DROP TABLESPACE sf_table INCLUDING CONTENTS AND DATAFILES
DROP TABLESPACE sf_table INCLUDING CONTENTS AND DATAFILES
*
ERROR at line 1:
ORA-00959: tablespace 'SF_TABLE' does not exist

SQL> CREATE TABLESPACE &4
2      DATAFILE '&8'
3      SIZE 256M REUSE
4      EXTENT MANAGEMENT LOCAL
5      UNIFORM SIZE 4M
6      SEGMENT SPACE MANAGEMENT AUTO;
old   1: CREATE TABLESPACE &4
new   1: CREATE TABLESPACE sf_table
old   2:     DATAFILE '&8'
new   2:     DATAFILE 'tbsinter.dbf'

Tablespace created.

SQL>
SQL> --Translate BasicFile to SecureFile
SQL> CREATE OR REPLACE PROCEDURE TranslateBasicToSecure( schemaName IN VARCHAR2,
2      originalTableName IN VARCHAR2, interimTableName IN VARCHAR2) IS
3  redefinition_errors PLS_INTEGER := 0;
4  BEGIN
5      -- Check whether table can be redefined
6      DBMS_OUTPUT.PUT_LINE('Checking if table can be redefined');
7      DBMS_REDEFINITION.CAN_REDEF_TABLE(schemaName, originalTableName);
8
9      -- Attempt a redefinition mapping.
10      DBMS_OUTPUT.PUT_LINE('Attempting to start redefinition');
11      DBMS_REDEFINITION.START_REDEF_TABLE (
12           uname => schemaName,
13           orig_table => originalTableName,
14           int_table => interimTableName,
15           col_mapping => NULL,
16           options_flag => DBMS_REDEFINITION.CONS_USE_PK
17      );
18
19      -- Copy data
20      DBMS_OUTPUT.PUT_LINE('Copying table dependents');
21      DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS (
22           uname => schemaName,
23           orig_table => originalTableName,
24           int_table => interimTableName,
25           copy_indexes => 0,
26           copy_triggers => TRUE,
27           copy_constraints => TRUE,
28           copy_privileges => TRUE,
29           ignore_errors => FALSE,
30           num_errors => redefinition_errors,
31           copy_statistics => FALSE,
32           copy_mvlog => FALSE
33      );
34
35      IF (redefinition_errors > 0) THEN
36          DBMS_OUTPUT.PUT_LINE('Migration errors: '
37              || TO_CHAR(redefinition_errors));
38      END IF;
39
40      DBMS_OUTPUT.PUT_LINE('Sync Interim Table');
41      DBMS_REDEFINITION.SYNC_INTERIM_TABLE(schemaName,
42          originalTableName, interimTableName);
43
44      -- Complete the redefinition process
45      DBMS_OUTPUT.PUT_LINE('Finish redefinition process');
46      DBMS_REDEFINITION.FINISH_REDEF_TABLE (
47           uname => schemaName,
48           orig_table => originalTableName,
49           int_table => interimTableName
50      );
51
52      EXCEPTION
53          WHEN OTHERS THEN
54              DBMS_OUTPUT.PUT_LINE('Exception Caught!!');
55              DBMS_OUTPUT.PUT_LINE('Error : ' || SQLCODE || ' - ' || SQLERRM);
56              DBMS_REDEFINITION.ABORT_REDEF_TABLE (
57                   uname => schemaName,
58                   orig_table => originalTableName,
59                   int_table => interimTableName
60              );
61
62  END;
63  /

Procedure created.

SQL> SHOW ERRORS;
No errors.
SQL>
SQL>
SQL>
SQL> -- Create sequence to generate unique id's
SQL> DROP SEQUENCE seq;
DROP SEQUENCE seq
            *
ERROR at line 1:
ORA-02289: sequence does not exist

SQL> CREATE SEQUENCE seq;

Sequence created.

SQL>
SQL>
SQL> -- Table containing BasicFile
SQL> DROP TABLE &3 PURGE;
old   1: DROP TABLE &3 PURGE
new   1: DROP TABLE basic_table PURGE
DROP TABLE basic_table PURGE
         *
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> CREATE TABLE &3 (
2       cnt        NUMBER,
3       cdata      CLOB,
4       bdata      BLOB,
5       prevcmb    VARCHAR2(500),
6       currentcmb VARCHAR2(500),
7       id         NUMBER DEFAULT seq.NEXTVAL
8  )
9      LOB(cdata)
10          STORE AS BASICFILE (TABLESPACE &3),
11      LOB(bdata)
12          STORE AS BASICFILE (TABLESPACE &3),
13      PARTITION BY RANGE (cnt)
14       SUBPARTITION BY HASH(id)
15      SUBPARTITIONS 8 STORE IN (&3, &3, &4, &4)
16        (PARTITION p1 VALUES LESS THAN (20),
17         PARTITION p2 VALUES LESS THAN (40),
18         PARTITION p3 VALUES LESS THAN (60));
old   1: CREATE TABLE &3 (
new   1: CREATE TABLE basic_table (
old  10:         STORE AS BASICFILE (TABLESPACE &3),
new  10:         STORE AS BASICFILE (TABLESPACE basic_table),
old  12:         STORE AS BASICFILE (TABLESPACE &3),
new  12:         STORE AS BASICFILE (TABLESPACE basic_table),
old  15:     SUBPARTITIONS 8 STORE IN (&3, &3, &4, &4)
new  15:     SUBPARTITIONS 8 STORE IN (basic_table, basic_table, sf_table, sf_table)

Table created.

SQL>
SQL>
SQL> ALTER TABLE &3 ADD CONSTRAINT PK_BASIC PRIMARY KEY(cnt);
old   1: ALTER TABLE &3 ADD CONSTRAINT PK_BASIC PRIMARY KEY(cnt)
new   1: ALTER TABLE basic_table ADD CONSTRAINT PK_BASIC PRIMARY KEY(cnt)

Table altered.

SQL>
SQL>
SQL> -- Table containing LOBs stored as SecureFile
SQL> DROP TABLE &4 PURGE;
old   1: DROP TABLE &4 PURGE
new   1: DROP TABLE sf_table PURGE
DROP TABLE sf_table PURGE
         *
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> CREATE TABLE &4 (
2       cnt        NUMBER,
3       cdata      CLOB,
4       bdata      BLOB,
5       prevcmb    VARCHAR2(500),
6       currentcmb VARCHAR2(500),
7       id         NUMBER DEFAULT seq.NEXTVAL
8  )
9      LOB(cdata)
10          STORE AS SECUREFILE (TABLESPACE &4),
11      LOB(bdata)
12          STORE AS SECUREFILE (TABLESPACE &4),
13      PARTITION BY RANGE (cnt)
14       SUBPARTITION BY HASH(id)
15      SUBPARTITIONS 8 STORE IN (&3, &3, &4, &4)
16        (PARTITION p1 VALUES LESS THAN (20),
17         PARTITION p2 VALUES LESS THAN (40),
18         PARTITION p3 VALUES LESS THAN (60));
old   1: CREATE TABLE &4 (
new   1: CREATE TABLE sf_table (
old  10:         STORE AS SECUREFILE (TABLESPACE &4),
new  10:         STORE AS SECUREFILE (TABLESPACE sf_table),
old  12:         STORE AS SECUREFILE (TABLESPACE &4),
new  12:         STORE AS SECUREFILE (TABLESPACE sf_table),
old  15:     SUBPARTITIONS 8 STORE IN (&3, &3, &4, &4)
new  15:     SUBPARTITIONS 8 STORE IN (basic_table, basic_table, sf_table, sf_table)

Table created.

SQL>
SQL>
SQL> -- Populate table containing BasicFile
SQL> DECLARE
2      cnt NUMBER;
3      dataBlob BLOB;
4  BEGIN
5      FOR cnt in 1..5 LOOP
6          INSERT INTO &3(cnt,cdata,bdata) VALUES (cnt,
7              dbms_random.string('a', round(dbms_random.value(low=>10,high=>4000))),
8              EMPTY_BLOB())
9              RETURNING bdata INTO dataBlob;
10          LoadBFile('T_WORK', 'tklolobdata.dmp', dataBlob);
11      END LOOP;
12  END;
13  /
old   6:         INSERT INTO &3(cnt,cdata,bdata) VALUES (cnt,
new   6:         INSERT INTO basic_table(cnt,cdata,bdata) VALUES (cnt,

PL/SQL procedure successfully completed.

SQL> SHOW ERRORS;
No errors.
SQL> COMMIT;

Commit complete.

SQL>
SQL> SELECT COUNT(*) FROM &3;
old   1: SELECT COUNT(*) FROM &3
new   1: SELECT COUNT(*) FROM basic_table

COUNT(*)
----------
       5

1 row selected.

SQL>
SQL> CONN &6
Connected.
SQL> SET SERVEROUTPUT ON
SQL>
SQL> SELECT SECUREFILE FROM dba_lobs WHERE table_name = upper('&3');
old   1: SELECT SECUREFILE FROM dba_lobs WHERE table_name = upper('&3')
new   1: SELECT SECUREFILE FROM dba_lobs WHERE table_name = upper('basic_table')

SEC
---
NO
NO

2 rows selected.

SQL>
SQL>
SQL> -- Translate table containing BasicFile to SecureFile
SQL> exec TranslateBasicToSecure('&1','&3','&4');
Checking if table can be redefined
Attempting to start redefinition
Copying table dependents
Exception Caught!!
Error : 100 - ORA-01403: no data found

PL/SQL procedure successfully completed.

SQL>
SQL> -- Verify if table is copied
SQL> SELECT SECUREFILE FROM dba_lobs WHERE table_name = upper('&3');
old   1: SELECT SECUREFILE FROM dba_lobs WHERE table_name = upper('&3')
new   1: SELECT SECUREFILE FROM dba_lobs WHERE table_name = upper('basic_table')

SEC
---
NO
NO

2 rows selected.

SQL> SQL>

Expected Result: Basicfile lob to be converted to Securefile lob.
Actual Result: Error : 100 - ORA-01403: no data found
SECUREFILE field in dba_lobs for the table after redefinition is 'NO'

A: Can you do a full demo? I can't replicate your error. Here's my top to bottom
SQL> create table T1 ( x int, y clob, t timestamp default systimestamp, constraint T1_PK primary key (x) )
  2   lob (y) store as basicfile ( tablespace users );

Table created.

SQL>
SQL> insert into t1 (x,y)
  2  select rownum, rpad(rownum,4000)
  3  from dual
  4  connect by level <= 100;

100 rows created.

SQL> commit;

Commit complete.

SQL>
SQL> create table T2 ( x int, y clob, t timestamp default systimestamp )
  2   lob (y) store as securefile ( tablespace largets );

Table created.

SQL>
SQL> EXEC DBMS_REDEFINITION.can_redef_table(user, 'T1');

PL/SQL procedure successfully completed.

SQL> EXEC DBMS_REDEFINITION.start_redef_table(user, 'T1', 'T2');

PL/SQL procedure successfully completed.

SQL> SET SERVEROUTPUT ON
SQL> DECLARE
  2    l_num_errors PLS_INTEGER;
  3  BEGIN
  4    DBMS_REDEFINITION.copy_table_dependents(
  5      uname             => user,
  6      orig_table        => 'T1',
  7      int_table         => 'T2',
  8      copy_indexes      => DBMS_REDEFINITION.cons_orig_params,
  9      copy_triggers     => TRUE,  -- Default
 10     copy_constraints  => TRUE,  -- Default
 11     copy_privileges   => TRUE,  -- Default
 12     ignore_errors     => FALSE, -- Default
 13     num_errors        => l_num_errors);
 14    DBMS_OUTPUT.put_line('l_num_errors=' || l_num_errors);
 15  END;
 16  /
l_num_errors=0

PL/SQL procedure successfully completed.

SQL> EXEC DBMS_REDEFINITION.sync_interim_table(user, 'T1', 'T2');

PL/SQL procedure successfully completed.

SQL> EXEC DBMS_REDEFINITION.finish_redef_table(user, 'T1', 'T2');

PL/SQL procedure successfully completed.

SQL>


text:
Q: 4x4 slide puzzle BATCH How can I make this more efficient and how can I keep the grid from breaking when you make a move. The first group of code is the setup for the batch file, the second group is part of the grid generation (I find to be to long), and the third group of code is the movement and display.
@echo off
title Slide Puzzle && setlocal enabledelayedexpansion && set default= %
set pos=16
set loop=1

Here is the 15th box in the 4x4 grid. The previous ones are not as long but the same. It first generates a random number between 1 and 15 and checks if its been used already. After this it tests if it is a single digit, if it is a single digit it adds a space in front of it so that it doesn't break the grid.
Is there a way I can shorten this?
:R15
set /a R15=%random% %% 15 +1
if %R15%==%R1% goto R15
if %R15%==%R2% goto R15
if %R15%==%R3% goto R15
if %R15%==%R4% goto R15
if %R15%==%R5% goto R15
if %R15%==%R6% goto R15
if %R15%==%R7% goto R15
if %R15%==%R8% goto R15
if %R15%==%R9% goto R15
if %R15%==%R10% goto R15
if %R15%==%R11% goto R15
if %R15%==%R12% goto R15
if %R15%==%R13% goto R15
if %R15%==%R14% goto R15
set slide15=%R15%
if %R15% lss 10 set slide15= %R15%

This is where the numbers are displayed in a 4x4 grid
:display
cls
echo  ____ ____ ____ ____
echo ^|    ^|    ^|    ^|    ^|
echo ^| %slide1% ^| %slide2% ^| %slide3% ^| %slide4% ^|
echo ^|____^|____^|____^|____^|
echo ^|    ^|    ^|    ^|    ^|
echo ^| %slide5% ^| %slide6% ^| %slide7% ^| %slide8% ^|
echo ^|____^|____^|____^|____^|
echo ^|    ^|    ^|    ^|    ^|
echo ^| %slide9% ^| %slide10% ^| %slide11% ^| %slide12% ^|
echo ^|____^|____^|____^|____^|
echo ^|    ^|    ^|    ^|    ^|
echo ^| %slide13% ^| %slide14% ^| %slide15% ^| %slide16%  ^|
echo ^|____^|____^|____^|____^|

Everything below this is how the numbers move around side to side and up and down. The problem here is that if you move a single digit number it removes one of the spaces making the grid uneven and distorted.
:movew
if %pos% GEQ 13 goto display
set /a helper=%pos% + 4
set /a slide%pos%=!slide%helper%!
set slide%helper%=%default%
set /a pos=%pos% + 4
goto display
:movea
if %pos% == 4 goto display
if %pos% == 8 goto display
if %pos% == 12 goto display
if %pos% == 16 goto display
set /a helper=%pos% + 1
set /a slide%pos%=!slide%helper%!
set slide%helper%=%default%
set /a pos=%pos% + 1
goto display
:moves
if %pos% LEQ 4 goto display
set /a helper=%pos% - 4
set /a slide%pos%=!slide%helper%!
set slide%helper%=%default%
set /a pos=%pos% - 4
goto display
:moved
if %pos% == 1 goto display
if %pos% == 5 goto display
if %pos% == 9 goto display
if %pos% == 13 goto display
set /a helper=%pos% - 1
set /a slide%pos%=!slide%helper%!
set slide%helper%=%default%
set /a pos=%pos% - 1
goto display

A: :R15
set /a R15=%random% %% 15 +1
for /l %%n in (1,1,14) do if !R%%n! equ %R15% goto R15
set slide15=%R15%
if %R15% lss 10 set slide15= %R15%

A: :set_all_r
for /L %%n in (1,1,16) do set /a R%%n=0
set /a count=1
:set_r
set /a r!count!=%random% %% 15 + 1
for /L %%n in (1,1,14) do if %%n neq %count% if !r%%n! equ !r%count%! goto set_r
set slide%count%=!r%count%!
if %count% lss 10 set "slide%count%= !r%count%!"
set /a count+=1
if %count% neq 16 goto set_r
set "slide16=  "

This routine should set R* and slide*
The first for sets R* to zero; non-zero values are assigned later.
For each count, limited to 15 (ie until incrementing it results in 16), set a random value and check that none of the R* has this value. If one is found having the same value, re-choose the random value otherwise increment the count until the limit is reached.
Since the last value to be assigned is R15 (R16 = 0, slide16="  ", an empty square) then only R1..14 need be checked.

((Please do NOT accept this answer as correct - it's merely a development on that presented by @PaulHoule ))

A:
The problem here is that if you move a single digit number it removes
  one of the spaces making the grid uneven and distorted.

You should be moving constant width label strings, not numbers.
I can think of multiple strategies for eliminating any spaces in the labels:
1) Use hexadecimal notation: 1 2 3 4 5 6 7 8 9 A B C D E F
2) Use 0 prefixes: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
Note that you cannot use such labels as numbers because 0 prefixed numbers are treated as octal, and 08 and 09 are invalid octal numbers.
3) Use Letters: A B C D E F G H I J K L M N O
But there should be no problem manipulating labels with spaces.

It first generates a random number between 1 and 15 and checks if its been used already. After this it tests if it is a single digit, if it
  is a single digit it adds a space in front of it so that it doesn't
  break the grid.
Is there a way I can shorten this?

Your strategy of randomly selecting a number between 1 and 15 until you get one that hasn't been used yet is very inefficient. Theoretically you could wait a long time before you succeed. With only 15 tiles, the wait will likely not be long, but if you had hundreds of selections to make, then you could be waiting for a loonnnnggggg time.
Much better to define a string of unused tiles, and then randomly select a position within the string. Assign the selected tile, and then remove the selected tile from the unused string.
@echo off
setlocal enableDelayedExpansion
cls

:: Define string of equal width tile labels
set "tiles= 1 2 3 4 5 6 7 8 9101112131415"

:: Iterate and assign in reverse order so %%N matches the number of available unused tiles
for /l %%N in (15 -1 1) do (

  %= Randomly select position of an unused tile, and compute the postion of next tile =%
  set /a "selected=!random!%%%%N*2,next=selected+2"

  %= Extract and assign the selected tile label =%
  for %%A in (!selected!) do (
    set "slide%%N=!tiles:~%%A,2!"

    %= Remove the selected tile from the list of unused tiles =%
    for %%B in (!next!) do set "tiles=!tiles:~0,%%A!!tiles:~%%B!
  )
)

:: Show results
set slide

Warning
I hope you realize that if you randomly arrange the tiles, you have a 50:50 chance of having an unsolvable puzzle. It is possible to compute if an arrangement is solvable. If your arrangement is not solvable, then you should be able to swap a pair of tiles to get a solvable puzzle.


text:
Q: What were the *other* two original Star Trek pilot stories submitted to NBC? When initially commissioned by NBC to write a pilot episode for Star Trek in 1964, Gene Roddenberry submitted three story outlines. Out of these three, the one that became "The Cage" was chosen by the network and filmed.
NBC rejected the pilot, but because they had chosen that story themselves from the three choices (and the story was perceived as the main source of the problems), they ordered a second set of three scripts for a second pilot, and the rest is history.
All three of these second-attempt pilot scripts eventually became episodes of the series: "Where No Man Has Gone Before", "Mudd's Women", and "The Omega Glory".
But what were the other two pilot story treatments rejected in favor of "The Cage"? I've read countless articles, "making-of" books, etc. and never seen an answer to this. Were they eventually revised and made as episodes of the show as well?
Given the "Law of Conservation of Stories" that episodic television is subject to (namely that -- due to budget crunches, tight schedules, writer strikes, and the like -- every remotely-workable plot idea will eventually be pulled out and produced as an episode), it seems unlikely that they were completely scrapped.

A: I combed through Stephen E. Whitfield's The Making of Star Trek to see what I could find.
There is no reference to titles of the other two stories that were pitched along with "The Cage."  However, after their viewing of The Cage, as we know, they ordered another pilot.  On page 134 of The Making of Star Trek the other stories are stated to be Omega Glory by Gene Roddenberry, Mudd's Women, but Stephen Kandel, and Where No Man Has Gone Before by Samuel A. Peeples.  It also states that "Roddenberry was taking no chances on a more 'cerebral' script this time -- all three represented strong action-adventure scripts."
I could not find any reference to whether any of these three stories were the same as, or in any way related to, the original stories pitched with The Cage, but it states that it was after _The Cage_ was rejected that they brought in Peeples and Kandel.  Still, that doesn't make it clear if the two were writing original stories or writing stories based on notes or an idea or other previously written stories.
I would consider The Making of Star Trek as the most authoritative source on the very early days of the series, since it was written even before the third season aired, with direct access to Roddenberry, Gene Coon, and others.  Whitfield was able to gather information before people were too involved and memories became fuzzy.
However, I found this web page Star Trek Tribute on Angelfier.  Considering this is essentially a personal page on Angelfire, I'm not sure how authoritative it is, but it states that Gene Roddenberry's Original outline for "Star Trek" was Dated March 11, 1964. And ran 16 Pages in length! In addition to it's descriptions of the series' concept and characters. It contained several story spring boards, including two which ultimately became the finish first-season Episodes "Charlie X" And "Mudd's Women"! (as Spock would Say "Fasinating".)
It does not state that those two were THE two other stories submitted with The Cage, but it's worth noting that one of those stories was fleshed out as a possible 2nd pilot.
Note: The Making of Star Trek is a LONG book and I haven't read it in years, but I'll be checking through it to see if I can find more information on this in other chapters on other topics.

A: I'm no Star Trek buff, but what I understand to be the original pitch for the series
 includes like 25 story ideas, many of which were eventually filmed, including the one that became "The Cage."  I would guess the missing two treatments are on that list.  Maybe that narrows it down a bit.


text:
Q: Prevent jquery draggable from getting -1 px when snap is on I'm using jQuery ui for the draggable function. I have snap on my parent object. The problem is the following: when the object snaps to the parent, it gets "top: -1px, left: -1px".
How can I prevent this and make it snap to 0 rather than -1?
See this jfiddle + Inspector to see what I mean:
jsfiddle.net/Fredettiw/L0dmzstq

As soon as you move the rectangle, it snaps to the .page, but it gets -1px.
(Sorry i couldnt link the jsfiddle with http, because I got an Error every time I tried to save as a link)

A: Only first time when the object snaps to the parent it gets "top: -1px, left: -1px". The reason is the parent border (border:1px solid black;). If you give parent border 10 px then it will get "top: -10px, left: -10px".
I have created 3 jsfiddle for you. In first one I removed parent border and added background property for parent (background: lightgray;) to test whether the parent border is causing issue which indeed is the root cause of the issue.
Please have a look at first jsfiddle:

     http://jsfiddle.net/Ashish_developer/cfcvyng3/

In second jsfiddle I have not removed border from parent but added top and left margin to draggable object.(ex. if parent border is 10px then give top and left margin 10 px to draggable object). It is working fine.
Second jsfiddle  URL:

     http://jsfiddle.net/Ashish_developer/7k8h131e/

In third jsfiddle I have not changed your CSS but jQuery code. Though this fiddle also serves the purpose but in this code draggable object can be dragged within the parent object not outside of it.
Third jsfiddle URL:

     http://jsfiddle.net/Ashish_developer/fr4bcpu5/

Second jsfiddle is working fine and fixes your issue.


text:
Q: Cannot find symbol using System.out.println(""); (NetBeans, IntelliJ or Eclipse) Bad english alert
Whenever I try to use System.out.println on another class besides main, every single IDE installed in my PC returns the error on the title.
I'm writing a really simple code.
On IntelliJ, I had already tried to use "Invalidated caches" but didn't work as well.
Works here:
package javaapplication3;

public class JavaApplication3 {

public static void main(String[] args) {
       System.out.println("Hi");    /* <-- This works on main, but doesn't
                                     work in any other class opened in
                                     another tab*/
}

But not in this other tab:
 package javaapplication3;

 public class NewClass {
  System.out.println("Hi");
 }

UPDATE
Here some images to specify the problem: Work here, but not here.

A: All code has to be in methods.
The command System.out.println("") will work only in a method.
Placing it under a class but not a method will result in the compiler throwing an error.
Eg:
public class test {    // class
    public static void main(String args[]) {
        // inside main method
        System.out.println("Hello, World!");  // correct
    }
}

will work perfectly fine.
But, if you place the command under just a class, it's going to result in an error.[Needs to be in a certain method]
Eg:
public class test{
    // inside a class, but no method
    System.out.println("Hello, World!"); //incorrect
}

Also, you need to make sure your class and function are not reserved keywords.
And from what you've specified above, main in not a class but it's the main method of the class.


text:
Q: Google maps nearest points avoiding rivers / by itinerary Here is the deal :
I need to find the closest points from  a point with a radius.
For example, I need to get all the points in a 15 km radius. Thats easy with Google Maps Radius and all the examples on the web ;)
The problem is that from my office, a point is under the 15km radius, but it's on the other side of a river, so the car itinerary is about 30 km (using a bridge)!
Is there a simple solution to exclude those points or to calculate by intineraries ?
I supposed that I'll need to calculate all itineraries with returned points?  DirectionsRequest API?
Thanks! :)

A: This mashup calculates driving routes in a given radius:
http://maps.forum.nu/gm_driving_radius.html
It is written with the API V2, but you can see how it's done.
note that when you say:

I need to get all the points in a 15 km radius

...you're going to need a fairly big computer because the number of points is infinite. :-)

A: *

*Use your 15km radius to refine the set of points.

*Use the Distance Matrix Service to get the distance (or at least verify that it is reasonable).


text:
Q: Fear of Information, which has been proven by statically data What is the psychological terminology for the fear of being presented with facts or shunning/deliberately ignoring facts?

A: epistemophobia: fear of knowledge
veritaphobia: fear of truth