text:
Q: File Provider Issue on Android TV I am using File provider for installing downloaded APK using Google Package installer in Android TV But always stuck on Package Parsing Error.
The same code base is working fine on android Mobile phone OS but not on Android TV. To note, Mine is a system application and have all the required permissions like REQUEST_INSTALL_PACKAGES, READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE but still no luck.
Can any folk please help me if this is a known bug on Android TV or there is something special need my attention.
Checklist:
1. Provider cross-checked with authority to grantURIPermissions
<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

provider_paths.xml
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
<files-path
    name="data"
    path="."/>
<cache-path
    name="cache"
    path="." />
<external-path name="external_download" path="Download"/>
<external-files-path name="Download" path="Download/" />

val uri = FileProvider.getUriForFile(this@MainActivity, BuildConfig.APPLICATION_ID+".provider", file)
                        val intent = Intent(Intent.ACTION_VIEW)
                        intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
                        intent.setDataAndType(uri, "application/vnd.android.package-archive")
                        val resInfoList = context?.packageManager?.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
                        resInfoList?.let {
                            for (res in resInfoList) {
                                val packageName = res.activityInfo.packageName
                                context.grantUriPermission(packageName, uri,  Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                context.grantUriPermission(packageName, uri,  Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                                context.grantUriPermission(packageName, uri,  Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
                            }
                        }

                        startActivity(intent)

internal fun getDownloadFileLoc(context: Context): String {
    val fileDir = "${Environment.getExternalStorageDirectory()}/download"
    val fileName = context.getString(R.string.apk_name)
    return "$fileDir/$fileName"
}

I get a warning that permission denial for provider. Please tell me if I have to provide some specific information.


text:
Q: Combining Unique Pairs of Files with find I have a series of actions I need to preform on pairs of files, on a fair number of files. For simplicity, I'll focus this down on just doing a simple cat on a pair, to discuss the pairing and how to write the most straight forward pairing part of shell script.
Say I have 4 files, A.txt, B.txt, C.txt, and D.txt, and I want to write a compact script that will basically do:
 cat A.txt B.txt > AB.txt
 cat A.txt C.txt > AC.txt
 cat A.txt D.txt > AD.txt
 cat B.txt C.txt > BC.txt
 cat B.txt D.txt > BD.txt
 cat C.txt D.txt > CD.txt

I want to have one output for each unique combination, and AD.txt and DA.txt are not "unique" by this criteria.
But I'd like to make it a bit easier than as a shell script, that I can do for different sets of files, and just run it in a directory, and have it find all matches recursively. I immediately seem to have went the wrong direction, and made a mess of things:
find "$PWD" -type f -iname "*.txt" -exec [[SOME MAGIC CODE CREATING PAIRS OF FILE NAMES]] {} \;
 \ cat "$MAGICPAIRfile1".txt "$MAGICPAIRfile2".txt >
 \ "$MAGICPAIRfile1"-"$MAGICPAIRfile2".txt

was thinking of exec'ing a couple pieces in there, one that dumps file names to a text buffer (bad buffer type for file name character strings, so I didn't), and then pass that buffer to yet another exec {} \;.
But I thought someone else might have a good idea?

A: Here's my suggestion.
#!/bin/bash
files="empty"
for i in A B C D ; do
    for j in B C D ; do
     fn="$i$j"
     nf="$( echo $fn | rev )"
     # if nn is 1 $nf wasn't found in $files
      nn=1
      for q in $files ; do
        if [[ "$q" == "$nf" ]] ; then
               nn=0
         fi
        done
        if  [[  $nn -eq 1 ]] && [[ "$fn" != "$nf" ]]
        then
           echo "cat $i.txt $j.txt >$fn.txt"
        fi
        files="$fn $nf $files"
    done
done

A: You can save the file arguments of your find command into an array. Also you can sort them before saving. Here, null separation has been used (-d '' for mapfile (==readarray), -print0 for find and -z for sort) which requires GNU utilities.
And do a double loop for them, i is running the whole length and j from i+1 to the end, and create the combinations. You can process into there each combination of the file arguments.
#!/bin/bash
mapfile -d '' arr < <(find . -type f -name '*.txt' -print0 | sort -z)

for ((i=0; i<"${#arr[@]}"; i++)); do
    for ((j=i+1; j<"${#arr[@]}"; j++)); do
        printf "Processing files: %s %s\n" "${arr[i]}" "${arr[j]}"
    done
done

Processing files: ./A.txt ./B.txt
Processing files: ./A.txt ./C.txt
Processing files: ./A.txt ./D.txt
Processing files: ./B.txt ./C.txt
Processing files: ./B.txt ./D.txt
Processing files: ./C.txt ./D.txt

For your specific example, to cat the files and have the desired output filename (assuming they are all in the same directory level), you could use find ... -printf '%f\0', to print only the filenames, and substring removal with parameter expansion, to create the commands. Slightly modified version, using newline separator for the filenames:
#!/bin/bash
mapfile -t arr < <(find . -type f -name '*.txt' -printf "%f\n" | sort)

for ((i=0; i<"${#arr[@]}"; i++)); do
    for ((j=i+1; j<"${#arr[@]}"; j++)); do
        cat "${arr[i]}" "${arr[j]}" > "${arr[i]%.*}${arr[j]}"
    done
done

A: If you can use perl and assuming your filenames are "well-behaved":
find ... |
perl -0777 -MMath::Combinatorics -anE \
  'BEGIN{$,=" "}; say sort(@$_) for (combine(2, @F))' |
sort

Output when A\nB\nC\nD\n is the input:
A B
A C
A D
B C
B D
C D

To recreate your example (GNU sed):
... |
sed -E 's/([^.]+).([^ ]+) ([^.]+).([^ ]+)/cat \1.\2 \3.\4 > \1\3.\2/'

cat A.txt B.txt > AB.txt
cat A.txt C.txt > AC.txt
cat A.txt D.txt > AD.txt
cat B.txt C.txt > BC.txt
cat B.txt D.txt > BD.txt
cat C.txt D.txt > CD.txt

Which can then be piped to a shell for execution or done with the /e flag in GNU sed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing parameter between ViewModels using MVVMLight I'm having a problem to pass parameters betweeen my ViewModels using the Messenger class in the MVVMLight Framework.
This is the code I'm using :
ViewModelLocator
public ViewModelLocator ()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<INavigationService, NavigationService>();

    SimpleIoc.Default.Register(() => new MainViewModel(NavigationService));
    SimpleIoc.Default.Register(() => new SecondViewModel(NavigationService));
}

public MainViewModel MainViewModel
{
    get { return SimpleIoc.Default.GetInstance<MainViewModel>(); }
}

public SecondViewModel SecondViewModel
{
    get { return SimpleIoc.Default.GetInstance<SecondViewModel>(); }
}

public INavigationService NavigationService
{
    get { return SimpleIoc.Default.GetInstance<INavigationService>(); }
}

MainViewModel
private void ShowPersonDetailsCommand(object obj)
{
    Messenger.Default.Send((Person)obj);
    _navigationService.NavigateTo(new Uri("/SecondPage.xaml", UriKind.Relative))
}

SecondViewModel
public SecondViewModel(INavigationService navigationService)
{
    _navigationService = navigationService;

    Messenger.Default.Register<Person>(
        this,
        person =>
        {
            Person = person;
        });
}

In my MainViewModel (ShowPersonDetailsCommand), I'm navigating to a SecondPage and sending a person as parameter in the Messenger class. At this point, the person is well constructed and sent as a message.
But in the SecondViewModel constructor, the person is null :(
Is there something I'm missing ?
I thinks I did something wrong ...
For your information :

*

*Windows Phone 8.1 (Silverlight)

*MVVMLight 5.0.2

*Visual Studio 2013 Update 4

A: I would suggest creating the SecondViewModel immediately as soon as it is registered in the ViewModelLocator. You can do that by using a overloaded method of Register.
SimpleIoc.Default.Register<SecondViewModel>(true);

This will make sure that ensure that the Messenger registration happens before the message is sent.

A: When you sent the message, the SecondViewModel was not created yet; it's only created when you access the SecondViewModel property of the ViewModelLocator. So your message was sent, and wasn't handled by anything. Then, when the SecondViewModel instance was created, the message had already been sent...
I suggest you send the message after the call to NavigateTo, it should fix the problem.

A: Instead of sending a message, you could pass a parameter in the NavigationServicesEx.Navigate method call.
This blog by Marco Minerva advises how to hook in to the Frame_Navigating event (that it missing from the vanilla NavigationServiceEx class) to access the argument when the destination page is navigated to.
Create the INavigable interface described in the blog:
public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.
You will then be able to access the parameter that you passed in your Navigate call:
NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);

In the OnNavigatedToAsync method that you implement in your ViewModel:
public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}


text:
Q: Twitter4j: how to get twit url from status? I am using twitter4j-3.0.5 on Windows.
When new status arrives to the StatusListener.onStatus() method, I would like to print out it's URL but I don't find any appropriate method. status.getURLEntities() is always empty, even tough if I look at the json passed to the client, the url field is not empty and contains valid URL.
I just don't know how to get this value from java.
Please advise.

A: The getURLEntities() method returns any URLs in the content of the tweet itself, not the URL of the tweet.
Fortunately the URL of a tweet is in the following format:
https://twitter.com/[screen name of user]/status/[id of status]
So you can get the URL of a status with this code:
Status status;
String url= "https://twitter.com/" + status.getUser().getScreenName()
    + "/status/" + status.getId();
System.out.println(url);

A: URL can be exposed by 2 ways.

*

*giving the twitter link

*giving the website link which is tweeted.
Sample Example:
package com.twitter.example;

import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.URLEntity;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterApplication {
    public static void main(String[] args) throws TwitterException {
        ConfigurationBuilder cf = new ConfigurationBuilder();
        cf.setOAuthConsumerKey("OAUTH_CONSUMER_KEY")
                .setOAuthConsumerSecret("OAUTH_CONSUMER_KEY_SECRET")
                .setOAuthAccessToken("OAUTH_ACCESS_TOKEN")
                .setOAuthAccessTokenSecret("OAUTH_ACCESS_TOKEN_SECRET");

        TwitterFactory tf = new TwitterFactory(cf.build());
        Twitter twitter = tf.getInstance();

        // get username and status
        List<Status> statusList = twitter.getHomeTimeline();

        int i = 0;
        for (Status status : statusList) {
            i++;
            String url = "https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId();
            System.out.println("Twitter URL:"+url);

            URLEntity[] urls = status.getURLEntities();
            for(URLEntity urlEntity : urls) {
                url = urlEntity.getURL();
                System.out.println("Website link URL in the tweet: "+url);
            }
            if (i == 1)
                break;
        }
    }
}

Output:

Twitter URL:https://twitter.com/CulturalGM/status/966308069884952577
Website link URL in the tweet: https://websitelink


text:
Q: Does this polynomial have a rational value which is the square of a rational number? I have the following polynomial:
$$P(x,y,z):=9y^2z^2-30x^2z+90xyz+54yz-270x+81\in\mathbb Q[x].$$
It came up in a larger proof, and I would need in order to complete the proof to prove the following result:

Does there exist $(x,y,z,r)\in\mathbb Q^4$ such that $x\ne 0$ and
$$P(x,y,z)=r^2.$$

