text:
Q: How do I Convert this Ajax Post request to C# I'm making a project in c# to get a facebook ID from any facebook URL. I an API that can helps but the code is using this Ajax POST code:
        // get facebook id
    $('#get-facebook-id').submit(function(event) {

        $('#answer').html("Working for you...");

        $.ajax({
            type: 'POST',
            url: 'https://codeofaninja.com/tools/get-facebook-id-answer.php',
            data: $(this).serialize()
        })
        .done(function(data){
            $('#answer').html(data);
            $('#page_url_tb').val('')
        })
        .fail(function() {
            alert( "Posting failed. Please try again." );
        });

        return false;
    });

I'm trying to make my own code but is giving me an error. My code and my error down bellow.
private string getFbAccountID(string facebookurl)
    {
        var request = (HttpWebRequest)WebRequest.Create("https://codeofaninja.com/tools/get-facebook-id-answer.php");

        var postData = "page_url="+facebookurl;
        var data = Encoding.ASCII.GetBytes(postData);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        return responseString;
    }

Error:

Notice:  Undefined index: page_url in /home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/tools/get-facebook-id-answer.php on line 3

Notice:  Undefined offset: 1 in /home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/tools/get-facebook-id-answer.php on line 19

There was an error. Please try a different input.

This is always giving me this error. I hope someone can helps me

A: I take it you're working on this exercise. :)
But to answer your question, you're not URL encoding facebookurl.
If you use one of the example Facebook URLs on their page, and watch the network traffic using the developer tools in the browser (F12), you will see this as the form data being sent: page_url=https%3A%2F%2Fwww.facebook.com%2Fpages%2FAndrew-Garfield%2F166865773328160
jQuery's serialize() function does that for you.
In C#, you can use WebUtility.UrlEncode:
var postData = "page_url=" + WebUtility.UrlEncode(facebookurl);

A: Here you have an alternative using System.Net.WebClient, it will make your code leaner:
private string getFbAccountID(string facebookurl)
{
    using (var webClient = new System.Net.WebClient())
    {
        var formValues = new System.Collections.Specialized.NameValueCollection
        {
            { "page_url", facebookurl }
        };

        var responseBytes = webClient.UploadValues(
            "https://codeofaninja.com/tools/get-facebook-id-answer.php",
            formValues
            );

        return System.Text.Encoding.UTF8.GetString(responseBytes);
    }
}


text:
Q: First time Ubuntu user looking fir a basic image editing software I have just installed Ubuntu as dual boot on my laptop and everything runs well. I'm looking for a simple image editor. Till now I have been using the default photos app in win 8.1 and am comfortable and satisfied with the results. Is there something similar in Ubuntu? I have installed Gimp but the learning curve is steep for me and I need something which shows me a handful of preset settings/filters. You know what I'm talking about if you have used the windows photos app or snapseed

A: Hey I also faced the same issue.
Polarr works fine for me. It should help you also.
You can download it from the Ubuntu Software or the polarr website.
https://www.polarr.co/editor/0
or use
sudo snap install polarr

redpajama_set_name: RedPajamaStackExchange


text:
Q: Struggling to use sergeyt:typeahead with code schema from Discover Meteor My hope is to use Typeahead as part of a Meteor project using the recommended code organization from Discover Meteor. Atmosphere has a package, and this package looks like it should work, sergeyt:typeahead.
I would like to enable input#wbsSearch in clent/views/application/layout.html, , with typeahead, but cannot seem to figure out how to get it working. Initially I put the logic in client/views/application/layout.js, but it was telling me the global name of my collection, Wbs, was not defined yet...which I still do not understand.
Moving the code to client/main.js solved the issue of the Wbs global collection being avaialable, although I do not know why. Still, though the input field does not have the typeahead behavior, so I am still pretty perplexed.
Any insight into this is greatly appreciated. Once past this, the rest of the CRUD functionality in this little application will be relatively straightforward, but this has me stumped...at somewhat of an impasse.

A: The likely reason that Wbs is undefined in client/views/application but not in client/main.js is that nested files are loaded first, whereas main.* files are loaded last (see the docs here about load order). The way to solve the problem with the load order and the typeahead not initializing is to wrap it inside a rendered function, for example:
Template.layout.rendered = function () {
  Meteor.typeahead('input#wbsSearch', function () {
    // create list of abbreviations
    var wbsList = Wbs.find({modifier: false}).fetch().map(function (wbsItem) {
        return wbsItem.abbrev;
    });
    // return the sorted list
    return wbsList.sort();
  });
};

Doing this should ensure that the DOM is ready to be 'infected' with the typeahead (even in the nested file, client/views/application/layout.js). Hope this helps!


text:
Q: how to pass calculated values using javascript the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
      { // getting the text field the values and calculated
         var valueCom = document.getElementById("computer").value ;
         var valueMon = document.getElementById("monitor").value ;
         var valueTv  = document.getElementById("tv").value ;
         var valueLap = document.getElementById("laptop").value ;
         var valueCel = document.getElementById("cell").value;

         var finalCom = valueCom * 0.1818937134 ;
         var finalMon = valueMon * 0.056842 ;
         var finalTv  = valueTv  * 0.056842 ;
         var finalLap = valueLap * 0.090947 ;
         var finalCel = valueCel * 0.045473 ;

         var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;

         var totalCarbon  = totalTonnes * 1 ;
         var totalTree    = totalTonnes * 17.1969 ;
         var totalPetrol  = totalTonnes * 286.396 ;
         var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield

      }
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here

how to pass this values using java script to the text field. can anyone help me please

A: you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">

then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;

and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......

or,
 document.getElementById("plastic").setAttribute('value',totalCarbon);
.....

A: Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);

A: set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;

and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >

Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;

A: document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;

A: If your controls are in a form, like:
<form>
  <input type="text" name="carbon">
  <input type="text" name="tree">
  <input type="text" name="petrol">
  <input type="text" name="plastic">
  ...
</form>

then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...

Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).

A: //globally i declared carbon, tree, petrol, plastic
  document.getElementById("carbon").value   = carbon ;
  document.getElementById("tree").value     = tree ;
  document.getElementById("petrol").value   = petrol ;
  document.getElementById("plastic").value  = plastic ;


text:
Q: semi-classical Green's function I am reading Gutzwiller's papers on the relation between Hamiltonian flows and solution to Schrodinger equations.
In the two papers, he gave a semi-classical approximation of the Green's function to the Laplacian
Gutzwiller, M. C.: "The Phase Integral Approximation in Momentum Space and the Bound States of an Atom," J. Math. Phys. 8, 1979-2000 (1967).
Gutzwiller, M. C.: "The Phase Integral Approximation in Momentum Space and the Bound States of an Atom II," J. Math. Phys. 10, 1004-1020 (1969).
and on a third paper, he calculated the trace of the operator
Gutzwiller, M. C.: "Periodic Orbits and Classical Quantization Conditions," J. Math. Phys. 12, 343-358 (1971).
There are quite some literature in mathematics giving related results to the trace formula, but I am wondering is there any literature in mathematics related to the approximation of Green's function ?

A: The difference between the semiclassical approximations of the full Green's function and the trace is whether or not you restrict the sum over paths to closed orbits; for a treatment of the semiclassical Green's function (the socalled Van Vleck-Gutzwiller propagator), see for example chapter 10 of David Tannor's Introduction to Quantum Mechanics or Maslov and Fedoriuk's Semiclassical Approximations in Quantum Mechanics.


text:
Q: MySQL: Getting a specfied using subquerys with MAX() and COUNT() I'm trying to get a specified attribute from a sub-query. What i want it's the id_prova (from the sub-query)  that relates to another table that holds the correspondent  value. How can i get it "out" from there so i can make the proper comparasings. I aprecciate any help.
My query looks like this:
SELECT
  nome_Animal,
  id_prova,
  MAX(TotalAmount)
FROM
  (SELECT
    provas_animais.nome_Animal,
    provas.id_prova,
    SUM(montante) AS TotalAmount
  FROM
    patrocinador_anologo,
    provas,
    provas_animais
  WHERE patrocinador_anologo.id_prova = provas.id_prova
    AND patrocinador_anologo.id_prova = provas_animais.id_prova
  GROUP BY (provas.id_prova)) provas,
  provas_animais
GROUP BY (id_prova)

A: You meant to make your like below. What you are doing is getting data from a derived table (FROM (...)). I have as well change your join syntax to make it proper. Also, your last group by is not needed since you are just trying to get the maximum of TotalAmount.
Select nome_Animal,
id_prova,
MAX(TotalAmount)
FROM
(
select provas_animais.nome_Animal,
provas.id_prova,
sum(montante) as TotalAmount
FROM patrocinador_anologo
join provas on patrocinador_anologo.id_prova = provas.id_prova
join provas_animais on patrocinador_anologo.id_prova = provas_animais.id_prova

GROUP BY provas.id_prova
) X


text:
Q: Timezone example in broadcast receiver I am trying to implement time zone change in broadcast receiver but its not working .my requirment is if i change the time zone it will go to another activity using broad cast receiver can anybody give example
Thanks

A: In manifest:

        <receiver android:name=".TimeZoneChangedReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.TIMEZONE_CHANGED" />
            </intent-filter>
        </receiver>

