text:
Q: Mockito + Dexmaker on Android I am trying to use Mockito in my Android project.
I have found very nice tutorial that deals with it: http://www.paulbutcher.com/2012/05/mockito-on-android-step-by-step/
Basically it uses new version of Mockito + Dexmaker and everything works as expected.
However, when I try to mock some Android specific object i.e:
Context context = mock(Context.class);

I receive this exception:
java.lang.IllegalArgumentException:
    dexcache == null (and no default could be found;
    consider setting the 'dexmaker.dexcache' system property)
at com.google.dexmaker.DexMaker.generateAndLoad(DexMaker.java:359)
at com.google.dexmaker.stock.ProxyBuilder.buildProxyClass(ProxyBuilder.java:252)
at com.google.dexmaker.mockito.DexmakerMockMaker.createMock(DexmakerMockMaker.java:54)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)

Any idea how to fix it?

A: So the problem is with Dexmaker not being able to find the cache path on Android >= 4.3 as other people mentioned and as described in this dexmaker issue.
I went with implementing the workaround in a custom instrumented test runner instead of in every test (or their superclass) setUp(), because it feels a bit less hacky (it really is in only one place - and not inherited in every subclass) and more flexible.
For the sake of documentation these are the necessary changes to do this:
public class CustomInstrumentationTestRunner extends InstrumentationTestRunner {

    @Override public void onCreate (final Bundle arguments) {
        super.onCreate(arguments);

        // temporary workaround for an incompatibility in current dexmaker (1.1) implementation and Android >= 4.3
        // cf. https://code.google.com/p/dexmaker/issues/detail?id=2 for details
        System.setProperty("dexmaker.dexcache", getTargetContext().getCacheDir().toString());
    }
}

And set up your project (or test project) to use this class as the instrumented test runner in its AndroidManifest.xml when building with ant:
<instrumentation
    android:name="my.package.CustomInstrumentationTestRunner"
    android:targetPackage="my.target.package" />

or its build.gradle when building with gradle:
android {
    defaultConfig {
        // ...
        testInstrumentationRunner 'my.package.CustomInstrumentationTestRunner'
    }
    // ...
}

If you have other instrumentation entries, you can switch between them either on the command line or select one in your IDE running configuration.

A: From @rjath's comment of @MrChaz's answer, this works better for me:
System.setProperty(
    "dexmaker.dexcache",
    getInstrumentation().getTargetContext().getCacheDir().getPath());

I put it in my setUp() method.

A: I had this issue for an Android Library project but NOT for the application project! Setting the System property "dexmaker.dexcache" as mentioned above worked around the issue.
I'm running Android 4.3 Nexus 4 device, building with 19.0.3 tools, target api 19,
my dependencies:
androidTestCompile "org.mockito:mockito-core:1.9.5"
androidTestCompile "com.google.dexmaker:dexmaker:1.0"
androidTestCompile "com.google.dexmaker:dexmaker-mockito:1.0"

A: It looks like the dexmaker project has moved from Google Code to GitHub.
In the maven central repository there are versions 1.1 and 1.2 published in March 2014 and December 2014.
I've verified this "dexcache == null" issue still exists through version 1.2 - but only on certain devices.  For example, a Galaxy S5 with Android 5.0 has the problem, and a Galaxy S4 with Android 4.4.2 does not.
I cloned the GitHub repository (last commit March 12th 2015 - ca74669), and ran locally, and the problem has been fixed (there are also commits in the history that back this up).  So once there is a 1.3 release, hopefully this problem is gone for good!
Anyone else wanting to run a local copy of 1.3-SNAPSHOT, here's how I did that (on a Mac, but other platforms should work too, you'll need mvn, adb, and dx on PATH):

*

*git clonehttps://github.com/crittercism/dexmaker.git

*cd dexmaker

*mvn install -Dmaven.test.skip=true

*cp -R ~/.m2/repository/com/google/dexmaker $ANDROID_HOME/extras/android/m2repository/com/google

*Then change version in app/build.gradle: androidTestCompile 'com.google.dexmaker:dexmaker:1.3-SNAPSHOT'

*

*Or pom.xml if using maven to build, or overwrite your libs/dexmaker.jar with ~/.m2/repository/com/google/dexmaker/dexmaker/1.3-SNAPSHOT/dexmaker-1.3-SNAPSHOT.jar if you are using eclipse/ant

Also, FYI, the original issue report for the same issue on Google Code as well.

A: You can add the mockito core as a dependency instead. Then, that error will not happen and you won't need a workaround.
dependencies {
   ...
   testCompile 'org.mockito:mockito-core:1.10.19'
}

A: I've managed to piece together a fix that seems to be working for me.
To the manifest I added read and write external storage.
To the test I added System.setProperty("dexmaker.dexcache", "/sdcard"); to the test.
To the emulator image I added an SD card.
I believe this works because by default mockito tries to use the apps cache directory but I never run an activity so I suspect the directory is never created by the OS

A: I observed this issue when did manipulations with resources and folders inside test folder. Actually just restarting Android Studio helped. Simple, but worked.


text:
Q: Remove 'keywords' and 'site section' from showing on front page links I have a Drupal 7 installation that shows the default front page. Published pages/nodes show up with the title, teaser text, and a list of keywords as well as the site-section under which they are categorized using the Taxonomy module.
I would like to limit the listing to only show the title and teaser, and not the site-section and keywords. How would I go about doing this?
Thanks.

A: Ok, figured it out. You have to go to:
 Administration » Structure » Content types » Story » Manage display

click on "Teaser", and choose to hide the appropriate bits.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configuring Windows Client for NFS this question is about configuring Windows 10 Client for NFS. There are two parts to it, 1) map the export (drive), 2) set IM
Let's have NFS export (/media/NFS_share 192.168.0.*(rw,async)) already present and running properly, verified from another *nix boxes sharing same network range. Now, for mounting the export on Windows box we need Services for NFS installed and simply mount:
mount.exe 192.168.0.2:/media/NFS_share *

Command unfortunately results in:
Network Error - 53
Type 'NET HELPMSG 53' for more information.

Which is clearly incorrect:
PS C:\Users> showmount -e 192.168.0.2
Exports list on 192.168.0.2:
/media/NFS_share                   192.168.0.*

So, 1) what is the issue with the mounting? 'Path not found' is somehow misleading message.
Next step would be setting identity mapping. While there are multiple ways, I chose local passwd and group files. But IdentityMapping log in ServicesForNFS-Client event log do not mention files at all, insisting on failed AD connection like there are no passwd/group files present in %SystemRoot%\system32\drivers\etc. 2) Are local files ment for Server only? Should AnonymousUid/Gid registry setting be used for client instead?
/edit: It would be worth of mentioning that opening \\192.168.0.2 in Windows explorer shows the share as \media\NFS_share but clicking it results in 'access denied' error, which seems to be more appropriate than err 53.


text:
Q: Asp.Net SQL Update Statement I have an Asp.net application on my page the user requests for a user to be removed. This then populates my 'Admin_TaskList' db.
An administrator then goes in the secure area of the site and enters the users name and clicks a button.  Upon the confirmation, the user is then deleted from my 'Users' db (already got this working) but I want my 'Admin_TaskList' db 'Status' column to change from 'To Do' to 'Completed'.
As I sad I have the delete bit working but I am struggling updating my other table.
Snippet of code I have tried
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = @Name", conn);
cmd2.Parameters.AddWithValue("@Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();

Full code
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
        {
            string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
            SqlConnection conn = new SqlConnection(connection);

            conn.Open();
            SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = @Name", conn);
            cmd1.Parameters.AddWithValue("@Name", txtRemoveUser.Text);
            SqlDataReader rd1 = cmd1.ExecuteReader();
            conn.Close();

            conn.Open();
            SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = @Name", conn);
            cmd2.Parameters.AddWithValue("@Name", txtRemoveUser.Text);
            SqlDataReader rd2 = cmd2.ExecuteReader();
            conn.Close();

            txtRemoveUser.Text = "";
            Response.Redirect("/AdminSide/TaskList.aspx");
        }

A: Instead of using a SqlDataReader to update a value use SqlCommand.ExecuteNonQuery:
int updated = cmd2.ExecuteNonQuery();

Remember that you need to use ExecuteNonQuery on commands that modify your data like Delete, Insert or Update.
MSDN:

You can use the ExecuteNonQuery to perform catalog operations (for
  example, querying the structure of a database or creating database
  objects such as tables), or to change the data in a database without
  using a DataSet by executing UPDATE, INSERT, or DELETE statements.

The complete method:
int deleted, updated;
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;

using (var conn = new SqlConnection(connection))
{
    conn.Open();
    string delSql = "DELETE FROM Users WHERE Name = @Name";
    using (var cmd = new SqlCommand(delSql, conn))
    {
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
        deleted = cmd.ExecuteNonQuery();
    }

    string updSql = @"UPDATE Admin_TaskList
                      SET Status = 'Complete'
                      WHERE Description = 'Remove User'
                      AND Name = @Name";
    using (var cmd = new SqlCommand(updSql, conn))
    {
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
        updated = cmd.ExecuteNonQuery();
    }
}


text:
Q: AccessDeniedException when retrieving AWS Parameters from Lambda I am attempting to access system parameters from a Lambda developed using C#
I have added the required lambda layer as per https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html#ps-integration-lambda-extensions-sample-commands
The lambda execution role has the following in the IAM definition (???????? replacing actual account id)
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ssm:*"
            ],
            "Resource": "arn:aws:ssm:*:???????????:parameter/*"
        }
    ]
}

As per the AWS page reference above I made a HTTP GET request to http://localhost:2773/systemsmanager/parameters/get/?name=/ClinMod/SyncfusionKey&version=1
This is failing with the following response
{
    "Version": "1.1",
    "Content": {
        "Headers": [
            {
                "Key": "Content-Type",
                "Value": [
                    "text/plain"
                ]
            },
            {
                "Key": "Content-Length",
                "Value": [
                    "31"
                ]
            }
        ]
    },
    "StatusCode": 401,
    "ReasonPhrase": "Unauthorized",
    "Headers": [
        {
            "Key": "X-Amzn-Errortype",
            "Value": [
                "AccessDeniedException"
            ]
        },
        {
            "Key": "Date",
            "Value": [
                "Thu, 01 Dec 2022 12:16:59 GMT"
            ]
        }
    ],
    "TrailingHeaders": [],
    "RequestMessage": {
        "Version": "1.1",
        "VersionPolicy": 0,
        "Content": null,
        "Method": {
            "Method": "GET"
        },
        "RequestUri": "http://localhost:2773/systemsmanager/parameters/get/?name=/ClinMod/SyncfusionKey&version=1",
        "Headers": [],
        "Properties": {},
        "Options": {}
    },
    "IsSuccessStatusCode": false
}

Any clues where I am going wrong?

A: After a discussion on an AWS forum, it looks like the issue was that I was not setting a required header of the HTTP GET request.
For this to work, it needs the  X-Aws-Parameters-Secrets-Token header set with the AWS_SESSION_TOKEN.
Once I did this it worked fine.