We can reformulate the problem in the following way:
Does the algebraic variety defined by
$$9Y^2Z^2-30X^2Z+90XYZ+54YZ-270X+81-T^2$$
have a rational point with $X\ne 0$?
I have no idea how to tackle this problem, I have looked up several articles, but nothing seems to apply to this particular question.
Any hints or references would be greatly appreciated.

A: Two obvious solutions are $P(0,0,0)=(\pm9)^2$.
To find more solutions, plugging in $z=0$ yields
$$P(x,y,0)=-270x+81,$$
which is a square for $x=\frac{81-t^2}{270}$ for any choice of $t\in\Bbb{Q}$, and any choice of $y\in\Bbb{Q}$.


text:
Q: ORA-12545: Network Transport: Unable to resolve connect hostname Getting following exception two week once in PROD, when calling azure function from core api 3.1.
Below issue occurred when establishing the connection with oracle DB using ADO.Net. especially when executes the conn.open().
            OracleConnection conn = new OracleConnection(connStr);
            conn.Open();
            OracleCommand cmd = new OracleCommand(strSQLQuery, conn)
            {
                CommandType = CommandType.Text
            };
            OracleDataReader odr = cmd.ExecuteReader();

Once restarted the app service from azure portal, it would be resolved.
Error - ora-12545 network transport unable to resolve connect hostname.

A: Please check if below can be worked around.

*

*If you are using the tnsname.ora,Please make sure its configured
correctly. Check tnsname.ora file for prod and check for
servername,See if the prod listener exists in listener.ora file, it
must be missing.So try to add the listener for prod environment similar to dev
,if present.

*If the Connection string had DNS name, try replacing it with IP
address. Try to use user service name as they have different names for
product and dev separately which can be useful  even if SID is same
(in some cases).Always Ensure that the host field of the local_listener is
properly set to a name which can be resolved by the Oracle client.

Or

*Try to update host files to contain the requird server and host port.
Go to
\etc\hosts . Insert  server name and
server IP in here and save.

*Also check the .net version , it may be incompatible sometimes,
maybe that's why , after restarting ,its setting itself and the
problem is resolved in azure app service.or Some times issue maybe
due to firewall being restricting in azure portal.

You can raise a support request from overview page from troubleshoot blade ,if the issue still remains.
Reference:
oracle - Stack Overflow


text:
Q: How to add image into UIAlertView? I want to add image at the top left corner of the UIAlertView.
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 40, 40)];

NSString *path = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"cloud.png"]];
UIImage *bkgImg = [[UIImage alloc] initWithContentsOfFile:path];
[imageView setImage:bkgImg];

[successAlert addSubview:imageView];

[successAlert show];

I am using this code but image does not come up with UIAlertView. Please help me

A: For iOS 7.0 +
Use:
[successAlert setValue:imageView forKey:@"accessoryView"];

A: UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:@"your Title" message:@"Your   Message" delegate:nil cancelButtonTitle:@"Your Title" otherButtonTitles:nil];

UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 40, 40)];

NSString *loc = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Your Image Name"]];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:loc];
[image setImage:img];

 if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
   [Alert setValue:image forKey:@"accessoryView"];
}else{
   [Alert addSubview:image];
}

[Alert show];

A: First add your image to image assets and give name as imgCloud Then update your code to :
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

UIImageView *imageViewCloud = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 40, 40)];
UIImage *bkgImg = [UIImage imageNamed:@"imgCloud"];
[imageViewCloud setImage:bkgImg];
[successAlert imageViewCloud forKey:@"accessoryView"];
[successAlert show];


text:
Q: SiteMapNode is readonly, property 'Url' cannot be modified I setup MVC breadcumbs for my website using MvcSiteMapProvider (Nuget package MvcSiteMapProvider.MVC5 (version 4.6.22)).
It works fine.
Then I want to update Url of Sitemap dynamically like:
SiteMaps.Current.CurrentNode.Url = Url.Action("Index");

Then I got this error:

SiteMapNode is readonly, property 'Url' cannot be modified

Note that I am still able to update Title:
SiteMaps.Current.CurrentNode.Title = "/Index";

Any idea?

A: The SiteMap is a statically cached object that is shared between all users. Technically, all of the properties are read-only at runtime. However, some of the properties (such as Title) are request-cached so you can safely update them at runtime without affecting other users.
The Url property is a special property that dynamically builds the URL through the MVC UrlHelper class (which is directly driven from your routes). It makes no sense to set it to Url.Action("Index") because that is effectively what it does just by itself (unless you are using a dynamic node provider or custom ISiteMapNodeProvider - those are startup extension points where you load the node configuration, so the properties are read-write).
You just need to set the correct controller and action in your node configuration (which could be XML, attribute based, or code based) and the URL will resolve on its own.
XML Example
<mvcSiteMapNode title="Projects" controller="Project" action="Index"/>

NOTE: You need to account for all route values in the request, either by adding them as another attribute myId="123" or by using preservedRouteParameters="myId" (which tells it to include the myId from the current request when building the URL). See this article for a detailed description of using these options.
NOTE: Setting a URL in the SiteMap configuration effectively overrides MVC support for that node. So, you shouldn't set a URL at all unless it is a non-MVC URL.


text:
Q: How do I fetch/re-push a submodule in git? In my git repository (Bitbucket) I have a reference to a sub project.
When I pushed it on the first place a .git/ folder was included (even though I use the repository only for backup so that'd not been really needed).
Now I have a reference to that submodule in the repository
 <folder_name> → <SHA> [<SHA>])

*

*When I do git pull origin master the folder if fetched but it's empty.

*When I try to put stuff in that folder (I removed it, then I pulled it from a different repository and then removed the .git/ folder to make it looks a normal folder, not a submodule) and then git add . && git commit -m ".." && git push origin master I only get Everything's up-to-date and of course nothing changed in the remote repository

Goal: push a past submodule as a normal folder part of the main repository.
What I missing out? How do submodules work? (the docs @ Github are not very clear to me)

A: As I explained this morning in "How to solve this Git issue?", this (ie '<folder_name> → <SHA> [<SHA>]') is not a submodule.
A submodule is composed of:

*

*a remote repo url (stored in a file called .gitmodules)

*a SHA1 recorded as a gitlink (special entry in the index)

If you record only the SHA1, but not the url, you will have something like:

A git clone --recursive won't be able to clone the repo with that SHA1, because it does not know its url.
If you want to reference a subproject as a submodule:

*

*read Git Submodules, and

*use git submodule add https://...


text:
Q: Combobox Value Loading Problem Using C# & MySQL
When i select a particular value from the combobox then i clicked the button, the corresponding value should display in the other textbox
code
protected void Button1_Click(object sender, EventArgs e)
    {
        cmd2 = new OdbcCommand("Select name from users where username = '" + combobox1.Text  + "' ", con);
        dr1 = cmd2.ExecuteReader();
        while (dr1.Read())
        {
            textbox1.Text = dr1.GetString(0);

        }
        dr1.Close();

    }

The Above Code is working, but nothing displaying in Textbox1, there is the problem only in the query, I changed the query like  Select name from users where username = '005'
Output is displaying in the textbox1, but when i used combobox value it is not displaying.
I also tried:
combobox1.text, combobox1.selectedvalue, combobox1.selecteditem, combobox1.selectedindex