In your `TimeZoneChangedReceiver` class:

   override fun onReceive(context: Context, intent: Intent) {
        var action : String? = intent.action
        var timeZone: String? = intent.getStringExtra("time-zone")
        Toast.makeText(context,action+timeZone,Toast.LENGTH_LONG).show()

A: The correct intent filter is "android.intent.action.TIMEZONE_CHANGED" (no "ACTION_" in the beginning).


text:
Q: How to use Solver Foundation to simplify a decision matrix Have been struggling a while, seek for some suggestion here hopefully.
First the decision matrix is something like this:
Condition 1 -> Condition 2 ->   Decision
 Yes           Yes          Go ahead
 Yes            No          Go ahead
  No           Yes          Go ahead
  No            No          Give up

Assumption:
1. We only consider in above sequence ("->").
2. All possible options from condition 1 & 2 are merely "Yes" and "No".
The criteria of simplification is that if the same decision is made under all possible options from the last condition, then the last condition can be omitted under the same last-1 condition. i.e.
For decision "Go ahead" *,
Condition 1 -> Condition 2 ->   Decision
 Yes        Yes =>  X       Go ahead
 Yes        Yes =>  X       Go ahead
  No           Yes          Go ahead

My initial idea is to apply solver foundation in this part(*), whereas other parts are handle by traditional programming, like for loop and recursive. In this case the final answer should be
Condition 1 -> Condition 2 ->   Decision
 Yes             X          Go ahead
  No           Yes          Go ahead
  No            No          Give up

What I am stuck in is the implementation of the following logic:
Decision & Goal:
From the set *, pick the smallest index i (i.e. pick a case which represent the key to simplify).
Constraint:
Pick cases whose condition 1 is equal to the decided case's condition 1 and then check if all possible options appear in condition 2 in all the cases picked.
Once we get the decision, which is 0, we knows the cases where condition 1 is "Yes" can have the condition 2 omitted.
See anyone can help. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SolverFoundation.Common;
using Microsoft.SolverFoundation.Services;
using Microsoft.SolverFoundation.Solvers;

namespace ConsoleApplication5
{
 class Program
 {
  static void Main(string[] args)
  {
   SolverContext context = SolverContext.GetContext();
   Model model = context.CreateModel();

   Segment[] segmentData = new Segment[] {
    new Segment { id = 0, col1 = 0, col2 = 0 },
    new Segment { id = 1, col1 = 0, col2 = 1 },//answer = 0, since this row's col1 and col2 = row 0's, thus can be omitted (simplified).
    new Segment { id = 2, col1 = 1, col2 = 0 } //answer = 0, since this row's col1 not = row 0's, thus remain unchanged.
   };

   //set
   Set items = new Set(Domain.Integer, "items");

   //decision
   Decision i = new Decision(Domain.IntegerRange(0,1), "index");
   model.AddDecisions(i);

   //parameter
   Parameter col1 = new Parameter(Domain.Integer, "col1", items);
   col1.SetBinding(segmentData, "col1", "id");
   Parameter col2 = new Parameter(Domain.Integer, "col2", items);
   col2.SetBinding(segmentData, "col2", "id");
   model.AddParameters(col1, col2);

   //constraint
   //sum of all possible col2 should be 0 + 1 = 1
   model.AddConstraint("cases",
    1 == Model.Sum(
     Model.ForEachWhere(
      items,
      s => col2[s],
      s => col1[s] == i
     )
    )
   );

   model.AddGoal("goal", GoalKind.Minimize, i);

   //problem: no suitable directive found.
   HybridLocalSearchDirective directive = new HybridLocalSearchDirective();
   directive.TimeLimit = 10000;
   Solution solution = context.Solve(directive);

   Report report = solution.GetReport();
   Console.WriteLine("{0}", i);
   Console.Write("{0}", report);
   Console.ReadLine();
  }
 }

 class Segment
 {
  public int id { get; set; }
  public int col1 { get; set; }
  public int col2 { get; set; }
 }
}

A: is it possible to use if command like this
if (Condition_One || Condition_Two)
{
 //Go ahead command
}
else
{
//Give up code
}

if you can provide a sample code which will help others to answer...
thanks


text:
Q: Error to create matrix with zeros in kotlin using Mat.zeros I'm working on developing an application using opencv. I'm uploading an image and assigning a new matrix with the same size as the original image, but in this matrix I need to fill all the rows and columns with 0. However, the function Mat.zeros is not assigning 0 in my matrix and I have the output filled with values: [D @ 13a5b9d, [D @ f3978b1, [D @ 30c17d0 ...
Oh, and I need it to be a matrix of type Mat () because I will work with opencv. Can someone help me solve this error
Code:
val srcOriginal = Imgcodecs.imread(currentPhotoPath)

val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

for(x in 0..markers.rows()) {
   for(y in 0..markers.cols()) {
      Log.i("teste", markers[x,y])
  }
}

Output expected:
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]

output:

A: Your code actually creates a matrix filled with the correct values. The thing is, markers[x,y] returns a value of type DoubleArray, not Double and hence you cannot see the actual content. If you print the values with the following line you will see that there are zeros in the matrix:
Log.i("teste", markers[x,y].contentToString())

// Alternative using the Java Arrays class
Log.i("teste", Arrays.toString(markers[x,y]))


text:
Q: Asterisk & IVR & provider I'm trying to setup an IVR or to be more specific an automated attendant using Asterisk. I don't want anything fancy besides the simple automated menu system, and instead of dialing an extension (for now) just ring the same phone line (POTS) if pressed 1 or play a recording if pressed 2. The server running Asterisk will be in a remote location.
My questions are:

*

*Is this setup doable?

*Do I need to sign up with a IAX VOIP
provider? (no VOIP calls will be
made/received) Only normal POTS calls will be made. (possible in other country)

*What hardware do I
need? Remote server side and client-wise
(POTS phone line)

Any comments will be appreciate it.
Thanks

A: This is definitely doable, however, it seems that your specifications need to be modified a bit. Here are some things to consider:

*

*What type of PSTN connectivity will your remote Asterisk server have? (SIP / POTS / T1 / PRI / etc.)

*If your remote Asterisk server is going to be using a physical medium, do you have the connectors and hardware in place? EG: If you are using a T1 line, do you have a channel bank or T1 card?

*Are you comfortable with Asterisk dialplan / AGI / AMI, or are you going to use an Asterisk distribution like trixbox, AsteriskNOW, Elastix, etc?

*Will your client location (with the POTS line you wish to ring) have a PBX, or will it just be a typical POTS line hooked up to an analog handset?

My recommendation to you:

*

*Get a cheap server (any 1U with a dual core processor and 512MB of RAM will do), and put it at your remote location.

*Load Asterisk 1.6+ onto your server. I recommend 1.6+ as it can use the dahdi_dummy driver as a reliable software timing source (it will ensure that your audio quality is not choppy and broken).

*Get a SIP account with a reliable SIP provider. My personal favorites are: flowroute and voipms.

*Set up your new SIP account in Asterisk, and purchase a DID (phone number). This phone number will be your business phone number, the one that you give out to clients and put on business cards.

*Configure your Asterisk dialplan to receive calls from your SIP account to your IVR menu.
Your IVR menu logic should be something like:
a. Play the IVR menu.
b. Wait for a keypress.
c. If the user dialed '1', then make an outgoing SIP call to the POTS line phone number you want to reach. If the user dialed '2', then playback the recorded message.
Now, if you are looking to save money, and have the most cost-effective setup for your remote IVR, I would recommend throwing up a second Asterisk server on site at your client location (where the POTS line comes in), and throw away the pots line and just setup an IAX2 trunk between your client location and your hosted server location. This way, when calls come in to your remote Asterisk server via your SIP provider, you can route the calls (when the user hits option 1) over your IAX2 trunk, directly to the client location for free!
Depending on your skill level, and comfort with Asterisk, this could be either a really fun learning experience or a confusing nightmare. If you would like to learn more about telephony and Asterisk, especially if you are going to use it for your business, you may want to use a simple (free) Asterisk distribution like: trixbox CE, Elastix, or AsteriskNOW.

A: You could code up a simple IVR in less time than it takes to install Asterisk if you use a hosted service like Twilio or Tropo. I'm partial to Twilio myself.
Edit: here's an example of a simple phone menu.

A: Quick answers to your simple questions:

*

*this setup is doable.

*no, IAX is not neccessary

*some hardware setups are listed in wiki
I think you should start with wiki and free Asterisk book


text:
Q: Set useState variable to another variable? I have two useState variables:
const [varOne, setVarOne] = useState(null);
const [varTwo, setVarTwo] = useState(null);

And a third variable that tells me which variables I need to use, varOne or varTwo:
const [whichVar, setWhichVar] = useState(0);

And I have a third variable curVar which will be either varOne or varTwo based on the value of whichVar:
const [curVar, setCurVar] = useState(null);
if (whichVar === 0) {
  curVar = varOne;
  setCurVar = setVarOne;
} else {
  curVar = varTwo;
  setCurVar = setVarTwo;
}

However I highly doubt this is the best way to do this. How would you suggest I approach this problem?


text:
Q: Insert into multiple tables connected by foreign keys Suppose I have 3 tables like so:
artist
- artist_id   // primary key, autoincrement
- artist_name // varchar

album
- album_id    // primary key, autoincrement
- artist_id   // foreign key to artist.artist_id
- album_name  // varchar

song
- song_id     // primary key, autoincrement
- album_id    // foreign key to album.album_id
- song_name   // varchar

What would be the best way to insert a single song - and associated artist and album, into their corresponding tables?

A: Easiest way is to do it like this, with 3 INSERT statements and LAST_INSERT_ID().
INSERT INTO artist(artist_name) VALUES("Name");
INSERT INTO album(artist_id, album_name) VALUES(LAST_INSERT_ID(),"Album");
INSERT INTO song(album_id,song_name) VALUES(LAST_INSERT_ID(),"Song");


text:
Q: MongoDB Aggregation and table modeling I am using MongoDB for a project that I am working on. My tables are designed as followed.
user = {
  id: ObjectID,
  friends: [ObjectID (user), ...]
  teams: [{
    "team_name": "example_team",
    "id": ObjectID,
    "users": [
      ObjectID (user),
      ObjectID (user),
      ....
    ]
  }]
}

I am trying to execute a MongoDB query in which I can find a team and return all members of the team that are friends to a given user. Would this be a suitable use case for using MongoDB aggregation? I have looked into the features of it however could not figure out how to fit it into my model. Along with that, notice how I am storing teams inside of the user. Would it be a better practice to have another table to hold users teams?
Thanks.

A: As per your description - having separate collection per team is more than accurate, but if your data usage pattern gets team data/info every time when getting user info - that could affect performance (as we need to have 2nd query to get team details).
As friend is private to user, then team is a kind of shareable object.
Aggregation framework in this case (having team separate or not) is a nice solution to scan/join data based on all userIds inside a team and return it.
As this data is not very deep (we have one level - team) transformations will be easy and efficient.
Any comment welcome!


text:
Q: How to get the confidence interval around the variable importance generated by randomForest? Using randomForest in R is it possible to get a variance or confidence interval around the importance of a variable (% difference in mean square error)?
From the randomForest package
set.seed(4543)
data(mtcars)
mtcars.rf <- randomForest(mpg ~ ., data=mtcars, ntree=1000, keep.forest=FALSE,
                          importance=TRUE)

importance(mtcars.rf, type=1)

%IncMSE
cyl  17.061579
disp 19.020929
hp   18.195448
drat  6.677707
wt   17.858616
qsec  5.849071
vs    5.467722
am    3.933137
gear  5.129811
carb  8.332738

varImpPlot(mtcars.rf)

A: In principle, permutation score (MeanDecreaseAccuracy/MeanIncreaseMSE) is an average over trees, so there is also standard deviation over trees; randomForest stores it in the importanceSD element of the model and uses when executing importance with scale=TRUE.
However, experiments show that the assumptions required to use this value for any parametric reasoning are violated in practice (see this for an overview), thus it is not a good idea to plot confidence intervals based on this.
So, if you wish to make some statistically significant claims about the importance order of attributes I would recommend doing a bootstrap and plotting boxplots of importance over iterations (possibly with notches).
And if you wish to establish a threshold between relevant attributes and noise, you really want to do feature selection, a task that will be done better by some feature selection algorithm than by visual judgement.


text:
Q: pandas assignment without loop? I have:

*

*NewData, a pd.DataFrame to be populated from

*SourceData, a list of dataframes holding source data and

*source, a dataframe holding index values for which dataframe in SourceData is to be assigned.

*indexlen, an integer for the length of indexes in the dataframes

(Using dataframes because it's critical the indexes align.)
For instance, assume that there are 1000 df's in SourceData, and indexlen is 10,000. At 10,000, I will be assigning all columns from SourceData to NewData, moving up the indexes (es because all df's share the same index) until source decrements, at which point I will start assigning the values from all columns in the dataframe in SourceData[999] to NewData, etc.
I'm currently doing this with a loop:
for j in range(1, indexlen + 1):
    NewData[j] = SourceData[source[j]].ix[j,:]

I would like to do this without using a loop, but I don't know how to broadcast this. I'm sure I'm missing something obvious, but any help would be appreciate. Thank you!
Edit:
I made source a list, because I figured that was more efficient to access by element.
In response to a question about the dataframes, they are standard price data:
>>>SourceData[1].head()

bpz1975     Open    High    Low     Close   Vol     OI
1975-02-13  2.275   2.275   2.275   2.275   0   50
1975-02-14  2.275   2.275   2.275   2.275   0   50
1975-02-18  2.275   2.275   2.275   2.275   0   50
1975-02-19  2.290   2.290   2.290   2.290   0   50
1975-02-20  2.290   2.290   2.290   2.290   0   50

In this case, reading in all months of a futures contract and then applying roll logic to create a series.

A: Creating the DataFrame, and filling it in is not usually the fastest or most pandastic way.
In this case it looks like you can do a concat:
pd.concat(SourceData)

If you need to include source, the index information, within the DataFrames in SourceData, then I would do this before doing the concat.
It's unclear exactly what this entails, but it sounds like your suggesting to set the index for each frame based on source... you can create a function which passes over SourceData changing the index of each DataFrame with that from source (without seeing source it's unclear what exactly how).


text:
Q: Preventing char pointer overflow in struct I have a function that accepts a struct * pointer containing sensitive data (in a char array) as an argument (sort of a small library).
The two struct models are as follows:
struct struct1 {
    char str[1024]; /* maybe even 4096 or 10KB+ */
    size_t str_length;
}

struct struct2 {
    char *str;
    size_t str_length;
}

The test function is:
/* Read str_length bytes from the char array. */
void foo(struct struct1/struct2 *s) {
    int i;
    for (i = 0; i < s->str_length; i++) {
        printf("%c\n", s->str[i]);
    }
}

My concern is that, since the str_length parameter is an arbitrary value, one could intentionally set it to cause a buffer overflow (actually someone stupid enough to purposely create a security flaw in its own program, but I feel I have to take such cases into account). By using the struct1 model, however, I could simply check for a possible buffer overflow by just using:
if (s->str_length > sizeof(s->str)) {
    /* ERROR */
}

The problem is that the length array is actually unknown at compile-time. So I don't know whether to use a char * pointer (struct2 style, so no overflow check) or define a very big array (struct1), which would limit the max length (something I would like to avoid) and would allocate unnecessary space most of the time (which could be problematic in embedded systems with scarce memory, I suppose). I know I have to make a compromise, I'd personally use the struct2 model, but I'm not sure if it's a good choice security-wise.

A: Put the big array at the end..
struct struct1 {
    anyType thisVar;
    someType anotherVar
    size_t str_length;
    char str[10240000]; /
}

Let the user malloc it to whatever 'real' size they wish.  If they set 'str_length' wrong, well, there's not much you can do about it, no matter what you do:(

A: Where does the user of your library get the struct2 instance to pass to the function from? I don't think he creates it by himself and then passes its address to your function, that would be a weird way to pass arguments. It is most likely returned from another function in your library, in which case you can make struct2 an opaque data type that the user cannot alter directly (or only in hacky ways):
/* in the header file */
typedef struct2_s struct2;

/* in the implementation file, where allocation is handled as well
 * so you know str_length is set to the proper value.
 */
struct struct2_s {
  char *str;
  size_t str_length;
};


text:
Q: Python subprocess nmap output different from terminal command I'm trying to use the output of nmap command in linux (shell output):
sudo nmap -sn 192.168.1.0/24
------
Nmap scan report for 192.168.1.98
Host is up (0.094s latency).
MAC Address: B8:27:EB:CE:0A:9F (Raspberry Pi Foundation)

In a python script via subprocess:
import subprocess
p = subprocess.Popen(["nmap", "-sn", "192.168.1.0/24"], stdout=subprocess.PIPE)
output, err = p.communicate()
print ("*** Running nmap -sn 192.168.1.0/24 ***\n", output)

Which works pretty well except from the fact that I NEED the MAC line that shell output has and subprocess doesn't.
subprocess output:
\nNmap scan report for 192.168.1.98\nHost is up (0.015s latency).\n

I'm working on an idea of getting IP via MAC/Name and I can't see how to do it without that line...

A: You don't need to run nmap as a subprocess in python, You can just install the nmap library and import it.
pip install python-nmap

Then write your code:
import json
import nmap

np = nmap.PortScanner()

target = '192.168.1.0/24'

# Scan the subnet
results = np.scan(hosts=target, arguments='-sn')

# Clean the data nmap returns
results = results['scan']
output = {}
for result in results:
    output[result] = {}
    # Add the MAC addr to the IP
    try:
        output[result]['mac']       = results[result]['addresses']['mac']
    except:
        output[result]['mac']       = 'No MAC address avalible'
    # Add the vendor to the IP
    try:
        output[result]['vendor']    = list(results[result]['vendor'].values())[0]
    except:
        output[result]['vendor']    = 'No vendor info avalible'

print(json.dumps(output,indent=2))

When you run your code you have to run it as sudo or else you wont get the MAC addresses.
Output should look like this
{
  "192.168.1.1": {
    "mac": "16:91:82:xx:xx:xx",
    "vendor": "No vendor info avalible"
  },
  "192.168.1.10": {
    "mac": "44:39:C4:xx:xx:xx",
    "vendor": "Universal Global Scientific Industrial"
  },
  "192.168.1.50": {
    "mac": "No MAC address avalible",
    "vendor": "No vendor info avalible"
  }
}

I hope it was helpful :-)


text:
Q: PL/SQL: Insert or Update Trigger "select count" results My trigger takes an input. (NEW:input_id) With this input, it will generate new ID's using a dynamically generate queries. The instructions
for the dynamically generated queries are stored in QUERY_REF.
It uses a cursor to retrieve query_ids for generating dynamic queries:
CURSOR C_QUERY IS
  SELECT QUERY_ID
    FROM QUERY_REF
    WHERE GENERATE_IND='Y';

OPEN C_QUERY;

LOOP
  FETCH C_QUERY INTO QUERY_ID_RET;
  EXIT WHEN C_QUERY%NOTFOUND;

INPUT_ID and QUERY_ID_RET have been used succesfully to create Output_ID in function gethostID.
I'm trying to run an insert, update based on whether a record is found. The Select counts are returning 0.
I discovered why the select counts were returning 0--I referenced the wrong table.  I still don't know why this is retrieving old dat.  Here is the entire trigger:
create or replace
TRIGGER INPUT_AUTO_QUERY_TRIG
AFTER INSERT OR UPDATE
ON INPUT_TABLE
FOR EACH ROW
 DECLARE
   ACTION_VALUE       VARCHAR2(6);
   HOLD_EVENT_ID      VARCHAR2(256);
   HOLD_USER_ID      VARCHAR2(30);
   HOLD_PK_VALUE      INTEGER(10);
   HOLD_AUDIT_ITEM_ID INTEGER(10);
   QUERY_ID_RET       NUMBER;
   resultcount        NUMBER;
   HostID      VARCHAR2(256);
   QUERY_ID       NUMBER;
   INPUT_ID         NUMBER(38,0);
   GENERATE_IND       VARCHAR2(1);
   pragma autonomous_transaction;
CURSOR C_QUERY IS
  SELECT QUERY_ID
    FROM QUERY_REF
    WHERE GENERATE_IND='Y';
BEGIN

OPEN C_QUERY;

LOOP
  FETCH C_QUERY INTO QUERY_ID_RET;
  EXIT WHEN C_QUERY%NOTFOUND;

 SELECT AUDIT_ID, USER_ID
   INTO HOLD_EVENT_ID, HOLD_USER_ID
   FROM AUDIT_EVENT_TEMP
   WHERE SESSION_ID = SYS_CONTEXT('USERENV', 'SESSIONID');

   OutputID:=getHostID(:NEW.INPUT_ID,QUERY_ID_RET);

  IF INSERTING THEN
    INSERT INTO DETAIL
  (
  DETAIL_ID,
  INPUT_ID,
  OUTPUT_ID,
  QUERY_ID,
  ACTIVE_IND,
  CREATED_BY,
  DATE_CREATED,
  MODIFIED_BY,
  DATE_MODIFIED
  ) VALUES
  (
    DETAIL_SEQ.NEXTVAL,
    :NEW.INPUT_ID,
    OutputID,
    QUERY_ID_RET,
    'Y',
    HOLD_USER_ID,
    SYSDATE,
    HOLD_USER_ID,
    SYSDATE
  );

ELSIF UPDATING THEN

SELECT COUNT(QUERY_ID) INTO resultcount FROM DETAIL WHERE             INPUT_ID=:NEW.INPUT_ID AND QUERY_ID=QUERY_ID_RET;
    IF resultcount>0 THEN
    UPDATE PATIENT_DATA_SOURCE
    SET
  HOST_ID = HostID,
  ACTIVE_IND ='Y',
  MODIFIED_BY =HOLD_USER_ID,
  DATE_MODIFIED =SYSDATE
  WHERE INPUT_ID=:NEW.INPUT_ID
  AND QUERY_ID=QUERY_ID_RET;

--don't want to change: DETAIL_ID,QUERY_ID,INPUT_ID,CREATED_BY,          DATE_CREATED in update

  ELSE
      INSERT INTO DETAIL
  (
  DETAIL_ID,
  INPUT_ID,
  HOST_ID,
  QUERY_ID,
  ACTIVE_IND,
  CREATED_BY,
  DATE_CREATED,
  MODIFIED_BY,
  DATE_MODIFIED
  ) VALUES
  (
  DETAIL_SEQ.NEXTVAL,
  :NEW.INPUT_ID,
  HostID,
   QUERY_ID_RET,
  'Y',
    HOLD_USER_ID,
    SYSDATE,
    HOLD_USER_ID,
    SYSDATE
  );
END IF;
--end if insert or update inside update

END IF;
--end IF UPDATING
END LOOP;
Close C_QUERY;

COMMIT;
END INPUT_AUTO_QUERY_TRIG;
--end trigger

A: There are no restrictions on using SELECT COUNT(*)
in a trigger - unless it is on the table the
trigger is defined on (possibility of a mutating
table).
http://psoug.org/reference/table_trigger.html
Does
    SELECT COUNT(*) FROM query_str_ref
      WHERE INPUT_ID=:NEW.INPUT_ID
        AND QUERY_ID=QUERY_ID_RET;
work on its own in an SQLPLUS session and return a
count more than zero?
If this line returns the correct count outside
the trigger, then either something in the trigger could
be impacting the count before the line is reached or
the line might not be reached at all.
If this line DOESN'T return the correct count
outside the trigger then it might be a good idea
to check the QUERY_STR_REF table data,
the new value input  ID and the
Also, are you sure that the CURSOR /FETCH
on QUERY_REF to set QUERY_ID_RET is either inside
the trigger or accessible from the trigger,
and there is no interference (QUERY_REF is
not being altered by the triggering statement)?


text:
Q: Sorting a sql database alphabetically with links/buttons Hello scripterfriends,
I'm working on a project where I need to sort a row in alphabetical order. After searching for some solutions I didn't find the one I was looking for. Lets say I need only the products that start with the letter "F". I want it like the picture below: https://gyazo.com/488ccc8fd2beaadbc96d687938e5a6ff
I need to be able to click the F and let it only show the product the start with the F.
The code I have so does the trick but I need to change the code in order to get another letter. This is the code I have so far:
<?php
require_once 'config.php';

try {
    $sQuery = "SELECT receptnummer, receptnaam, receptingredient, receptbereidingstijd, receptbereidingswijze, receptcategorie, receptbenodigdheden, receptserveertips, klantnummer
     FROM recept
     WHERE receptnaam LIKE '%f%' ORDER BY receptnaam";

    $oStmt = $db->prepare($sQuery);

    $oStmt->execute();

    if ($oStmt->rowCount() > 0) {
        echo '
';
        echo '
';
        echo 'receptnummer	';
        echo 'receptnaam	';
        echo 'receptingredient	';
        echo 'receptbereidingstijd	';
        echo 'receptbereidingswijze	';
        echo 'receptcategorie	';
        echo 'receptbenodigdheden	';
        echo 'receptserveertips	';
        echo 'klantnummer	';

        while ($aRow = $oStmt->fetch(PDO::FETCH_ASSOC)) {

            echo '
';
            echo '' . $aRow['receptnummer'] . '	';
            echo '' . $aRow['receptnaam'] . '	';
            echo '' . $aRow['receptingredient'] . '	';
            echo '' . $aRow['receptbereidingstijd'] . '	';
            echo '' . $aRow['receptbereidingswijze'] . '	';
            echo '' . $aRow['receptcategorie'] . '	';
            echo '' . $aRow['receptbenodigdheden'] . '	';
            echo '' . $aRow['receptserveertips'] . '	';
            echo '' . $aRow['klantnummer'] . '	';
            echo '
';
        }
        echo '
';
    } else {
        echo 'helaas, geen gegevens gevonden';
    }

} catch (PDOException $e) {
    $sMsg = '

    Regelnummer: ' . $e->getLine() . '

    Bestand: ' . $e->getFile() . '

    Foutmelding: ' . $e->getMessage() . '

';

    trigger_error($sMsg);
}
$db = null;
?>

Can someone help me out on this one???
Thanks in advance,
DigitalDentist

A: Apply This query
 $sQuery="SELECT receptnummer, receptnaam, receptingredient, receptbereidingstijd, receptbereidingswijze, receptcategorie, receptbenodigdheden, receptserveertips, klantnummer
 FROM recept
 WHERE receptnaam LIKE 'f%' ORDER BY receptnaam";

A: The whole trick is inside this query:
$sQuery="SELECT receptnummer, receptnaam, receptingredient, receptbereidingstijd, receptbereidingswijze, receptcategorie, receptbenodigdheden, receptserveertips, klantnummer
 FROM recept
 WHERE receptnaam LIKE '%f%' ORDER BY receptnaam";

All you need to do is to replace f in LIKE '%f%' with a variable, which you can get from a POST/GET request.
Edit: as others mentioned, you should probably replace your %f% with f%, unless you're looking for word that just include, not only start with, the letter f.


text:
Q: How to add files and folders to program directory in .NET? I'm writing a winforms application in C#. I want to have some folders (and potentially some files) always in my program's ('install') directory which I will be using in the application. Potentially moving these when I deploy the app on different machines. I also need these to be present when I am writing, compiling and testing the programme obviously.
How can I do this without writing code to create these folders on programme startup?

A: You can add whatever files you want to work with in your project  and then set the
Copy to Output Directory property of the files to Copy always option.
so that the files willbe always copied to your output directory either bin/Debug or bin/Release and you can always access them.

A: To copy a directory, go to Project->Properties->Build Events and add this:
XCOPY "$(SolutionDir)Resources\MyDir" "$(TargetDir)\MyDir\" /S /Y

"/S" will copy files recursively, and "/Y" will overwrite without prompt.


text:
Q: NSWindowController Autosave using Storyboard I have a Swift application that is launching a simple NSWindow, like so:
func applicationDidFinishLaunching(notification: NSNotification!) {
    let storyboard = NSStoryboard(name: "MainStoryboard", bundle: NSBundle.mainBundle())
    windowController = storyboard.instantiateInitialController() as? NSWindowController
    windowController?.showWindow(self)
}

This works great, my app launches and the window appears. However: The size is always the same.
In the storyboard, I have specified an Autosave name:

Note also the Restorable checkbox is checked.
But regardless, the window appears the same size, every time. This has always "just worked" in the past, so I can't tell if this is a bug, or a piece I'm missing. Does autosaving automatically work with storyboards when instantiating and showing windows manually?

A: I don't know if there is a better way, but the problem here is that when the AutosaveName is set in Interface Builder, and the Window is open via a Segue, the window is open at a predefined location and the frame is saved, overwriting the last saved frame...
If you have a predefined position to the center of the screen, each time the window will be open, it will appear in the center and the position will be saved.
To avoid this, I set the AutosaveName in the Window Controller (Not in IB), after restoring the saved Frame:
class MyWindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()

        let thewindow = window as! NSWindow

        /// restore position
        thewindow.setFrameUsingName("MyWindow")
        self.windowFrameAutosaveName = "MyWindow"
    }
}