text:
Q: Additional interfaces in Routing and Remote Access Ok, so some of my basic installs use Routing and Remote Access the only problem is if I need to add additional Interfaces they only way I can seem to be able to do it is to disable and delete the service and then recreate it from scratch. Which luckily so far most of the system have been quite a simple setup so its not taken too long.
I seem to be having issue in both Windows Server 2008 R2 and 2012, I can't comment on the others I have not tired it.
The problem is with trying to add an interface from a physical NIC or virtual adaptor. There is no options to add one, the only interface you can add is a demand-dial interface. Restarting the system or service does nothing.
Does anyone know of any fixes for this? or quick solutions that don't including rebuilding the routing server?

A: The closest I have found to a solution is the below.

*

*Open RegEdit.exe. Go to
"HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
where each of your network adaptors (physical or virtual) has a GUID
named sub-key.

*Identify which one is your network adapter (look at
the IP or DHCP settings in the child key=values or configure a
temporary address so you can find it). Copy or note down the
GUID. (Click the GUID key then hit F2 to goto rename mode and
highlight the whole key, hit CTRL+C to copy to the clipboard.)

*Go to
"HKLM\System\CurrentControlSet\Services\RemoteAccess\Interfaces". Add
a new sub-key which is the next in sequence, for example I had
1...6 so I added "7". In is key add the following...

*

*A DWORD32 (32bit integer) called "Enabled" set to 1.

*A REG_SZ (string) called "InterfaceName" then paste your interface GUID, e.g. set to "{XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}".

*A DWORD32 called "Stamp" set to 0.

*A DWORD32 called "Type" set to 3 (LAN).

*Restart RRAS, the interface will appear! Right click each protocol, e.g. IPv4, IPv6 then you can right click "General" to add a "New Interface..." and your interface will then be enabled for that protocol.


text:
Q: Imdb iframe code not working I need to embed trailer from imdb in my application for that purpose i try to load this code which is provided by imdb officially.
<iframe src="http://www.imdb.com/video/imdb/vi336244761//embed?autoplay=false&width=480" width="480" height="270" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true" frameborder="no" scrolling="no"></iframe>

It return back a black page. I don't know why is this not working, can you help. thanks

A: There is typo with imdb api.
"http://www.imdb.com/video/imdb/vi336244761//embed?autoplay=false&width=480"
It should be:
"http://www.imdb.com/video/imdb/vi336244761/imdb/embed?autoplay=false&width=480"


text:
Q: Overwrite Expansion File (Android) My expansion file is 200 Mb. I can't see it viable to pull files out of it in realtime (too slow for my purposes). So, I'm extracting all of them to regular files in other folder.
Now, I want to save some space on the card for my beloved user by avoiding app data duplication.
I have an idea to delete the actual expansion file and replace it with a zero size dummy, to fool Google Play and prevent it from downloading 200Mb again. Would that trick work?
I can't test for that as my app is not published yet.

A: I have no idea what kind of data they look at in order to redownload the expansion file, but if you don't want to use it as intended I think you'll have an easier time hosting your files and downloading them through your own download mechanism.


text:
Q: Is there a way to update the dojo tree item id with the id come from database? I have a dojo tree that its nodes are created temporary in memory. I assigned every new node an id by timestamp like this:
var newID = new Date().getTime().
This new node will associate with a form to control its info. My expected is: when the form is submit, the new id came from the database will replace the timestamp id above. How can I do this?
Thanks!!!


text:
Q: How to show a process list using Ansible ad-hoc? How to show a process list using ansible ad-hoc command?

A: Ansible Ad-hoc Syntax:
ansible <"hosts"> [-m <"module_name">] -a <"arguments"> -u  [--become]
Ex:
ansible <"hosts"> -m shell -a 'ps -ef'
Hosts: It can be any entry in the inventory file. For specifying all hosts in inventory, use all or '*'. Wild card patterns are also accepted.
module_name: It's an optional parameter. There are hundreds of modules available in Ansible. By default it is a command. For example, shell, copy, yum, apt, file.
Arguments: We should pass values that are required by the module. It may change according to the module used.
Username: It specifies the user account in which Ansible can execute commands. User account, SSH.
Become: It's an optional parameter specified when we want to execute operations that need sudo privilege. By default become is false.
PS: If you put a -c option, then Ansible will do a dry run of the command. It will not actually be applied on the nodes.


text:
Q: Convert a entryGetText into Int gtk2hs I'm trying to convert a entryText into a string, so I can use it for other functions.
`unsafePerformIO (entryGetText txtMagn)`

While trying to compile this code, I get the error message:
`Couldn't match type 'IO a0 -> a0' with '[Char]'
    Expected type: String
      Actual type: IO a0 -> a0
    Probable cause: 'unsafePerformIO' is applied to too few arguments
    In the first argument of 'putStrLn', namely 'unsafePerformIO'`

Thanks in advance

A: This is because you wrote
putStrLn unsafePerformIO (entryGetText txtMagn)

Here you pass unsafePerformIO to putStrLn as a parameter. You actually meant:
putStrLn (unsafePerformIO (entryGetText txtMagn))

Now to the unsafePerformIO. As its name suggests, it is unsafe, so you'd better have a clear idea what are you trying to accomplish. To safely pull out your value out of the IO and use it later:
text <- entryGetText txtMagn
putStrLn text

A: To get the value, you have to use the read function:
val <- getLine
someFunctionWhichNeedsTheValue (read val ::Float)


text:
Q: Adding a css ::before to an element using jQuery I know this sounds silly and you're going to ask why I'm just not using css, I assure you I have a reason. I'm building an app that is configurable to the user and part of that is changing the background color. Changing the background color is no problem however I have one spot where I'm gently fading an image into the background using a css shadow on a ::before.
My css kind of looks like this
-moz-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);
-webkit-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);
box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);

And to try and covert it to jQuery I tried something like this
$('.titleImage .shadow::before').css('-webkit-box-shadow', "inset 0px 0px 90px 50px" + Props['BackgroundColor']);

But it doesn't want to work. Any help would be appreciated!

A: jQuery can't target pseudo elements (don't ask for a workaround, there isn't one), but you can toggle a class on an element that adds/removes/modifies pseudo elements.

$('div').on('click',function(){ $(this).toggleClass('pseudo'); });
div:before {
  content:"Hi";
  border: 1px solid #000;
  }

div.pseudo:before { border-width: 3px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  </div>

A: Pseudo selector can not select using jquery. Work around is using inline css instead like below:
$('.titleImage .shadow').append('<style> .titleImage .shadow::before {-moz-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98); -webkit-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);}</style>');

You can remove that style as well if needed

A: Add an element to the dom, like:
<style id="mySpecialStyles"></style>

And a function like:
function changeColor(newColor){
    $('#mySpecialStyles').text(
        '.titleImage .shadow::before{' +
        '-webkit-box-shadow:inset 0px 0px 90px 50px '+ newColor +';' +
        'box-shadow:inset 0px 0px 90px 50px '+ newColor +';}'
    )
}

// called like
changeColor('#000000');

That keeps it to a single style tag that you alter.
Check out this demo fiddle.
HTH


text:
Q: Convert distance matrix to adjacency matrix - Graph Analysis I have a dataset made up of 62 variables (categorical and numerical) and 60,000 observations. I want to generate a graph analysis from a distance matrix that I have calculated for the predictor variables.
As there is a distance between all the units evaluated, each node has the same number of vertices. I would like only those units with the shortest distance (strongest relationship). How can I do this? Is there any way to weight the distance matrix and turn it into a binary adjacency matrix?
A replicable example:
library(RColorBrewer)
library(igraph)

size=200
set.seed(1)

df <- data.frame(
  x1 = rnorm(size,mean = 0, sd=1),
  x2 = rnorm(size,mean = 0, sd=1),
  x3 = rnorm(size,mean = 0, sd=1),
  x4 = sample(c(1, 0), size, replace = TRUE),
  x5 = sample(c(1, 0), size, replace = TRUE),
  x6 = sample(c(1, 0), size, replace = TRUE))
y = rnorm(size,mean = 0, sd=1)

df <- data.frame(df, row.names = paste0("ID_",1:size))

d <- dist(df, method = "euclidean")
m <- data.frame(t(combn(rownames(df),2)), as.numeric(d))
names(m) <- c("c1", "c2", "distance")

n <- cbind(paste0("ID_",1:size),sample(LETTERS[1:5],size, replace = T))
unities <- graph_from_data_frame(m, directed = FALSE, vertices = n)

set.seed(1001)
unities_deg<-degree(unities,mode=c("All"))

pal<-brewer.pal(length(unique(V(unities)$V2 )), "Set3")
plot(unities,edge.color = 'black',vertex.label.cex =0.5,
     vertex.color=pal[as.numeric(as.factor(vertex_attr(unities, "V2")))],
     vertex.size = sqrt(unities_deg)/3, edge.width=sqrt(E(unities)$weight/800),
     layout = layout.fruchterman.reingold)


text:
Q: How can I display an array of strings but selecting the index of the string in the array for form Here is my problem.
I have a table for roles with two columns id and name.
The column id is linked through foreign key to the column role_id in the users table. The columns id and role_id are of type integer.
In the table roles I have these 4 records:
id name
-- ----
1  owner
2  doctor
3  receptionist
4  customer

For user I have a form to edit the privileges like admin and role_id.
I want to display values like the role names but when I click on the Submit button I want the id or role_id integer value to be used to update the customer.
The user_controller.rb file:
  def show
    @user = User.includes(:role).find(params[:id])
    #@role = @user.role
  end

  def edit
    @user = User.includes(:role).find(params[:id])
  end

  def update
    @user = User.includes(:role).find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "User Priviladges Updated"
      #log_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :role_id,
      :password, :password_confirmation, :admin)
    end

The edit.html.erb file:

Edit User Privileges

<%= "Name: " %><%=@user.name%>

<%= "Email: " %><%=@user.email%>

<%= "Role: " %><%=@user.role.name%>

<%= "Role ID: " %><%=@user.role_id%>

<%= form_for(@user) do |f| %>

    <%= f.check_box :admin %>
    <%= f.label :admin %>

    <%= f.label :role_id %>
    <%=f.select :role_id, options_for_select([1,2,3,4], f.object.role_id), :include_blank => false %>

    <%= f.button 'Submit', class: "btn btn-sm btn-info" %>

  <%= link_to 'Back', :back %>
<% end %>

The code works and values for role_id are updated correctly. However how I can display string in the drop down select list instead of numbers?

A: The solution I found is:
<%= f.select :role_id, options_from_collection_for_select(Role.order("id"), :id, :name, @user.try(:role_id)) %>


text:
Q: Read the second largest number in an array I've written a console application (.NET 5.0) in C# in Visual Studio which sorts an array from high to low and then it has to print out the second largest element in that array.
Im getting close but ive been trying things for the past 2 hours and I don't get why I always get an out of bounds error at the last 'if'. The program is supposed to detect duplicates so for instance if the input is '1 1 2 2 5 5 9 9" it will print out "5" as it is the second largest.
My current code is below I can't get it to work without crashing
using System;
namespace second_largest
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] input = Array.ConvertAll(Console.ReadLine().Split(" "), Convert.ToDouble);

            for (int repeat = 0; repeat < input.Length; repeat++)
            {
                for (int j = 0; j < input.Length - 1; j++)
                {
                    if(input[j] < input[j+1])
                    {
                        double temp = input[j];
                        input[j] = input[j + 1];
                        input[j + 1] = temp;
                    }
                }
            }

            for (int i = 0; i < input.Length; i++)
            {
                if(input[i] == input[i + 1])
                {

                }
                else
                {
                    Console.WriteLine(input[i]);
                }
                Console.WriteLine(input[i]);
            }
        }
    }
}