Combobox Filling Code
cmd2 = new OdbcCommand("Select username from users, con);
        ada2 = new OdbcDataAdapter(cmd2);
        ada2.Fill(data2);
        combobox1.DataValueField = "username";
        combobox1.DataSource = data2;

combobox1.DataBind();
Username values like 201, 202, 203....,
Why is the query executing while using the combobox value....
Need Query Help

A: if you are using winform controls, please use below code
comboBox1.DataSource = list;
 comboBox1.ValueMember = "Name";

to get value from combobox use comboBox1.SelectedValue[It will return object type]

A: comboBox1.Items[comboBox1.SelectedIndex].Text should give you what you want.

wrap your combo box's filling code in
if (!Page.IsPostBack) {}

It should be filled only when the page is loaded the first time and not on subsequent postbacks otherwise it will reset the binding everytime the page is posted back.

A: you should use combobox1.SelectedItem.Text for the desired result.


text:
Q: Ruby Shoes App with two buttons to give a file either Name "A" or Name "B" Lets say I have a file a.txt on my C:.
When I press button one in the gui I want to rename C:\a.txt to c:\xyz_a.txt.
When I press button two in the gui I want to rename the file back to c:\a.txt.
How would you do that with ruby shoes? Any hints would be much appriciated.

A: Here is a Shoes app that with two buttons that will rename file back and forth.
Shoes.app {

    file_orig = "E:/abc.txt"
    file_renamed = "E:/xyz_a.txt"

    stack do
        @push_1 = button "Rename"
        @push_2 = button "Rename back"
        @note = para ""
    end

    @push_1.click {
        begin
            File.rename(file_orig, file_renamed)
            @note.replace "File #{file_orig} renamed to #{file_renamed}"
        rescue => e
            @note.replace "Error while renaming #{file_orig} : #{e.message}"
        end
    }
    @push_2.click {
        begin
            File.rename(file_renamed, file_orig)
            @note.replace "File #{file_renamed} renamed BACK to #{file_orig}"
        rescue => e
            @note.replace "Error while renaming #{file_renamed} : #{e.message}"
        end
    }
}

Note that my example uses file from E drive. To rename files in C drive, one typically needs administrator privilege.  You may get error like: rename': Permission denied @ sys_fail2 - (C:/abc.txt, C:/xyz_a.txt) (Errno::EACCES).
To give administrator privilege to your Shoes app, you can launch a command line window using Run as administrator option (Right-click on command icon in application list and select Run as administrator), and from that command window run the shoes app using shoes app.rb.

A: Here is another simple solution.
The folder is C:\Test\, the file is called A.txt and will be renamed to INACTIVE_A.txt with button one and back to A.txt with button two.
Shoes.app do
  stack do
    button "Rename A.txt to INACTIVE_A.txt" do
      Dir.chdir("C:/Test")
      File.rename("A.txt", "INACTIVE_A.txt")
    end
    button "Rename INACTIVE_A.txt to A.txt" do
      Dir.chdir("C:/Test")
      File.rename("INACTIVE_A.txt", "A.txt")
    end
  end

end


text:
Q: SQL Data entities Entity Association I have about 8 entities that all have a one to one relationship with a common entity.
The client is not choosing from pre-defined data so it is not necessary to apply a FK to be used as a constraint.
The main table in question is call a finish table and it contains four unknown hex colors that are sent from the client to the server.
For example, when a door is built the colors for the different parts of the door and it's outer parts can all have different colors. So, all of these tables in question, their data is always fresh from the client and not chosen from a drop down, or from some other pre-defined data that I am given to the client to choose from.
My question is, what would be the best way to association this finish entity with the other entities that need a way to express their finish?
I am adding a screen shot of a diagram that I am working on, these are not all the entities and are just the ones in question right now and ones that will help articulate to others what I am needing a solution for.
I have also included some script as well.
    /****** Object:  Table [dbo].[Finish]    Script Date: 06/22/2012 15:08:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Finish](
    [ID] [int] NOT NULL,
    [Left] [varchar](30) NULL,
    [Right] [varchar](30) NULL,
    [Top] [varchar](30) NULL,
    [Bottom] [varchar](30) NULL,
    [Note] [varchar](150) NULL,
 CONSTRAINT [PK_Finish] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Horizontal]    Script Date: 06/22/2012 15:08:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Horizontal](
    [ID] [int] IDENTITY(11,1) NOT NULL,
    [Name] [varchar](15) NOT NULL,
    [Floor] [smallint] NOT NULL,
    [SizeID] [int] NOT NULL,
    [GlassPocket] [decimal](5, 3) NULL,
    [IsFiller] [bit] NOT NULL,
    [Note] [varchar](150) NULL,
 CONSTRAINT [PK_Horizontal] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Door]    Script Date: 06/22/2012 15:08:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Door](
    [ID] [int] IDENTITY(421,1) NOT NULL,
    [BayID] [int] NOT NULL,
    [Position] [tinyint] NOT NULL,
    [HasJamb] [bit] NOT NULL,
    [HasThreshold] [bit] NOT NULL,
    [IsAutoShowroom] [bit] NOT NULL,
    [IsSingle] [bit] NOT NULL,
    [Type] [varchar](10) NOT NULL,
    [SizeID] [int] NOT NULL,
    [Note] [varchar](150) NULL,
 CONSTRAINT [PK_Door] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Leaf]    Script Date: 06/22/2012 15:08:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Leaf](
    [ID] [int] IDENTITY(21,1) NOT NULL,
    [DoorID] [int] NOT NULL,
    [Position] [tinyint] NOT NULL,
    [Stile] [varchar](10) NOT NULL,
    [Bottomrail] [decimal](5, 3) NOT NULL,
    [Hand] [varchar](5) NOT NULL,
    [IsActive] [bit] NOT NULL,
    [Swing] [varchar](5) NOT NULL,
    [SizeID] [int] NOT NULL,
    [Note] [varchar](150) NULL,
 CONSTRAINT [PK_Leaf] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Bay]    Script Date: 06/22/2012 15:08:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Bay](
    [ID] [int] IDENTITY(1213,1) NOT NULL,
    [ElevationID] [int] NOT NULL,
    [Position] [tinyint] NOT NULL,
    [SizeID] [int] NOT NULL,
    [Note] [varchar](150) NULL,
 CONSTRAINT [PK_Bay] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Each one of the entities below need to be associated with the finish table. Each entity new record has exactly one finish relationship.
Is it possible to associate these and still be able to do a Cascade On DELETE, with-out having a circular reference issues?

A: Yes, it's possible.
You would add a reference to Finish entity in each of the tables that has a relationship to it.
You would define the column with the same datatype, (and normally) as the referenced_table_name and id. In our shop, the column_name would be [finish_id]. (I see here that you are using a CamelCase style.)
At any rate, I would recommend you define this as a foreign key.
You say there is no need to, but from what you describe, this is exactly the kind of situation that calls for a foreign key constraint.
You need to decide on the action when the id in the finish table is updated or deleted. (Do you want to disallow the update or delete? Do you want to preserve existing relationship?) I expect you would want the default ON DELETE RESTRICT.  You could allow for updates, and preserve the relationships, with ON UPDATE CASCADE.)
I don't see any potential problem with circular references, as long as the finish table will be the parent (all the other tables reference it, and the finish table doesn't have any references to the other tables.)


text:
Q: Dynamic conditional correlation in Stata I am testing the co-movement between 2 exchanges by using the dynamic conditional correlation (DCC) developed by Robert Engle (2002). I want to apply this method in stata 12 and used this command:
Mgarch DCC (var1 var2=), arch(1) garch(1) distribution(t)

I read that it should give me a column with correlations per time unit. But i am not getting this colums. Does someone have any idea how to apply the DCC in Stata 12?

A: You need to read the help file for -mgarch dcc postestimation-. You will find the following example of computing the dynamic correlations and their forecasts.
webuse stocks
mgarch dcc (toyota nissan = , noconstant) (honda = , noconstant), ///
    arch(1) garch(1)
tsappend, add(50)
predict H*, variance dynamic(2016)
tsline H_nissan_toyota H_honda_toyota H_honda_nissan if t>1600, ///
    legend(rows(3)) xline(2015)

which produces the graph of the dynamic correlations between the three individual stocks.

Update 1
If you are only interested in the in-sample fits of the conditional correlations, then it becomes really simple, and you can drop the tsappend command:
webuse stocks
mgarch dcc (toyota nissan = , noconstant) (honda = , noconstant), ///
    arch(1) garch(1)
predict H*, variance
tsline H_nissan_toyota H_honda_toyota H_honda_nissan if t>1600, ///
    legend(rows(3))

The option t>1600 asks that the in-sample predictions be plotted starting at "time period" 1600 (this dataset has a time index that runs from 1 to 2015). The xline option asks for a vertical line at t=2015 (in the previous example, this was to indicate that at t=2015, forecasts were out-of-sample), and the legend(row(3)) specifies that you want the graph legend to placed in three separate rows -- this is just graph formatting.

Update 2
The OP has asked about adding explanatory variables in the equations for the conditional mean and the conditional variance. This is explained in the help file for mgarch dcc. The syntax is
        mgarch dcc eq [eq ... eq] [if] [in] [, options]
    where each eq has the form
        (depvarlist = [indepvars] [, eqoptions])

*

*The optional argument [indepvars] allows you to add explanatory variables to the conditional mean to any one, to sets of, or to all the dependent variables at the same time.

*The optional equation options, eqoptions, has the following optional component
  het(varlist)             include varlist in the specification of the conditional variance

which allows you to add explanatory variables to the conditional variance equation of any one, to sets of, or to all the dependent variables at the same time.
Example
So, for example, if  you had three series return1, return2 and return3, and three independent variables x1, x2 and x3, then the command
mgarch dcc (return1 return2 = x1 x2, het(x1 x2 x3)) (return3 = x3, het(x1 x2 x3))

implies that the variables x1 and x2 enter the conditional mean of return1 and return2, x3 enters the conditional mean of return3. Similarly, x1, x2 and x3 enter the conditional variance of return1, return2 and return3.


text:
Q: JdbcSQLSyntaxErrorException when using text array from hibernate types I'm using this hibernate-types that allows hibernate to translate SQL layer data types into java classes in my springboot application, here I'm trying to add a text array field called user array.
@Entity
@Table(name = "user_update")
@Getter
@Setter
@NoArgsConstructor
@RequiredArgsConstructor
@TypeDef(name = "list-array", typeClass = ListArrayType.class)
public class UserUpdate {

  @Id @NonNull private String userKey;

  @Column @NonNull private String userName;

  @Column @NonNull private Instant updatedAt;

  @Type(type = "list-array")
  @Column(columnDefinition = "text[]")
  @NonNull
  private List<String> userArray;
}

I can insert data into the table, but now I want to add a test and I see the following error message from the table.sql
CREATE TABLE IF NOT EXISTS user_update (
    user_key VARCHAR(255) NOT NULL,
    user_name VARCHAR(255) NOT NULL,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL,
    user_array TEXT ARRAY NOT NULL,
    PRIMARY KEY(org_key)
);

maybe it is because the test I'm running uses @DataJpaTest and for some reason it can not recognize the new text[] field ?
Error executing DDL "create table user_update (user_key varchar(255) not null, user_name varchar(255), user_array text[], updated_at timestamp, primary key (user_key))" via JDBC Statement

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "create table user_update (user_key varchar(255) not null, user_name varchar(255), user_array text[*][], updated_at timestamp, primary key (user_key))"; expected "(, ARRAY, INVISIBLE, VISIBLE, NOT, NULL, AS, DEFAULT, GENERATED, ON, NOT, NULL, DEFAULT, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, COMMENT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:

A: With @DataJpaTest Spring will instruct Hibernate to create the schema and that will use the information that you provided in your annotations, but it seems this is not legal for H2.
Try using the following instead:
@Column(columnDefinition = "text array")


text:
Q: OVER_QUERY_LIMIT while using google maps I have a problem while acessing google maps from my application, when i send more than 10 requests in loop from java script i get the exception as OVER_QUERY_LIMIT from geocoder service.
is there any way that i can get rid of this, i tried giving some time delays using setInterval() etc.. .but doesnt work.

A: Geocoding in the JavaScript API is rate-limited. When you first load the API, you can send 10 requests for address geocoding or 5 for reverse (latlng) geocoding before you get an OVER_QUERY_LIMIT response. When you do, use "exponential backoff" to delay your queries.
You may also want to join the discussion in Issue 4805 (gmaps-api-issues).

A: Probably you are sending too many requests per second and Google doesn't let you do that.
Read http://code.google.com/apis/maps/faq.html#geocoder_classorhttp

A: If you are using an autocomplete, try using Google's Places Autocomplete API. (Even though this isn't exactly what he asked, I assume many will arrive here from this question)

A: Have a list of API's and use them randomly for each request .
For Example in python
like keys = [key1,key1,key3....]
location = Geocoder(random.choice(keys)).geocode(address)

or
location = Geocoder(random.choice(keys)).reverse_geocode(Lat,Long)

Based on your Requirement

A: We can use ajax queue.
At a time 20 ajax request will get executed and others will wait in the queue.
Create multiple geocode key and keep in an array and use it randomly for each ajax request.
Here I have loaded 2200 markers. It takes around 1 min to add 2200 locations.
<https://jsfiddle.net/suchg/qm1pqunz/11/>

A: First read this article.
https://developers.google.com/maps/premium/previous-licenses/articles/usage-limits
If you are send many request in one second then use delay method.
function sleep(milliSeconds) {
  var startTime = new Date().getTime();
  while (new Date().getTime() < startTime + milliSeconds);
}

call this method in your loop structure.
      sleep(2200);


text:
Q: Swiping on a jqxgrid does not work on my mobile phone I have a page containing a jqxgrid from JQWidgets, which is bigger than the screen size of my mobile phone. If I want to swipe the grid to the left to see the content on the right part I have to swipe on an area outside of the grid.
Now if it happens that the grid covers the whole screen and I do not see any area outside of it I cannot swipe at all any more to see any other part of the grid/page
I tried selectionmode: 'none', enablehover: false, but it did not make any difference for the swiping.
I just installed the latest version 8.3.2 of the 12 jqxgrid files. -> Same
What I just discovered: If I start swiping the screen by touching an area outside of the grid and then while the screen is still moving I quickly place my finger on top of the grid and continue swiping it works. However as soon as the screen stops moving I cannot start moving it any more by swiping on the grid

A: The problem was with the version of the JQWidgets. I had version 4.1.2 installed. I replaced it with version 8.3.2 (the whole package had to be replaced not just the jqxgrid files) and now it works fine.


text:
Q: How to create a custom validator for file upload which accepts image files in asp.net mvc 3 I am using asp.net mvc3.
I am using dataannotation and Jquery unobstrusive for server side and client side validation.
How to validate fileupload which accepts only image file extensions.Need to work exactly same as others.
Do I need to create a custom validator for server side and client side?
Thanks in advance

A: You can do something like this:
If u are using property in model
public class ValidateFileAttribute : ValidationAttribute
        {
            public override bool IsValid(object value)
            {
                int MaxContentLength = 1 * 1024 * 700; //3 MB
                string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
            var file = value as HttpPostedFileBase;

            if (file == null)
                return false;
            else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "Please upload Your image of type: " + string.Join(", ", AllowedFileExtensions);
                return false;
            }
            else if (file.ContentLength > MaxContentLength)
            {
                ErrorMessage = "Your image is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
                return false;
            }
            else
                return true;
        }
    }


text:
Q: If $PE$ is defined the following way, then for arbitrary force field which tends to zero at infinity, will $\vec{F}=-\vec{\triangledown}(PE)$ Potential energy is defined as the work done by external force to move from infinity to that point.
$$PE=-\int^{r}_{\infty}\vec{F}.\vec{dr}$$
(for an arbitrary force field $\vec{F}$ which tends to zero at infinity)
$$=-\left[     \int\vec{F}.\vec{dr}    \right]_{at\ r}
+\left[     \int\vec{F}.\vec{dr}    \right]_{at\ \infty}....(1)$$
Now whenever the force tends to zero at infinity, can we say the second term in $(1)$ is zero?? so that potential energy simplifies to:
$$PE=-\int\vec{F}.\vec{dr}$$
$$=-\int F_xdx-\int F_ydy-\int F_zdz$$
and hence:
$\vec{F}=-\vec{\triangledown}(PE)$

A: First of all as @Alpha001 commented, it does not necessarily mean that the line integral is zero if the force tends to zero at infinity. There is another reason why this is not always true. The relation holds only for conservative forces, the class of forces for which the line integral is independent of the path chosen. This is a very crucial point to observe. A potential function "at a point" can be defined only if the function is single valued at that point. It does not make sense to define potential at a point differently for different paths chosen, in that case the potential is no longer a function.
So in summary, only conservative forces can be written as a gradient of a scalar potential.


text:
Q: Delete files after deleting a specific row of a table I have a table that store the ADDRESS of uploaded files. e. g. "upload/news/pic1.jpg" .
Now my question is:
How can I delete these uploaded files after deleting rows from table. Is there a way to do this automatically? I can't let them stay on host permanently!
thanks...

A: Go through the file names and delete the files.
foreach ($files as $filepath) {
    unlink('/path/to/root/'.$filepath);
}

Then delete the file names from the database.
Computers are stupid. They will only do something if you tell them to do it.


text:
Q: javax.mail.transport not sending alert for 1000 or 1000+ active email ids I can send a message to exact 999 active users and also email alerts to same in my application but can send the only message to 1000 or more than 1000 active users and not the email alerts. I am using javax.mail.transport class to send the email alerts.
While debugging I can see all the users with their respective email ids in toAddresses but after transport.send(msg) statement control goes off and their won't be an exception and also alerts don't get sent if toAddresses contains 1000 or 1000+ active email ids.
Any help or suggestions would be appreciated.
if (toList != null && toList.size() > 0) {
toAddresses = new InternetAddress[toList.size()];
toList.copyInto(toAddresses);
}

Message msg = prepareHeader(smtp_host, from, toAddresses, null, null,
subject,header);
MimeMultipart mp = new MimeMultipart();
MimeBodyPart text = new MimeBodyPart();
msg.setContent(message, "text/html; charset=utf-8");
text.setHeader("Content-Type", "text/html;charset=utf-8");
text.setHeader("Content-Transfer-Encoding", "quoted-printable");
text.setDisposition(Part.INLINE);
text.setContent(appendHTMLStartEnd(message), "text/html; charset=utf-8");
mp.addBodyPart(text);

try
{
Transport.send(msg);
}
catch (SendFailedException ex)
{
ex.printStackTrace();
throw ex;
}


text:
Q: Expected voltage on external gain resistor pre-amp I want to build an amplifier with digitally controlled gain, using the THAT1510 pre-amp IC.
The IC provides two pins to set the gain, using resistors.
I want to switch between resistors with analog switching ICs.  In order to choose the right IC, I need do know the maximum voltage I can expect between RG1 and RG2.
Internally, the pre-amp looks like this:

V- being tied to GND and V+ being 36V, what maximum voltage can I expect?

A: Assuming this functional block diagram is a reasonably accurate depiction of the actual internals, all you can say is that the potential at \$R_{G1}\$ will be slightly less than \$-In\$, and \$R_{G2}\$ will be slightly less than \$+In\$.
This is a huge assumption though, and all the things we know about making assumptions are very applicable here.
My preferred approach would be to use a digital potentiometer IC to attenuate the output, like the MCP45HVX1, or use a combination of DAC and voltage-controlled variable gain amplifier.
Suggestion:
Use this amplifier, by all means, but with a much lower supply voltage, so that you widen the range of compatible analogue switches available to you.
Use a second gain stage, with a 36V supply, to further scale up this this small excursion signal to become a larger version that falls within your required extremes.


text:
Q: netbeans 7 groovy editor I've been trying out Netbeans 7 for its native groovy support, and one thing that seems to be a problem is automatically generated getters for boolean members using the isXXX syntax.
I have a groovy class
class MyClass {
   boolean finished
}

From my Java code, I should be able to call either isFinished or getFinished as follows:
MyClass mc = new MyClass();
System.out.println(mc.isFinished());
System.out.println(mc.getFinished());

However, the groovy editor within netbeans tells me that mc.isFinished cannot be found (but it compiles fine in maven and eclipse). I've filed a bug with netbeans, but this seems like a major issue with the netbeans editor. Has anyone had this problem before and/or know if there is a way to work around it?
thanks,
Jeff

A: Last time I looked, the Groovy support in Netbeans was stuck at Groovy v1.6.4.
This is over 2 years old :-(
I have heard rumours that it is set to improve in the future, but at the time of writing this, if you need a full IDE with current Groovy support, I would look at IntelliJ IDEA, the Groovy plugin for Eclipse, or STS


text:
Q: Statmodel OLS fails at column names with multiple words-Linear regression I trying a simple linear regression using ols and it fails at columns with multiple word name.
mod = smf.ols(formula='Sales ~ Sub Region + Customer Segment', data=df)

I am searching how to fix but none has worked so far. The Q transformation I found hereas I use it below dsnt resolve it either. Does anyone know how can get this fixed?
mod = smf.ols(formula='Sales ~ Q(Sub Region) + Q(Customer Segment)', data=df)


text:
Q: Java RMI Reference I am trying to teach myself about Java RMI. But till now, I cannot find any particular reference book/video/site that could be able to teach me clearly about this. Sure that there is the documentation site here http://docs.oracle.com/javase/tutorial/rmi and I have tried looking at them (and still) . But i want a different tutorial that could guide me step by step on creating one simple java rmi application. So do u guys have any idea about this? thanks!

A: Here are some of the references you may find useful for learning Java RMI.
http://www.java2all.com/1/5/22/114/Technology/RMI/RMI-Program/RMI-example
http://www.studytonight.com/java/rmi-in-java.php

A: Have you used Java 6 Black Book (by Kognet Solutions chapter no 31)...?? It is best book for RMI..


text:
Q: How to remove many rows duplicate in two datatable? I using C#. I have 2 datatable dtUser, dtUserNotAllow.
I want to check all rows in dtUseris contain in datatable dtUserNotAllow? If it have, remove it.
Like this.
dtUser: user1  user2 user8
dtUserNotAllow: user2.
This will delete user2.
=> dtUser: user1 user8
foreach(DataRow rows in dtUserNotAllow)
{
    if(dtUser.Columns.Contains(rows["user_name"].ToString()))
    {

    }
}

But show error like:
foreach statement cannot operate on variables of type 'System.Data.DataTable' because 'System.Data.DataTable' does not contain a public definition for 'GetEnumerator'

A: you have to replace
foreach(DataRow rows in dtUserNotAllow)

with
foreach (DataRow row in dtUserNotAllow.Rows)

to remove invalid rows, your code should look something like
List<String> lUserNotAllow = dtUserNotAllow.AsEnumerable().Select(x => (string)x["user_name"]).ToList();
foreach (DataRow row in dtUser.Rows)
{
    if(dtUserNotAllow.AsEnumerable().Any(x => row["user_name"]  == x["user_name"]))
    {
        dtUser.Rows.Remove(row);
    }
}

to iterate through the rows of the DataTable


text:
Q: Evaluate $\sum_{n=1}^\infty \frac{n}{2^n}$ This is a homework question; I'm supposed to use power series to find the following sum: $$\sum_{n=1}^\infty \frac{n}{2^n}$$ I took the geometric series $$\frac{1}{1-x}=\sum_{n=0}^\infty {x^n}$$ and differentiated and multiplied both sides by x to get $$\frac{x}{(1-x)^2}=\sum_{n=1}^\infty {nx^n}$$ I'm stuck because I'm not sure how to make the $$\frac{1}{2^n}$$ term appear.

A: For $x=\frac {1} {2}$, we have $\sum _{i} nx^n=\sum _{i} n(\frac {1} {2})^n=\sum _{i} \frac {n} {2^n}$

A: Without power series:
$$2S-S:=\frac11+\frac22+\frac34+\frac48\cdots-\frac12-\frac24-\frac38-\cdots
=\frac11+\frac12+\frac14+\frac1{8}+\cdots=2.$$

A: You are basically all of the way there.  In your last step, you have
$$ \frac{1}{(1-x)^2} = \sum_{n=1}^{\infty} n x^n, \tag{$\ast$}$$
where the series on the right converges for any $|x| < 1$ to the rational expression on the left.  Since we get to pick $x$ to be anything we like (as long as $|x| < 1$), we might as well choose $x = \frac{1}{2}$.  If we do this, the series on the right-hand side of ($\ast$) becomes
$$ \sum_{n=1}^{\infty} n \left( \frac{1}{2} \right)^n
= \sum_{n=1}^{\infty} n \cdot \frac{1}{2^n}
= \sum_{n=1}^{\infty} \frac{n}{2^n}, $$
which is the original series that you were given to evaluate.  But with $x = \frac{1}{2}$, the left-hand side of ($\ast$) is
$$ \frac{1}{\left( 1 - \frac{1}{2} \right)^2} = \frac{1}{\left(\frac{1}{2}\right)^2} = \frac{1}{\frac{1}{4}} = 4.$$
Therefore, equating the left- and right-hand sides of ($\ast$) when $x = \frac{1}{2}$, we obtain
$$ \sum_{n=1}^{\infty} \frac{n}{2^n} = 4.$$


text:
Q: SubSonic 2 Migrations Addon: Create a MySQL specific ForeignKey Migrationstep I use migrations a lot (only MySQL) and since SubSonic Migrations only allows to define the parent and the master column in CreateForeignKey, I cannot define the update/delete actions in a FK Relation.
However there a quite a number of scenarios where I, for instance, need to define a FK relation where, if I delete the parent record, all records in the child table should be set to null (default would be to restrict the delete).
I use a little function that does this for me.
However since this is totally MySQL specific, and it breaks the idea that stands behand migrations (to be DB independent), I decided not to provide a patch for this. So I post the code snippet here.
But if someone needs this, too. Feel free to use it.
There is only one drawback: Since sonic.exe reads the code file and complies it on the fly you have to paste the code into every migration where you use it.

A: Here's a sample migration where I use this.
In the down method you can just use the existing "DropForeignKey(...)" method, since the naming stays the same.
using System;
using System.Collections.Generic;
using System.Text;
using SubSonic;

namespace MyNameSpace.Migrations
{

    public class Migration001 : Migration
    {

        public override void Up()
        {
            TableSchema.Table parent = GetTable("parent");
            TableSchema.Table child = GetTable("child");

            CreateForeignKeyMySQL(parent.GetColumn("id"), child.GetColumn("parent_id"),
                CreateForeignKeyAction.SetNull, CreateForeignKeyAction.Restrict);

            base.Up();
        }

        public override void Down()
        {
            DropForeignKey(parent.GetColumn("id"), child.GetColumn("parent_id"));

            base.Down();
        }

        #region foreign key helper function

        public enum CreateForeignKeyAction
        {
            Cascade,
            Restrict,
            SetNull,
            NoAction
        }

        private String CreateForeignKeyActionValue(CreateForeignKeyAction action)
        {
            switch (action)
            {
                case CreateForeignKeyAction.Cascade:
                    return "CASCADE";
                case CreateForeignKeyAction.Restrict:
                    return "RESTRICT";
                case CreateForeignKeyAction.SetNull:
                    return "SET NULL";
                case CreateForeignKeyAction.NoAction:
                    return "NO ACTION";
                default:
                    return "CASCADE";
            }
        }

        public void CreateForeignKeyMySQL(
            TableSchema.TableColumn oneTable, TableSchema.TableColumn manyTable,
            CreateForeignKeyAction onDelete, CreateForeignKeyAction onUpdate)
        {

            String sqlAppend = String.Format(" ON DELETE {0} ON UPDATE {1}",
                CreateForeignKeyActionValue(onDelete), CreateForeignKeyActionValue(onUpdate));

            SubSonic.MySqlGenerator generator = new SubSonic.MySqlGenerator(null);
            String sqlCommand =
                System.Text.RegularExpressions.Regex.Replace(
                    generator.BuildForeignKeyStatement(oneTable, manyTable), ";?$", sqlAppend
                );

            Execute(sqlCommand);
        }

        #endregion

    }

}


text:
Q: Parity POA: the validator's are not getting paid in ETH for sealing blocks I am working on creating Parity private Blockchain, however,the validator's are not getting paid in ETH for sealing blocks.
I use this command line to check the balance:
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x0037a6b811ffeb6e072da21179d11b1406371c63", "latest"],"id":1}' http://172.0.0.1:8545

I want to ask how can I fix these problem.
{
"name": "Testnet",
    "engine": {
    "authorityRound": {
        "params": {
            "gasLimitBoundDivisor": "0x400",
            "stepDuration": "2",
            "validators" : {
                "list": [ "0xa19b0e4f7ba1d5f74960c0aad794756a0a16eab4", "0x9c8f23e0a9377bd98322f8333142eadbaed200e8", "0x2f2033e303d4bf17403521e0c1830bac4ba09323", "0xe883b46f02ecd0e624082fe6ff12af0337ba0cde", "0xbdc56eb866933e7ba827fa293d4545ef2a350ce2"]
            }
        }
    }
},

"params": {
    "maximumExtraDataSize": "0x20",
    "minGasLimit": "0x1388",
    "gasLimitBoundDivisor": "0x400",
    "networkID" : "0x11"
},
"genesis": {
    "seal": {
        "authorityRound": {
            "step": "0x0",
            "signature": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
        }
    },
    "difficulty": "0x20000",
    "gasLimit": "0x1312D00"
},
"accounts": {
    "0x0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
    "0x0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
    "0x0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
    "0x0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
    "0x00Ea169ce7e0992960D3BdE6F5D539C955316432": { "balance": "1606938044258990275541962092341162602522202993782792835301376" }
}
}

A: You are querying the wrong balance:

*

*0x0037a6b811ffeb6e072da21179d11b1406371c63 is not in your validator node list.

You only specified the following validators:

*

*"list": [
    "0xa19b0e4f7ba1d5f74960c0aad794756a0a16eab4",
    "0x9c8f23e0a9377bd98322f8333142eadbaed200e8",
    "0x2f2033e303d4bf17403521e0c1830bac4ba09323",
    "0xe883b46f02ecd0e624082fe6ff12af0337ba0cde",
    "0xbdc56eb866933e7ba827fa293d4545ef2a350ce2"
]

Try to get the balance of these nodes.


text:
Q: Access Apache VHost Domain through OpenVPN In my company, we're using OpenVPN to connect to our network for remote-working
We have a local server that our employees can access (so through the VPN too), which contains a lot of local websites served by Apache VHost
The problem is, we have domain to access to those websites (i.e thewebsite.company.com) but the ones who come from the VPN can't access them because Windows don't know how to map the domain with the IP address of the concerned Apache server
The workaround I found is to declare the mapping in the hosts file of Windows, which works totally good, but is so not user-friendly and have to be effected in every desktops accessing through VPN
So, I wonder if there is a better method to configure that server-side so on Apache or OpenVPN ?


text:
Q: PowerShell: Looping through an .ini file I'm working on a PowerShell script that will do the following:

*

*Use a function to grab the ini data and assign it to a hashtable (basically what Get-IniContent does, but I'm using one I found on this site).

*Check the nested keys (not the sections, but the keys of each section) to see if the value "NoRequest" exists.

*If a section contains a NoRequest key, and ONLY IF the NoRequest value is false, then I want to return the name of the section, the NoRequest key, and the key's value. For example, something like "Section [DataStuff] has a NoRequest value set to false." If a section doesn't contain a NoRequest key, or the value is set to true, then it can be skipped.

I believe I've accomplished the first two parts of this, but I'm unsure of how to proceed with the third step. Here's the code I have so far:
function Get-IniFile
{
    param(
        [parameter(Mandatory = $true)] [string] $filePath
    )

    $anonymous = "NoSection"

    $ini = @{}
    switch -regex -file $filePath
    {
        "^\[(.+)\]$" # Section
        {
            $section = $matches[1]
            $ini[$section] = @{}
            $CommentCount = 0
        }

        "^(;.*)$" # Comment
        {
            if (!($section))
            {
                $section = $anonymous
                $ini[$section] = @{}
            }
            $value = $matches[1]
            $CommentCount = $CommentCount + 1
            $name = "Comment" + $CommentCount
            $ini[$section][$name] = $value
        }

        "(.+?)\s*=\s*(.*)" # Key
        {
            if (!($section))
            {
                $section = $anonymous
                $ini[$section] = @{}
            }
            $name,$value = $matches[1..2]
            $ini[$section][$name] = $value
        }
    }

    return $ini
}

$iniContents = Get-IniFile C:\testing.ini

    foreach ($key in $iniContents.Keys){
    if ($iniContents.$key.Contains("NoRequest")){
        if ($iniContents.$key.NoRequest -ne "true"){
        Write-Output $iniContents.$key.NoRequest
        }
    }
}

When I run the run the above code, it gives me the following expected output, since I know there are four instance of NoRequest in the INI and only one of them is set to false:
false

I believe I've solved the problem of finding the correct value(s) from the file, but I'm unsure of how to proceed with getting the correct output as mentioned in step 3 above.

A: You were almost there. This will output a string in the form you mentioned:
$key = "NoRequest" # They key you're looking for
$expected = "false" # The expected value
foreach ($section in $iniContents.Keys) {
    # check if key exists and is set to expected value
    if ($iniContents[$section].Contains($key) -and $iniContents[$section][$key] -eq $expected) {
        # output section-name, key-name and expected value
        "Section '$section' has a '$key' key set to '$expected'."
    }
}

Of course, since you said..

If a section contains a NoRequest key, and ONLY IF the NoRequest value
  is false, then I want to return the name of the section, the NoRequest
  key, and the key's value.

.. the key-name and -value will always be the same in the output.


text:
Q: Microsoft Graph: How to get the alias from an email message? When I use Microsoft Graph to retrieve a message's toRecipients or internetMessageHeaders, I am unable to find the actual email alias that the mail was sent to. How do I get the alias? It is always returning the "parent" account, never the alias account.
For example, this shows alias1@company.com as an alias to account email1@company.com.
Request:
https://graph.microsoft.com/v1.0/users/email1@company.com?$select=proxyAddresses
Response:
{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(proxyAddresses)/$entity",
    "proxyAddresses": [
        "smtp:alias1@company.com",
        "X500:/o=Org1/ou=External (xxxxx)/cn=Recipients/cn=00000000000000000000",
        "x500:/o=ExchangeLabs/ou=Exchange Administrative Group (xxxxx)/cn=Recipients/cn=1111111111111111",
        "smtp:email1@company.mail.onmicrosoft.com",
        "X500:/o=Org1/ou=Exchange Administrative Group (xxxxx)/cn=Recipients/cn=yyyyyyyy",
        "smtp:email1@company.onmicrosoft.com",
        "SMTP:email1@company.com"
    ]
}

I then send an email to alias1@company.com. I do not see the alias when retrieving toRecipients or internetMessageHeaders, only the parent account email@company.com.
Request:
https://graph.microsoft.com/v1.0/me/messages/{messageId}?$select=toRecipients,internetMessageHeader
Response:
{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('...')/messages(toRecipients,internetMessageHeaders)/$entity",
    "@odata.etag": "W/\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"",
    "id": "{messageId}",
    "internetMessageHeaders": [
        {
            "name": "Received",
            "value": "...."
        },
        {
            "name": "Received",
            "value": "..."
        },
        {
            "name": "Received",
            "value": "..."
        },
        {
            "name": "Authentication-Results",
            "value": "company.com; dkim=none (message not signed) header.d=none;company.com; dmarc=none action=none header.from=company.com;"
        },
        {
         ...
        }
    ],
    "toRecipients": [
        {
            "emailAddress": {
                "name": "FirstName LastName",
                "address": "email1@company.com"
            }
        }
    ]
}

A: I found this in another SO article: Can you get PR_TRANSPORT_MESSAGE_HEADERS 0x007D from the .Net Microsoft Graph API?
That will return the headers you need

A: You can't.
Microsoft Exchange Server, Office 365 and Outlook.com (formerly Hotmail) do not preserve (or at least expose) the SMTP RCPT TO value (i.e. the envelope address) - which is distinct from the To:, Cc:, and Bcc: headers (note that the Bcc header isn't usually sent at all to the recipient anyway).
This is how e-mail users can receive emails that don't look like they're intended for them (as e-mail servers use the RCPT TO value to route the email and ignore the To: header.
Note that anti-spam software will often flag emails when the RCPT TO value doesn't appear in any of the To:, Cc:, or Bcc: headers as in the late-1990s/early-200s mass-mailed spam didn't have personalised To: headers.
Warning: editorial content below:
I did submit a request with Office 365 support (as I'm an Enterprise subscriber, which I hope means something) to request that they add support for storing the RCPT TO envelope address, but it was thrown onto the backlog and so will never happen. It's yet another bloody obvious feature of an e-mail system that Microsoft steadfastly refuses to adopt, just like disposable addresses, messaging tagging, inline quote replies, separating mailboxes from users, and a tree-view for conversation threads - and more besides. Oy vey.


text:
Q: Laravel 5.1 Authentication without password I'm developing an app in Laravel 5.1. I need to be able to login users only with e-mail (not using password). I have a password field in my login form because I need it for other reasons, but the only thing that I need to check is that the user email exists in my users table.
I rewrited the AuthController, and I'm trying to use the attempt() method, but when i try to login with a valid e-mail, it gives me the following error:
ErrorException in EloquentUserProvider.php line 112: Undefined index: password
How can I tell to EloquentUserProvider that I'm not using password to login, only username (e-mail)?
Thank you!!

A: you can find the email with queries and have the id of user and then
Auth::loginUsingId(user_id);

it will authenticate the user_id .

A: If you're not using a password, really all you need to do is:
$authorised = User::where('email', $email)->exists();

But, if you want to create your own passwordless UserProvider, you could extend EloquentUserProvider and override the validateCredentials to not check the password, as so:
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Auth\EloquentUserProvider;

class NoPasswordUserProvider extends EloquentUserProvider {

public function __construct(HasherContract $hasher, $model)
{
    parent::__construct($hasher, $model);
}

/**
 * Validate a user against the given credentials.
 *
 * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
 * @param  array  $credentials
 * @return bool
 */
public function validateCredentials(UserContract $user, array $credentials)
{
    return true;
}

}