A: In order to satisfy the two conditions identified in the accepted answer and comments, subclassing the window controller seems to work. You can then avoid setting this property uniquely in code for every window controller and simply specify the storyboard's window autosave property (and set the window controller's subclass).
The WindowController's windowFrameAutosaveName must be

*

*not blank

*different to Window's frameAutosaveName
class AutoFrameSavingWindowController: NSWindowController
{
    override func awakeFromNib() {
        if let autosaveName = window?.frameAutosaveName {
            windowFrameAutosaveName = autosaveName + " temp"
            }
        }
    }
}

A: This seems to be an Xcode bug. I was able to workaround it by manually setting the NSWindowController windowFrameAutosaveName property:
windowController?.windowFrameAutosaveName = "Main App Window"
However... This only worked for me if the property was set to a different value than what is displayed in Interface Builder. If it's programmatically set to the same value that's being used in IB, it doesn't work.
So in IB the autosave name is left to MainAppWindow, and programmatically it's set to Main App Window.


text:
Q: geometric algebra: dot products of vectors with vectors vs bivectors The book "Matrix Gateway to Geometric Algebra" by Garret Sobczyk gives the following identity:
$a\cdot(b \wedge c)=(a\cdot b)c - (a\cdot c)b$
Using the identities
$a\cdot b= (ab+ba)/2$
$a\wedge b=(ab-ba)/2$
to expand the proposed identity, including the step, e.g.,
$$a\cdot (b\wedge c)=(a(b\wedge c) + (b\wedge c) a)/2$$
I get $$abc + bca - acb - cba = abc + cba - acb - bca$$
which does not appear to check.
Is there a step I am missing?
On the same page 31 the author writes (equation 2.14)
$$a\cdot(b\wedge c) = (a(b\wedge c) - (b\wedge c)a)/2$$
which is the opposite sign to the basic "identity" I relied upon. Why is there sign minus in this instance? Is not $x=(b\wedge c)$, where x is an element, subject to the identity $a\cdot x = (ax+xa)/2$? There is a similar reversal of sign in equation 2.15.
Thanks,
Gary