A: There is a much easier way to get the second highest using LINQ
It involves grouping by the number (to eliminate duplicates), then ordering by the grouped key descending, then skipping one and taking one
var secondHighest = nums.GroupBy(n => n)
                        .OrderByDescending(n => n.Key)
                        .Skip(1)
                        .First()
                        .Key;

Live example: https://dotnetfiddle.net/WlFyWr

A: You see the error because you iterate up to i < input.Length which means that i + 1 on the following if statement is out of bounds of the length of the input array. You need to do the same thing you've done on the previous nested for loop:
for(int i = 0; i < input.Length - 1; i++)


text:
Q: Spinner in AlertDialog Box - Android Here's the code I have so far.
playername.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:fontFamily="sans-serif"
        android:paddingTop="@dimen/fab_margin"
        android:text="Choose the server: "
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textStyle="bold" />
    <Spinner
        android:id="@+id/serverspinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/servers_array">
    </Spinner>
</LinearLayout>

<EditText
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:hint="@string/insert_name"
    android:maxLines="1" />

</LinearLayout>

MainActivity.java
....
public void playerStats(final View v) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    final LayoutInflater inflater = getLayoutInflater();
    final View inflator = inflater.inflate(R.layout.playername, null);
    final Spinner spinner = (Spinner) findViewById(R.id.serverspinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(v.getContext(),
            android.R.layout.simple_spinner_item, getResources()
            .getStringArray(R.array.servers_array));
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    builder.setView(inflator)
            .setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    String server = spinner.getSelectedItem().toString();
                    EditText userNameText = (EditText) inflator.findViewById(R.id.username);
                    String userName = userNameText.getText().toString();
                    Intent intent = new Intent(MainActivity.this,PlayerStats.class);
                    intent.putExtra("nume",userName);
                    intent.putExtra("sever",server);
                    startActivity(intent);
                }
            })
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
                              })
    ;
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

In my layout.xml (not shown because it's not important), I have a button that starts "playerStats" function from my activity which brings up an alertdialog window where I give some input. In this window, I have a spinner and an edittext and I can't get the spinner to work properly (to work properly means to be able to get the string selected from the array - servers_array).
From the line marked in MainActivity, I get this error:
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference

A: I managed to get it to work.
Replace this line:
final Spinner spinner = (Spinner) findViewById(R.id.serverspinner);

With this one:
final Spinner spinner = (Spinner) inflator.findViewById(R.id.serverspinner);


text:
Q: Invalid C if statement? I am teaching myself C and I seem to be getting incorrect output when running the program. I always get 'They are equal', even if they are not, also, the return value seems to only print the first word of whatever is inputted, how can I fix this?:
#include <stdio.h>
char var[0];
char var2[0];
int main(void) {
    printf("Enter Var 1=> ");
    scanf("%s", &var);
    printf(var);
    printf("\n");
    printf("Enter Var 2=> ");
    scanf("%s", &var2);
    printf(var2);
    printf("\n");
    if (var == var2)
        printf("They are equal");
    else
        printf("They Are not equal");
}

A: Your var and var2 buffers are zero-length arrays ([0]), so your use of scanf is writing to unallocated memory and you're encountering undefined behavior.
Allocate a sufficiently sized buffer, preferably on the stack because you should avoid global variables and use a scanf format-string with a length restriction: https://msdn.microsoft.com/en-us/library/xdb9w69d.aspx
If you're outputting a string without a format-specifier, use puts instead of printf.
int main(void) {

    char var1[100] = {0}; // 100 characters should be sufficient
    char var2[100] = {0};
    puts( "Enter Var 1=> " );
    scanf( "%99s", &var1 ); // restricted to 99 characters, +1 for the null terminator equals 100
    printf( "%s\n", var1 );

    puts( "Enter Var 2=> " );
    scanf( "%99s", &var2 );
    printf( "%s\n", var2 );

    if( strcmp( var1, var2 ) == 0 ) { // use strcmp to compare strings, not the `==` operator because C does not have operator overloading
        puts("They are equal");
    }
    else {
        puts("They are not equal");
    }
}


text:
Q: How to target react components in JSX using CSS media queries I am creating a blog using Gatsby, and for simplicity's sake, I have a main content component and a blog posting archive component as a second column to the right of the main content component. How do I target the archive component to make it "display: none" when using a CSS media query for mobile screen sizes?
For example, here is a snippet of layout.js:
const MainLayout = styled.main`
  font-family: Roboto, sans-serif;
  max-width: 90%;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 3fr 1fr;
  grid-gap: 40px;
  footer {
    padding-bottom: 30px;
    a {
      color: red;
    }
  }
`;

const Layout = ({ children }) => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => (

        <MainLayout>

{children}

          <Archive />

            © {new Date().getFullYear()} / Built by Michael Henry with
            {` `}
            Gatsby

        </MainLayout>

    )}
  />
);

If I select the <Archive> component in a media query like this:
@media only screen and (max-width: 480px) {
  Archive {
    display: none;
  }
}

Nothing happens. If I wrap the <Archive> component with a
 like so:

  <Archive />

@media only screen and (max-width: 480px) {
  .noMobile {
    display: none;
  }
}

I can make the archive component disappear, but the  is now at the top of the page in the same column to the right in which the archive component was. I think it may have something to do with my grid layout, but I cannot figure it out. How do I select the grid layout to change within this media query if it is in a styled component (<MainLayout>)?
Thanks


text:
Q: NeoVim/Vim showing wrong Python version I used to have Python 3.8-dev installed via pyenv but later I uninstalled this version. Now I only have 3.7.5 installed on my machine. pyenv versions results:

Now I believe the global default is also 3.7.5. However, when I open a python file using either NeoVim or Vim, from the bottom bar it still shows Python 3.8.1 64-bit although I believe I don't have that version on this machine at all. Any idea why this would happen? I believe it's because somehow Vim still thinks I have the 3.8.1 version but don't know how to fix it. Thanks!

Vim v8.1
NeoVim v0.4.3

A: You could specify the python version you have on your computer
first, locate your python interpreter with:
which python
then you take that output and on top of your .vimrc ( for vim ) or init.vim ( for neovim ) :
let g:python3_host_prog = expand('/path/to/your/python')

hope it help!

A: Turned out this is the coc.nvim extension coc-python. You need to manually set :CocCommand python.setInterpreter to pick the right python version in neovim. Related issue is here.


text:
Q: Feature selection when data is less, sparse and imbalanced Is there any way to select the features when i am having less, sparse and imbalanced data.
Around 90% of samples are ordinal and 10% are numerical.
Number of features: 200
Number of samples: around 1000

A: Yes, It is possible to do feature selection for sparse data. The possible approaches are:

*

*chi-2 based feature selection

*RandomForestClassifier/RandomForestRegressor

*xgboost

Try doing feature selection in the original dataset and in the balanced dataset using oversampling techniques (such as SMOTE) or undersampling. SMOTE stands for Synthetic Minority Over-sampling. There is a dedicated package for balancing imbalanced datasets in Python. You may use this package https://pypi.python.org/pypi/imbalanced-learn.
Some kind of domain knowledge is preferred in feature selection as suggested in this highly cited paper on feature selection. Compare the feature importance on balanced and the original data to do the final selection of features.
References:
http://blog.kaggle.com/2016/07/21/approaching-almost-any-machine-learning-problem-abhishek-thakur/
http://ogrisel.github.io/scikit-learn.org/sklearn-tutorial/modules/generated/sklearn.feature_selection.chi2.html#sklearn.feature_selection.chi2
http://ogrisel.github.io/scikit-learn.org/sklearn-tutorial/modules/feature_selection.html
https://www.cs.cmu.edu/afs/cs/project/jair/pub/volume16/chawla02a-html/node6.html


text:
Q: Not getting output while creating Hash of Arrays I am trying to create hash of arrays. I am taking data from a txt file and converting this into hash of arrays.
Txt file data is as below
group1 : usr1 usr4 usr6
group2 : usr2 usr1 usr5
group3 : usr1 usr2 usr3

so on ......
I am converting this hash of arrays like
%hash = (group1 => [usr1 usr4 usr6], group2 => [usr2 usr1 usr5]);

Following code i am trying
%hash = ();
open (FH, "2.txt") or die "file not found";
while (<FH>) {
@array = split (":", $_);
$array[1] =~ s/^\s*//;
$array[1] =~ s/\s*$//;
@arrayRef = split (" ", $array[1]);
$hash{$array[0]} = [ @arrayRef ];
#print @array;
#print "\n";
}
close FH;

print $hash{group1}[0];
print @{ $hash{group2}};

I am not getting output. There is something wrong in the code. Please help me understanding it better

A: Your code works for me, but the problem is that you are using the key "group1 " (note the extra space), and not "group1" like you think. When you split on colon :, you remember to strip the fields after from spaces, but not the field before. You should probably do:
my @array = split /\s*:\s*/, $_;

Also, you should always use
use strict;
use warnings;

Coding without these two pragmas is difficult and takes much longer.

A: use strict;
use warnings;

my %hash;
open (my $FH, "<", "2.txt") or die $!;
while (<$FH>) {
  my ($key, @array) = split /[:\s]+/, $_;
  $hash{$key} = \@array;
}
close $FH;

use Data::Dumper;
print Dumper \%hash;


text:
Q: breaking line after "and" in cleveref Cleveref formats a long list of references to theorem-like environments as "Thm. 1, Prop. 2, ..., and Cor. 3". Is there a way to generally allow a line break after "and"? The line breaks between "Thm.", "Prop.", "Cor.", etc., and the following numbers should stay forbidden.
For example, in the code below, the line

No sex, but an overly, very clever space-filling text. (Thm. 1.1.1 and Cor. 1.2.1.10).

runs into the page margin, which is not what I wish.
\documentclass{article}
\usepackage{cleveref}
\usepackage{lipsum}
\newtheorem{thmSS}{Theorem}[subsection]
\newtheorem{corSSS}{Corollary}[subsubsection]
\crefname{thmSS}{Thm.}{Thms.}
\crefname{corSSS}{Cor.}{Cors.}
\begin{document}
\section{Clever section title}
\lipsum[1]
No sex, but an overly, very clever space-filling text. (\cref{mythm,mycor}).
\lipsum[1]
\subsection{Clever subsection title}
\begin{thmSS}\label{mythm}Clever theorem\end{thmSS}
\subsection{Another clever subsection title}
\subsubsection{Clever subsubsection title}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}\label{mycor}Clever corollary\end{corSSS}
\end{document}

I would not like to use \begin{sloppypar}...\end{sloppyppar}, since it introduces a line break before "and", making the spaces between the words visually too long.