You'll probably need to create new service provider for it, too:
class NoPasswordUserServiceProvider extends ServiceProvider {

public function boot()
{
    Auth::extend('NoPasswordAuth', function($app)
    {
        $model = $this->app['config']['auth.model'];
        return new NoPasswordUserProvider($this->app['hash'], $model);
    });
}

/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
    // TODO: Implement register() method.
}
}

Obviously, the code isn't fully tested but that should more or less work.

A: What I finally did was to write my own Auth Controller. I also writed my own middleware. I did like this because I needed to do more actions when user logs in. I suppose the other answers were OK but as I needed other functionality while user login I decided to write my own controller to implement the functions I need.
In my Auth controller I wrote my own login function, my own logout and so on....
Thank you so much for the answers!


text:
Q: Make editor toolbar more distinct when images are turned off If I turn off automatic image loading in my browser, which happens to be Firefox if that's relevant, the editor toolbar buttons become invisible and the toolbar itself quite indistinct.
Here's an illustration:

I have a suspicion that some of those people who post badly formatted code examples may actually be the ones who are simply unaware of the toolbar buttons being there, and that's what actually made me come up with this question.
I don't have actual numbers of how many newcomers post their questions with messed-up formatting against those who do things right, so it may not be worth the effort, but if it does appear reasonable, I have some suggestions of how to make the toolbar more distinct.