A: The identities
$$a\cdot b= (ab+ba)/2$$
$$a\wedge b=(ab-ba)/2$$
are correct, but they are only for vectors $ a, b $.  Eq 2.14 from the text:
$$a\cdot(b\wedge c) = (a(b\wedge c) - (b\wedge c)a)/2$$
(with the negative sign), is also correct.  In general, if $ M $ is a k-vector, and $ a $ is a vector, then one has
$$a \cdot M=\frac{1}{{2}} \left( { a M + (-1)^{k-1} M a } \right).$$
I don't know how the Matrix Gateway book derives eq 2.14.  Here's one way to show it, rewriting the dot product as a grade 1 selection (i.e. take just the vector parts of any multivector products)
$$\begin{aligned}a \cdot \left( { b \wedge c } \right)&={\left\langle{{ a \left( { b \wedge c } \right) }}\right\rangle}_{1} \\    &={\left\langle{{ a \left( { b c - b \cdot c } \right) }}\right\rangle}_{1} \\ &={\left\langle{{ a b c }}\right\rangle}_{1} - a \left( { b \cdot c } \right),\end{aligned}$$
however, using $ b a = 2 a \cdot b - b a $, we have
$$\begin{aligned}{\left\langle{{ a b c }}\right\rangle}_{1}&={\left\langle{{ \left( { 2 a \cdot b - b a } \right) c }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - {\left\langle{{ b a c }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - {\left\langle{{ b \left( { 2 a \cdot c - c a } \right) }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b + {\left\langle{{ b c a }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b + \left( { b \wedge c } \right) \cdot a + \left( { b \cdot c } \right) a.\end{aligned}$$
Putting the pieces together, we have
$$a \cdot \left( { b \wedge c } \right)=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b + \left( { b \wedge c } \right) \cdot a.$$
Finally, note that the reverse of vector is a vector ($\tilde{a} = a$), so if we apply the reversion operator to the last term:
$$\begin{aligned}\left( { b \wedge c } \right) \cdot a&=a \cdot \left( { c \wedge b } \right) \\ &=-a \cdot \left( { b \wedge c } \right),\end{aligned}$$
and then substitute this back in, we are most of the way towards a derivation of eq 2.14 from the text:
$$a \cdot \left( { b \wedge c } \right)=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b - a \left( { b \wedge c } \right),$$
so after some trivial rearrangement, we have:
$$a \cdot \left( { b \wedge c } \right)=\left( { a \cdot b } \right) c - \left( { a \cdot c } \right) b.$$
You could also derive this from 2.14, using the reversion argument above, since the trivector terms in that antisymmetric sum cancel.

A: Assuming that we are given a multiplication that is associative
and bilinear, but not commutative, then define
$$a\cdot b := \frac12(ab+ba),\qquad
a\wedge b := \frac12(ab-ba),$$
which apply, at least for $1$-vectors, with perhaps some sign
changes for general $k$-vectors. No equation such as
$$a\cdot(b \wedge c)=(a\cdot b)c -
  (a\cdot c)b$$
can be an identity because, as you computed,
the left side is equal to
$\,\frac14(abc + cba - acb - bca)\,$ while
$\, (a\cdot b)c = \frac12(abc+bac)\,$ and
$\, a(b\cdot c) = \frac12(abc+acb).\,$
There is no way to get $\,\frac12(abc+cba)\,$
no matter what scalar factors are introduced.
The proof is by linear algebra using as the basis $$(abc,acb,bac,bca,cab,cba).$$


text:
Q: The HomeController default on laravel doesn't exist I am new on laravel, and I am making some test and following a tutorial. The matter is that I don´t know what I did two days ago that I got any defaults controllers (maybe only one... I don´t remember, for example: HomeController). I removed the project and create a new one... but now these defaults controllers don´t exit. And my routes.php on app/http folder is like this:
Route::get('/', function () {
    return view('welcome');
});

ONLY THIS!!!
I remember that the routes.php file of the first laravel test project had something like: get("home")... or get("login"), etc...
Do I need to install them via artisan or something?

A: When installing Laravel, i. e. with this command composer create-project --prefer-dist laravel/laravel blog, there is no app/Http/Controller/HomeController.php generated.
You only get one route in your routes.php. That's it!
What you could do, of course, is:

*

*Create a class HomeController.php in app/Htpp/Controllers - use php artisan make:controller HomeController

*Change the route in your routes.php to utilize the new HomeController

*

*Route::get('/', 'HomeController@index');

Another thing you may did in the past was running php artisan make:auth to initialize basic controller ands views to get a scaffold for logins/registers of users.

A: no you don't if you want to create a controller just tphp artisan make:controller HomeController and a controller will be created for you :)

A: Maybe authentication? It will create some views and routes.
https://laravel.com/docs/5.2/authentication#authentication-quickstart
The command php artisan make:auth if you are using 5.2.*


text:
Q: Error returned when calling Application.cfc method via Ajax (CF11) I'm trying to test calling methods in a ColdFusion Application.cfc file using Ajax. As far as I can tell the following should work but I keep getting the following error returned:
"Invalid request of Application.cfm, Application.cfc, or OnRequestEnd.cfm file".
I am using ColdFusion 11.
The following is my Ajax call and the relevant method in the CFC.
$.ajax({
  async: false,
  type: 'GET',
  cache: false,
  url: 'Application.cfc?method=letsTestThis',
  success: function(response){
    alert(response);
  },
  error: function(xhr, status, error){
    alert(error);
  }
});

<cfcomponent displayname="NAME" output="true" hint="Handle the application.">

  ... some more functions etc. ...

  <cffunction name="letsTestThis" access="public" returntype="string" output="false" description="">
    <cfreturn "It worked!">
  </cffunction>
</cfcomponent>

What am I doing wrong?

A: You can't directly access Application.cfc from the URL.  Your ajax call needs to hit another CFC.  Also, access type of the method will need to be public.


text:
Q: Alternatives to static methods in Java I'm making a mini ORM for a Java program I'm writing... there is a class for each table in my db, all inheriting from ModelBase.
ModelBase is abstract & provides a bunch of static methods for finding & binding objects from the db, for example:
public static ArrayList findAll(Class cast_to_class) {
  //build the sql query & execute it
}

So you can do things like ModelBase.findAll(Albums.class) to get a list of all persisted albums.
My problem is that in this static context, I need to get the appropriate sql string from the concrete class Album. I can't have a static method like
public class Album extends ModelBase {
  public static String getSelectSQL() { return "select * from albums.....";}
}

because there is no polymorphism for static methods in Java. But I don't want to make getSelectSQL() an instance method in Album because then I need to create an instance of it just to get a string that is really static in behavior.
At the moment, findAll() uses reflection to get the appropriate sql for the class in question:
select_sql = (String)cast_to_class.getDeclaredMethod("getSelectSql", new Class[]{} ).invoke(null, null);

But that's pretty gross.
So any ideas? It's a general problem I'm having time and time again - the inability to specify abstract static methods in classes or interfaces. I know why static method polymorphism doesn't and can't work, but that doesn't stop me from wanting to use it time again!
Is there any pattern/construct that allows me to ensure that concrete subclasses X and Y implement a class method(or failing that, a class constant!)?

A: Static is the wrong thing to be using here.
Conceptually static is wrong because it's only for services that don't correspond to an an actual object, physical or conceptual. You have a number of tables, and each should be represented by an actual object in the system, not just be a class. That sounds like it's a bit theoretical but it has actual consequences, as we'll see.
Each table is of a different class, and that's OK. Since you can only ever have one of each table, limit the number of instances of each class to one (use a flag - don't make it a Singleton). Make the program create an instance of the class before it accesses the table.
Now you have a couple of advantages. You can use the full power of inheritance and overriding since your methods are no longer static. You can use the constructor to do any initialisation, including associating SQL with the table (SQL that your methods can use later). This should make all your problems above go away, or at least get much simpler.
It seems like there is extra work in having to create the object, and extra memory, but it's really trivial compared with the advantages. A few bytes of memory for the object won't be noticed, and a handful of constructor calls will take maybe ten minutes to add. Against that is the advantage that code to initialise any tables doesn't need to be run if the table isn't used (the constructor shouldn't be called). You will find it simplifies things a lot.

A: Albeit, I totally agree in the point of "Static is the wrong thing to be using here", I kind of understand what you're trying to address here. Still instance behavior should be the way to work, but if you insist this is what I would do:
Starting from your comment "I need to create an instance of it just to get a string that is really static in behaviour"
It is not completely correct. If you look well, you are not changing the behavior of your base class, just changing the parameter for a method. In other words you're changing the data, not the algorithm.
Inheritance is more useful when a new subclass wants to change the way a method works, if you just need to change the "data" the class uses to work probably an approach like this would do the trick.
class ModelBase {
    // Initialize the queries
    private static Map<String,String> selectMap = new HashMap<String,String>(); static {
        selectMap.put( "Album", "select field_1, field_2 from album");
        selectMap.put( "Artist", "select field_1, field_2 from artist");
        selectMap.put( "Track", "select field_1, field_2 from track");
    }

    // Finds all the objects for the specified class...
    // Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
    public static List findAll(Class classToFind ) {
        String sql = getSelectSQL( classToFind );
        results = execute( sql );
        //etc...
        return ....
    }

    // Return the correct select sql..
    private static String getSelectSQL( Class classToFind ){
        String statement = tableMap.get( classToFind.getSimpleName() );
        if( statement == null ) {
            throw new IllegalArgumentException("Class " +
                 classToFind.getSimpleName + " is not mapped");
        }
        return statement;

    }
}

That is, map all the statements with a Map. The "obvious" next step to this is to load the map from an external resource, such as a properties file, or a xml or even ( why not ) a database table, for extra flexibility.
This way you can keep your class clients ( and your self ) happy, because you don't needed  "creating an instance" to do the work.
// Client usage:

...
List albums = ModelBase.findAll( Album.class );

...
Another approach is to create the instances from behind, and keep your client interface intact while using instance methods, the methods are marked as "protected" to avoid having external invocation. In a similar fashion of the previous sample you can also do this
// Second option, instance used under the hood.
class ModelBase {
    // Initialize the queries
    private static Map<String,ModelBase> daoMap = new HashMap<String,ModelBase>(); static {
        selectMap.put( "Album", new AlbumModel() );
        selectMap.put( "Artist", new ArtistModel());
        selectMap.put( "Track", new TrackModel());
    }

    // Finds all the objects for the specified class...
    // Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
    public static List findAll(Class classToFind ) {
        String sql = getSelectSQL( classToFind );
        results = execute( sql );
        //etc...
        return ....
    }

    // Return the correct select sql..
    private static String getSelectSQL( Class classToFind ){
        ModelBase dao = tableMap.get( classToFind.getSimpleName() );
        if( statement == null ) {
            throw new IllegalArgumentException("Class " +
                 classToFind.getSimpleName + " is not mapped");
        }
        return dao.selectSql();
    }
    // Instance class to be overrided...
    // this is "protected" ...
    protected abstract String selectSql();
}
class AlbumModel  extends ModelBase {
    public String selectSql(){
        return "select ... from album";
    }
}
class ArtistModel  extends ModelBase {
    public String selectSql(){
        return "select ... from artist";
    }
}
class TrackModel  extends ModelBase {
    public String selectSql(){
        return "select ... from track";
    }
}

And you don't need to change the client code, and still have the power of polymorphism.
// Client usage:

...
List albums = ModelBase.findAll( Album.class ); // Does not know , behind the scenes you use instances.

...
I hope this helps.
A final note on using List vs. ArrayList. It is always better to program to the interface than to the implementation, this way you make your code more flexible. You can use another List implementation that is faster, or does something else, without changing your client code.

A: Why not using annotations? They fitpretty well what you're doing: to add meta-information (here an SQL query) to a class.

A: As suggested, you could use annotations, or you could move the static methods to factory objects:
public abstract class BaseFactory<E> {
    public abstract String getSelectSQL();
    public List<E> findAll(Class<E> clazz) {
       // Use getSelectSQL();
    }
}

public class AlbumFactory extends BaseFactory<Album> {
    public String getSelectSQL() { return "select * from albums....."; }
}

But it is not a very good smell to have objects without any state.

A: If you are passing a Class to findAll, why can't you pass a class to getSelectSQL in ModelBase?

A: asterite: do you mean that getSelectSQL exists only in ModelBase, and it uses the passed in class to make a tablename or something like that?
I cant do that, because some of the Models have wildy differeing select constructs, so I cant use a universal "select * from " + classToTableName();. And any attempt to get information from the Models about their select construct runs into the same problem from the original question - you need an instance of the Model or some fancy reflection.
gizmo: I will definatly have a look into annotations. Although I cant help but wonder what people did with these problems before there was reflection?

A: You could have your SQL methods as instance methods in a separate class.
Then pass the model object into the constructor of this new class and call its methods for getting SQL.

A: Wow - this is a far better example of something I asked previously in more general terms - how to implement properties or methods that are Static to each implementing class in a way that avoids duplication, provides Static access without needing to instantiate the class concerned and feels 'Right'.
Short answer (Java or .NET): You can't.
Longer answer - you can if you don't mind to use a Class level annotation (reflection) or instantiating an object (instance method) but neither are truly 'clean'.
See my previous (related) question here: How to handle static fields that vary by implementing class
I thought the answers were all really lame and missed the point. Your question is much better worded.

A: I agree with Gizmo: you're either looking at annotations or some sort of configuration file.  I'd take a look at Hibernate and other ORM frameworks (and maybe even libraries like log4j!) to see how they handle loading of class-level meta-information.
Not everything can or should be done programmatically, I feel this may be one of those cases.


text:
Q: Drawing overlapping semi-transparent lines without darkening at overlaps I have read the post with the same title, and it was useful, but did not answer my question. My drawing program allows the user to freely draw wide lines over an image; however, I don't want the transparency darkening when they overlap lines by drawing in the same space twice.
Is there anyway to draw using canvas lineTo, stroke, strokeStyle etc so that this does not happen. Below is a code snippet to give the idea of what I did:
drawPencilDown: function(e, $this)
        {
            $this.ctx.lineJoin = "round";
            $this.ctx.lineCap = "round";
            $this.ctx.strokeStyle = "rgba(255, 255, 255, 1.0)";
            $this.ctx.fillStyle   = "rgba(255, 255, 255, 0.5)";

            $this.ctx.lineWidth = $this.settings.lineWidth;
            //draw single dot in case of a click without a move
            $this.ctx.beginPath();
            $this.ctx.arc(e.pageX*sx, e.pageY*sy, $this.settings.lineWidth/2, 0, Math.PI*2, true);
            $this.ctx.closePath();
            $this.ctx.fill();
            $this.ctx.beginPath();
            $this.ctx.moveTo(e.pageX*sx, e.pageY*sy);
        },

        drawPencilMove: function(e, $this)
        {
            $this.ctx.lineTo(e.pageX*sx, e.pageY*sy);
            $this.ctx.stroke();
        },

        drawPencilUp: function(e, $this)
        {
            $this.ctx.closePath();
        },

A: Use globalCompositeOperation="xor" and set a globalAlpha < 1.

A: I think you should use the  globalCompositeOperation property:
https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html
Both
source-atop and
destination-atop would work


text:
Q: django-mptt filter without breaking the tree I'm using django-mptt for a Article model in my Django application. If I want to get all Articles which are set to for example hidden, I could do
Article.objects.filter(hidden=False)

but that would break the mptt-tree. How can I filter on my queryset in such a way that not only does it exclude all hidden articles, but also the childs of those nodes and that way maintain the integrity of the tree so that I still can use the tree_info template tag?

A: I am having a similar issue. I would like to remove a node and all of its children.
Here is how I manage to do that:
class FolderForm(forms.ModelForm):
    class Meta:
        model = Folder
        fields = ('name', 'parent')

    def __init__(self, *args, **kwargs)
        super(FolderForm, self).__init__(*args, **kwargs)

        if self.instance is not None:
            exclude_ids = [f.id for f in self.instance.get_descendants(
                include_self=True)]

            self.fields['parent'].queryset = self.fields['parent'].queryset \
                .exclude(pk__in=exclude_ids)

A: There is a simpler solution: just set all the children to hidden as well.


text:
Q: Running my JSP myEclipse page gives a blank page I'm new to Java and I'm trying to create a project in myEclipse latest version and I'm using the following code:
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
     <title>My JSP 'blockmails.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
 </head>
   <%
          try
    {
        String flag="false";
        String ctr="false";
        String mailto=session.getAttribute("mailto").toString();
        String sub=session.getAttribute("subject").toString();
        String mess=session.getAttribute("message").toString();
        String user=request.getParameter("user");
        System.out.println(mailto+" "+sub+" "+mess+" "+user);
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","email","email");
        Statement pst=con.createStatement();
        Statement pst1=con.createStatement();
        //System.out.println("pst1:"+pst1);
        //System.out.println("pst2:"+pst2);
        Statement st=con.createStatement();
        Statement srs=con.createStatement();
        Statement st3=con.createStatement();
        //out.println("connection estblished");
        ResultSet rs=pst.executeQuery("select * from Encryptedwords");
       ResultSet rs2=st3.executeQuery("select * from swords");
      while(rs.next()&& rs2.next())
        {
            String query="select * from MAILS where subject like '%"+rs.getString(1)+"%' or subject like '%"+rs2.getString(1)+"%' or message like '%"+rs.getString(1)+"%' or message like '%"+rs2.getString(1)+"%' and mailfrom='"+user+"'";

            ResultSet rs1=st.executeQuery(query);
            ResultSet rsr1=srs.executeQuery("select * from MAILS where subject like '%"+rs.getString(2)+"%' or message like '%"+rs.getString(2)+"%' and mailfrom='"+user+"'");
            if(rs1.next()||rsr1.next())
            {
                flag="true";
                break;
            }
            else
                flag="false";
        }
        if(flag.equals("true"))
        {
            //out.println("suspicious");
            String to=user;
            String mailfrom="GNITS@suspicious mail.com";
            String subject="mail-daemon";
            String message="The mail you had sent consists of suspicious information";
            PreparedStatement pst2=con.prepareStatement("insert into inbox values(?,?,?,?)");
            pst2.setString(1,to);
            pst2.setString(2,mailfrom);
            pst2.setString(3,subject);
            pst2.setString(4,message);
            int d=pst2.executeUpdate();
        PreparedStatement pst3=con.prepareStatement("insert into blocklist values(?,?,?,?)");
            pst3.setString(1,mailto);
            pst3.setString(2,user);
            pst3.setString(3,sub);
            pst3.setString(4,mess);
            int r=pst3.executeUpdate();
            System.out.println("r is:"+d);
            if(d>0)
            {
                Statement st2=con.createStatement();
                st2.executeUpdate("delete from mails");
                response.sendRedirect("inbox.jsp?user="+to);
            }

        }
        else
        {

            Statement pss=con.createStatement();
     ResultSet sr=pss.executeQuery("select * from alertwords");
        //out.println(sr);
         while(sr.next())
        {
            Statement ss=con.createStatement();
            String query2="select * from MAILS where subject like '%"+sr.getString(1)+"%' or message like '%"+sr.getString(1)+"%' and mailfrom='"+user+"'";
            out.println("hello");
            out.println("query:"+query2);
            ResultSet sr1=ss.executeQuery(query2);
            out.println(sr1);
            if(sr1.next())
            {
                ctr="true";
                break;
            }
            else
                ctr="false";
               }
        if(ctr.equals("true"))
            {
            /*System.out.println("suspicious");
            String to=user;
            String mailfrom="krest@gmail.com";
            String subject="mail-daemon";
            String message="The mail you had sent consists of suspicious information";*/
            /*PreparedStatement pss1=con.prepareStatement("insert into inbox values(?,?,?,?)");
            pss1.setString(1,mailto);
            pss1.setString(2,mailfrom);
            pss1.setString(3,subject);
            pss1.setString(4,message);
            int d1=pss1.executeUpdate();*/
    PreparedStatement pss4=con.prepareStatement("insert into inbox values(?,?,?,?)");
            pss4.setString(1,mailto);
            pss4.setString(2,user);
            pss4.setString(3,sub);
            pss4.setString(4,mess);
            int rk=pss4.executeUpdate();
            System.out.println("r is:"+rk);
PreparedStatement pss3=con.prepareStatement("insert into alertlist values(?,?,?,?)");
            pss3.setString(1,mailto);
            pss3.setString(2,user);
            pss3.setString(3,sub);
            pss3.setString(4,mess);
            int r1=pss3.executeUpdate();
            /*System.out.println("r is:"+d1);
            if(d1>0)
            {
                Statement st3=con.createStatement();
                st3.executeUpdate("delete from mails");
                response.sendRedirect("inbox.jsp?user="+to);
            }*/
        }
        else
            System.out.println("not suspicious");
      PreparedStatement pss2=con.prepareStatement("insert into inbox values(?,?,?,?)");
            pss2.setString(1,mailto);
            pss2.setString(2,user);
            pss2.setString(3,sub);
            pss2.setString(4,mess);
            int r=pss2.executeUpdate();
            System.out.println("r is:"+r);
            if(r>0)
            {
                Statement st4=con.createStatement();
                st4.executeUpdate("delete from mails");
                response.sendRedirect("user.jsp?user="+user);
                //out.println("mail sent successfully");
            }
        }
}
    catch(Exception e){}
%>
</html>

I'm trying to create a JSP page. But the problem is, when I try to run the code, it gives a blank page. No errors or anything. Just blank. I'm very confused and I have been at this for weeks now, with no progress at all. Any help would be greatly appreciated.


text:
Q: Checking to see if path is in url I have a path that I want to check for in a url. How would I isolate
'pages/morepages/'
http://www.mypage.com/pages/morepages/
I've tried running a parse url function on my url and then I get the path. I don't know how to access that key in that array though. For example..
$url = 'http://www.mypage.com/pages/morepages/';

print_r(parse_url($url));

if ($url['path'] == '/pages/morepages/') {
    echo 'This works.';
};

I want to run an if conditional on if that path exists, but I am having trouble accessing it.

A: If you're just looking for one string within another, strpos() will work pretty well.
echo strpos( $url, $path ) !== false ? 'Exists' : 'Does Not Exist' ;

A: something like find in string ?
if ( strpos($url['path'], '/pages/morepages/') !== false ){
//echo "this works";
}

A: Here you go
$url = 'http://www.mypage.com/pages/morepages/';

    if (strpos($url, '/pages/morepages/') !== false) {
        echo "found";
    } else {
        echo "not found";
    }

A: You can simply use
if (parse_url($url['path'], PHP_URL_PATH) == '/pages/morepages/') {
    echo 'This works.';
} // No semicolon

It's probably better to use strpos() though, which is a LOT faster.

A: Just assign function's result to any variable:
$parts = parse_url($url);

if ($parts['path'] == '/pages/morepages') {
}

A: Parse_url needs to return something to a new array variable. So use:
$parsedUrl = parse_url($url));

if ($parsedUrl['path'] == '/pages/morepages/') {
    echo 'This works.';
};

A: You are not assigning the output of parse_url to a variable. $url is still equal to the string (parse_url returns an array, it doesn't modify the string passed in).
$url = parse_url($url);


text:
Q: Enable onclick event with JavaScript I need to disable all buttons that match by class name and after the function runs, enable them back. I've tried the following but no luck.
let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb.onclick = null;
}
// run some additional functions and enable

stb.onclick = true;

What am I missing?

A: You need to loop through stb again:
let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = null;
}
// run some additional functions and enable

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = true;
}

Keep in mind however that setting the onclick attribute to null won't disable the event (see @Jeremy Thille's comment).
If you want to disable a button, you should instead set its disabled property:
let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb[i].disabled = true;
}
// run some additional functions and enable

for (let i = 0; i < stb.length; i++) {
    stb[i].disabled = false;
}

A: So the main two things that are missing is that the document.getElementsByClassName("btn-st"); returns an array so when you first go through and disable the .onclick you would have to do:
let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = null;
}

For the second portion, a couple people have mentioned that setting .onclick = true; doesn't really make sense, so instead you should set the onclick to an unnamed function with the following:
// run some additional functions and enable

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = function() {
        // do things when this button is clicked
    };
}


text:
Q: Compare two files in Erlang I have two different files. First file look like this:
hallo
bye
something
new

And in second file I have eg. bye. From name of second file (eg. msg-0002) I know that this message must be second in first file. How can I, in Erlang, find that particularly word in first file? I just have to see if the second word is really bye.
That's the code I made so far:
-module(compare).
-export([compare/0]).

compare () ->
    {ok, Pars} = file:read_file("words.txt"),
    {ok, Dump} = file:read_file("msg-0002.file"),
    L1 = binary:split(Pars, <<"\n">>, [global]).
    L2 = binary:split(Dump, <<"\n">>, [global]).

In this code I get all the words in lists. I don't know how to get from name of msg-0002 file that word must be in 2. place in first file. And how to check if this particularly word is really in eg. second place in first file? That's important.

A: to extract the line number from the file name (assuming the file names are always of the form "msg-XXX.file":
FileName = "msg-0002.file",
{ok,[NumLine],_} = io_lib:fread("msg-~d.file",FileName),

and then to check if the 2 files are consistent, use Dogbert proposal:
{ok, Pars} = file:read_file("words.txt"),
{ok, Dump} = file:read_file(FileName),
L1 = binary:split(Pars, <<"\n">>, [global]),
L2 = binary:split(Dump, <<"\n">>, [global]),
Check = lists:nth(NumLine, L1) == lists:nth(1, L2),
...

A: There are many ways how you can do it, for example in escript:
#!/usr/bin/env escript

main(["-q"|ARGS]) ->
    compare(ARGS, true);
main(ARGS) ->
    compare(ARGS, false).

compare([MsgFile, WordsFile], Quiet) ->
    case io_lib:fread("msg-~d", MsgFile) of
        {ok, [N], _} when N > 0 ->
            Msg  = read_msg(MsgFile),
            Word = read_nth(WordsFile, N),
            case Msg =:= Word of
                true ->
                    Quiet orelse io:put_chars("Yes\n"),
                    halt(0);
                false ->
                    Quiet orelse io:put_chars("No\n"),
                    halt(1)
            end;
        _ -> usage()
    end;
compare(_, _) ->
    usage().

read_msg(File) ->
    {ok, FH} = file:open(File, [read, binary]),
    {ok, Msg} = file:read_line(FH),
    ok = file:close(FH),
    Msg.

read_nth(File, N) ->
    {ok, FH} = file:open(File, [raw, read, binary, read_ahead]),
    Word = read_nth_(FH, N),
    ok = file:close(FH),
    Word.

read_nth_(FH, N) ->
    case file:read_line(FH) of
        {ok, Word} when N =:= 1 -> Word;
        {ok, _} -> read_nth_(FH, N-1);
        Error -> error({words_file, Error})
    end.

usage() ->
    io:format(standard_error, "~ts [-q] <msg-file> <words-file>~n"
              "\t<msg-file> - must have name in form msg-N*~n",
              [escript:script_name()]),
    halt(255).


text:
Q: Java 8 handling of invalid UTF-8 encodings different than Java 7....? log.info(new String(new byte[]{-7, 'a'}, "UTF-8").length());

Oracle Java 1.8.0_60 leads to a printout of "2", 1.7.0_79 to "1".
?

A: You're passing in an invalid UTF-8 sequence. From the docs

The behavior of this constructor when the given bytes are not valid in the given charset is unspecified.

So in a correct implementation the returned String may as well be "Hello world!".


text:
Q: Wordpress admin search not returning results for custom post type with custom fields So I defined a custom post type of type 'Clients' with custom fields as follows:
// Clients
register_post_type( 'isa_client',
    array(
        'labels' => array(
            'name' => __( 'Clients' ),
            'singular_name' => __( 'Client' )
        ),
    'public' => true,
    'has_archive' => true,
    'hierarchical' => false,
    'show_ui' => true,
    'show_in_menu' => 'mnuIsAppointments',
    'rewrite' => true,
    'supports' => array('thumbnail')
    )
);

and also specified which columns to show on the admin clients page as follows:
add_filter("manage_edit-isa_client_columns", "isa_client_edit_columns");

function isa_client_custom_columns($column){
        global $post;
        switch ($column)
        {
            case "isa_client_salutation":
                $custom = get_post_custom();
                echo "id) . ">" . $custom["isa_client_salutation"][0] . " " . $custom["isa_client_name"][0] . " " . $custom["isa_client_surname"][0] . "";
                break;
            case "isa_client_phone":
                $custom = get_post_custom();
                echo $custom["isa_client_phone"][0];
                break;
            case "isa_client_email":
                $custom = get_post_custom();
                echo $custom["isa_client_email"][0];
                break;
            case "isa_client_address":
                $custom = get_post_custom();
                echo $custom["isa_client_address"][0];
                break;
        }
}

However when trying to search for a client using a custom field value I am not getting any results


text:
Q: Fatal Error: Found Nil While Unwrapping Optional Value TableViewCell to UIViewController I don't know what's happening.  Need help with either segue, didSelectRowAtIndexPath, or casting.  I have a tableview on top of a uiviewcontroller with a custom tableviewcell.  I successfully got an 4 arrays of Strings to present themselves in the custom cell.  Now I'm trying to pass this information to another uiviewcontroller.  I'm creating a public Int as....
var selectedVideoIndex: Int!

didSelectRowAtIndexPath is.....
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {

        let cell = self.resultsTableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath) as! ResultsTableViewCell

        let newIndexPath = resultsTableView.indexPathForCell(cell)!
        selectedVideoIndex = newIndexPath.row
        self.performSegueWithIdentifier("playerSegue", sender: self)

    }

and prepareForSegue is.....
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        if segue.identifier == "playerSegue"
        {
            let controller = segue.destinationViewController as! VideoViewController

            controller.vidTitleLBL.text = self.videoTitle[selectedVideoIndex]
            controller.videoId = self.videoId[selectedVideoIndex]

        }
    }