A: The conjunction between both is a command that you can redefine (\crefpairgroupconjunction). It should be done after \begin{document} (or through \AtBeginDocument), if babel is involved you should do it in the language settings. But redefining it and so removing the nonbreakspace won't help much in your case, TeX will still not break, you need e.g. some \emergencystretch too:
\documentclass{article}
\usepackage{cleveref}
\usepackage{lipsum}
\newtheorem{thmSS}{Theorem}[subsection]
\newtheorem{corSSS}{Corollary}[subsubsection]
\crefname{thmSS}{Thm.}{Thms.}
\crefname{corSSS}{Cor.}{Cors.}
\begin{document}
\renewcommand\crefpairgroupconjunction{ and  }
\section{Clever section title}
\lipsum[1]
{\emergencystretch2em No sex, but an overly, very clever space-filling text. (\cref{mythm,mycor}).\par}
\lipsum[1]
\subsection{Clever subsection title}
\begin{thmSS}\label{mythm}Clever theorem\end{thmSS}
\subsection{Another clever subsection title}
\subsubsection{Clever subsubsection title}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}Clever corollary\end{corSSS}
\begin{corSSS}\label{mycor}Clever corollary\end{corSSS}
\end{document}

A: For the occasional unbreakable space to remove, you can redefine locally \crefpairgroupconjunction:
No sex, but some overly, very clever space-filling text.
\begingroup\renewcommand\crefpairgroupconjunction{ and }(\cref{mythm,mycor})\endgroup.


text:
Q: Tried to open external harddrive img file I have an img file, which is packaged in a centos virtual machine. I don't know how to open it. Now I have "parted" it on another machine and found that it is an lvm structure. The question now is how do I mount the lvm part inside the .img file inside my external USB drive

A: Use losetup to associate the image file with a free /dev/loopN device:
losetup -P -f /mnt/usb/vdisk1.img

This will report the name of the actual loop device used: if there are no other loop devices in use, it will report /dev/loop0 and so you will be able to access the partitions within the image as /dev/loop0p1, /dev/loop0p2 and /dev/loop0p3. If the reported loop device name is different, the names of the partition devices will also vary accordingly.
(With the following examples, I assume that the loop device was /dev/loop0.)
Since the first partition is flagged bios_grub, it probably contains just raw embedded BIOS GRUB code, not a filesystem. Therefore there will be no need to inspect it.
If you need to access the second partition in the image, you will be able to do it now:
mkdir /mnt/image/partition2
mount /dev/loop0p2 /mnt/image/partition2

For the LVM in the third partition, first run vgscan to ensure the LVM PV is detected, then vgchange -ay to activate it:
vgscan
vgchange -ay

If these commands report a duplicate volume group error, then the VG on the image has the same name as an already-activated VG in the local system, and the VG on the image will not activate unless the name conflict is removed first. To rename a VG when you have two VGs with the same name, you'll need the VG UUID: use vgs -o +VG_UUID to view the VG UUIDs, then use vgrename to rename the duplicate, using the UUID to identify the VG to rename. Then run vgchange -ay to try and activate it again.
When vgchange -ay runs without errors, use lvs to view the names of the logical volumes on the image. Now you will be able to mount them using mount /dev/<VG>/<LV> <mountpoint> as usual.

To disconnect the image after you're done with it:

*

*first unmount all filesystems you've mounted from the image

*then deactivate the volume group with vgchange -an <VG>

*finally detach the loop device: losetup --detach /dev/loop0
Now you will be able to unmount the USB drive without device is busy errors.

A: Use losetup to create a loop device from the image
losetup -P -f /mnt/usb/vdisk1.img

the content of the image will be available as /dev/loopX, if the LVM structure on it isn't auto activated use vgs and/or vgscan to get name of the volume group, activate it using vgchange -ay <name> and then mount the logical volumes (you can get list of them using lvs and mount them using mount /dev/<vgname>/<lvname> <mountpoint>).


text:
Q: Looking for an more efficient way to create a 4 directional linked-list I am trying to create a method that will link all Cell objects set up in a 2D array named CellGrid[,]
My question is: Since most of the code in SetDirection() is so similar, it seem there is a better way to achieve my goal.
(Side note: This is functional but the execution feels "off"  )
private void SetDirection()
    {
        int x = 0, y = 0;
        for ( int i = 0 ; i < Size * (Size - 1);)//setting all UP pointers
        {
            if ( i == 0 ) { x = 0; y = 1;}//initial setup
            for ( x = 0 ; x < Size ; x++ )
            {
                CellGrid[x,y].SetPointer(CellGrid[x,y-1] , Direction.Up );
                i++;
            }
            y++;
        }
        for ( int i = 0 ; i < Size * (Size - 1);) //setting all DOWN pointers
        {
            if ( i == 0 ) { x = 0; y = 0;}//initial setup
            for ( x = 0 ; x < Size ; x++ )
            {
                CellGrid[x,y].SetPointer(CellGrid[x,y+1], Direction.Down);
                i++;
            }
            y++;
        }
        for ( int i = 0 ; i < Size * (Size - 1);)//setting all LEFT pointers
        {
            if ( i == 0 ) { x = 1; y = 0;}//initial setup
            for ( y = 0 ; y < Size ; y++ )
            {
                CellGrid[x, y].SetPointer( CellGrid[x-1,y], Direction.Left);
                i++;
            }
            x++;
        }
        for ( int i = 0 ; i < Size * (Size - 1);) //setting all RIGHT pointers
        {
            if ( i == 0 ) { x = 0; y = 0;}//initial setup
            for ( y = 0 ; y < Size ; y++ )
            {
                CellGrid[x, y].SetPointer( CellGrid[x+1,y], Direction.Right);
                i++;
            }
            x++;
        }
    }

public void SetPointer( Cell cellRef ,GridBuilder.Direction dir)
    {
        switch ( dir )
        {
            case GridBuilder.Direction.Up:
                this.Up = cellRef;
                break;
            case GridBuilder.Direction.Down:
                this.Down = cellRef;
                break;
            case GridBuilder.Direction.Left:
                this.Left = cellRef;
                break;
            case GridBuilder.Direction.Right:
                this.Right = cellRef;
                break;
        }
    }

A: You can indeed use one set of loops to make the links in all four directions. This is based on two ideas:

*

*When setting a link, immediately set the link in the opposite direction between the same two cells.

*When setting a link, immediately set the link between the two cells that are located in the mirrored positions -- mirrored by the main diagonal (x <--> y).

private void SetDirection() {
    for (int i = 1; i < Size; i++) {
        for (int j = 0; j < Size; j++) {
            CellGrid[i, j].SetPointer(CellGrid[i-1, j], Direction.Left);
            CellGrid[i-1, j].SetPointer(CellGrid[i, j], Direction.Right);
            CellGrid[j, i].SetPointer(CellGrid[j, i-1], Direction.Up);
            CellGrid[j, i-1].SetPointer(CellGrid[j, i], Direction.Down);
        }
    }
}


text:
Q: HTML Tables columns control by php I just make a HTML Table and it can control by php codes, but I find problem here, I can not understand why that happen, there is a gap come at first then it start from Database Id numbers, here is my PHP codes,
    <?php
error_reporting(E_ERROR | E_PARSE);
include('connect.php');

    // Get page data
    $query = "SELECT * FROM profile ORDER BY `id` ASC";
    $rs1 = mysql_query($query);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Barat Store Product Profile</title>

IMAGE

    <?php