*

*Alt text: [B], [I], ... (sorry, haven't made up all of them yet).

*Frames around empty button slots.

*Different background for the button slots.

*Different background for the toolbar itself.

A: I don't see any way we can make this happen easily. I think that the cost to benefit ration here is massively high. Yes, it's good practice to make sites try to fit most user's needs, but some things are just not worth it. ANyone who has images turned off is likely to know that most sites will look very broken, and I doubt very many people browse this way. It would make for a terrible web browsing experience.
And before the "OMG SHUT UP I ONLY BROWSE THE INERNET USING lynx SO EVERYTHING MUST BE TEXT ONLY" crowd starts attacking me, keep in mind that knowledgeable users are probably the ones who will be creating these edge cases and they will be smart enough to know there's missing images there, and to load them. Besides, those tools are just that: tools. I never hardly ever even use them myself, markdown is easy to write by hand.
That being said, I do think it would be wise to make the help link an actual text ? with a red image background so it would still show up in your screen capture above.


text:
Q: Accessing UIView from UIViewController I have added a UIView to a UIViewController using storyboards (See Image Below)
The problem is I cannot access anything from the UIView. I believe the issue is because when I init the class which UIView uses, I am creating a new instance of VASettingsView rather than using the one which has been added to the UIView frame using storyboards:

VARendererViewController.m
-(void)viewDidLoad{
...
    // Initalise settings subview
    self.settingsInit = [[VASettingsView alloc] init];
    self.settingsInit.delegate = self;
....
}

-(void)update{
        int test = [[self settingsInit] getTest];
        NSLog(@"%d", test);
}

Returns 0, Should return '12345'
Any suggestions?

A: You are correct that you should not need to create a new VASettingsView in -viewDidLoad.  Is settingsInit declared as an IBOutlet?  You should be able to make a connection from the VASettingsView in Interface Builder to the outlet in your view controller.
-viewDidLoad is the method that is called after your nib is loaded; at that point all of the IBOutlets that were connected in your nib will be available for you to use.  It is not necessary to create and set those properties.


text:
Q: Meteor How to Avoid Publishing All I thought I understood pub/sub in Meteor until I ran into this issue.
Suppose you have many blog entries that are meant for public consumption and a user navigates to /:blogId.
You use something like
Blogs.findOne(FlowRouter.getParam('blogId'));

Currently, on the server side, I'm publishing all blog entries.
Meteor.publish("blogs", function () {
    return Blogs.find({});
});

I'm guessing I should only publish the blog entries that are requested with something like:
Meteor.publish("blogs", function (_id) {
    return Blogs.find(_id);
});

What is best practice here?

A: You have it exactly right in your question:
Meteor.publish("oneBlog", function (_id) {
  return Blogs.find(_id); // must return a *cursor* or array of cursors, not an object
});

Meteor.publish("allBlogs", function () {
  return Blogs.find();
});

From the client subscribe to the oneBlog based on the route parameter:
Meteor.subscribe("oneBlog", FlowRouter.getParam('blogId'));

A: You can make another publication (which returns only one) for specific route.


text:
Q: Confusion with quantum superposition I have been studying QM and I think doing research on quantum superposition got me more confused about the topic. So I have two interpretation that I came across:

*

*A quantum state that is in superposition (say) of state 1 and 2 means that it is not in exactly state 1 and 2 but a unique state called superposition that gets influenced by the measurement. (This is the explanation I understood by first lecture of MIT QM 8.04 lecture on youtube by Allan Adams).

*A quantum state that is in superposition of state 1 and 2 is already in state 1 or 2 but since we don't know until we take a measurement we mathematically write it with these two possibilities.
The difference is that idea 2) says that the state is already fixed between 1 and 2 but we just don't know until we measure it and 1) says that the quantum state behaves something that is neither like state 1 and 2.
I understand that this might be a basic question but even after looking at questions on here at stackexchange and quora, I didn't know which answer to believe because both were presented.