Also I'm manually creating segue in storyboard. Should I do it from cell to the new controller or from the view?  Thanks.
****New****
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{

    selectedVideoIndex = indexPath.row
    self.performSegueWithIdentifier("seguePlayer", sender: self)

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath) as! ResultsTableViewCell
    cell.titleLabel.text = self.videoTitle[indexPath.row]
    cell.titleLabel.adjustsFontSizeToFitWidth = true
    cell.descriptionLabel.text = self.videoDescription[indexPath.row]
    cell.descriptionLabel.adjustsFontSizeToFitWidth = true
    let url = NSURL(string: self.videoIMG[indexPath.row])
    let data = NSData(contentsOfURL: url!)
    cell.videoImage.image = UIImage(data: data!)

    return cell

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        if segue.identifier == "seguePlayer"
        {

            print(self.videoTitle[selectedVideoIndex])
            print(self.videoId[selectedVideoIndex])
            let controller = segue.destinationViewController as! VideoViewController
            controller.vidTitleLBL.text = self.videoTitle[selectedVideoIndex]
            controller.videoId = self.videoId[selectedVideoIndex]

        }
    }

Got it to successfully print.  Now giving error casting at..
controller.vidTitleLBL.text = self.videoTitle[selectedVideoIndex]
            controller.videoId = self.videoId[selectedVideoIndex]