$rs1_endRow = 0;
$rs1_columns = 3; // number of columns
$rs1_hloopRow1 = 1; // first row flag
do {
    if($rs1_endRow == 0  && $rs1_hloopRow1++ != 0) echo "
";
   ?>
<?php echo $row_rs1['id']; ?>

<a href="ASASAS#.php?id=<?php echo $row_rs1['id']; ?>" target="_blank"><?php echo $row_rs1['name']; ?>

      <img src="#<?php echo $row_rs1['id']; ?>.jpg.jpg" width="400" height="280" />

    <?php $rs1_endRow++;
if($rs1_endRow >= $rs1_columns) {
  ?>

  <?php
$rs1_endRow = 0;
  }
} while ($row_rs1 = mysql_fetch_array($rs1));
if($rs1_endRow != 0) {
while ($rs1_endRow < $rs1_columns) {
    echo(" 	");
    $rs1_endRow++;
}
echo("
");
}?>

2nd Page

here is my sql code:
    -- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jul 26, 2016 at 11:11 PM
-- Server version: 10.1.13-MariaDB
-- PHP Version: 5.5.35

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `probarat`
--

-- --------------------------------------------------------

--
-- Table structure for table `profile`
--

CREATE TABLE `profile` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `profile`
--

INSERT INTO `profile` (`id`, `name`) VALUES
(1, 'AMLOKI (INDIAN)'),
(2, 'ANAR DODHI'),
(3, 'AL-VALUKA'),
(4, 'AKARKORA (NUM.1)'),
(5, 'AKARKORA (NUM.2)'),
(6, 'ATMORA'),
(7, 'ANAR DANA'),
(8, 'ADA SOOT (NUM.1)'),
(9, 'AKRABIJ (DORENJO)'),
(10, 'AFTIMUN'),
(11, 'ANJIBAR'),
(12, 'ASHOGONDHA (DESHI)'),
(13, 'ASHOGONDHA (NUM.2)'),
(14, 'ALOYA (MOSABBAR)'),
(15, 'ATUS'),
(16, 'AMLOKI (DESHI)'),
(17, 'AORJUN CHAL'),
(18, 'AL VALU'),
(19, 'ANANTOMUL'),
(20, 'ARBI GUM'),
(21, 'ANARFUL'),
(22, 'BELA GOTA'),
(23, 'BOOJ PATA'),
(24, 'BHAMAN LAL'),
(25, 'BONGSHOLOCHON'),
(26, 'BUCHKI DANA'),
(27, 'B.K KASNI'),
(28, 'BIS FAIJ'),
(29, 'BOHERA'),
(30, 'BIJ LONG'),
(31, 'BADIYAN'),
(32, 'BARENGO SEP'),
(33, 'BUJI DANA'),
(34, 'BABUNA'),
(35, 'BIRONGO DANA'),
(36, 'CHIROTA'),
(37, 'DAIFUL'),
(38, 'DALIM CHALA'),
(39, 'DARHORIDRA'),
(40, 'DARHORIDRA CHAL'),
(41, 'CHAL - MUGORA'),
(42, 'CUNIYA GUM'),
(43, 'FUNDUK'),
(44, 'ISPAGUL HUSK (VUSHI)'),
(45, 'JOIN (ORGINAL)'),
(46, 'GOLAP FUL (NUM.1)'),
(47, 'GOLAP FUL (NUM.2)'),
(48, 'GOR BOCH'),
(49, 'JOISTI MODHU (CUTTING) (NUM.1)'),
(50, 'JOISTI MODHU (REKCIN) (NUM.2)'),
(51, 'JOISTI MODHU (REKCIN) (NUM.3)'),
(52, 'HORTOKI JUNGLI'),
(53, 'HENA JAL (30KG)/ (50KG)'),
(54, 'GOKUR KATA'),
(55, 'HING'),
(56, 'GUGUL (INDIA)'),
(57, 'GUGUL (PAKISTANI)'),
(58, 'GAOJABON'),
(59, 'HORTUKI'),
(60, 'GORMAR BOTI/PATA'),
(61, 'JOHORMOHRA'),
(62, 'JAMAL GOTA'),
(63, 'JOTAMANSHI (NUM.1)'),
(64, 'GULE JUFA'),
(65, 'INDROJOB RED'),
(66, 'KUTKI'),
(67, 'KAKRASHING'),
(68, 'LOCHCHAL'),
(69, 'KUCHILA'),
(70, 'KHOSH'),
(71, 'KHORASANI JOIN'),
(72, 'LAL CHONDON'),
(73, 'KATILA (NUM.1)'),
(74, 'KATILA (NUM.2)'),
(75, 'KATILA (NUM.3)'),
(76, 'KUNDOR'),
(77, 'KALO MEGH'),
(78, 'KALO DANA'),
(79, 'LAL DANA'),
(80, 'KUMKUM'),
(81, 'KATILA CUTTING'),
(82, 'METHI (INDIA)'),
(83, 'METHI (DESHI)'),
(84, 'MAJUFOL (GREEN)'),
(85, 'MAJUFOL (WHITE)'),
(86, 'MARJAN'),
(87, 'MONJESTA'),
(88, 'MOHURI'),
(89, 'MAKU DANA'),
(90, 'MOTA BOCH'),
(91, 'MEHEDI PATA'),
(92, 'NEPALI KHOR (RAKCIN)'),
(93, 'NAGOR MOTHA'),
(94, 'PARSUSA'),
(95, 'PIPUL (CHOTO DANA)'),
(96, 'PIPUL (GOL DANA)'),
(97, 'PIPUL (S.P INDIAN)'),
(98, 'RITHA (NUM.1)'),
(99, 'REWCHINI'),
(100, 'ROTON JUT'),
(101, 'TOKME ISPAST'),
(102, 'SONAPATA'),
(103, 'SAHI JIRA'),
(104, 'SOYLOJ'),
(105, 'SADA KORI'),
(106, 'TOKME KHATMI'),
(107, 'TOKME KHOBBAJI'),
(108, 'TOKME KASHNI'),
(109, 'SUNRISE KHOR'),
(110, 'SADA CHONDON'),
(111, 'TOKME KARAF'),
(112, 'TOKME HAMMAJ'),
(113, 'SAPISTAN'),
(114, 'SILAJEET'),
(115, 'SALEM GOTA'),
(116, 'SAKAKUL MISRI'),
(117, 'TOP CHINI'),
(118, 'TOJ (LALUKA)'),
(119, 'SURONJON'),
(120, 'TAL MAKHNA (INDIAN)'),
(121, 'TAL MAKHNA (DESHI)'),
(122, 'TOKMA (KALA TULSI)'),
(123, 'THANKUNI PATA'),
(124, 'SURMA KALO'),
(125, 'SURMA SADA'),
(126, 'TOKME KASUS'),
(127, 'S.K.F KHOR'),
(128, 'SORNOLOTA'),
(129, 'SIMUL MUL'),
(130, 'UDE KUDDUS'),
(131, 'UDE SALIB'),
(132, 'UNNAB'),
(133, 'ISABGUL DANA'),
(134, 'KAKULI'),
(135, 'TOKME KHAKSI'),
(136, 'TOKME ISPAK');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `profile`
--
ALTER TABLE `profile`
  ADD PRIMARY KEY (`id`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

This is my result photo:

Please help me as soon as possible.

A: You get it because you told it to be output:
do {
    if($rs1_endRow == 0  && $rs1_hloopRow1++ != 0) echo "
";
   ?>
<?php echo $row_rs1['id']; ?>

                                 ^^^^---undefined
    [..snip...]
} while ($row_rs1 = mysql_fetch_array($rs1));
           ^---until this executes

Since $row_rs1 doesn't get set until AFTER the first iteration of your do/while loop, you output a bunch of undefined variables.

A: Look at this line: <img src="#<?php echo $row_rs1['id']; ?>.jpg.jpg" width="400" height="280" />
Make sure that the image path is correct, and I doubt that you have ".jpg.jpg".
Use "Inspector" from your browser to ensure the image link is correct.


text:
Q: How do I stop Topsy from spamming my site with those annoying trackbacks? Every time I publish a post, Tospy adds their pingback to my post.
It's annoying, but I don't know how to stop it.
Any advice?

A: Add topsy.com/trackback (or whatever they are using for those links now) to Settings > Discussion > Comment Blacklist.

A: Have you marked their comments as spam? Akismet is supposed to learn from comments you mark as spam. Try that, it should start being marked as spam eventually.

A: just unmark the allow pingback/trackback while adding the post..

A: This codex article is rather old but most of it is still relevant.


text:
Q: Given bivariate data (X, Y), how to determine a cut-off of X that meets some condition of Y? I have two distributions, $X$ and $Y$ (shown on the horizontal X axis and vertical Y axis, respectively, see image), that represent different ways of scoring some complex system. For a subset of states of a complex system, I have calculated both a score $x$ using the $X$ method, and a score $y$ using the $Y$ method (i.e. the methods are independent), which produces the plot below. Some more points:

*

*The method for scoring X is quick but can be inaccurate

*The method for scoring Y is slow to compute but extremely robust

*Larger scores are better

*Each distribution has a different scale (the distributions are correlated).

I would like to use the $X$ method as a proxy for the $Y$ method. Is it possible to say that some score $x_{cut}$ in $X$, will map to a score $Y \ge 4$, so for any $x \ge x_{cut}$, we will be certain that the corresponding $y \ge 4$   , with a confidence of say 99.95%? If so, how would I calculate $x_{cut}$?
My naive thinking is to choose the largest $x$ value found for all $y \lt 4$, and use that as my cut-off. But as I've only measured scores for some states in my complex system, I realise that I may not have encountered the largest $x$ that corresponds to $y \lt 4$.

A: If you are willing to assume the x value is normally distributed you can use Bayes' theorem to calculate the probability of some y score given a value of x.
Bayes' theorem where $X$ is continuous and $Y$ is discrete is given by,
$P(Y=k|X=x) = \frac{f_{X|Y=k}(x)\cdot P(Y=k)}{f_X(x)}$
where $P(Y=k|X=x)$ is the probability of $Y$ is equal to some score $k$, given the x-score is equal to some value $x$. The density function $f_{X|Y=k}$ is the density of $X$ conditional on the y-score. For this density we can use a density, which is normal conditional on $Y$. The numerator is the "global" density of $X$, also we you can assume a normal distribution.
Given some data it is quite easy estimating the different "global" or unconditional probabilities of the y-score ($P(Y=k)$), it's simply the proportions of the scores in the categories 1,2,3,4 and 5.
Also the denominator is quite easy to estimate. The normal distribution is fully characterized by the parameters $\mu$ and $\sigma$, which are the mean and standard deviation, respectively. The empirical counterparts are just the average and the standard deviation of the x-score.
The tricky part is the conditional normal in the numerator. Here you need a set of means, and standard deviations, one for each value of y (1,2,3,4 and 5). So, you need to group the x-values for each corresponding y-value and compute the mean and standard deviation. These values needs to be saved and you can use them to compute the conditional normal for each value of $Y$.
R-code for estimating and computing the conditional probability function
Here is an R example simulating some values and doing the estimation just described. The function conditional_prob computes the probability of some y-score given a x-score. If you want the probability of say Y>=4 given some x-value you can simply sum the probabilities for y=4 and y=5.
# Simulating x and y scores
n <- 100
mean_x <- 35
sd_x <- 2

x <- rnorm(n, mean=mean_x, sd=sd_x)
y <- as.numeric(cut(x, breaks=5))

plot(x,y)

# Estimating parameters for conditional probability
x_grouped_means <- aggregate(x, list(y), mean)
colnames(x_grouped_means) <- c('y', 'mu_hat')

x_grouped_stds <- aggregate(x, list(y), sd)
colnames(x_grouped_stds) <- c('y', 'sigma_hat')

x_global_mean <- mean(x)
x_gloabal_std <- sd(x)

y_relative_freqs <- as.data.frame(table(factor(y))/length(y))
colnames(y_relative_freqs) <- c('y', 'p_hat')

conditional_prob <- function(x, y, grouped_mu_hat_x, grouped_sigma_hat_x, mu_hat_x, sigma_hat_x, p_hat_y) {
  mu_hat_x_given_y <- grouped_mu_hat_x[grouped_mu_hat_x['y']==y, 'mu_hat']
  sigma_hat_x_given_y <- grouped_sigma_hat_x[grouped_sigma_hat_x['y']==y, 'sigma_hat']
  prob_y <- p_hat_y[p_hat_y['y']==y, 'p_hat']
  dnorm(x, mean=mu_hat_x, sd=sigma_hat_x)*prob_y/dnorm(x, mean=mu_hat_x, sd=sigma_hat_x)
}

Compution the probability of Y=>4 given x=35
p4 <- conditional_prob(35, 4, x_grouped_means, x_grouped_stds, x_global_mean, x_gloabal_std, y_relative_freqs)
p5 <- conditional_prob(35, 5, x_grouped_means, x_grouped_stds, x_global_mean, x_gloabal_std, y_relative_freqs)
p4+p5


text:
Q: Analytic Geometry | Two Planes and a Angle | Two Solutions This is me again, I have another problem which I haven't been able to solve, the
legend goes like this:
Find the equation of the plane that contains the points $P_1(1,0,-1)$, $P_2(2,0,2)$ and forms a 600 ($\theta$) angle with the other plane $2x-2y+z+6=0$ (Two Solutions).
Here's what I've done:
Since we already know two points, P1$(1, 0, -1)$ and P2$(2,0,2)$ they both satisfy a planes equation:
$$Ax+By+Cz+D=0$$
So, we substitute $x,y,z$ respectively for each point, giving use these two equations

*

*$A(1)+B(0)+C(-1)+D=0$

*$A(2)+B(0)+C(2)+D=0$

Simplifying we get:

*

* $A-C+D=0$

* $2A+2C+D=0$

Now, according to the following theorem the angle that is formed by the perpendiculars of to planes is the following:
$$\cos{\theta} = \pm \frac{AA'+BB'+CC'}{\sqrt{A^2+B^2+C^2} \sqrt{(A')^2+(B')^2+(C')^2}}$$ Where $[A,B,C]$ Are the director numbers of the normal in the first plane and $[A',B',C']$ Are the director numbers of the normal in the second plane.
Now, given those and taking the known angle of 60o, we substitute the director numbers of $2x-2y+z+6-0:[A'=2,B'=-2,C'=1]$ and the angle in the last formula, giving us:
$$\cos{60^\circ} = \pm \frac{A(2)-B(-2)+C(1)}{\sqrt{A^2+B^2+C^2} \sqrt{(2)^2+(-2)^2+(1)^2}}$$
Simplifying, we get(positive because $\theta$ is acute):
$$\frac{1}{2}=\frac{2A-2B+C}{3 \sqrt{A^2+B^2+C^2}}$$
Another simplification finally for:
$$3(A^2+B^2+C^2)=(4A-4B+2C)^2$$
Now, we have 3 equations:

*

* $A-C+D=0$

* $2A+2C+D=0$

*$3(A^2+B^2+C^2)=(4A-4B+2C)^2$

If we take 1) and 2) and write them as $D(A,C)$ we get:

*

*$D=C-A$

*$D=-2A-2C$

From which we can obtain A in terms of C
$$-2A-2C=C-A$$
$$A=-3C$$
Now we substitute back in 1):
$$(-3C)-C+D=0$$
$$C=\frac{1}{4}D$$
Since I want every director number in terms of D we substitute again but in A since A was in function of C.
$$A=-3C$$
$$A=-3(\frac{1}{4}D)$$
$$A=\frac{-3}{4}D$$
Now, we have found $A(D)$, $C(D)$ we have yet to find $B(D)$ I'll explain why I think and want everything in terms of D, if we take the general form of a planes equation $Ax+By+Cz+D=0$ and substitute $A$ and $C$ with our known values we get:
$$(\frac{-3}{4}D)x+By+(\frac{1}{4}D)z+D=0$$
if we divide by $D \neq 0$ and then multiply by 4 to eliminate fractions:
$$\frac{-3}{4}x+\frac{B}{D}y+\frac{1}{4}z+1=0$$
$$-3x+\frac{4B}{D}y+z+4=0$$
From here it's clear that if we find B in terms of D and B is linear we have the planes equation, so, in 3) $3(A^2+B^2+C^2)=(4A-4B+2C)^2$ we substitute A and C:
$$3((\frac{-3}{4}D)^2+B^2+(\frac{1}{4}D)^2)=(4(\frac{-3}{4})-4B+2(\frac{1}{4}D))^2$$
$$\vdots$$
$$104B^2+80DB+35D^2=0$$
Here is were I get stuck, I get imaginary parts, since I have to use the quadratic formula, so any help is really appreciated, the problem states that there are two solutions, but this is what I have thought of if anyone can supply any solution I'll be very grateful.
Regards.. Tristian

A: The normal vector to the sought plane is orthogonal to the
line $P_1 P_2$ and at angle $\pi/3$ to the normal to your given plane.

A: To flesh out Robin's answer a little: The thing that you really want to find is the unit normal vector $n=(A,B,C)^t$ to the sought plane. Once you have that, it's easy to find the equation of the plane. This vector has to satisfy three conditions:

*

*Length one: $A^2+B^2+C^2=1$.

*Orthogonal to the vector $\overrightarrow{P_1 P_2} = (1,0,3)^t$.

*60 degrees to the normal vector of the other plane. If we normalize that vector too, this condition becomes $\frac13 (2,-2,1)^t \cdot (A,B,C) = \cos 60^{\circ}$.
Conditions 2 and 3 give a linear system with two equations and three unknowns $A$, $B$, $C$; solve it and you will get a family of solutions depending on one parameter $t$. Condition 1 then gives a quadratic eqation for determining the two possible values of $t$.

A: Computation approach:
If you are familiar with generalized coordinate rotation in 3D (using a 3x3 matrix rotator), the problem can be simplified using a coordinate rotate where the  direction vector of line P1 --> p2 specifies the newZaxis.  You would let the software choose arbitrary newXaxis and newYaxis forming a valid 3x3 rotator.
You have to coordinate rotate the given plane PL --> PL'., P1 --> P1' and P2 --> P2'.
In this rotated space, the goal is to solve for the orientation (perpendicular direction) of variable Plane PL_v.  These orientations have no z-components, so we can parameterize them using a single sweep variable theta, where
PL_v'.o = [ costheata,   sintheta,   0 ]
When two planes meet at a 60 degree dihedral angle, that pins down the dot-product of their orientations to cos (60), or cos(120) = +- 1/2.
+- 1/2 = [ costheta,     sintheta,    0 ] • PL'.o
+- 1/2 =  PL'.o.x * costheta  + PL'.o.y * sintheta
After solving for the 2 values of theta, the desired planes can be found by dotting their orientation with either P1' or P2'
PL_v'.location = PL_v'.o  •  P1'
And then coordinate unrotating PL_v' --> PL_v
The final plane equation comes out in vector form:
p  •  PL_v.o  == PL_v.location
(where p = [ x, y, z] is any point on the plane)


text:
Q: In Rails 4 with devise gem, overriding after_sign_in_path_for is not effective In ApplicationController, according to devise docs, How To: Redirect to a specific page on successful sign in and sign out, the case switch when can not be reached, even in pry debugging console, it shows 'resource.class == User is true'.  I don't know what part of Rails processing I missed, any hint will be appreciated!
# ApplicationController.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  protected
  def after_sign_in_path_for(resource)
    # check for the class of the object to determine what type it is
    binding.pry
    case resource.class
    when User
      puts "user redirect ==== "
      return session.delete(:return_to) || current_user_path
    else
      puts "super call ....."
      super
    end
  end
end

A: You are pretty close. Just need to get the resource class name using resource.class.name , so that you can compare it with a string such as 'User' which is nothing but your class name.
def after_sign_in_path_for(resource)
  # check for the class of the object to determine what type it is
  binding.pry
  case resource.class.name   #=>this would return the class name i.e 'User'
  when 'User'
    puts "user redirect ==== "
    return session.delete(:return_to) || current_user_path
  else
    puts "super call ....."
    super
  end
end

A: You can make workaround by creating SessionsController that inherits from Devise::SessionsController.
class SessionsController < Devise::SessionsController
  skip_before_filter :authenticate_user!

  def create
    user = User.find_for_database_authentication(email: params[:session][:email])

    if user && user.valid_password?(params[:session][:password])
      sign_in user
      redirect_to session.delete(:return_to) || '/authorized'
    else
      redirect_to '/sign_in'
    end
  end

  def destroy
    sign_out :user
    redirect_to '/signed_out'
  end
end

Point to it inside your routes.rb like this:
devise_for :users, controllers: {sessions: 'sessions'}


text:
Q: Running Total and Integer Value Allocation I need to be able to determine the remaining amount of point allocation for each row. Let me explain the following query:
Variables

*

*@allocated int --> already allocated points

*@to_allocate int --> the point that we need to allocate now

View "audits"

*

*ts --> date on which the points were collected

*points --> the amount of points collected

So far, I have only been able to get proper results when the data in "audits" is something like this:
This works
IF OBJECT_ID('audits') IS NOT NULL
DROP VIEW audits;

GO

CREATE VIEW audits
AS
SELECT '2000-1-1' AS ts, 10 AS points UNION ALL
SELECT '2000-1-2' AS ts, 12 AS points UNION ALL
SELECT '2000-1-3' AS ts, 123 AS points UNION ALL
SELECT '2000-1-4' AS ts, 100 AS points;

GO

Does not work
CREATE VIEW audits
AS
SELECT '2000-1-1' AS ts, 106 AS points UNION ALL
SELECT '2000-1-2' AS ts, 12 AS points UNION ALL
SELECT '2000-1-3' AS ts, 123 AS points UNION ALL
SELECT '2000-1-4' AS ts, 100 AS points;

GO

Query
DECLARE @to_allocate int = 92;
DECLARE @allocated int = 4;

WITH result
AS
(
    SELECT
        ts,
        points,
        SUM(points) OVER(ORDER BY ts) AS total
    FROM audits
),
points
AS
(
    SELECT
        ts,
        points,
        total,
        CASE
            WHEN @to_allocate > total - @allocated THEN total - @allocated
            ELSE @to_allocate - SUM(total - @allocated)
                                OVER(ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
        END as result
    FROM result
)
SELECT * FROM points
WHERE result > 0;

Desired Output for "Does not work" data
Please note that the value in result column should not be greater than point of the corresponding row. Therefore,

*

*when @to_allocate is 92

*

*when @to_allocate is 200

I can solve this issue by using temporary tables and loops but that's something that I don't want to do because it prevents me to use this on a function. Any help or pointing me to the right direction will be appreciated.

A: Something like this?
DECLARE @to_allocate int = 200
DECLARE @allocated int = 4

select *,
  points -
  case when total < @allocated then points
       when prev < @allocated then @allocated - prev
       else 0
  end -
  case when total > @to_allocate + @allocated
       then total - @to_allocate - @allocated
       else 0
  end

from
(
  select *, lag(total, 1, 0) over (order by ts asc) as prev
  from
  (
      select *, sum(points) over (order by ts asc) as total from audits
  ) X
) X
where prev < @to_allocate + @allocated

SQL Fiddle
I made the assumption that @allocated must remove values from more than just the first row, although your examples only had that.


text:
Q: Why I couldn't write all the characters to the file with java FileWriter? I'm trying to use Java FileWriter (and BufferedWriter) to write content to a csv file.
This is my code:
import com.github.javafaker.service.FakeValuesService;
import com.github.javafaker.service.RandomService;

import java.io.*;
import java.nio.file.Path;
import java.util.Locale;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UIDFaker {
    private final static Logger logger = Logger.getLogger(UIDFaker.class.getName());
    private FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService());
    private static int MAX_NB_OF_ROWS;
    private String[] linesToWrite;

    public void writeToFile(int maxNbOfRows, String fileName) {
        MAX_NB_OF_ROWS = maxNbOfRows;
        linesToWrite = new String[MAX_NB_OF_ROWS + 1];
        initiateCSVFileHeader();
        initiateFakeData();
        writeToFile(fileName);
    }

    private void writeToFile(String fileName) {
        try {
            FileWriter fileWriter = new FileWriter(fileName);
            Writer bufferedWriter = new BufferedWriter(fileWriter);
            fileWriter.append(linesToWrite[0], 0, 13);
            for (int i = 1; i < MAX_NB_OF_ROWS + 1; i++) {
                fileWriter.write(linesToWrite[i], 0, 25);
            }

            //fileWriter.close();
            //bufferedWriter.close();
        }
        catch (IOException exception) {
            logger.info(exception.getMessage());
        }
    }

    private void initiateCSVFileHeader() {
        linesToWrite[0] = "\"RANK\";\"UID\"\n";
    }

    private void initiateFakeData() {
        String rank = "";
        String uid = "";
        String line = "";
        for (int i = 1; i < MAX_NB_OF_ROWS + 1; i++) {
            rank = generateFakeRank();
            uid = generateFakeUID();
            line = "\"" + rank + "\";\"" + uid + "\"\n";
            linesToWrite[i] = line;
        }
    }

    public String generateFakeRank () {
        return fakeValuesService.regexify("[0-9]{5}");
    }

    public String generateFakeUID() {
        return fakeValuesService.regexify("[0-9]{3}([A-Z][0-9]){4}[0-9]{3}");
    }

}

And when I opened the csv file, some of the characters didn't appear at the end of the file. I'm supposed to write 1001 lines including headers to the file (I set MAX_NB_OF_ROWS equals to 1000)  but the file only showed me 984 lines, as in this picture:
my csv file
Does anybody know how to fix it? Thank you very much