A: According to quantum mechanics, the answer is interpretation 1: the system is in a state that is neither 1 nor 2, but a superposition.
We can make things a little more concrete by considering a single particle with spin. Let's suppose that that whenever we measure the particle's spin along a particular axis, we always get one of two values, $+1$ or $-1$, relative to that axis.
Then suppose the particle is in the superposition state
\begin{equation}
|\psi\rangle = \frac{|+1; z\rangle + |-1; z\rangle}{\sqrt{2}}
\end{equation}
where the notation $|+1; z\rangle$ refers to a state in which the particle is measured to have spin $+1$ along the $z$ axis.
It turns out that this same state, expressed in terms of the outcome of measuring spin along the $x$ axis, is
\begin{equation}
|\psi\rangle = |+1; x \rangle
\end{equation}
With interpretation 1, there is no problem. The state of the system is $|\psi\rangle$; there is no extra information that the system has that we don't know (a "hidden variable"). If we try to impose interpretation 2, we will run into a contradiction with quantum mechanics. For interpretation 2 to be true, the system must secretly have a definite spin direction for both the $x$ and $z$ components of spin. This contradicts the Heisenberg uncertainty principle, which (in this case) states that we cannot measure the $x$ and $z$ components of spin simultaneously. If we cannot measure a quantity even in principle, we should not ascribe physical meaning to it.
Now, being in contradiction with the Heisenberg uncertainty principle doesn't necessarily mean that the particle really doesn't have definite spin along the $x$ and $z$ axes; it could be that Nature does not follow the rules of quantum mechanics. However, you can make the above arguments sharper by including multiple entangled particles separated by a spacelike distance -- so far that light cannot travel between them. This leads to the Bell inequalities, which have been shown to hold experimentally, demonstrating that no local hidden variable theory can explain the predictions of quantum mechanics. There are "loopholes" -- ways to explain the predictions of quantum mechanics while having "extra" information we don't directly observe like you are describing -- but as time has gone on and more careful experiments have been done, these loopholes have become smaller and smaller and to date quantum mechanics is consistent with all experiments that have been done to test it.

A: The first statement is correct (see also this important article on the interpretations of quantum mechanics).

A quantum state that is in superposition of state 1 and 2 is already in state 1 or 2

This is poorly worded. Saying that the system is in a superposition and then saying "already in state 1..." is contradictory. It doesn't make much sense to say that the system is in any particular state (prior to measurement).

A quantum state that is in superposition (say) of state 1 and 2 means that it is not in exactly state 1 and 2 but a unique state called superposition

This is the right way to look at it. The system is in a superposition of its possible eigenstates.

The difference is that idea 2) says that the state is already fixed

If this is what the statement implies, then it is clearly wrong. The system is in a superposition, and that is perhaps all that can be said. Saying that the state is fixed (prior to measurement) contradicts the notion of superposition.

*

*says that the quantum state behaves something that is neither like state 1 and 2.

Right. It is in a superposition of its possible eigenstates.
The concept of quantum superposition is an idea that never quite "makes sense" when we use classical thinking. What we can do, as you have alluded to, is write down the state of the system in a superposition of its possible eigenstates, and the coefficients$^1$ give us a measure of the likelihood of finding the system in a particular state.
$^1$ For example, a quantum state $$\Psi = \sqrt{\frac{1}{3}}\ |1\rangle + \sqrt{\frac{2}{3}}\ |2\rangle$$ tells us that if we were to  measure the system, we will find the system in the states $|1\rangle$ or $|2\rangle$ with probability $\frac 13$ and $\frac 23$ respectively.


text:
Q: Cannot find symbol java netbeans Can someone tell me why I'm getting the error Cannot find symbol when I'm creating an object? in bank_account Christine = new bank_account();
public class BankAccountTester
{
public static void main (String []args)
{
bank_account Christine = new bank_account();

Christine.deposit(10000);
Christine.withdraw(2000);

System.out.println(Christine.getBalance());
}
}

this is my class
public class bank_account{

private double balance;

public bank_account()
{
balance = 0;
}

public bank_account (double initialBalance)
{
balance = initialBalance;
}

public void deposit(double amount)
{
balance = balance + amount;
}

public void withdraw (double amount)
{
balance = balance - amount;
}

public double getBalance()
{
return balance;
}
}

A: The program is fully functional, I've tried your code and it works fine.
This is your compact code: https://gist.github.com/anonymous/8f055d981b27de4ce75c8c64d9a58498
Just go on www.compilejava.net and 'compile and run' it there.
It works on compilejava.net and on my netbeans too.
I think there's a problem with your compiler. You can try to reset it or even clean the cache:  Deleting this directory should clear the cache for you- C:\Users\username.netbeans\7.0\var\cache //adapt with your version
An other error could be in creating project. In netbeans you have to create a project for each app you're developing. Have you did it and connected the 2 file of the program?


text:
Q: PHP => Call to non-existing class constants, way to handle? just like the __call magic method we can use in PHP to hook a call to a non defined method, is there a way to hook a call to an undefined constant or variable?
Like A::B, where B doesn't exist.

A: No.  Constants are evaluated at opcode compile time not runtime, so there's no way to 'catch' them.  There is still an issue with php related to this where a parent class cannot call a childs constant inside a parents method.

A: You're probably looking for __get and __set. I'm not really sure how it works with static constants though, you might only be able to work with instanced objects. See G-Nugget's comment regarding using them statically.