What do think this is??  Thank for the printing suggestion btw.

A: func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) already passes the indexPath so you should not create a cell in that delegate:
selectedVideoIndex = indexPath.row

should be enough, remove the cell code .
Or better way in prepareForSegue use:
let indexPath = tableView.indexPathForSelectedRows()

then use that indexPath
print(self.videoTitle[indexPath.row])
print(self.videoId[indexPath.row])


text:
Q: Android: Access external storage directory and pass to JavaScript function in webview I want to pass a sound file which is recorded from the device and stored in device External Storage(not SD card)  to webview/javascript function.
But unable to get the actual path.
Implemented as below
    String filePath = "file://"+ Environment.getExternalStorageDirectory() + "/sound001.wav";

 webView.loadUrl("file:///android_asset/test_fft.html");
            webView.setWebViewClient(new WebViewClient() {
                public void onPageFinished(WebView view, String loc) {

                    webView.loadUrl("javascript:AudioFileRequest('"+filePath+"',0,5)");

                }
            });

filepath is giving "file:///storage/emulated/0/sound001.wav"
But my javascript function is not accepting the filepath soundfile.
Below is my javascript function
function AudioFileRequest(url,tBegin,tEnd, async) {
console.log(url);
console.log(tBegin);
console.log(tEnd+"haresh");
    window.tbegin=tBegin;
    window.tend=tEnd;
    this.tBegin=tBegin;
        this.tEnd=tEnd;
    this.url = url;
    if (typeof async == 'undefined' || async == null) {
        async = true;
    }
    this.async = async;
    var splitURL = url.split('.');
    this.extension = splitURL[splitURL.length - 1].toLowerCase();
}