text:
Q: Close tab after redirecting to a new tab in Firefox I am trying to close a tab using JavaScript on Firefox. I went through a few older questions posted here on Stackoverflow and I understand that Firefox doesn't allow a tab to be closed using JavaScript unless the tab has been opened from JavaScript itself.
However, I could open a blank tab in place of the existing tab using
window.open('about:blank','_self','');.
My question is since the blank tab has been opened through JavaScript, why can't I close it using window.close();?

A:
My question is since the blank tab has been opened through JavaScript

The tab wasn't opened with JS. A window.open call just used the name of an existing tab so the document was loaded there instead of opening a new window.


text:
Q: c++ stl selection for multiple keys c++ stl experts,
In a protocol stack implementation, I have a Message being sent from one layer to another. The source layer stores some information, and processes that information, on recepton of response from the second layer.
Now the information stored has 3 parameters which is used to compare the responses from the destination layer. (to get the correct one). i.e lets says session id, request number and infoID. The stored info contains a struture, lets say struct A.
which is the best way to implement this in the source layer to store info ?
Initially i thought of the following, as then there were only two keys
 std::map<std::pair<u32, u32>, StructA> m_mSessionId2RNum2StructA;

But later requirement for another key. this got complicated
struct StructZ
{
     u32 InfoId;
     StructA stStructA;
};

std::map<std::pair<u32, u32>, StructZ> m_mSessionId2RNum2StructZ;

This doesnot look good. Any inputs/suggestions to improve this much appreciated
thanks
~pdk

A: Perhaps StructK can be a key for StructA as a value in a map:
struct StructK
{
     u32 k1;
     u32 k2;
     u32 k3;
};

inline bool operator< (const StructK& lhs, const StructK& rhs)
{
    if(lhs.k1 < rhs.k1)
        return true;
    else
        if(lhs.k1 == rhs.k1)
        {
            if(lhs.k2 < rhs.k2)
                return true;
            else
                if(lhs.k2 == rhs.k2)
                {
                    return lhs.k3 < rhs.k3;
                }
                else
                    return false;
        }
        else
            return false;
}

and then
 map<StructK, StructA> myMap;

Of course, you can use any logic for operator<

A: std::pair is a special type of std::tuple which can only hold two values, whereas tuple can hold dozens (1). I.e. you seem to want std::tuple<u32, u32,u32> as a key now.
You get operator< for free with tuple, same as with pair.
If you need alternate indices, i.e. search by key 1, 2 or 3, then you need boost::multi_index containers.
(1) Check your implementation for precise limits.


text:
Q: Do I have to return TwiMl when I receive a callback from Twilio? When we get an inbound text from Twilio (via a callback endpoint),  are we required to return TwiMl?
This is what our controller looks like, which works fine:

We have no use for replying and generating messages as they come in automatically and would like to just let Twilio know that the call was successful.
When I try to return a 201 status code or an application/json response, we get the following warning in the Twilio console:

Their documentation is all over the place and almost implies that you HAVE to reply with TwinMl - is this this the case or is there another way to respond without generating the warning above?

A: You'll have to reply with TwiML, but an empty (TwiML) response, as mentioned in your question, is also valid. There's no need to respond with a text message.


text:
Q: Query with Double Pointers in C In the university we did this code:
int cargaArreglo(int ** A);

int main(){

int * A = NULL;
int i = 0;
int dimension = cargaArreglo(&A);

for( i = 0; i < dimension; i++ )
     printf( "[%d]", A[i] );

free( A );
return 0;
}

int cargaArreglo(int ** A){

int i = 0;
char bandera = 's';
(*A) = malloc( 1*sizeof(int) );

while( bandera != 'n' ){
     printf( "Ingrese un numero" );
     scanf( "%d", &(*A)[i] );
     printf( "Desea seguir ingresando?" );
     i++;
     fflush( stdin );
     scanf( "%c", &bandera );
     if( bandera != 'n' )
     (*A) = realloc( (*A), (i+1)*sizeof(int) );
}
return i;
}

We tried to load a dinamic array, and add values without a limit. The code works very fine but in the functions we need to declare the parameters with Double Pointers, exist any posibility of to convert this in a simple pointer? I mean, the teacher said that is impossible, because without the double pointer I cant change the value of the global variable. This made me confuse respect to the pointers.
Thank you for your time!
PD: If you find a mistake respect a my english, please tell me because I would help me much with my studies.

A: If you don't like pointers-to-pointers, you could always modify the function's signature so that it returns the new pointer-value to assign to A, and sets the dimension value via a pointer instead:
[...]
int dimension;
int * A = cargaArreglo(&dimension);
[...]

int * cargaArreglo(int * retDimension){
   int i = 0;
   char bandera = 's';
   int * B = malloc( 1*sizeof(int) );

   while( bandera != 'n' ){
        printf( "Ingrese un numero" );
        scanf( "%d", &B[i] );
        printf( "Desea seguir ingresando?" );
        i++;
        fflush( stdout ); /* fflush( stdin ) is UB */
        scanf( "%c", &bandera );
        if( bandera != 'n' )
           B = realloc( B, (i+1)*sizeof(int) );
   }
   *retDimension = i;

   return B;
}

I mean, the teacher said that is impossible, because without the
  double pointer I cant change the value of the global variable. This
  made me confuse respect to the pointers.

What the teacher meant was that when you call a function in C, a temporary copy of each argument is pushed onto the stack for use inside the function.  So if you change the value of the argument inside the called function, it doesn't change the value back in the calling function... for example, running this code:
void foo(int x, int * A)
{
   x = 6;
   A = NULL;
}

int x = 5;
int * A = &x;
printf("BEFORE x=%i A=%p &x=%p\n", x, A, &x);
foo(x, A);
printf("AFTER x=%i A=%p &x=%p\n", x, A, &x);

... will print out:
BEFORE x=5 A=0x2345678 &x=0x2345678
AFTER x=5 A=0x2345678 &x=0x2345678

... which is to say that foo() did not actually change the value of either x or A in the calling function, because foo() modified only the copy of x and the copy of A that were passed to it, and not the original variables.
However, foo() can use the A pointer to (indirectly) modify the value of calling function's x, because the function's copy of A still points to the calling function's x, so you could implement foo do this:
void foo(int * A)
{
   *A = 666;
}

int x = 5;
printf("BEFORE x=%i\n", x);
foo(&x);
printf("AFTER x=%i\n", x);

... and you'd get this output:
BEFORE x=5
AFTER x=666

... and if the above makes sense to you, then the pointer-to-a-pointer case is really just the same thing as above, except that instead of A pointing to an int, the type of the value it is pointing to is a pointer:
void foo(int ** x)
{
    *x = NULL;
}

int y = 5;
int * x = &y;
int ** A = &x;
printf("BEFORE x=%p\n", x);
foo(A);
printf("AFTER x=%p\n", x);

... would print out:
BEFORE x=0x2345845  (actual value will vary depending on your computer)
AFTER x=NULL

A:
exist any posibility of to convert this in a simple pointer?

It is a simple pointer.  C has no other kind.
Understanding that point is one of the keys to C mastery.  Another way to look at it is that pointers are just one kind of value the C supports.  Valid pointer values have significance as addresses (in some sense) of functions or objects in the program, but that does not make them in any way magical.  They are first-class values.  In particular, pointers can point objects of pointer type as a natural consequence of the language's type system.  That a pointer points to another pointer does not make it non-simple.
I think some people get confused by pointers because they read the type from left to right, so they see the name of some base type first (int in your case) and attribute the most significance to that.  But although the int *, int **, etc. types are related to the int type, values of those pointer types are not much related to ints at all.  Instead of reading types from left to right, you should read them from the inside out, which in many common cases is right-to-left.  Reading int **A as "A is a pointer to pointer to int" emphasizes that its value is a pointer, which is the most significant thing about it.
As for specific ways in which you could restructure your program, @JeremyFriesner has already covered the matter very well.  The key thing to understand in this area is why you (may) want to use a pointer argument in the first place.
In general, there are several reasons why you might want to do so, but the main one and the one applicable to your particular code is the one your instructor gave you: so that the function can modify an object declared in a different scope or allocated dynamically.  In this case, that object is a pointer to the address of your dynamically-allocated array.  (Remember:  pointers are objects in their own right.)
Additionally, C functions have only one return value.  If you want a function to communicate several pieces of data to its caller then either you must provide pointer arguments by which it can do so, or you must return a value of a suitable structure type (which you might not have studied yet), or you must return a pointer to a structure or array containing all the data.

A: If you don't like the way the syntax looks, you can use a local pointer variable when doing the work inside of the function and assign that back to the dereferenced pointer-to-pointer at the end:
int cargaArreglo(int **A){

    int i = 0;
    char bandera = 's';
    int *B;
    B = malloc( 1*sizeof(int) );

    while( bandera != 'n' ){
         printf( "Ingrese un numero" );
         scanf( "%d", &B[i] );
         printf( "Desea seguir ingresando?" );
         i++;
         fflush( stdin );
         scanf( "%c", &bandera );
         if( bandera != 'n' )
         B = realloc( B, (i+1)*sizeof(int) );
    }
    *A = B;
    return i;
}