text:
Q: Running a file using terminal on Ubuntu: os.system is functional where subprocess.Popen cannot find the file I'm trying to run a file via python using subprocess.Popen on Ubuntu version 16. A open source application  is installed and using the command CopasiUI at the terminal will open the Copasi GUI whereas the command CopasiSE at the terminal opens the command line interface to the same program. Using CopasiSE <file path> where <file path> is the full path to a copasi file will submit the copasi file for running. This fully works when done manually.
Code:
    `
In [13]: f='/home/b3053674/Documents/PyCoTools/PyCoTools/PyCoToolsTutorial/Kholodenko_0.cps'

In [14]: import os

In [15]: f
Out[15]: '/home/b3053674/Documents/PyCoTools/PyCoTools/PyCoToolsTutorial/Kholodenko_0.cps'

In [16]: os.path.isfile(f)
Out[16]: True

And the symlink to the program also is functional:
In [20]: subprocess.Popen('CopasiSE')
Out[20]: <subprocess.Popen at 0x7f72a2643e90>

In [21]: COPASI 4.16 (Build 104)
The use of this software indicates the acceptance of the attached license.
To view the license please use the option: --license

Usage: CopasiSE [options] [file]
  --SBMLSchema schema           The Schema of the SBML file to export.
  --configdir dir               The configuration directory for copasi. The
                                default is .copasi in the home directory.
  --configfile file             The configuration file for copasi. The
                                default is copasi in the ConfigDir.
  --exportBerkeleyMadonna file  The Berkeley Madonna file to export.
  --exportC file                The C code file to export.
  --exportXPPAUT file           The XPPAUT file to export.
  --home dir                    Your home directory.
  --license                     Display the license.
  --maxTime seconds             The maximal time CopasiSE may run in
                                seconds.
  --nologo                      Surpresses the startup message.
  --validate                    Only validate the given input file (COPASI,
                                Gepasi, or SBML) without performing any
                                calculations.
  --verbose                     Enable output of messages during runtime to
                                std::error.
  -c, --copasidir dir           The COPASI installation directory.
  -e, --exportSBML file         The SBML file to export.
  -i, --importSBML file         A SBML file to import.
  -s, --save file               The file the model is saved to after work.
  -t, --tmp dir                 The temp directory used for autosave.

And using os.system works:
In [21]: os.system('CopasiSE {}'.format(f))
COPASI 4.16 (Build 104)
The use of this software indicates the acceptance of the attached license.
To view the license please use the option: --license

This is expected output for a running Copasi file.
BUT subprocess.Popen give me this:
In [22]: subprocess.Popen('CopasiSE {}'.format(f))
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-22-c8cd60af5d46> in <module>()
----> 1 subprocess.Popen('CopasiSE {}'.format(f))

/home/b3053674/anaconda2/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
    388                                 p2cread, p2cwrite,
    389                                 c2pread, c2pwrite,
--> 390                                 errread, errwrite)
    391         except Exception:
    392             # Preserve original exception in case os.close raises.

/home/b3053674/anaconda2/lib/python2.7/subprocess.pyc in _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, to_close, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
   1022                         raise
   1023                 child_exception = pickle.loads(data)
-> 1024                 raise child_exception
   1025
   1026

OSError: [Errno 2] No such file or directory

In [23]:

Could anybody suggest why?

A: With subprocess.Popen you should pass parameters separately: subprocess.Popen(['CopasiSE', f]) because it's shell (invoked by os.system()) that splits command line.


text:
Q: Need help with $\int_0^1\frac{\log(1+x)-\log(1-x)}{\left(1+\log^2x\right)x}\,dx$ Please help me to evaluate this integral
$$\int_0^1\frac{\log(1+x)-\log(1-x)}{\left(1+\log^2x\right)x}\,dx$$
I tried a change of variable $x=\tanh z$, that transforms it into the form
$$\int_0^\infty\frac{4z}{\left(1+\log^2\tanh z\right)\sinh2z}\,dz,$$
but I do not know what to do next.

A: An alternative way to evaluate $$\frac{\pi}{2} \int_{0}^{\infty} \tanh \left(\frac{\pi u}{2} \right) \frac{e^{-u}}{u} \, du ,$$ which is line $3d$ in robjohn's answer, is to add a parameter and then differentiate under the integral sign.
Specifically, let $$I(a) = \frac{\pi}{2}\int_{0}^{\infty} \tanh \left(\frac{\pi u}{2} \right) \frac{e^{-au}}{u} \, du.$$
Then $$ \begin{align} I'(a) &= - \frac{\pi}{2} \int_{0}^{\infty} \tanh \left(\frac{\pi u}{2} \right) e^{-au} \, du \\ &= -\frac{\pi}{2} \int_{0}^{\infty} \left(\frac{1}{1+e^{- \pi u}}- \frac{e^{- \pi u}}{1+e^{-\pi u}}  \right)e^{-au} \, du \\ &= -\frac{\pi}{2} \int_{0}^{\infty} \left(\sum_{n=0}^{\infty} (-1)^{n} e^{-n \pi u} + \sum_{n=1}^{\infty} (-1)^{n} e^{-n \pi u} \right)e^{-au} \, du \\ &= \frac{\pi}{2} \int_{0}^{\infty} \left(1- 2 \sum_{n=0}^{\infty} (-1)^{n}e^{-n \pi u} \right) e^{-au} \, du \\ &=  \frac{\pi }{2a} -\pi \sum_{n=0}^{\infty} \frac{(-1)^{n}}{a+n \pi} \\ &= \frac{\pi }{2a} -\frac{1}{2} \psi \left(\frac{a+\pi}{2 \pi} \right) + \frac{1}{2} \psi \left(\frac{a}{2 \pi} \right) \tag{1}. \end{align}$$
Integrating back, we get $$ \begin{align} I(a) &= \frac{\pi}{2} \log(a) - \pi \log \Gamma \left(\frac{a+\pi}{2 \pi} \right) + \pi \log \Gamma\left(\frac{a}{2 \pi} \right) +C \\ &= \pi \log \left(\frac{\sqrt{a} \, \Gamma \left(\frac{a}{2 \pi } \right)}{\Gamma \left(\frac{a}{2 \pi} + \frac{1}{2} \right)} \right) + C,\end{align} $$
where $$\lim_{a \to \infty} I(a) =0 = \lim_{a \to \infty} \pi \log \left(\frac{\sqrt{a} \, \Gamma \left(\frac{a}{2 \pi } \right)}{\Gamma \left(\frac{a}{2 \pi} + \frac{1}{2} \right)} \right) +C $$
$$= \pi \log (\sqrt{2 \pi}) + C. \tag{2} $$
Therefore,
$$\frac{\pi}{2} \int_{0}^{\infty} \tanh \left(\frac{\pi u}{2} \right) \frac{e^{-u}}{u} \, du = I(1) =\pi \log \left(\frac{ \Gamma \left(\frac{1}{2 \pi } \right)}{\sqrt{2 \pi} \, \Gamma \left(\frac{1}{2 \pi} + \frac{1}{2} \right)} \right).$$
$$ $$
$(1)$ http://mathworld.wolfram.com/DigammaFunction.html (6)
$(2)$ In general, for $x,y>0$, $\lim_{a \to \infty} \frac{a^{x} \Gamma(ya)}{\Gamma(ya+x)} = y^{-x}$. This can be proven using Stirling's approximation formula for the gamma function.

A: Recall the Frullani Integral:
$$
\int_0^\infty\frac{e^{-ax}-e^{-bx}}{x}\,\mathrm{d}x
=\log(b/a)\tag{1}
$$
and scale equation $(4)$ from this answer to get
$$
\sum_{k=0}^\infty\frac1{(2k+1)^2+u^2}
=\frac\pi{4u}\tanh\left(\frac{\pi u}2\right)\tag{2}
$$
Then
$$
\begin{align}
&\int_0^1\frac{\log(1+x)-\log(1-x)}{\left(1+\log^2(x)\right)x}\,\mathrm{d}x\\
&=\int_0^\infty\frac{\log\left(1+e^{-u}\right)-\log\left(1-e^{-u}\right)}{1+u^2}\,\mathrm{d}u\tag{3a}\\
&=2\sum_{k=0}^\infty\int_0^\infty\frac{e^{-(2k+1)u}}{2k+1}\frac{\mathrm{d}u}{1+u^2}\tag{3b}\\
&=2\sum_{k=0}^\infty\int_0^\infty\frac{e^{-u}\,\mathrm{d}u}{(2k+1)^2+u^2}\tag{3c}\\
&=2\int_0^\infty\frac\pi{4u}\tanh\left(\frac{\pi u}2\right)e^{-u}\,\mathrm{d}u\tag{3d}\\
&=\frac\pi2\int_0^\infty\frac{1-e^{-\pi u}}{u}\frac{e^{-u}}{1+e^{-\pi u}}\,\mathrm{d}u\tag{3e}\\
&=\frac\pi2\int_0^\infty\sum_{k=0}^\infty(-1)^k\frac{e^{-(k\pi+1)u}-e^{-((k+1)\pi+1)u}}u\,\mathrm{d}u\tag{3f}\\
&=\frac\pi2\sum_{k=0}^\infty(-1)^k\log\left(\frac{(k+1)\pi+1}{k\pi+1}\right)\tag{3g}\\
&=\frac\pi2\sum_{k=0}^\infty\log\left(\frac{(2k+1)\pi+1}{2k\pi+1}\frac{(2k+1)\pi+1}{(2k+2)\pi+1}\right)\tag{3h}\\
&=\lim_{n\to\infty}\frac\pi2\log\left[\prod_{k=0}^n\frac{k+\frac12+\frac1{2\pi}}{k+\frac1{2\pi}}\frac{k+\frac12+\frac1{2\pi}}{k+1+\frac1{2\pi}}\right]\tag{3i}\\
&=\lim_{n\to\infty}\frac\pi2\log\,\left[\frac{\Gamma\left(n+\frac32+\frac1{2\pi}\right)^2}{\Gamma\left(\frac12+\frac1{2\pi}\right)^2}\frac{\Gamma\left(\frac1{2\pi}\right)\Gamma\left(1+\frac1{2\pi}\right)}{\Gamma\left(n+1+\frac1{2\pi}\right)\Gamma\left(n+2+\frac1{2\pi}\right)}\right]\tag{3j}\\
&=\frac\pi2\log\,\left[\frac{\Gamma\left(\frac1{2\pi}\right)\Gamma\left(1+\frac1{2\pi}\right)}{\Gamma\left(\frac12+\frac1{2\pi}\right)^2}\right]\tag{3k}\\
&=\bbox[5px,border:2px solid #C0A000]{\pi\log\,\left[\frac{\frac1{\sqrt{2\pi}}\Gamma\left(\frac1{2\pi}\right)}{\Gamma\left(\frac12+\frac1{2\pi}\right)}\right]}\tag{3m}
\end{align}
$$
Explanation:
$\text{(3a)}$: Substitute $x=e^{-u}$
$\text{(3b)}$: $\log\left(\frac{1+x}{1-x}\right)=2\sum\limits_{k=0}^\infty\frac{x^{2k+1}}{2k+1}$
$\text{(3c)}$: Substitute $u\mapsto\frac u{2k+1}$
$\text{(3d)}$: apply $(2)$
$\text{(3e)}$: $\tanh\left(\frac{\pi u}2\right)=\frac{1-e^{-\pi u}}{1+e^{-\pi u}}$
$\text{(3f)}$: $\frac1{1+x}=\sum\limits_{k=0}^\infty(-1)^kx^k$
$\text{(3g)}$: apply $(1)$
$\text{(3h)}$: combine $2k$ and $2k+1$ terms
$\text{(3i)}$: change a sum of logs to a log of a product
$\text{(3j)}$: write products as ratios of Gamma functions
$\text{(3k)}$: apply Gautschi's Inequality
$\text{(3m)}$: $\Gamma(1+x)=x\Gamma(x)$


text:
Q: JQuery using selectors for variables I am trying to create tabs using JQuery for a website. I got this to work:
$("#tabs_1").click(function(){
    $("[id*=tabc]").css({"z-index":0,"opacity":0})
    $("#tabc_1").css({"z-index":1,"opacity":100});
});
$("#tabs_2").click(function(){
    $("[id*=tabc]").css({"z-index":0,"opacity":0})
    $("#tabc_2").css({"z-index":1,"opacity":100});
});
$("#tabs_3").click(function(){
    $("[id*=tabc]").css({"z-index":0,"opacity":0})
    $("#tabc_3").css({"z-index":1,"opacity":100});

However I was wondering if there was a way to neaten the code... Maybe something like this:
$("#tabs_[x]").click(function(){
    var tab_num = x
    $("[id*=tabc]").css({"z-index":0,"opacity":0})
    $("#tabc_(tab_num)").css({"z-index":1,"opacity":100});
});

A: You should use jquery attribute starts with selector. Try this:
$("[id^=tabs]").click(function(){
    var tab_num = this.id.split("tabs_")[1];
    $("[id*=tabc]").css({"z-index":0,"opacity":0})
    $("#tabc_"+tab_num).css({"z-index":1,"opacity":100});
});


text:
Q: how to get parameters from the URL and pass it as a HashMap key JSF? Environment Glassfish , Java 7 , Icefaces I need pass a key parameter trought URL like this:
http://localhost:8080/ProvAt-war/monitor.jsf?&id=77-6
And you show the list based on the parameter received 77-6
I get the parameter through javascript funtion
<ui:repeat value="#{provatBean.descargandoHashMap.get(QueryString)}" var="desc" rendered="#{not empty provatBean.descargandoHashMap.get('QueryString')}">
    <h:outputText value="#{desc.descProveedor}"/>
    <h:outputText value="EDI" rendered="#{desc.id_grupo/>
    <h:outputText value=" NO-EDI" rendered="#{desc.id_grupo/>
    <h:outputText value="PERECEDEROS" rendered="#{desc.id_grupo}"/>
</ui:repeat>

var QueryString = function () {
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = decodeURIComponent(pair[1]);
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  }
  alert(vars[1]);
  return vars[1];
}();

A: The parameters of a request are already available via EL via #{param['key']}, where key is the parameter name of interest. You don't need two dozen lines of JavaScript. And they're already decoded.
This is rather basic.


text:
Q: Maxmimum and minimum value of inverse trigonometric functions If maximum and minimum value of $|\arcsin x|+|\arccos x| $ is represented by $M$  and $m$ respectively then find M+m.
Since, $ -\frac{\pi}{2} \leq \arcsin x \leq \frac{\pi}{2}$
and $0 \leq |\arcsin x| \leq \frac{\pi}{2}$
Also, $ \pi \leq \arccos x \leq 0$
$ \frac{\pi}{2} \leq |\arccos x| \leq 0 $
Can we proceed in this way... please guide... the correct method thanks..

A:
Can we proceed in this way...

Yes. For the $sin^{-1}(x)$, use the chain rule to take the derivative of $|sin^{-1}(x)|$:
$$\frac{d}{dx}|sin^{-1}(x)|=\frac{|sin^{-1}(x)|}{sin^{-1}(x)}\frac{1}{\sqrt{1-x^2}}$$
Find the critical points b finding when the derivative equals 0, and you'll find that it equals 0 when x = 0. Since the only other two critical points are the boundaries, which are both $\pi/2$, 0 must be the minimum, and $\pi/2$ must be the maximum.
The same can be done for $cos^{-1}(x)$, but you'll find that $cos^{-1}(x)$ has no critical points in its domain. This means that the minimum and maximum are simply the endpoints of its co-domain (also known as range).


text:
Q: Interesting definite integral involving exp and trig I'm trying to evaluate the following integrals:
$$\int_0^{2\pi} e^{\kappa \cos(\phi - \mu)} \cos(\phi) d\phi$$
$$\int_0^{2\pi} e^{\kappa \cos(\phi - \mu)} \sin(\phi) d\phi$$
for which I want to find an easily computable function. This may be either a closed form, or something in terms of special functions that are available in most scientific computing libraries (e.g. scipy.special).
I found the following result on wikipedia, which may be useful.
$$\int_0^{2\pi} e^{x \cos(\theta)} d\theta = 2\pi I_0(x),$$
where $I_0(x)$ is the modified Bessel function of the first kind, of order 0.
I want to apologize in advance if this is a basic question; I have not had formal training in advanced calculus (beyond highschool), except for a few online lectures and wikipedia reading.
Any help is greatly appreciated.

A: Consider $$f(x):=\int_0^{2\pi} e^{x \cos(\phi)}\;d\phi=2\pi I_0(x)$$
since $I'_0(x)=I_1(x)$ and using derivation under the integral sign this becomes :
$$f'(x)=\int_0^{2\pi} e^{x \cos(\phi)}\;\cos(\phi) \;d\phi=2\pi I'_0(x)=2\pi I_1(x)$$
Let's rewrite your first integral (using the substitution $\theta:=\phi - \mu$) :
\begin{align}
I_c:&=\int_{-\mu}^{2\pi-\mu} e^{\kappa \cos(\theta)} \cos(\theta+\mu)\;d\theta\\
&=\int_0^{2\pi} e^{\kappa \cos(\theta)} \cos(\theta+\mu)\;d\theta\\
&=\cos(\mu)\int_0^{2\pi} e^{\kappa \cos(\theta)} \cos(\theta)\;d\theta-\sin(\mu)\int_0^{2\pi} e^{\kappa \cos(\theta)} \sin(\theta)\;d\theta\\
&=2\pi\cos(\mu)I_1(\kappa)+\sin(\mu)\int_0^{2\pi} e^{\kappa \cos(\theta)} \;d\cos(\theta)\\
&=2\pi\cos(\mu)I_1(\kappa)+\sin(\mu)\frac{e^{\kappa\cos(2\pi)}-e^{\kappa\cos(0)}}{\kappa}\\
I_c&=2\pi\cos(\mu)\;I_1(\kappa)
\end{align}
The same way I got the second integral as :
$\qquad\qquad\qquad I_s=2\pi\sin(\mu)\;I_1(\kappa)$
For interesting properties and rewriting of the modified Bessel function $I_1$ see the excellent references available :

*

*Abramowitz & Stegun (with a picture of $I_1$ and numerical approximations page $378$)

*DLMF (kind of online successor of A & S)

*Wolfram functions (very large database of information).


text:
Q: C : warning: assignment makes pointer from integer without a cast [enabled by default] This is my code
#include<stdio.h>
#include<stdlib.h>

void main() {
    FILE *fp;
    char * word;
    char line[255];
    fp=fopen("input.txt","r");
    while(fgets(line,255,fp)){
        word=strtok(line," ");
        while(word){
            printf("%s",word);
            word=strtok(NULL," ");
        }
    }
}

This the warning I get.
token.c:10:7: warning: assignment makes pointer from integer without a cast [enabled by default]
   word=strtok(line," ");
       ^

token.c:13:8: warning: assignment makes pointer from integer without a cast [enabled by default]
    word=strtok(NULL," ");
        ^

The word is declared as char*. Then why this warning arises?

A: strtok() is prototyped in <string.h>, you need to include it.
Otherwise, with the lack of forward declaration, your compiler assumes that any function used for which the signature is not known to it, returns an int and accepts any number of parameters. This was called implicit declarration .
FWIW, implicit function declaration is now invalid as per the latest standard. Quoting C11, Foreward, "Major changes in the second edition included:"

*

*remove implicit function declaration

A: You need to include string.h
#include <string.h>

A: Include #include <string.h> to get the prototype for strtok().
Your compiler (like in pre-C99 C) assumed strtok() returns an int because of that. But not providing function declaration/prototype is not valid in modern C (since C99).
There used an old rule in C which allowed implicit function declarations. But implicit int rule has been removed from C language since C99.
See: C function calls: Understanding the "implicit int" rule


text:
Q: For each line L of a file file1.txt, remove the line of the file composer.json that contains L I have a file file1.txt that contains almost forty lines, each line contains a package name.
I have another file composer.json that contains hundreds of packages. I need to remove all packages of my file1.txt from composer.json

file1.txt

remote5/package40
remote1/package1
remote4/package3
...
remote1/package2

Current composer.json

{
    "name": "name/project_name",
    "description": "sf project blabla",
    ...
    "config": {
        "installer-paths: {
            "remote34/package345",
            "remote21/package345",
            "remote123/package345",
            "remote384/package345",
            "remote444/package345",
            ...
            "remote1/package1",
            "remote1/package2",
            "remote4/package3",
            ...
            "remote5/package40",
         }
     }
}

As you can see, the files are different, so I can't use this solution Remove Lines from File which appear in another File

Wanted composer.json

{
    "name": "name/project_name",
    "description": "sf project blabla",
    ...
    "config": {
        "installer-paths: {
            "remote34/package345",
            "remote21/package345",
            "remote123/package345",
            "remote384/package345",
            "remote444/package345",
            ...
         }
     }
}

Here is the command I've been trying so far
for i in `cat file1.txt`; do echo $i && sed -i '/$i/d' composer.json; done

This doesn't change composer.json. However the command below works
sed -i '/remote4\/package3/d' composer.json

UPDATE
grep -Fvxf file1.txt composer.json

The output is exactly composer.json's content

A: with grep
grep -Fvf <(sed 's/.*/"&",/' file1.txt) composer.json

decorate your search keys with the json format and look for fixed string match.

A: Apparently, your composer.json is not valid.
With your data, you can try
awk 'NR==FNR{a[$0];next} {b=$0;sub("[^\"]*\"","");sub("\"[^\"]*$","");if(!($0 in a))print b}' file1.txt composer.json


text:
Q: My McClellan Oscillator graph getting too low at the end I am making a stock McClellan-Oscillator indicator graph for DAX-30 stock index.
I have the following dataset where I have calculated the MO(McClellan Oscillator) from 'ADV'(advance) and 'RED'(reduce/decline).

The formula for MOC is :
e1 = ema19 of (advancing_issues - declining_issues)
e2 = ema39 of (advancing_issues - declining_issues)
mo = e1 - e2 (here 'mo' is the McClellan Oscillator)

I have used the following code to make the mo column:
difference = adv_dec_dax['ADV']-adv_dec_dax['RED']
ema19 = difference.ewm(span=19,adjust=False,ignore_na=False).mean()
ema39 = difference.ewm(span=39,adjust=False,ignore_na=False).mean()
adv_dec_dax['MO'] = ema19-ema39

I dont know what Have gone wrong , heres a comparative image of My graph and from other sources:

I have tried to be as precise as possible . I apologize for any mistakes. Any help will be appreciated. Thnx.