text:
Q: Custom hook to call Axios POST request and sending from data but response keeps saying product_id is empty I generally call apis using custom hooks so I'm trying to get a response  from axios POST call and the data needs to be passed as form-data plus it also needs params but for some reason, it keeps showing an error saying product_id is empty because this API works in postman
Custom hook
const useProductDetails = ({ form }: ListProps) => {
  console.log("form:", form);
  const [response, setResponse] = useState<any>(null);
  const [error, setError] = useState("");

  const fetchData = (data?: any) => {
    console.log("data:", data);
    axios({
      method: "POST",
      url: BaseUrl.baseurl + "product_detail",
      data: form ? form : data,
      params: { endpoint: "product_detail" },
      headers: {
        accept: "application/json",
        "Content-Type": "multipart/form-data",
      },
    })
      .then(function (res) {
        if (res) {
          setResponse(res.data);
        }
        console.log("datainside", data);
        console.log("responsedetail", res.data);
      })
      .catch(function (error) {
        console.log("error123", error.response);
        setError(error.response.data.msg);
        console.log("errorcode", error.response.status);
      });
  };

  const callFunc = (data: any) => {
    fetchData(data);
  };

  return { response, error, callFunc };
};

Calling Custom hook
const { response, error, callFunc } = useProductDetails({
    form: null,
  });

  useEffect(() => {
    callFunc({
      product_id: "3",
    });
  }, []);

  useEffect(() => {
    if (response !== null) {
      setproduct(response.data?.product_detail);
      console.log("responsedet", response);
    }
  }, [response]);`


text:
Q: fetching an Integer from DB using Zend Framework returns the value as a string When I run an sql query using the ZF wrappers, all the numeric values return as strings.
What do I need to change so the values will return in the same data type as they are in the DB?

A: I implemented a lot of the Zend_Db code in Zend Framework.
As other have stated, the reason that Zend_Db returns strings instead of native PHP integers or floats is that PHP's database extensions return strings.  And the reason for that is that there might be no native PHP type to represent certain database type.
For example, MySQL's BIGINT is a 64-bit signed integer.  By default, the PHP int type is limited to 32-bit values, so if you fetch data from the database and implicitly convert it to int, some values might be truncated.  There are several other similar cases, for float and dates, etc.
Using the string representation for all data types is the best way to remain simple and consistent, be safe about avoiding data loss, and avoid writing lots of vendor-specific special-case code to do data type mapping.  That extra code would incur a performance penalty, too.
So if you have specific cases where you need database results to be mapped to native PHP data types, you should implement it yourself in your application code (e.g. in a custom Zend_Db_Table_Row class).

A: Databases typically return result sets as text.  Unless your db adaptor converts things for you (and to sounds like yours does not), all values will come back as strings--dates, enums, etc. as well as integers.
If you are dealing with a small number of tables with only a few integer fields, just hand convert them.  If you are dealing with a slightly more complex situation, you could iterate through the columns using the database definitions (see sqlite_fetch_column_types(), etc.).  If your situation is more complex than seems reasonable for these solutions, consider switching to a more featureful framework.

A: It appears as if this has been requested in the past but has not yet been implemented. #ZF-300 was last commented on on 9 Jan 09.
Maybe you could share why you are wanting to perform the typecasting and we could help you out another way? PHP is pretty lenient when it comes to variable datatypes...

A: For an example of using a custom Zend_Db_Table_Row to get correct data types, as Bill Karwin suggested, have a look at the class here: http://www.zfsnippets.com/snippets/view/id/70
It can be implemented in your model as:
class YourTableName extends Zend_Db_Table_Abstract
{
    protected $_name = 'your_table_name';
    protected $_rowClass = 'Model_Row_Abstract';
}

You may want to change Model_Row_Abstract's datatype for tinyint to bool if you use it strictly to hold boolean values.


text:
Q: iphone UIProgressView disappears on update Im updating a UIProgressView called "ammo". When i update the progress the UIProgressView disappears from the UIView like its being hidden or moved behind another view.
Code
- (void)updateAmmo:(float) inputAmmo capacity:(float)inputCapacity{

   //Calculate the progress value
   float value = inputAmmo/inputCapacity;

   //If nothing has changed don't update
   if(value != ammo.progress){
      [ammo setProgress:value];
   }
}

Things I have checked

*

*Checked to see if it is being hidden.

*Brought the UIProgressView to the front.

*Tried [ammo setProgress: ammo.progress-0.01]; this breaks it aswell

*Inserting a value directly works [ammo setProgress: 0.950000];

*Tried adding [ammo setNeedsDisplay];

Logging value extracts

*

*2011-07-23 15:15:34.659 XXXXXXX[2399:207] value - 1.000000

*2011-07-23 15:15:34.659 XXXXXXX[2399:207] value - 0.950000

*2011-07-23 15:15:34.712 XXXXXXX[2399:207] value - 0.900000

Thanks in advance for any assistance.

A: if u use IB for progress creation checkout u r connect with them.
i suspect about ur value property goes to immediately to 0 or below 0
        - (void)updateAmmo:(float) inputAmmo capacity:(float)inputCapacity{

            float value = inputAmmo/inputCapacity;

            if(value != [ammo progress]){
                [ammo setProgress:value];
            }
        }


text:
Q: I have a warning error when plotting with plotly I am plotting one of the first examples in Plotly:
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()

but I have the following warning:
**/opt/anaconda3/lib/python3.8/site-packages/google/colab/data_table.py:30: UserWarning:
IPython.utils.traitlets has moved to a top-level traitlets package.**

I think it is probably some installation issue. Here are some the versions of Jupyter

*

*jupyter core     : 4.6.3

*jupyter-notebook : 6.1.5

*qtconsole        : 4.7.5

*ipython          : 7.19.0

*ipykernel        : 5.3.4

*jupyter client   : 6.1.6

*jupyter lab      : 2.1.5

*nbconvert        : 5.6.1

*ipywidgets       : 7.5.1

*nbformat         : 5.0.7

*traitlets        : 4.3.3

Please let me know if you have any clue on this!!!!!
Thanks!

A: All this message is telling you that on line 30 in the file **/opt/anaconda3/lib/python3.8/site-packages/google/colab/data_table.py the import call for traitlets is now a top-level package instead of a module within IPython.utils. So you can just call traitlets directly instead of from IPython.
To solve it, you can open the file **/opt/anaconda3/lib/python3.8/site-packages/google/colab/data_table.py, make the change below on line 30. Then the message will go away.
from IPython.utils import traitlets as _traitlets

Should be changed to
import traitlets as _traitlets

If you have problems with your plot showing, you may need to change the inline magic for matplotlib to
%matplotlib auto


text:
Q: Sudden increase of response time in Jmeter I run some load tests using Jmeter.
and found out unexpected increase of response time at the end of each test plan.
Just before the end of the test plan(duration 20 minutes), the response time increased all of sudden.
It occurred again when I run same test plan with different duration(duration 30 minutes). and latency is almost the same as response times, that seems no problem on network.
I'm very curious why the response time increased even when the number of threads are decreasing. Could you guess what the reason is?
Thank you in advance.

A: From your screenshot, it is clearly visible that for both cases (20 min and 30 min) response time got increased after the test is complete (duration reached to its endpoint). That's because of threads insufficient ramp-down time.
If your JMeter test is stopped forcefully, all the active threads will be closed immediately. So the requests generated by those threads will get higher response time.

A: See  I am gussing. This happened once for me also. have you checked request are sended properly using View Result Tree Listener. Please check request status once graph getting increasing.
Or
Due to other traffic or Api is used by other users. This my be cause.


text:
Q: Drawing a simple chart using D3 and C3 I am using node.js (I am not sure if it matters in this case). I am trying to draw a simple bar chart using d3 and c3. My html looks like below. There is no output. What am I doing wrong here?

var chart = c3.generate({
 data:{
  columns:[
  ['data1', 90, 30]
  ],
  type: 'bar'
 }
});

  <title></title>

A: Use D3 v3 not v4.

  var chart = c3.generate({
 data:{
  columns:[
  ['data1', 90, 30]
  ],
  type: 'bar'
 }
});

A:

var chart = c3.generate({
 data:{
  columns:[
    ['data1', 90, 30, 100, 200]
  ],
  type: 'bar'
 }
});
<link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet"/>

You have to use d3.v3 with c3 and not the d3.v4...


text:
Q: Rails User.joins.not(...) in Active Record? Im looking to query all Users without Comments in a single sql query?
Models:
class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
end

So I want the opposite of this:
User.joins(:comments).group('users.id')

But not like this: (because it generates two queries)
User.where.not(id: Comment.pluck(:user_id))

Maybe something like this?
User.joins.not(:comments).group('users.id')

Thanks for any input!

A: If you are using postgresql you can do something like this
User.joins("LEFT join comments c on users.id = c.comment_id").
select("users.id").
group("users.id").
having("count(users.id) = 1")

This will generate this query
select u.id from users u
LEFT join comments c
on c.comment_id = u.id
group by u.id
having count(u.id) = 1

This query is not generating two SQL (neither nested sql), the above answer does.

A: You can accomplish this with:
User.includes(:comments).where.not(comments: { id: nil })

This will result in raw SQL that looks something like:
SELECT DISTINCT `users`.`*` FROM `users` LEFT OUTER JOIN `comments` ON `comments`.`user_id` = `users`.`id` WHERE `comments`.`id` IS NULL

For accomplishing this via a subquery, see the below answer.
Old Answer:
You can do something like
User.where.not(id: Comment.select(:user_id))

If you wanted a single (though nested) query.
Otherwise, check out http://guides.rubyonrails.org/active_record_querying.html#joining-tables for using an outer join.

A: Another simple solution
User.where("id NOT IN (?)", Comment.pluck(:user_id))


text:
Q: Crear consulta en SQL para calcular un precio Quisiera hacer una consulta que me retorne el costo total de una receta.

Mis tablas son:

Viandas

*

*ID

*Nombre

*ID_Cliente

*Costo (Este campo se completa cuando creo una nueva receta, donde se calcula su precio, pero la idea seria hacer la consulta que planteo en esta pregunta, y eliminar este campo)

Igredientes

*

*ID

*Nombre

*Unidad_de_Medida

*Precio

Vianda-Ingredientes

*

*ID_Ingrediente

*ID_Vianda

*Cantidad

Como pueden ver, la ultima tabla es la que relaciona a ambas. Yo quisiera obtener el costo de la vianda, que seria, primero obtener el ID de dicha vianda, ir a la tabla vianda-ingredientes y recoger todos los elementos que tengan id=id_vianda. Ahora tengo todos los Ingredientes (sus ID) que forman la receta, con sus cantidades. Tengo que ir ahora con cada uno de estos ingredientes a la tabla en cuestion, a verificar su precio. Y tengo que multiplicar cantidad*precio de ingrediente, (seria una multiplicacion por cada ingrediente que integre la receta) e ir sumando estas operaciones.
Yo lo hice con JAVASCRIPT para el front-end, y asi lo guardo originalmente en la base de datos. Esto funciona perfecto, pero el problema vino cuando quise meter un trigger que actualice mis precios de menu al actualizar un precio de un ingrediente.
Entonces estoy pensando hacer caso a lo que me dijeron los yankees, y borrar este valor de mi base de datos y calcularlo cada vez que sea necesario. De esta manera no voy a necesitar dicho trigger.
La cosa es que en JS pude hacerlo, pero con SqL soy bastante queso.

A: Si quieres calcular el costo al vuelo, lo puedes hacer en la misma consulta de esta forma.
SELECT v.ID,
    v.Nombre,
    Costo = SUM(vi.Cantidad * i.Precio)
FROM Viandas v
JOIN [Vianda-Ingredientes] vi ON v.ID = vi.ID_Vianda
JOIN Ingredientes i ON vi.ID_Ingrediente = i.ID
GROUP BY v.ID, v.Nombre;

Si quieres actualizar todos los costos para que no tengas que calcularlos cada vez (algo que no es necesario y se debe cuidar de actualizar los datos automáticamente) puedes hacer de la siguiente manera (en SQL Server)
UPDATE v SET
    Costo = c.Costo
FROM Viandas v
CROSS APPLY( SELECT SUM(vi.Cantidad * i.Precio) AS Costo
            FROM [Vianda-Ingredientes] vi
            JOIN Ingredientes i ON vi.ID_Ingrediente = i.ID
            WHERE v.ID = vi.ID_Vianda)c;

No es necesario ningún foreach o varias llamadas a la base de datos que solo agregan tráfico en la red.