text:
Q: Why is File.Move not working as expected? I am trying to move all files from rootFolderPath to destinationPath
try
{
    string rootFolderPath = @"D:\Log_siteq\";
    if (!Directory.Exists(Path.Combine(@"D:\Log_takaya\" + comboBox1.SelectedItem.ToString())))
    {
        System.IO.Directory.CreateDirectory(Path.Combine(@"D:\Log_takaya\" + comboBox1.SelectedItem.ToString()));
    }

    string destinationPath = Path.Combine(@"D:\Log_takaya\" + comboBox1.SelectedItem.ToString() );
    string fileTypes = @"*.*";
    string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, fileTypes);
    foreach (string file in fileList)
    {
        string ext = Path.GetExtension(file);
        string destination = Path.Combine(destinationPath,file);
        File.Move( file,destination);
        MessageBox.Show(file);
        MessageBox.Show(destination);
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.ToString());
}

Apparently MessageBox.Show(file); shows me my root folder path ( as is normal) but MessageBox.Show(destination); is showing me the same thing.
What gives? It just moves my file from my root folder in the same folder.Am I not getting something?

A: You are combining the destinationPath with the complete file path of file:
string destination = Path.Combine(destinationPath, file);

which will just overwrite the destination with the original file path (because "C:\desitnation\C:\source\filename.txt" isn't a valid path).
Instead, you need only the file name like this:
string destination = Path.Combine(destinationPath, Path.GetFileName(file));


text:
Q: Help in building an 16 bit os I am trying to build an old 16 bit DOS like OS.
My example kernel code:
    asm(".code16\n");
    void putchar(char);
    int main()
    {
    putchar('A');
    return 0;
    }
    void putchar(char val)
    {
       asm("movb %0, %%al\n"
           "movb $0x0E, %%ah\n"
           "int $0x10\n"
          :
          :"r"(val)
          ) ;
    }

This is how I compile it :
nasm -f bin -o ./bin/boot.bin ./source/boot.asm
gcc -nostdinc -fno-builtin -I./include -c -o ./bin/kernel.o ./source/kernel.c
ld -Ttext=0x9000 -o ./bin/kernel.bin ./bin/kernel.o -e 0x0
dd if=/dev/zero of=./bin/empty.bin bs=1440K count=1
cat ./bin/boot.bin ./bin/kernel.bin ./bin/empty.bin|head -c 1440K > ./bin/os
rm ./bin/empty.bin

and I run it in a virtual machine.
When I make the putchar function ( in kernel code ) for constant value ....i.e like this:
 void putchar()
 {
    char val = 'A';
    asm("movb %0, %%al\n"
    "movb $0x0E, %%ah\n"
    "int $0x10\n"
    :
    :"r"(val)
    ) ;
 }

then it works fine. But when I pass argument to it (That is in the previous code), then it prints a space for any character.
What should I do?

A: If you're trying to make gcc generate 16-bit code, you need to use .code16gcc rather than .code16, in order to get the stack manipulation right for function parameters: see "Writing 16-bit Code" in the gas documentation.
(Also, depending on which gcc version you're using, you may need to compile your kernel.c with either the -fno-unit-at-a-time or -fno-toplevel-reorder option, to ensure that the asm() directive really is encountered by the assembler before any compiled code - otherwise the compiler may shuffle things around.)

A: I find another compiler to solve the problem: bcc
This is a C-compiler for 8086 cpus which is important for the development of boot loaders or BIOS related 8086 code.


text:
Q: Can anyone explain to me, how magento cron_schedule exactly runs? When we run cron.php of magento then some jobs created in cron_schedule table of magento ? Can anyone let me know how magento execute these jobs exactly ? I mean how job status is changed from pending to success.  Cron.php only insert jobs in the table not execute jobs

A: You'd want to read through the following article available directly from the MagentoCommerce website which covers all that you need to know about cron functionality & Magento:
Magento - Wiki - How to Set Up a Cron Job
To highlight: Inner workings
Magento crontab mechanism is triggered periodically using system cron job.
The call is initiated in cron.php file:
<?php
// initialize configuration and load event observers only from /crontab/ section
Mage::getConfig()->init()->loadEventObservers('crontab');

// initialize crontab event area
Mage::app()->addEventArea('crontab');

// dispatch 'default' event for observers specified in crontab configuration
Mage::dispatchEvent('default');

This sequence will invoke Mage_Cron_Model_Observer→dispatch(), which in turn will:

*

*execute scheduled tasks

*generate future scheduled tasks if needed

*clean up history of scheduled tasks

Tasks are scheduled for each time the job needs to be run based on
<schedule><cron_expr>0 1 * * *</cron_expr></schedule>

expression and stored in cron_schedule table. Each record consists of the following fields:

*

*schedule_id - unique identifier for scheduled task

*job_code - job identifier from configuration

*status - can be one of pending, running, success, missed, error

*messages - custom text reported by method that was executed by the job

*created_at - date/time when the task was created at

*scheduled_at - date/time when the task is planned to be executed

*executed_at - date/time when the task was actually executed (null prior to execution)

*finished_at - date/time when the task finished execution (null prior to execution)
When schedules are generated, status is set to pending, created_at to now() and scheduled_at to target date/time.
When pending schedules are executed, status is set to running and executed_at to now().
When scheduled task is finished successfully, status is set to success and finished_at to now().
When scheduled task has thrown an exception, status is set to error and finished_at to now().
If task status is pending and scheduled_at is older than "Missed if not run within" configured value, status is set to missed.


text:
Q: Displaying attributes of associated models in a datagrid column I have two models: User and Dog.  I want to be able to show them both in a single Datagrid report. What syntax do I use to refer to a specific attribute of the user model when using the column() method? Right now I am just displaying the User object but I would like to display various columns with :name, :gender and :age attributes of the User model.
class User < ActiveRecord::Base
  attr_accessible :email, :age, :gender, :name
  has_many :dogs

class Dog < ActiveRecord::Base
  attr_accessible :name, :age
  belongs_to :user

class DogReport
    include Datagrid

  #
  # Scope
  #

  scope do
    Dog.includes(:user)
  end

  #
  # Filters
  #

  filter(:dog_id, :integer)

  #
  # Columns
  #

  column(:id)
  column(:name)
  column(:age)
  column(:user)
end

A: column(:user, :header => "user.name") do
  self.user.name
end


text:
Q: Async Parallel duplicate entries So I am going through an array called candidates and performing certain tasks using each item in the array and then at the end pushing results to Firebase candfb . Here's the code:
    var candidates = json.stageCandidates.candidate;
    var list = [];
    for (var i = 0; i < 20; i++) {
        var candidate = [];
        var id = candidates[i].candidateId;
        async.parallel([
            function(callback) {
                votesmart.getDetailedBio(id, function(err, json) {
                    if (!err && json.bio != undefined)
                        candidate.bio = json.bio;
                    callback();
                });
            },
            function(callback) {
                votesmart.getAddress(id, function(err, json) {
                    if (!err && json.address != undefined)
                        candidate.address = json.address.office[0];
                    callback();
                });
            },
            function(callback) {
                votesmart.getRating(id, function(err, json) {
                    if (!err && json.candidateRating != undefined)
                        candidate.ratings = json.candidateRating;
                    callback();
                });
            },
            function(callback) {
                votesmart.getVotes(id, function(err, json) {
                    if (!err && json.bills != undefined)
                        candidate.votes = json.bills;
                    callback();
                })
            },
            function(callback) {
                votesmart.getStances(id, function(err, json) {
                    if (!err && json.npat != undefined)
                        candidate.stances = json.npat;
                    callback();
                })
            }
        ], function() {
            candfb.push(candidate);
            // res.send(candidate);
        })
    };

Now the problem is that even though there are exactly 20 items being pushed (hardcoded in the loop) there are duplicates of some items and some are being skipped. Some items might be unique while others may have as much as 3 copies being pushed to Firebase. I've also checked and the array candidates does not have duplicates.
I suspect it might be due to me using async.parallel() but I'm unsure as to what to change to make it work.

A: Try this, it should fix your issue. It's a common mistake when mixing synchronous for loops with asynchronous calls. You need to close over i, otherwise it will be mutated.
  var candidates = json.stageCandidates.candidate;
    var list = [];
    for (var i = 0; i < 20; i++) {
        (function(i){
            var candidate = [];
            var id = candidates[i].candidateId;
            async.parallel([
                function(callback) {
                    votesmart.getDetailedBio(id, function(err, json) {
                        if (!err && json.bio != undefined)
                            candidate.bio = json.bio;
                        callback();
                    });
                },
                function(callback) {
                    votesmart.getAddress(id, function(err, json) {
                        if (!err && json.address != undefined)
                            candidate.address = json.address.office[0];
                        callback();
                    });
                },
                function(callback) {
                    votesmart.getRating(id, function(err, json) {
                        if (!err && json.candidateRating != undefined)
                            candidate.ratings = json.candidateRating;
                        callback();
                    });
                },
                function(callback) {
                    votesmart.getVotes(id, function(err, json) {
                        if (!err && json.bills != undefined)
                            candidate.votes = json.bills;
                        callback();
                    })
                },
                function(callback) {
                    votesmart.getStances(id, function(err, json) {
                        if (!err && json.npat != undefined)
                            candidate.stances = json.npat;
                        callback();
                    })
                }
            ], function() {
                candfb.push(candidate);
                // res.send(candidate);
            })
        })(i)
    };


text:
Q: Is there a relay that disconnects BOTH positive and ground wires? My latest time-lapse camera rig, was failing to run due to the constant ground connection on the camera power input.
This is an off-grid, solar-powered rig, combining a Raspberry Pi and an Arduino, to share tasks using a minimum of energy.
As a novice in electronics I felt I was making progress, having used GPIO controlled relays to break the positive wire connection on several of my rigs.
However, in this rig, I use two different methods to take the pictures:
1/ An in-camera script (C.H.D.K. Canon Hackers Development Kit) which takes a picture automatically, on power up of the camera by the Arduino,
2/ A PTP connection to the camera's USB port when the Raspberry Pi is active and supplying the power to the camera as well.
Due to the ground wire of the Raspberry Pi remaining connected to the Camera power input, I found that my on-board script failed, due to it falsely detecting a USB connection.  On disconnection of the ground wire, the script works as intended.
I imagined this need for 'double disconnection' ie. of both the positive AND negative wires, would be a common issue in electronics and that there would be a relay component ready made for the job but Google doesn't turn one up.
I suspect I simply just don't know the right name for the task, among the many versions of relays out there.
Please advise, or, if there's another approach in circumstances like mine, I'd love to hear it.  it seems wasteful to be using a two channel relay to operate a single power switch. ie. one channel for the positive wire and one for the ground.
I hope I explained myself well enough. If not, I apologize and will correct as best I can
Thanks in advance

A: Hi you really need a DPST ( double pole single throw) relay.
but DPDT (double pole double throw) will be mostly available with the hobby stores.
You can use any of the above
Pls follow the link
https://www.evelta.com/relays/power-relay/hongfa-hf115f-024-2zs4


text:
Q: continuous image of non-compact sets We know that continuous image of a compact set is closed and bounded. But, compactness is not necessary to claim that. I want to know is there any theorem that says that continuous image of some special kind of non-compact set is also closed and bounded.

A: No, there can't be any such theorem.  Here's a negative result.
Proposition. Let $(X,d)$ be a metric space, and suppose $E \subset X$ is not compact.  Then there exists a continuous function $f : X \to \mathbb{R}$ such that the image $f(E)$ is not closed.
Proof.  By the Bolzano-Weierstrass theorem, there is a sequence $\{x_n\} \subset E$ which does not have a limit point in $E$.  (Without loss of generality, assume all the points $x_n$ are distinct.)  This sequence may or may not have a limit point in $X$.
If $\{x_n\}$ does have a limit point in $X \setminus E$, call it $p$, then let $f(x) = d(p,x)$.  Since $p \notin E$, we have $0 \notin f(E)$.  But since $x$ is a limit point of $\{x_n\}$, we have $f(x_n) = d(p, x_n) \to 0$, so $0$ is a limit point of $f(E)$.  Thus $f(E)$ is not closed.
If $\{x_n\}$ does not have a limit point in $X$, then $D := \{x_n\}$ is a closed discrete set.  So any function on $D$ is continuous; in particular, consider the function $g : D \to \mathbb{R}$ defined by $g(x_n) = n$.  By the Tietze extension theorem, $g$ has a continuous extension $\bar{g} : X \to \mathbb{R}$, so that $\bar{g}(x_n) = n$ as well.  Set $f(x) = 1/(1 + \bar{g}(x)^2)$.  Clearly $0 \notin f(X)$ so $0 \notin f(E)$.  But $f(x_n) = 1/(1+n^2) \to 0$, so $0$ is a limit point of $f(E)$.  Thus $f(E)$ is not closed. $\Box$
Getting a function which is not bounded could be a little trickier.  For instance, if $E$ is not compact but is contained in a compact set $F$ (such an $E$ is sometimes called "precompact" or "relatively compact"), then for every metric space $Y$ and every continuous $f : X \to Y$, $f(E)$ will be bounded (since it is a subset of $f(F)$ which is compact and thus bounded).