text:
Q: How to return the file path after saving a json file? I can successfully save a json file i created and i know in which directory it is saved, but i want to display the file path to where it is being saved as a text display. I'm stuck on which Qt class and functions to use. Below is my save_json() function:
void EditWindow::save_json()
{
    // update Plot vector
    for(size_t i = 0; i < plots.size(); i++)  {
        //update json object
        if(plots[i]->save_changes())  {
              // reload_nodes(i);
        }
    }

    /* Update json file
     *
     */
    cout<<"Json filename" <<jsonfile<<endl;
    QFile saveFile(QString::fromStdString(jsonfile));
    if (!saveFile.open(QIODevice::WriteOnly))  {

        qWarning("Couldn't open save file.");

    }

    QJsonArray plotsArray;
    for(size_t i = 0; i < plots.size(); i++){
        plotsArray.append(plots[i]->get_json_val());
    }

    QJsonDocument saveDoc(plotsArray);
    saveFile.write(saveDoc.toJson());
    setup_plot_list();
    cout<<"JSON FILE SAVED"<<endl;
}

A: Assuming that _std::string jsonfile and QLabel *text are members of EditWindow, use QFileInfo to do something like this:
...
jsonfile.assign(...); // this is where you set the value of jsonfile
QFileInfo fi(QString::fromStdString(jsonfile));
text->setText(fi.path());
...

That should do the work, but you could experiment with different methods of QFileInfo in order to display different information.


text:
Q: Hodge theory for toric varieties Say we are given a complex smooth projective toric variety $X$. How can one read off hodge theoretic information from combinatorial data? For example I would like to extract dimensions of the various $H^{pq}(X,\mathbb C)$ from the fan or the $sl_2(\mathbb C)$ action on $H^*(X,\mathbb C)$ from the moment polytope etc.

A: Say the toric variety $X$ is defined by the lattice polytope $P$ (dimension = $n$).  Let $f_i$ denote the number of $i$-dimensional faces of $P$, and set $h_p = \sum_{i=p}^n (-1)^{i-p} \binom{i}{p} f_i$.  Then $h^{p,q}(X) = h_p$ if $p=q$ and $0$ otherwise.
I'm reading this from section 9.4 of a version Cox-Little-Schenk's "Toric Varieties".  Haven't read the whole book, so I'm afraid I can't shed much light on why this is true, but a draft used to be available online and I bet you can track down a copy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automatically loading models referenced in a template with ember-data I would like to have model binding relationships loaded automatically when referenced in a template. For example, if I have models like this:
App.User = DS.Model.extend
    name: DS.attr 'name'

App.Contact = DS.Model.extend
    addedBy: DS.belongsTo 'App.User'

and a view like this:
<div>{{contact.addedBy.name}}</div>

it would be really nice if ember-data caught on that it needs to load the User with a primary key in "addedBy". Currently I have to load the User manually with App.User.find(contact.get('addedBy')) and then the template binding updates to display the user's name.
This is a very simple example but in practice I sometimes find myself traversing relationships pretty far. Is there an easy way to automate this?
Thanks folks!

A: What about side-loading the associated users when serving contacts?
Assuming you are using Rails & active_model_serializers gem, you would have a ContactSerializer like this:
class ContactSerializer < ActiveModel::Serializer
  embed :ids, :include => true
  #...
  has_one :user
end

Doing so, the user will be auto-populated when contact is retrieved.
See documentation.

A: Turns out that ember-data does exactly what I want by default, and the problem was a bug in my code.
Make sure that the backend for your adapter's findMany() method returns the records in the same order as the argument array of IDs otherwise your DS.hasMany relationships will act very very weird!


text:
Q: How can a rope's tension be at a maximum as a body is about to move up a slope in the rope's direction? Note: I do NOT need this exercise's answer. I have no problem working the math out and noticing the truth of my title.

A box of mass 0.5 kg is placed on a plane which is inclined at an angle of 40 degrees to the horizontal. The coefficient of friction between the box and the plane is 1/5. The box is kept in equilibrium by a light string which lies in a vertical plane containing a line of greatest slope of the plane. The string makes an angle of 20 degrees with the plane, as shown in the diagram. The box is in limiting equilibrium and may be modelled as a particle. The tension in the string is $t$ newtons.
Find the range of possible values of $t$.

(https://i.postimg.cc/5NC5PRNZ/Capture2.png)
How can a rope's tension be at a maximum as a body is about to move up a slope in the rope's direction?
Perhaps my confusion is due to not really understanding how tension works. I know there are complicated tension based interactions both internal and external acting on a body.
In earlier question's tension in a rope was seen as working in the opposite direction to a force acting on a weight held by said rope. In this case it is not quite the opposite direction, but I can not say that intuitively I understand why the tension would be at a maximum as the body is about to move in the general direction of the rope.

A: The key phrase in the problem is "limiting equilibrium".  By definition, this means that the frictional force between the block and the surface is as large as it can be, and that it is still just managing to cancel out the other applied forces (gravity and the tension.)
When you say that the tension is "at its maximum value", you mean "at the maximum value that still allows for limiting equilibrium".  At some point in your solution, you probably assumed that the acceleration of the block vanishes ($a = 0$);  this is the assumption of limiting equilibrium.  You could certainly pull on the rope with a tension greater than this critical value, but then the block would start accelerating and it wouldn't be in equilibrium any more.


text:
Q: react-native-fbsdk working n ios side but not working on android side I have fully setup the facebook app
Facebook login error app, not setup: the app is still in development mode, and you don't have access to it. switch to registered test user or ask an app admin for permissions

A: STEP 1:
In Settings -> Basic -> Contact Email. (Give your/any email)
STEP 2: In 'App Review' Tab : change
Do you want to make this app and all its live features available to the general public? Yes


text:
Q: Installing a local npm package in Dockerfile I have a local package that I packed into an npm package using npm pack.
I then install this package to some nodejs apps that are external to this local package using npm install path/to/package.tgz. This works like a charm, but now I want to dockerize the apps and I can't manage to install the local package.
My structure looks like this:
-my_package
 |-package.tgz

-app1
 |-app1.js
 |-Dockerfile

-app2
 |-app2.js
 |-Dockerfile

My Dockerfile looks like this:
FROM node:16

WORKDIR /app

# Copy and download dependencies
COPY package.json .
RUN npm install

# Copy the source files into the image
COPY . .

EXPOSE 4002

CMD ["npm", "start"]

And the error I'm getting when running docker build . -t js/app1 is:
npm WARN tarball tarball data for @my_package@file:/package.tgz (sha512-u9tY/j1VOzO1y1RpcCgYteDOEsh7TaSMYwmR2Rs7hoJopE11qa1XcnrrMKNx1/H/aHsZ3Gr0bOMx1SygYTf/rg==) seems to be corrupted. Trying again.
npm WARN tarball tarball data for @my_package@file:/package.tgz (sha512-u9tY/j1VOzO1y1RpcCgYteDOEsh7TaSMYwmR2Rs7hoJopE11qa1XcnrrMKNx1/H/aHsZ3Gr0bOMx1SygYTf/rg==) seems to be corrupted. Trying again.
npm notice
npm notice New major version of npm available! 8.19.2 -> 9.2.0
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v9.2.0>
npm notice Run `npm install -g npm@9.2.0` to update!
npm notice
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /my_package/package.tgz
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/my_package/package.tgz'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-09T04_54_04_868Z-debug-0.log
The command '/bin/sh -c npm ci' returned a non-zero code: 254

Some times I get null instead of the sha512 stuff, otherwise the error is the same.
Is there anything I can do to fix this?
Thanks!

A: The documentation says:

COPY obeys the following rules:
The  path must be inside the context of the build; you cannot
COPY ../something /something, because the first step of a docker build
is to send the context directory (and subdirectories) to the docker
daemon.

The easiest fix is to paste the file(s) you need into the same folder that your Dockerfile is in.


text:
Q: convert hyperlink to text in python dataframe I would like to convert the web column to plain text. Thanks in advance
i used tools.ignore_hyperlink but it gave me error, saying list index
import pandas as pd
import random
import tools

data = pd.read_csv('https://s3-eu-west-1.amazonaws.com/shanebucket/downloads/uk-500.csv')
# set a numeric id for use as an index for examples.
data['id'] = [random.randint(0, 1000) for x in range(data.shape[0])]

data = tools.ignore_hyperlink(data, ['web'])
print(data.head())

A: Check the data type using dtypes. It is object/string, there is no hyperlink dtype. The reason you see the web column as hyperlink is most likely because of the IDE displaying the string as hyperlink, as it auto detects "http://"
data.dtypes

If you are using Jupyter notebook you can type disable auto hyprelink
%%javascript
Jupyter.utils.autoLinkUrls = function (txt) {
    return txt;
}


text:
Q: SQL (sqlsrv) Cursor not finishing when execute from PHP The SQL code below works great in MSSQL but when called via php it only outputs roughly half the results. I have tried placing this in a stored procedure and executing from php but that produces the same result as well.
It should be inserting 150 rows, but I am getting only 77, sometimes 78, but it is always one of those two numbers, which leads me to believe its stopping close to half way every time...

error_reporting(0);   //turn off error reporting

session_start();

if ($_SESSION['id']) {

require('../config.php');

$connectionInfo = array( "Database"=>$database, "UID"=>$user, "PWD"=>$password);
$conn = sqlsrv_connect( $host, $connectionInfo);

$sql = "INSERT INTO [RP].[dbo].[RP_UniqueOffers] (offertype)
Select distinct(offertype) from [RP].[dbo].[Offers] t2
where convert(date,[RedeemedDate]) >= convert(date,getdate()-30)
and not exists (Select distinct(offertype) from [RP].[dbo].[RP_UniqueOffers] t1 where t1.OfferType = t2.offertype )

truncate table [RP].[dbo].[RP_Last30days]

DECLARE @id INT
DECLARE @OfferType NVARCHAR(100)
DECLARE @getid CURSOR
Declare @counter int
Declare @nextDate as Date

SET @getid = CURSOR FOR
SELECT [RP].[dbo].[RP_UniqueOffers].ID,
       [RP].[dbo].[RP_UniqueOffers].OfferType
FROM   [RP].[dbo].[RP_UniqueOffers]

OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @OfferType
WHILE @@FETCH_STATUS = 0
BEGIN
    --print @offertype

    Set @counter = 1
    WHILE (@counter < 31 )
    begin
    Set @nextDate = convert(varchar,getdate() -30 + @counter,101)
    insert into [RP].[dbo].[Last30Days] ([Date],[OfferType])
    Select Convert(varchar,@nextDate,101), @OfferType
    Set @counter = @counter + 1
    END

    FETCH NEXT
    FROM @getid INTO @id, @OfferType
END

CLOSE @getid
DEALLOCATE @getid";

$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
if ($stmt === False) {
    echo "Faild to worked!";
} else {
   // echo "Should have worked... ";
}

sqlsrv_free_stmt($stmt);

}

?>```

A: For your consideration: lose the cursor. This can be set-based.
$sql = "INSERT INTO [RP].[dbo].[RP_UniqueOffers] (offertype)
Select distinct(offertype) from [RP].[dbo].[Offers] t2
where convert(date,[RedeemedDate]) >= convert(date,getdate()-30)
and not exists (Select distinct(offertype) from [RP].[dbo].[RP_UniqueOffers] t1 where t1.OfferType = t2.offertype )

truncate table [RP].[dbo].[RP_Last30days];

WITH ThirtyDays
AS (
   SELECT top(30)
          DATEADD(DAY,ROW_NUMBER() OVER (ORDER BY object_id)*-1,GETDATE()) as nextDate
     FROM sys.columns
)
INSERT [RP].[dbo].[Last30Days] ([Date],[OfferType])
SELECT CONVERT(char(10),ThirtyDays.nextDate,101)
     , RP_UniqueOffers.OfferType
  from [RP].[dbo].[RP_UniqueOffers]
CROSS JOIN ThirtyDays;
";

A: Credit to @SalmanA
I needed to add SET NOCOUNT ON to the top of the script as well as using sqlsrv_prepare and sqlsrv_execute in place of sqlsrv_query.


text:
Q: How to reset a form to its original state? I am working on a vb.net windows application. In this I have a windows form which has few textboxes and few controls on it. Now after loading the form I create and remove few controls in that form. I also have a reset button on the form so user can click on it an can get the original design of the form. I tried to call InitializeComponents() method. But It doesn't reflect any changes on the form. How to get my original design on button click?
Alright, I need to modify my question. I don't want to redesign my all the controls but only the treeview which I have modified.

A: The "original" state/settings of a Windows Form is not tracked anywhere. The modifications you make at runtime (adding, resizing, removing, etc. controls) all happen in real-time and become the current and only state of the form.
You could keep track of the original settings yourself and then write code to loop through all of the controls and restore them, but that would be a lot of work.
The easier solution is to just destroy the current form and replace it with a newly-created one. Of course, when a new form is created, it will have the default state, which is exactly what you want.

Edit: Calling InitializeComponents() is not a perfect solution. There's a reason it isn't called ReinitializeComponents(). It is designed to do the initial initialization when the form is first created and displayed. It was not designed to be called again elsewhere by client code. If you do so anyway, it's going to clobber things up.
If tree nodes are the only thing you're worried about preserving, why not declare a class-level member to hold the ones you delete? You can use something like a Queue or Stack collection to hold them after they are deleted, and pop them back out when you want to restore them to the TreeView.

A: Public Sub resetform(ByVal form_name as Form)
    form_name.dispose
    form_name.show
End Sub

call the resetform on your button click event
resetform(YourFormName)

A: I just worked around and its done now. I took a variable as treenode and assigned with Clone of the original treeview. Finally just add that variable to my treeview.


text:
Q: Webservice for past weather data for JAPAN I want a web-service that provide weather information for japan.
somewhere i have found this, but here i can get data only for US.
Reference i have found yet

A: You can find the web service on http://worldweatheronline.com/ but they are providing data to premium customer only and premium membership is free for 2 month after that you have to pay 5$ per month or 54$ per year.
Please let me know if u want code.


text:
Q: Restoring MySQL files to new disk 14.04 - permissions? I am rebuilding my computer with a new disk and have a backup of my MySQL db's - I have moved them to /var/lib/mysql and when I try:
sudo /etc/init.d/mysql start

MySQL refuses to start - the error log shows this error below. I am assuming my perms on /var/lib/mysql are wrong but am unsure how to proceed.
140421 12:03:59 InnoDB: Mutexes and rw_locks use GCC atomic builtins
140421 12:03:59 InnoDB: Compressed tables use zlib 1.2.8
140421 12:03:59 InnoDB: Using Linux native AIO
140421 12:03:59 InnoDB: Initializing buffer pool, size = 128.0M
140421 12:03:59 InnoDB: Completed initialization of buffer pool
140421 12:03:59  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.

Many thanks...

A: Permissions (ownership, specifically) may be an issue, in which case they can be corrected to the default by doing:
sudo chown -R mysql:mysql /var/lib/mysql

Obviously, change the username (the first mysql in that command) and the group (the second) if you've edited your user/group that MySQL runs as.
However, I'd like to note that backing up the raw files is generally discouraged when migrating. Using the mysqldump command is generally preferred, as it outputs to a text file using SQL which can be imported and executed cleanly by the new version.
Between 12.04 and 14.04, you probably won't see too many issues, but more dramatic changes can sometimes be a problem. For instance, in some past upgrades, the way that usernames were hashed changed dramatically, and using older raw files required a special config option that could not be resolved without using special tools or commands.


text:
Q: Python debugger for bazel targets in Pycharm I am studying a repository and for that I am running bazel targets that require command line arguments. I want to debug the code in Pycharm, using the Pycharm debugger(I don't want to use pdb). The repository is structured in a way that when I run the code using the Pycharm debugger, I get import errors, and I can only run it as a bazel target from terminal using bazel run <path to file> -- arguments.
I want to run it in such a way that I can load all the variables similar to the image - Pycharm console image


text:
Q: animate() for view is not working correctly I wanted to create an effect like this :
Image
The bottom left circle is going to be moved to the circle at top right.
I tried to implement it by :
1 - Getting the coordinates of the top right circle by :
(I tried these two)
The first method :
relativeLayout_1_x = (int)relativeLayout_1_2.getX() ;
    relativeLayout_1_y = (int)relativeLayout_1_2.getY();
    relativeLayout_2_x = (int)relativeLayout_2_2.getX();
    relativeLayout_2_y = (int)relativeLayout_2_2.getY();

The second method :
    int[] _pos_a = new int[2];
    int[] _pos_b = new int[2];

    relativeLayout_1_2.getLocationInWindow(_pos_a);
    relativeLayout_2_2.getLocationInWindow(_pos_b);

    relativeLayout_1_x = _pos_a[0];
    relativeLayout_1_y =  _pos_a[1];

    relativeLayout_2_x =  _pos_b[0];
    relativeLayout_2_y =  _pos_b[1];

2 - Animating the relativeLayout to move to the position by :
button_1.animate()
        .translationX((float)relativeLayout_1_x)
        .translationY((float)relativeLayout_1_y);

But instead of moving to the position , The view goes down :
Image
Instead of using "translationX I tried using ".x" but to no avail.
I don't know what's my error. All the four circles are in a RelativeLayout which is in a LinearLayout.

A: For the first I suppose you animate View to incorrect value.
change it to
button_1.animate()
        .translationX((float)relativeLayout_2_x)
        .translationY((float)relativeLayout_2_y);


text:
Q: I would like to do a While loop using HTML and JavaScript however with my current code the loop is not ending Currently the loop is running constantly. It seems my else function is not being read properly. Could someone please send some assistance.
Also when I run it on Google Chrome, the first thing to pop up is a "Hello Null" box meaning that the window.alert function is running automatically.

    <title>JavaScript Example</title>

Javascript Test Page

A: It looks to me like you are trying to prompt until the user identifies themselves as "end".
If that's the case, you probably want a do...while around the prompt.
let name;
do {
    name = window.prompt....;
} while (name !== 'end');

Note that you are mixing 2 goals without a well defined usecase. If you want to tell them to go away mate should you be using a while loop? A while loop sounds like you want to keep asking the question. The if...else makes it seem like you want to validate their entry and reject if it's not "end". If your actual goal is to ask the user twice then keep a count and use the count as a condition in your while loop. while (name !== 'end' && count < 3). You can can tell the user to "buzz off" after your while loop is complete AND there's name is still not end
Your other question, it makes sense that it shows your prompt as soon as the page loads because you are binding it to onLoad event. Shouldn't it?

A: Watching at louis answer; I have similar questions and added the code below as an example implementation. please try it and use the console browser to check if there aren't any errors next time. Before adding the code online.

*

*also pay attention to indents, and be consistent with them below is an example.

*use variables which are readable, another developer might not know what ino means.

    <title>JavaScript Example</title>

  <button onclick="start()">start</button>

Javascript Test Page


text:
Q: What exactly does the type lambda do when used with defaultdict I remember this example
from collections import defaultdict
d_int = defaultdict(int, a=10, b=12, c=13)
d_int.default_factory = lambda: 1
d_int['d']
1

When we pass an unknown key it returns the default value instead of error,I understand this.
But in this SO question,populating a nested dictionary thing get more complicated.
final = collections.defaultdict(lambda: collections.defaultdict(list))

What does lambda type do in this case?

A: This kind of default dictionary would be useful for 2 levels of data. Something like this:
{ k11 : { k21 : [...], k22 : [...] }, k12 : { ... } }

Here, each dictionary is defaultdict.
The lambda returns a defaultdict for the second level, when the first level key does not exist:
In [234]: final['k11'] # first level access
Out[234]: defaultdict(list, {})

In [235]: final['k11']['k21']  # second level access
Out[235]: []

A: defaultdict needs a function (the factory).
In the second case, you need to create a collections.defaultdict(list). For that you need a function, and it's simpler to define this function inline with a lambda that generates a new collections.defaultdict(list) object.


text:
Q: IEEE Floating Point Sign? Heyy, I am working on an assignment which requires me to convert floating point numbers to binary representation using IEEE Float Representation. I am able to convert floating point from decimal system to binary but on one part I have to convert 0.001111111 (Base 2) into IEEE Floating Representation.
I first normalized the number and got the exponential part as well as the mantissa part but I cannot determine the bit for the sign of the number as the actual float number is not given. Is there a way to determine whether the number is a negative or a positive from the given information?
Thank you in advance.


text:
Q: NO matches found on a lookup field I've a weird issue where am creating a parent opportunity record and from the same record I've a custom button where am creating a child record by populating some of the values but the issue here is on the child record there is a field called parent oppty where it is populating the value but throwing an error 'no matches found' even though value is populated. when I searched in google I found that it might due to special characters. Please help how to solve this issue. Below is the code
/006/e?recordtypeselect.jsp?ent=Opportunity
&save_new_url=%2F006%2Fe%3F
&retURL=/{!Opportunity.Id}
&CF00NU00000053wwx={!Opportunity.Name}
&opp3=Child Opp - {!Opportunity.Name}
&opp4_lkid={!Account.Id}
&opp7=0
&opp11={!Opportunity.StageName}
&opp9={!Opportunity.CloseDate}
&RecordType={!Opportunity.RecordTypeId}

A: The general pattern of how you populate a lookup field via a URL hack looks like this:
/<keyprefix>/e?CF<lookup_field_id>_lkid={!Opportunity.Id}
&CF<lookup_field_id>={!Opportunity.Name}

Note that you obtain the field Id of the Lookup Field and then add two entries to your URL hack: one with CF + the lookup field id set to the Name of the linked record, and one with CF + the lookup field id + _lkid set to the Id of the target record. You're not populating the Id of the target record here.


text:
Q: Autopopulate company name in lead conversion page in lightning We have a client where they use lightning. When they click convert, the company name from the lead does not autopopulate on the conversion page. They have to retype the company name and search for companies or add a new company which is annoying. Is there a hack to override the current lead conversion page to autopopulate the company name on the lightning conversion page?
Buyan

A: There is no way to override this as of now. One solution is to skip the standard lead conversion screen and use a custom visualforce page or component for this.


text:
Q: Check playa count in expression engine I am using playa in expression engine. My structure is an h1 heading, then loop through the playa results. However, before I have the h1, I want to check if playa has any results. If yes, then display heading and results. If no, don't display heading.
How can I check the count of playa results before I use them?

Related Products

    {exp:playa:children field="related_products"}

{title}

    {/exp:playa:children}

A: Indeed!
{if "{exp:playa:total_children field='related_products'}"}
    ...
{/if}

(As per the docs.)
Also - please consider posting future questions on the dedicated ExpressionEngine StackExchange site. That is where the action is.


text:
Q: backbone.js - map standard url parameters - use multiple parameters I'm quite new to backbone.js and trying to convert a normal javascript/jquery application into backbone MVC. With it I came of Backbone.Router and I'm currently trying to solve my old URL handling with backbone, but there some problems I'd like to discuss with you:
My traditional URL pattern looks like this:
/#/lang=1&page=panorama&cats=13,3,4,6,7,8,9,10,11&pid=4

How could this look like with backbone and how to code it?
The thing is, that my traditional handling allowed me to evaluate my URL string with not caring about the order of the parameters. With backbone this seems not to be possible. For my application its like necessary to pass categories (see cats=..) and so on in the url, to link to a specific app position/state.
I already tried it with the pid (panorama-id), so the patters is like:
/panorama/:id

"panorama" is currently no parameter, but stand for a certain page in the application.
I would be really thankful if someone has got a solution for me.

A: Best solution: https://github.com/jhudson8/backbone-query-parameters


text:
Q: How to assign date to shell variable? Given a parameter $1, I want to subtract 5 minutes from that time, and echo it (later reuse the variable).
echo $1
time5=date -d "$1 5 minutes ago" +'%H:%M'
echo ${time5}

Call with: ./script.sh 16:55
Result:

prints  16:50
./script.sh: line 2: -d: command not found

Why can't I assign the date to the variable time5?

A: You can use the $() operator for this:
echo "$1"
time5=$(date -d "$1 5 minutes ago" +'%H:%M')
echo "$time5"


text:
Q: Bluej - JButton Image Loading Every time I am trying to load an image file to give an icon to my JButton, Java shows a null pointer exception.  I have Checked the directories The image is present.
Can you please help me out?
Here is my code.
jButton1.setIcon(new ImageIcon(getClass().getResource("/Users/Stallion/Yo/Key-50.png " )));

A: I was having the same problem I fixed created a new package and put the images inside because when u export .jar the images come in the program

Then i wrote
    JButton buttonNew =
           new JButton(new ImageIcon(this.getClass().getResource("/res/new_con.gif")));

and it worked perfectly.


text:
Q: Counting Fields in Relation to their Column I am trying to find the correct SQL to perform my task. I am trying to find the count of all actors that all act in the same movie. For all the movies. My SQL statement to fetch the film title and the first and last name of each actor is.
SELECT title, actor.first_name, actor.last_name,
FROM film
INNER JOIN film_actor ON film.film_id = film_actor.film_id
INNER JOIN actor ON film_actor.actor_id = actor.actor_id
ORDER BY film.title

My database returns this :

As you can see there are 10 actors belonging to the movie title ACADEMY DINOSAUR. What is the SQL that would provide me with a number of actors for each film?

A: Your SQL can be like this
SELECT title, count(1) COUNT
FROM film
INNER JOIN film_actor ON film.film_id = film_actor.film_id
INNER JOIN actor ON film_actor.actor_id = actor.actor_id
GROUP BY title

A: Pls try this
select tt.title, count(1) from (
SELECT title, actor.first_name, actor.last_name,
     FROM film
INNER JOIN film_actor ON film.film_id = film_actor.film_id
INNER JOIN actor ON film_actor.actor_id = actor.actor_id
) tt group by tt.title
ORDER BY tt.title


text:
Q: how this regular expression expand and works? I want to know how this regular expression is expand and how it validates proper E-mail address ?
"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)↪*(\.[a-z]{2,3})$"

A: Actually, to validate a proper email address you need to use something like this:
(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)

Source: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
This handles most of the complexities of the RFC. I recommend however checking into filter_var instead:
filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);

Easier to read and understand.
EDIT
I got curious. filter_var does email validation by regex in the backend as well. Here's the function that handles it, which can be found in ext/filters/logical_filter.c in the PHP source:
void php_filter_validate_email(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */
{
    /*
     * The regex below is based on a regex by Michael Rushton.
     * However, it is not identical.  I changed it to only consider routeable
     * addresses as valid.  Michael's regex considers a@b a valid address
     * which conflicts with section 2.3.5 of RFC 5321 which states that:
     *
     *   Only resolvable, fully-qualified domain names (FQDNs) are permitted
     *   when domain names are used in SMTP.  In other words, names that can
     *   be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed
     *   in Section 5) are permitted, as are CNAME RRs whose targets can be
     *   resolved, in turn, to MX or address RRs.  Local nicknames or
     *   unqualified names MUST NOT be used.
     *
     * This regex does not handle comments and folding whitespace.  While
     * this is technically valid in an email address, these parts aren't
     * actually part of the address itself.
     *
     * Michael's regex carries this copyright:
     *
     * Copyright © Michael Rushton 2009-10
     * http://squiloople.com/
     * Feel free to use and redistribute this code. But please keep this copyright notice.
     *
     */
    const char regexp[] = "/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD";

    pcre       *re = NULL;
    pcre_extra *pcre_extra = NULL;
    int preg_options = 0;
    int         ovector[150]; /* Needs to be a multiple of 3 */
    int         matches;

    /* The maximum length of an e-mail address is 320 octets, per RFC 2821. */
    if (Z_STRLEN_P(value) > 320) {
        RETURN_VALIDATION_FAILED
    }

    re = pcre_get_compiled_regex((char *)regexp, &pcre_extra, &preg_options TSRMLS_CC);
    if (!re) {
        RETURN_VALIDATION_FAILED
    }
    matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3);

    /* 0 means that the vector is too small to hold all the captured substring offsets */
    if (matches < 0) {
        RETURN_VALIDATION_FAILED
    }

}

A: You can use http://xenon.stanford.edu/~xusch/regexp/analyzer.html to have it explained to you. Some more tools are listed under Is there an online RegexBuddy-like regular expression analyzer? and https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world
Let me also just mention that your regex is insufficient. It fails on many valid addresses. See also http://www.regular-expressions.info/email.html

A: > I want to understand how that regular expression works not this @Viswanathan Iyer

^[_a-z0-9-]+ - address should be started with at least one letter or digit symbol
(.[_a-z0-9-]+)* - then address could contain some letters, digits, dots, '_' or '-'
@ - no comment
[a-z0-9-]+ - the part after @ should be started with at least one letter, digit symbol or '-' (why?)
(.[a-z0-9-]+)* - then address could contain some letters, digits, dots, '_' or '-'
(.[a-z]{2,3})$ - in the end of the string - dot before domain zone, than 2- or 3-letters domain (for example .net, .eu)
Note, that this pattern is incorrect: it doesn't allow uppercase, doesn't support new zones (such as .mobi) and non-latin encoding.

A: What is a valid email address? It's usually name@FQDN
Whereby FQDN is "fully qualified domain name"
A FQDN must consist of one hostname and one top-level domain.
It CAN have one or more optional subdomains.
^ start of match (see below)
[_a-z0-9-]+ the very first character of a valid email account name (required, hence the + qualifier 1..n)
(\.[_a-z0-9-]+)* optional characters for a valid email account name (hence the * quantifier 0..n)
@ @-literal (delimiting account name from FQDN)
[a-z0-9-]+ character set for domain names (second-level domains / subdomain)
(\.[a-z0-9-]+)* character set for domain names (second-level domains / subdomain)
(\.[a-z]{2,3}) character set for top level domains (.com, .net, etc. - won't be useful for the 'new' TLDs like .info, .business, .museum and so on
$ end of match
That ^ . . . $ is often used to declare that the whole string must consist of the pattern (and not just include it somewhere).

A: Note that if you're trying to match e-mail addresses with this, the regex is completely outdated (and has been outdated for ten years), Bad and Wrong. In other words, this is completely unsuitable for validating e-mail addresses, as it will incorrectly reject many valid addresses. See this and this for further discussion.
Here is what it does:
^ beginning of string
[_a-z0-9-]+ 1 or more characters from _abcdefghijklmnopqrstuvwxyz0123456789-
(\.[_a-z0-9-]+)* 0 or more times:

\. literal dot
[_a-z0-9-]+ same as line 2

@ literal @
[a-z0-9-]+ 1 or more characters from abcdefghijklmnopqrstuvwxyz0123456789-
(\.[_a-z0-9-]+) exactly one time - same as line 3
↪* literal ↪, zero or more times
(\.[a-z]{2,3}) exactly one time:

\. literal dot
[a-z]{2,3} 2 or 3 characters from abcdefghijklmnopqrstuvwxyz

$: end of string


text:
Q: Why do interpreted/scripting languages rarely have multi-line comments? Of the interpreted languages I know (Python, Perl, R, bash), multi-line comments seem to usually involve some misuse of another feature of the language (e.g. multiline strings).
Is there something inherent to the type of parsing which interpreters do that makes multiline comments hard? It doesn't seem like it should be significantly different from, say, multiline strings.

A: In truth, I'm sure there is no significance when it comes to implementing any form of multi-line comments (based on the methods that most parsers utilize to read/execute the script). In my personal opinion, scripts need multi-line comments the most because of distribution and explanation (most high level languages are usually compiled and only a percentage of it is open sourced anyways). I do know that Lua, a scripting language, does provide multi-line comments:
--[==[
COMMENT
]==]--

I'm sure it's just a fluke that many languages don't support this. It is commonly acceptable to just use single line comments to create a multi-line comment.
//*****************************************\\
//**                                     **\\
//**            JOHN SMITH               **\\
//**        COPYRIGHT 2008-2011          **\\
//**                                     **\\
//*****************************************\\

Lots of people will also utilize single line comments to create a cool image (ASCII ART) using the comment character to start off the image (kind of what is displayed above, where // is the commenting character(s)/phrase).

A: No, there's no reason for scripting languages to not support multiline comments. JavaScript, Groovy, Lua, PHP, REXX, Smalltalk, and Dart all support multiline comments.

A: In Python we simply use a multiline string as a comment.
Why have two kinds of syntax when one will do?

A: Not all interpreted languages lack multi-line comments. Ruby, for example, has them.
I suspect this is largely the preference of the language designer. Some just don't see multi-line comments as a necessary feature. (Many code editors these days offer shortcuts that comment/uncomment large blocks of code using single-line comments.)
Also, multi-line comments add complexity to a parser. It has to deal with the possibility of nested comments, for example. Why add complexity if you don't have to?

A: I suspect it's just a bit of language bias. C style multiline comments tend to show up in c-esque languages, but most other langs don't have an equivalent.
As for the parsers themselves. There's no reason I can think of that parsers don't implement multi line comments, other than that the lang designer just didn't want to. Most parser generators can easily handle the construct.

A: There are two wrong assumptions in your question.
The first wrong assumption is that "interpreted/scripting languages rarely have multi-line comments". You're suffering from confirmation bias. There are compiled languages with single-line comments (e.g. Fortran, many Lisp dialects) and interpreted languages with multi-line comments (e.g. Perl, Python).
The second wrong assumption is that "misuse of another feature" is involved. Languages are better designed as a whole, there's no need to introduce an extra feature for multiline comments if some feature that exists anyway will do the trick. For example, in Python, multiline strings exist, and an instruction consisting only of a string is a no-op, so multiline strings make fine comments. In Perl, one way to have multiline comments is through Pod, a documentation format; comments are a kind of documentation, so it's quite natural to use =pod … =cut for multiline comments (multiline strings, through here documents <<'EOF'; … EOF, are another method).


text:
Q: How can i match decimal value with comma and parenthesis in regex? I want to match decimal place and comma using  regular expression .
Below is my input :
  Tst:      (2344.45)
    Tst:      53.00
    Tst:     2777,46.00

o/p should be
    Tst: (2344.45)
    Tst: 53.00
    Tst: 2777,46.00

I need to remove the spaces after Tst.
To match comma and decimal place I have used below regex .
(?:\d+)((\d)*([\,\ ]\d)*)(\.\d+)?

Edit :
Updated regex to match brackets and comma .
\(*(?:\d+)((\d)*([\,\ ]\d)*)(\.\d+)?\)*

Any clue on this would be  helpful .I want to achieve this in java

A: You could use 2 capturing groups, first matching word characters followed by a colon in the first and the number part in the second group.
Match 1 or more horizontal whitespace chars between them, and replace those with a single space.
Pattern
(\w+:)\h+((?:\(\d+(?:,\d+)*(?:\.\d+)?\)|\d+(?:,\d+)*(?:\.\d+)?))

Explanation

*

*(\w+:) Capture group 1, Match 1+ word chars and :

*\h+ Match 1+ horizontal whitespace chars

*( Capture group 2

*

*(?: Non capture group

*\(\d+(?:,\d+)*(?:\.\d+)?\) Match the number part with ( and )

*| Or

*\d+(?:,\d+)*(?:\.\d+)?) Match the number part without parenthesis

*) Close non capture group group

Regex demo | Java demo
Replace with
$1 $2

Example code
String regex = "(\\w+:)\\h+((?:\\(\\d+(?:,\\d+)*(?:\\.\\d+)?\\)|\\d+(?:,\\d+)*(?:\\.\\d+)?))";
String string = "Tst:      (2344.45)\n"
     + "Tst:      53.00\n"
     + "Tst:     2777,46.00";
String subst = "$1 $2";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
System.out.printlnmatcher.replaceAll(subst);

Output
Tst: (2344.45)
Tst: 53.00
Tst: 2777,46.00

If you want to match multiple : you could use a quantifier (Note to double escape the backslashes in Java)
(\w+:+)\h+((?:\(\d+(?:,\d+)*(?:\.\d+)?\)|\d+(?:,\d+)*(?:\.\d+)?))

Regex demo

A: Try with this regex:  \s*(\w+):\s*(\(?)(\d[\d,]*(\.[\d]+)?)(\)?)
If you ignore text then try with this only: (\(?)(\d[\d,]*(\.[\d]+)?)(\)?)
Demo here
Java code here:
Pattern p = Pattern.compile("\\s*(\\S+)\\s*(\\(?)(\\d[\\d,]*(\\.[\\d]+)?)(\\)?)");
        List<String> inputs = Arrays.asList(
                "Tst:      (2344.45)",
                "        Tst:      53.00",
                "Tst:     2777,46.00",
                "Tst: 245"
        );
        inputs.forEach(in->{
            Matcher m = p.matcher(in);
            if (m.matches()) {
                System.out.println(m.group(1)+" "+m.group(2)+m.group(3)+m.group(5));
            }
        });

A: Try the following regExp:
[\\d+,?\\d+]*[\\.\\d+]?

Now if you just want the number, this regexp will work. If however, you want to extract both text as well as the number, you can use group operator in Java:
(\\w+:)\\s+([\\d+,?\\d+]*[\\.\\d+]?)

Now you can get the String value using in group(1) and the number with decimal and comma using group(2)


text:
Q: Umbraco - Add more than one RTE in Custom Grid Editor I am creating custom grid editor and I would like to have more than one RTE inside of it. Currently, I am initializing RTE like this

This works fine for one instance of RTE. However, when I try to add 2nd or 3rd RTE in this manner, they are not initialized, instead I am getting multiline textbox.
So, how to add more than one RTE, and, is this best way to add RTE?

A: I had the same problem. I have solved the problem by adding $index. Like so:

A:

The previous answer works when the control is inside the ng-repeat directive, ie

Otherwise yes, manually modifying the unique-id would be the answer for a known amount of multiple amount of Rich Text Editors in the editor


text:
Q: Why are items with unique permissions being affected when I delete Users/Groups in the list permission I'm new to SharePoint and csom. I'm trying to figure out how to change existing group/user permissions in the list without inadvertently changing the item permission inside that said list. Here's the code:
myList.BreakRoleInheritance(true, true);

var roletypes = ctx.Web.RoleDefinitions.GetByType(RoleType.Reader);
ctx.ExecuteQuery();
RoleDefinitionBindingCollection colRoleDefinitionBinding = new RoleDefinitionBindingCollection(ctx);
colRoleDefinitionBinding.Add(roletypes);

// if user, add him with read access
if (!item.ContainsKey("group"))
{
     Principal entity = ctx.Web.EnsureUser(item["user"]);
     myList.RoleAssignments.GetByPrincipal(entity).DeleteObject();
     myList.RoleAssignments.Add(entity, colRoleDefinitionBinding);
}
else
{
     Group entity = ctx.Web.SiteGroups.GetById(Int32.Parse(item["group"]));
     myList.RoleAssignments.GetByPrincipal(entity).DeleteObject();
     myList.RoleAssignments.Add(entity, colRoleDefinitionBinding);
}

ctx.ExecuteQuery();

I'm essentially just removing the user or group and adding them again with their new permissions. When deleting the user/group, if that user or group exist in the item permission then it is also removed. What I dont understand is why the item permission is being tampered when it has unique permissions? Is there another way to change the list permissions without affecting the item permission?

A: Figured it out. Just use ImportRoleDefinitionBindings to change the permission:
Principal entity = ctx.Web.EnsureUser(item["user"]);
roleAssignment = myList.RoleAssignments.GetByPrincipal(entity);
roleAssignment.ImportRoleDefinitionBindings(colRoleDefinitionBinding);
roleAssignment.Update();
ctx.ExecuteQuery();


text:
Q: How to slice a generator object or iterator? I would like to loop over a "slice" of an iterator. I'm not sure if this is possible as I understand that it is not possible to slice an iterator. What I would like to do is this:
def f():
    for i in range(100):
        yield(i)
x = f()

for i in x[95:]:
    print(i)

This of course fails with:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-15f166d16ed2> in <module>()
  4 x = f()
  5
----> 6 for i in x[95:]:
  7     print(i)

TypeError: 'generator' object is not subscriptable

Is there a pythonic way to loop through a "slice" of a generator?
Basically the generator I'm actually concerned with reads a very large file and performs some operations on it line by line. I would like to test slices of the file to make sure that things are performing as expected, but it is very time consuming to let it run over the entire file.
Edit:
As mentioned I need to to this on a file. I was hoping that there was a way of specifying this explicitly with the generator for instance:
import skbio

f = 'seqs.fna'
seqs = skbio.io.read(f, format='fasta')

seqs is a generator object
for seq in itertools.islice(seqs, 30516420, 30516432):
    #do a bunch of stuff here
    pass

The above code does what I need, however is still very slow as the generator still loops through the all of the lines. I was hoping to only loop over the specified slice

A: islice is the pythonic way
from itertools import islice

g = (i for i in range(100))

for num in islice(g, 95, None):
    print num

A: You can't slice a generator object or iterator using  a normal slice operations.
Instead you need to use  itertools.islice as @jonrsharpe already mentioned in his comment.
import itertools

for i in itertools.islice(x, 95)
    print(i)

Also  note that islice returns an iterator and consume data on the iterator or generator. So you will need to convert you data to list or create a new generator object if you need to go back and do something or use the little known itertools.tee to create a copy of your generator.
from itertools import tee

first, second = tee(f())

A: In general, the answer is itertools.islice, but you should note that islice doesn't, and can't, actually skip values. It just grabs and throws away start values before it starts yield-ing values. So it's usually best to avoid islice if possible when you need to skip a lot of values and/or the values being skipped are expensive to acquire/compute. If you can find a way to not generate the values in the first place, do so. In your (obviously contrived) example, you'd just adjust the start index for the range object.
In the specific cases of trying to run on a file object, pulling a huge number of lines (particularly reading from a slow medium) may not be ideal. Assuming you don't need specific lines, one trick you can use to avoid actually reading huge blocks of the file, while still testing some distance in to the file, is the seek to a guessed offset, read out to the end of the line (to discard the partial line you probably seeked to the middle of), then islice off however many lines you want from that point. For example:
import itertools

with open('myhugefile') as f:
    # Assuming roughly 80 characters per line, this seeks to somewhere roughly
    # around the 100,000th line without reading in the data preceding it
    f.seek(80 * 100000)
    next(f)  # Throw away the partial line you probably landed in the middle of
    for line in itertools.islice(f, 100):  # Process 100 lines
        # Do stuff with each line

For the specific case of files, you might also want to look at mmap which can be used in similar ways (and is unusually useful if you're processing blocks of data rather than lines of text, possibly randomly jumping around as you go).
Update: From your updated question, you'll need to look at your API docs and/or data format to figure out exactly how to skip around properly. It looks like skbio offers some features for skipping using seq_num, but that's still going to read if not process most of the file. If the data was written out with equal sequence lengths, I'd look at the docs on Alignment; aligned data may be loadable without processing the preceding data at all, by e.g by using Alignment.subalignment to create new Alignments that skip the rest of the data for you.

A: let's clarify something first.
Spouse you want to extract the first  values from your generator, based on the number of arguments you specified to the left of the expression. Starting from this moment, we have a problem, because in Python there are two alternatives to unpack something.
Let's discuss these alternatives using the following example. Imagine you have the following list l = [1, 2, 3]
1) The first alternative is to NOT use the "start" expression
a, b, c = l # a=1, b=2, c=3

This works great if the number of arguments at the left of the expression (in this case,  3 arguments) is equal to the number of elements in the list.
But, if you try something like this
a, b = l # ValueError: too many values to unpack (expected 2)

This is because the list contains more arguments than those specified to the left of the expression
2) The second alternative is to use the "start" expression; this solve the previous error
a, b, c* = l #  a=1, b=2, c=[3]

The "start" argument act like a buffer list.
The buffer can have three possible values:
    a, b, *c = [1, 2] # a=1, b=2, c=[]
    a, b, *c = [1, 2, 3] # a=1, b=2, c=[3]
    a, b, *c = [1, 2, 3, 4, 5] # a=1, b=2, c=[3,4,5]

Note that the list must contain at least 2 values (in the above example). If not, an error will be raised
Now, jump to your problem. If you try something like this:
a, b, c = generator

This will work only if the generator contains only three values (the number of the generator values must be the same as the number of left arguments). Elese, an error will be raise.
If you try something like this:
a, b, *c = generator

*

*If the number of values in the generator is lower than 2; an error will be raise because variables "a", "b" must have a value

*If the number of values in the generator is 3; then a=, b=(val_2>, c=[]

*If the numeber of values in the generator is greater than 3; then a=, b=(val_2>, c=[, ... ]
In this case, if the generator is infinite; the program will be blocked trying to consume the generator

What I propose for you is the following solution
# Create a dummy generator for this example
def my_generator():
i = 0
while i < 2:
    yield i
    i += 1

# Our Generator Unpacker
class GeneratorUnpacker:
    def __init__(self, generator):
        self.generator = generator

    def __iter__(self):
        return self

    def __next__(self):
        try:
            return next(self.generator)
        except StopIteration:
            return None # When the generator ends; we will return None as value

if __name__ == '__main__':
    dummy_generator = my_generator()
    g =  GeneratorUnpacker(dummy_generator )
    a, b, c = next(g), next(g), next(g)


text:
Q: Postgres connection problem in docker-compose up in Django project My Django project works fine with python manage.py runserver with no problem. Postgres, redis, django, djangorestframework all fine together.
I try to Dockerize the project, but I get the following error for Postgres:
....
web_1    |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
web_1    | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1    |      Is the server running on host "127.0.0.1" and accepting
web_1    |      TCP/IP connections on port 5432?

Here's my docker-compose.
version: '3'

services:
  db:
    image: postgres # use latest official postgres version
    env_file:
      - database.env # configure postgres
    volumes:
      - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down
  redis:
    image: bitnami/redis:latest
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

volumes:
  database-data:

Note: I also tried an alternative postgres repo:
https://github.com/sameersbn/docker-postgresql

A: OK, I solved the problem, it was about the settings:
In my settings.py, HOST value was 127.0.0.1, I changed it to 'db', this solved everything....
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'bigdata',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}


text:
Q: How to get Huawei phones Y530 and Y300 to connect via USB on Windows? We have Huawei Y530 and Y300 smartphones.
When we connect either of these with the USB cable to either Windows 7 or Windows 8.1, the operating systems say "USB Device Not Recognized".
No USB driver came with the phones when we bought them.
On the Huawei website for these phones there is no USB driver to download, e.g. on the Y530 page it says "Sorry, no results were found":
http://consumer.huawei.com/en/mobile-phones/support/downloads/ascendy530.htm
On the Huawei website under popular downloads, I found:
"Huawei Android Phones USB Driver"
http://consumer.huawei.com/en/support/downloads/detail/index.htm?id=11802
which is a zip file which contains DriverSetup.exe.
I executed this and it installs the driver software, allows me to install them:

And then reports that they were installed:

However, after installing this on both Windows 7 and Windows 8.1 on two different computers, even after rebooting both machines, the Huawei Smartphones still are not recognized via USB cable, the operating systems still say: "USB Device Not Recognized".
What else can I do to get Windows to recognize these Huawei smartphones via USB?

A: I have Huawei Ascend Y300 and had lot of trouble getting it in developer mode for Android app dev. However, once I installed drivers from Huawei on my Windows 8.1 laptop it started showing up on ADB:
Here are some additional tips that might help:

*

*Before turning Developer Settings ON, turn FASTBOOT off on your Android phone.

*Also, restart the phone.

*With Developer Settings On, Stay Awake checked connect the phone to your PC.

Needless to say, have Device Manager running and Android Studio running, to see how your device shows up.

A: Plug in the Hauwei Android phone to the USB port on your computer.
Pull down notifications on the phone. One of the selections should be 'USB Connection Type'. Short press it and you will get three options. Choose the 'USB Connection' option. You should then be able to use the phone's storage as both read and write enabled.

A: What I found you have to use USB cable coming with the box, the drivers have been preinstall in the phone. I tried other USB cable it did not work. OK, good luck.

A: I tried everything to get the usb connection to be recognised by windows 7.
I had sort of given up and then I connected the phone to the computer using the usb connection for a Logitech harmony 600 controller and, unbelievably, everything suddenly worked. I have no idea why but that is what happened!

A: I had trouble getting access to the drive once connected via USB to my PC using my Y6II.
Once you plug the lead in, it kept saying charging only. After I plugged the USB lead in, I swiped down from the very top of the screen and it then gave me options to either charge only or to access photos or files.
Once I selected the files box, Windows 7 installed some more drivers and finally the standalone drive window appeared and I was able to gain access to the internal memory of the phone.
Unfortunately it would appear that you have to swipe down from the top of the screen every time you plug in your phone to access the drive.
I hope this helps anyone else puzzled with the charging only message.

A: Use USB cable to connect phone to PC.
From options displayed - Install 'Huawei Hi Suite' on your PC.
On Phone, Flick down from top of screen. Select (tick) 'Connect to PC Software' also select (tick) 'USB Debugging '.
'Hi Suite' should now kick in and complete the connection.
Good luck. Worked for me in UK !

A: Until a couple of minutes ago, I had the same problem with my Y360-U03.
The usb connection setting in Notifications was set to "USB Storage - XP recommended", didn't work in W10, nor in XP running in VirtualBox.
Tried connecting as "Media Device", this showed the phone system files, but not my pics. Then connected as "Camera" - all good. Another slight wrinkle was that it would appear in Explorer, but not in FreeCommander XE.

A: On my Y300, I had to change the default storage setting from internal storage to SD storage so it then gave the option to have Camera, and USB Mass storage settings and boom the PC  can see it now.

A: You must turn on the phone as normal, then simply connect the usb cable to an empty USB port.  The SD card and internal memories should both appear as separate drives (eg I: and H:) on explorer with their respective folders.  I have a Y300 and Windows 8.


text:
Q: Huffman compression doesn't result in less bytes saving storing tree and pad with coded 0's and 1's I'm working on implementing a lossless compression algorithm called Huffman Coding in Swift. I started with a version that used Strings of "1"'s and "0"'s but then learned that a single string for example "0" takes a whole byte itself. So I've now converted my string into [UInt8] (see packBits func). It seems some people approach it with writing a BitWriter and BitReader which I could eventually refactor to, but I think my approach at least gets the same [UInt8] results in the end and this definitely cuts down on the size of HuffData.code vs text bytes, however I need to store the tree to traverse as well as a pad for decoding. Since encode func returns HuffData, a struct that contains all three, I noticed that the size is actually larger than text I pass to encode.
For example a paragraph.utf8.count that equals 8959 bytes, encodes to a total data of about 21099 bytes! 2763 of this is the tree, 5050 is the code and 2 is the pad. The remaining I assume is from the struct? Why don't these add up?
let huff = try? Huffman.encode(paragraph)

huff.count = total data bytes
I'm looking to understand why these byte counts don't add up and what in my code is causing the total to be significantly larger than the text. Do just I need to work with much larger text to see a real result? Can I store tree, code and pad in a more memory efficient way? Why does the total not equal tree + code + pad? Does serializing the data add more bytes? Thanks for the advice!
import Foundation

struct HuffData: Codable {
    var code: [UInt8]
    var tree: Node
    var pad: Int
}

class Huffman {
    static func decode(_ data: Data) throws -> String {
        let huff = try JSONDecoder().decode(HuffData.self, from: data)
        var bits: String = ""
        // return bits to a string O and 1
        for i in huff.code {
            var str = String(i, radix: 2)
            // if bits originally started with zeros, that was removed e.g. 32
            if str.count < 8 {
                str = String(repeating: "0", count: 8 - str.count) + str
            }
            bits += str
        }
        return Huffman.traverse(tree: huff.tree, with: String(bits.dropLast(huff.pad)))
    }

    static func encode(_ input: String) throws -> Data {
        // count letter frequency
        let sortedFrequency = input.reduce(into: [String: Int](), { freq, char in
            freq[String(char), default: 0] += 1
        })
        // create queue of initial Nodes
        let queue = sortedFrequency.map{ Node(name: $0.key, value: $0.value)}
        // create tree
        let tree = Huffman.createTree(with: queue)
        // generate key by traversing tree
        let key = Huffman.generateKey(for: tree, prefix: "")
        // bit packed code
        let code = input.compactMap({key[String($0)]}).joined()
        let buffer = Huffman.packBits(for: code)
        // save data
        let huff = HuffData(code: buffer.code, tree: tree, pad: buffer.pad)
        let data = try JSONEncoder().encode(huff)
        return data
    }

    static private func generateKey(for node: Node, prefix: String) -> [String: String] {
        var key = [String: String]()
        if let left = node.left, let right = node.right {
            key.merge(generateKey(for: left, prefix: prefix + "0"), uniquingKeysWith: {current,_ in current})
            key.merge(generateKey(for: right, prefix: prefix + "1"), uniquingKeysWith: {current,_ in current})
        }else {
            key[node.name] = prefix
        }
        return key
    }

    static private func createTree(with queue: [Node]) -> Node {
        // initialize queue that sorts by decreasing count
        var queue = PriorityQueue(queue: queue)
        // until we have 1 root node, join subtrees of least frequency
        while queue.count > 1 {
            let node1 = queue.dequeue()
            let node2 = queue.dequeue()
            let rootNode = Huffman.createRoot(with: node1, and: node2)
            queue.enqueue(node: rootNode)
        }
        return queue.queue[0]
    }

    static private func traverse(tree: Node, with code: String) -> String {
        var result = ""
        var node = tree
        for bit in code {
            if bit == "0", let left = node.left {
                node = left
            } else if bit == "1", let right = node.right {
                node = right
            }
            if node.left == nil && node.right == nil {
                result += node.name
                node = tree
            }
        }
        return result
    }

    static private func createRoot(with first: Node, and second: Node) -> Node {
        return Node(name: "\(first.name)\(second.name)", value: first.value + second.value, left: first, right: second)
    }

    static private func packBits(for s: String) -> (pad: Int, code: [UInt8]) {
        var result = [UInt8]()
        // pad with extra "0"'s to a length that is exact multiple of 8
        let padding = 8 - (s.count % 8)
        var bits = s + String(repeating: "0", count: padding)
        // convert 8 bits at a time to a byte
        while !bits.isEmpty {
            result.append(UInt8(bits.prefix(8), radix: 2)!)
            bits = String(bits.dropFirst(8))
        }
        return (pad: padding, code: result)
    }
}

struct PriorityQueue {
    var queue: [Node]
    var count: Int {
        return queue.count
    }
    mutating func enqueue(node: Node) {
        queue.insert(node, at: queue.index(where: {$0.value <= node.value}) ?? 0)
    }
    mutating func dequeue() -> Node {
        return queue.removeLast()
    }
    init(queue: [Node]){
        // assumes queue will always be sorted by decreasing count
        self.queue = queue.sorted(by: {$0.value > $1.value})
    }
}

class Node: CustomStringConvertible, Codable {
    var description: String {
        return "\(name): \(value)"
    }
    let name: String
    let value: Int
    let left: Node?
    let right: Node?

    init(name: String, value: Int, left: Node? = nil, right: Node? = nil) {
        self.name = name
        self.value = value
        self.left = left
        self.right = right
    }
}

A: You are encoding a sequence of bits using one Uint8 = 1 byte = 8 bits per bit. So your "compression" is a factor 8 worse than needed.
First create a data structure that can store 8 bits per byte.


text:
Q: some error occured when commit My project to github I am new to the github. I tryed to commit my project. but has occured following error on My cmd.
*** Please tell me who you are.
Run
git config --global user.email "you@example.com"
  git config --global user.name "Your Name"
to set your account's default identity.
Omit --global to set the identity only in this repository.
fatal: unable to auto-detect email address (got 'Hema@Hema-PC.(none)')
how can solve this problem?

A: for this error you only have to execute the command they show
git config --global user.email "you@example.com"
git config --global user.name "Your Name"

That will set your name in the ~/.gitconfig.


text:
Q: Will TcpClient.Available throw or not? The docs at MSDN contain this sentence which is rather ambigous:

If the remote host shuts down or closes the connection, Available may
  throw a SocketException.

What does that mean? The docs are not clear.
What determines if the Available property will throw or not?

A:
What does that mean?

That you need to wrap it in a try..catch block, because it may throw an exception.
Furthermore I think the when will be an implementation detail. Decompile the System.Net assembly to see for yourself when it does throw.
I suspect it won't throw if the remote party properly shut down the socket (and that in that case 0 will be returned), but that is not something you can rely on.


text:
Q: Setspace consistency along varying font sizes Is there a way to get \setspace to work for the font size specified? In my MWE below you can see that when I use tiny the double spacing is the same as it would be for the default font. However, I want the double spacing to be tiny double spacing, not normalsize double spacing
\documentclass{article}

\usepackage{setspace}
\usepackage{blindtext}

\begin{document}
\setstretch{2}

    \blindtext[1]

    \begin{tiny}
        \blindtext[2]
    \end{tiny}

\end{document}


text:
Q: I need to remove the highlight off of the radtreeview in WPF Here is my code. I just need to take the highlight off of the radtreeview. I would just use IsHitTestVisible like I did in the others, but then it does not allow me to click on triggers to extend the nodes.
Any help would be appreciated.
 <telerik:RadTreeView x:Name="radTreeView" Margin="8" ItemsSource="{Binding Errors}" Background="Salmon" IsHitTestVisible="True" IsDropPreviewLineEnabled="False" IsDragTooltipEnabled="False" Focusable="False">
            <telerik:RadTreeView.ItemTemplate>
                 <HierarchicalDataTemplate ItemsSource="{Binding SubItems}" >
                    <Grid Background="Salmon">
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>

                        </Grid.RowDefinitions>
                        <TextBlock Text="{Binding Description}" IsHitTestVisible="False" />

                        <ListBox Grid.Row="1" ItemsSource="{Binding Messages}" Margin="20,0,0,0" BorderBrush="#00000000" BorderThickness="0" Background="Salmon" IsHitTestVisible="False" >
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding Message}"/>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </Grid>

                </HierarchicalDataTemplate>

            </telerik:RadTreeView.ItemTemplate>
        </telerik:RadTreeView>

A: Approach it from a different angle. You should try changing the following on the TreeViewItem:

*

*SystemColors.HighlightBrushKey

*SystemColors.HighlightTextBrushKey

Example:
<Style TargetType="TreeViewItem">
      <Style.Resources>
          <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FFF"/>
          <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="#000"/>
     </Style.Resources>
</Style>

This will also work on Rad controls. You just need to adjust for a RadTreeViewItem.


text:
Q: Azure Cloud Service - EventProcessor IEventProcessor.ProcessEventsAsync not getting hit I'm having an issue with a worker role where the role seems to start up successfully and register the EventProcessor class implementations (EventProcessorA and EventProcessorB) but neither of them picks up any events. By this, I mean that the method IEventProcessor.ProcessEventsAsync does not get hit at all.
Each EventProcessor class has it's own event hub set up for it.
My logs show that the constructor and the OpenAsync methods get called for the EventProcessor classes. In fact, they get called exactly 4 times as follows. But after this, there's no additional activity that takes place. I'm guessing 4 times is because there are four partitions.
SimpleEventProcessorA - Constructor
SimpleEventProcessorA - OpenAsync
SimpleEventProcessorA - Constructor
SimpleEventProcessorA - OpenAsync
SimpleEventProcessorA - Constructor
SimpleEventProcessorA - OpenAsync
SimpleEventProcessorB - Constructor
SimpleEventProcessorB - Open Async
SimpleEventProcessorB - Constructor
SimpleEventProcessorB - OpenAsync
SimpleEventProcessorB - Constructor
SimpleEventProcessorB - OpenAsync
SimpleEventProcessorB - Constructor
SimpleEventProcessorB - OpenAsync
SimpleEventProcessorA - Constructor
SimpleEventProcessorA - OpenAsync

There's no offset provided for the EventProcessorOptions in the Worker role's RunAsync method either so all the events should come flooding in.
Also, in the Azure portal I see events coming through when I kick them off.
Worker Role code that registers the EventProcessor:
public class WorkerRole : RoleEntryPoint
{
    private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
    private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);

    private EventProcessorHost eventProcessorHostA;
    private EventProcessorHost eventProcessorHostB;

    public override void Run()
    {
        Trace.TraceInformation("ReportWorkerRole is running");

        try
        {
            this.RunAsync(this.cancellationTokenSource.Token).Wait();
        }
        finally
        {
            this.runCompleteEvent.Set();
        }
    }

    public override bool OnStart()
    {
        // Set the maximum number of concurrent connections
        ServicePointManager.DefaultConnectionLimit = 12;

        // For information on handling configuration changes
        // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

        bool result = base.OnStart();

        Trace.TraceInformation("ReportWorkerRole has been started");

        //EventHub Processing
        try
        {
            string eventHubNameA = CloudConfigurationManager.GetSetting("EventHubNameA");
            string eventHubNameB = CloudConfigurationManager.GetSetting("EventHubNameB");
            string eventHubConnectionString = CloudConfigurationManager.GetSetting("EventHubConnectionString");

            string storageAccountName = CloudConfigurationManager.GetSetting("AzureStorageAccount");
            string storageAccountKey = CloudConfigurationManager.GetSetting("AzureStorageAccountKey");
            string storageConnectionString = CloudConfigurationManager.GetSetting("AzureStorageAccountConnectionString");

            string eventProcessorHostNameA = Guid.NewGuid().ToString();
            eventProcessorHostA = new EventProcessorHost(eventProcessorHostNameA, eventHubNameA, EventHubConsumerGroup.DefaultGroupName, eventHubConnectionString, storageConnectionString);

            string eventProcessorHostNameB = Guid.NewGuid().ToString();
            eventProcessorHostB = new EventProcessorHost(eventProcessorHostNameB, eventHubNameB, EventHubConsumerGroup.DefaultGroupName, eventHubConnectionString, storageConnectionString);

        }
        catch (Exception ex)
        {
            //Logging omitted
        }

        return result;
    }

    public override void OnStop()
    {
        Trace.TraceInformation("ReportWorkerRole is stopping");

        this.eventProcessorHostA.UnregisterEventProcessorAsync().Wait();
        this.eventProcessorHostB.UnregisterEventProcessorAsync().Wait();

        this.cancellationTokenSource.Cancel();
        this.runCompleteEvent.WaitOne();

        base.OnStop();

        Trace.TraceInformation("ReportWorkerRole has stopped");
    }

    private async Task RunAsync(CancellationToken cancellationToken)
    {

        var options = new EventProcessorOptions()
        {
            MaxBatchSize = 100,
            PrefetchCount = 10,
            ReceiveTimeOut = TimeSpan.FromSeconds(20),
            //InitialOffsetProvider = (partitionId) => DateTime.Now
        };

        options.ExceptionReceived += (sender, e) =>
        {
            //Logging omitted
        };

        //Tried both using await and wait
        eventProcessorHostA.RegisterEventProcessorAsync<SimpleEventProcessorA>(options).Wait();
        eventProcessorHostB.RegisterEventProcessorAsync<SimpleEventProcessorB>(options).Wait();
        //await eventProcessorHostA.RegisterEventProcessorAsync<SimpleEventProcessorA>(options);
        //await eventProcessorHostB.RegisterEventProcessorAsync<SimpleEventProcessorB>(options);

        // TODO: Replace the following with your own logic.
        while (!cancellationToken.IsCancellationRequested)
        {
            Trace.TraceInformation("Working");
            await Task.Delay(1000);
        }
    }
}

Event Processor A (same configuration as B):
class SimpleEventProcessorA : IEventProcessor
{

    Stopwatch checkpointStopWatch;

    //Non-relevant variables omitted

    public SimpleEventProcessorA()
    {
        try
        {
            //Initializing variables using CloudConfigurationManager

            //Logging omitted
        }
        catch (Exception ex)
        {
            //Logging omitted
        }
    }

    async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason)
    {
        //Logging omitted

        Console.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason);
        if (reason == CloseReason.Shutdown)
        {
            await context.CheckpointAsync();
        }
    }

    Task IEventProcessor.OpenAsync(PartitionContext context)
    {
        try
        {
            //Logging omitted

            Console.WriteLine("Initialized.  Partition: '{0}', Offset: '{1}'", context.Lease.PartitionId, context.Lease.Offset);
            this.checkpointStopWatch = new Stopwatch();
            this.checkpointStopWatch.Start();

            return Task.FromResult<object>(null);
        }
        catch (Exception ex)
        {
            //Logging omitted

            return Task.FromResult<object>(null);
        }
    }

    async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
    {
        //Logging omitted

        foreach (EventData eventData in messages)
        {
            try
            {
                //Logging omitted

                Console.WriteLine(string.Format("Message received.  Partition: '{0}', Data: '{1}'",
                    context.Lease.PartitionId, data));
            }
            catch (Exception ex)
            {
                //Logging omitted

                throw;
            }
        }

        //Call checkpoint every 5 minutes, so that worker can resume processing from 5 minutes back if it restarts.
        if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
        {
            await context.CheckpointAsync();
            this.checkpointStopWatch.Restart();
        }
    }

}

Would appreciate any help, thanks!
UPDATE
Looks like everything was fine... it was the connection string I was using when pushing things into the event hub.
This was my event hub connection string:
Endpoint=sb://[myEventHubName].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;entityPath=[old-eventhub-name];SharedAccessKey=[mykey]

The entityPath was set incorrectly. It was using an older event hub name I had set. It should have been the value set for eventHubNameA or eventHubNameB.

A: Answering the question so that others may benefit from it. Although the answer is detailed in the question under the "UPDATE" section, I'll reiterate it here:
The entityPath was set incorrectly. It was using an older event hub name I had set. It should have been the value set for eventHubNameA or eventHubNameB.
Instead of
Endpoint=sb://[myEventHubName].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;entityPath=[old-eventhub-name];SharedAccessKey=[mykey]
It should have been Endpoint=sb://[myEventHubName].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;entityPath=[eventHubNameA];SharedAccessKey=[mykey]


text:
Q: Can McNemar's test be improved upon by adjustments for zeros like those in a sign test? McNemar's test is a special example of the binomial sign test, but the ('vanilla') sign test suffers from bias due to ignoring differences equal to zero.
McNemar's test statistic is given by:
$\chi^{2} = \frac{\left(|r-s|-1\right)^{2}}{r+s}$, where $r$ and $s$ are the counts of discordant pairs (0,1) versus (1,0), distributed $\chi^{2}$ with 1 degree of freedom under the null hypothesis.
I am having a hard time parsing Sribney on the sign test:

The test statistic for the sign test is the number $n_{+}$ of observations greater than zero. Assuming that the probability of an observation being equal to zero is exactly zero, then, under the null hypothesis, $n_{+} \sim \text{Binomial}(n, p=\frac{1}{2})$, where $n$ is the total number of observations. But what do we do if we have some observations that are zero?
Fisher's Principle of Randomization
We have a ready answer to this question if we view the test from the perspective of Fisher's Principle of Randomization (Fisher 1935). Fisher's idea (stated in a modern way) was to look at a family of transformations of the observed data such that the a priori likelihood (under the null hypothesis) of the transformed data is the same as the likelihood of the observed data. The distribution of the test statistic is then produced by calculating its value for each of the transformed "randomization" data sets, considering each data set equally likely.
For the sign test, the "data" are simply the set of signs of the observations. Under the null hypothesis of the sign test, $P(X_{i}>0)= P(X_{i}<0)$, so we can transform the observed signs by flipping any number of them and the set of signs will have the same likelihood. The $2^{n}$ possible sign changes form the family of randomization data sets. If we have no zeros, this procedure again leads to $n_{+} \sim \text{Binomial}(n, p=\frac{1}{2})$.
If we do have zeros, changing their signs leaves them as zeros. So if we observe $n_{0}$ zeros, each of the $2^{n}$ sign-change data sets will also have $n_{0}$ zeros. Hence, the values of $n_{+}$ calculated over the sign-change data sets range from 0 to $n-n_{0}$, and the "randomization" distribution of $n_{+}$ is $n_{+} \sim \text{Binomial}(n-n_{0}, p=\frac{1}{2})$.

Because this seems to be saying go ahead and ignore zeros. But then later in the paper, Sribney provides an adjustment for the sign-rank test that accounts for zeros just along the lines I am wondering about:

The adjustment for zeros is the change in the variance when the ranks for the zeros are signed to make $r_{j}=0$; i.e., the variance is reduced by $\frac{1}{4}\sum_{i=1}^{n-{0}}{i^{2}}=n_{0}\frac{\left(n_{0}+1\right)\left(2n_{0}+1\right)}{24}$.

Should I instead be asking whether or not to apply the signed-rank test to individually-matched case control data?
A simple made up example will illustrate why ignoring zeros presents a problem. Imagine you've paired data with no differences equal to zero (this would correspond to data for a McNemar's test with only discordant pairs present). With a sample size of, say, 20, you find 15 positive signs of differences and 5 negative signs of differences, and conclude significant difference. Now imagine that you have 1000 observed differences equal to zero in addition to those 15 positive and 5 negative signs of differences: now you conclude difference is not significant. If McNemar's test is conducted on 1020 pairs, 1000 of which are zeros, and with discordant pairs of 15 and 5, we should not reject the null hypothesis (e.g. at $\alpha = 0.05$).
There is an adjustment to the sign test to correct for observed zero differences based upon Fisher's "Principle of Randomization" (Sribney, 1995).
Is there a way of improving on McNemar's test that addresses the effect of observed zero differences (i.e. by accounting for number of concordant pairs relative to number of discordant pairs)? How? What about for the asymptotic z approximation for the sign test?

References
Sribney WM. (1995) Correcting for ties and zeros in sign and rank tests. Stata Technical Bulletin. 26:2–4.

A: E.L. Lehmann, J.P. Romano. Testing Statistical Hypotheses. 3rd ed. Springer, 2005. P. 136:

P(-), P(+) and P(0) denote the probabilities of preference for product
  [A over B, B over A, or A=B, tie], ... The hypothesis to be tested H0: P(+)=P(-)
  ... The problem reduces to that of testing the hypothesis P=1/2 in a
  binomial distribution with n-z [n = sample size, z = number of ties]
  trials ... The unbiased test is obtained therefore by disregarding the
  number of cases with no preference (ties), and applying the sign test
  to the remaining data.
The power of the test depends strongly on P(0) ... For large P(0), the
  number n-z of trials in the conditional [on z] binomial distribution
  can be expected to be small, and the test will thus have little power
  ... A sufficiently high value of P(0), regardless of the value of
  P(+)/P(-), implies that the population as a whole is largely
  indifferent with respect to the product.
As an alternative treatment of ties, it is sometimes proposed to
  assign each tie at random (with probability 1/2 each) to either plus
  or minus ... The hypothesis H0 becomes P(+)+1/2P(0)=1/2 ... This test
  can be viewed also as a randomized test ... and it is unbiased for
  testing H0 in its original form ... [But] Since the test involves
  randomization other than on the boundaries of the rejection region, it
  is less powerful than the [original test disregarding ties]..., so that the
  random breaking of ties results in a loss of power.

A: I don't see how this would be helpful, or even possible.  McNemar's test only uses the discordant pairs.  The Wikipedia page states:

The McNemar test statistic is:
   $$
    \chi^2 = {(b-c)^2 \over b+c}.
$$

I have a lengthy explanation of McNemar's test here: What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?  The whole post may be of value, but borrowing the example there:
\begin{array}{rrrrrr}
            &            &{\rm After} &          & &             \\
            &            &{\rm No}    &{\rm Yes} & &{\rm total}  \\
{\rm Before}&{\rm No}    &1157        &35        & &1192         \\
            &{\rm Yes}   &220         &13        & &233          \\
            &            &            &          & &             \\
            &{\rm total} &1377        &48        & &1425         \\
\end{array}
McNemar's test is the binomial test of $220/(220+35)$; the concordant pairs (i.e., $1157$, and $13$) don't show up.


text:
Q: Data from the SQL is not loading within AngularJS I have tried to retrieve some data from the SQL but it does not work.
I have the PHP working fine.
I think the ANGULARJS Controller is having some problems.
Here are the codes:
[PHP]
require_once 'connect.php';
$query = $conn->query("SELECT * FROM `calendars`") or die(mysqli_error());
$data = array();

while($row = $query->fetch_array()){
    $data[] = $row;
}

echo json_encode($data);

[AngularJS Controller]
function CalendarCtrl($scope,$http) {

$http.get('../crud/calendars_read.php').then(function(response){
    //$scope.calendar = [];
    $scope.calendars = response.data;

});

$scope.events = [

    {title: $scope.calendars.calendar_title,
    start: new Date(2017, 8, 2)},
// This Part does not work.

    {title: 'Click for Google',start: new Date(y, m, 28),end: new Date(y, m, 29),url: 'http://google.com/'}
// This Part works well if there is no $scope calling as above.
];

I think the $scope.event is in array, and that is why $scope.calendars is not working. Can anyone please help me how to retrieve
$scope.calendars.calendar_title

from the query to the array?
Thank you in advance and have a great day!!

A: http get is async, it will continue run $scope.events without waiting response.data back, so $scope.calendars.calendar_title is not defined yet at this timing.
Try to move $scope.events into then function.
$http.get('../crud/calendars_read.php').then(function(response){
    //$scope.calendar = [];
    $scope.calendars = response.data;

    $scope.events = [

        {title: $scope.calendars.calendar_title,
        start: new Date(2017, 8, 2)},

        {title: 'Click for Google',start: new Date(y, m, 28),end: new Date(y, m, 29),url: 'http://google.com/'}
    ];
});


text:
Q: Display an another application's window in a WPF application I want to display another application's window that is running concurrently in my WPF application. Like a live display, I need to be able to see real-time changes to the window (in this case, Chrome's) even if it is hidden behind other windows while my WPF application is running. It's kind of like the image below:
I understand I have to get the window's handle first, but how would I be able to display an external window like this? Is there a way I can use the Win32 API for this function?

A: Try looking into the Frame element (documentation here).
<Frame Source="https://www.google.com"/>


text:
Q: Evanescent waves in material with negative refractive index $n$ When $n<0$ an evanescent wave will exponentially  grow. It means that in the evanescent region the energy density can be very high.
Is it correct that if I have a large slab of a such material the wave may take a long time to get reflected because first the wave has to deposit the energy in the evanescent  region.
Does it lead in reality to a high absorption /ohmic losses?
appendix: materials with negative refractive index doesn't occur naturally. They have to be created artificiality. These materials are called "meta-materials" and posses many counterintuitive properties such as growths of evanescent  waves.
It is a hot research topic. The application are superlenses ,  invisibility cloak to name just few.


text:
Q: Match words separated by punctuation characters using regex The sample string:

this!is.an?example

I want to match: this is an example.
I tried this:
<script type="text/javascript">
   var string="this!is.an?example";
   var pattern=/^\W/g;
   alert(string.match(pattern));
</script>

A: Try this:
var words = "this!is.an?example".split(/[!.?,;:'"-]/);

This will create an string array containing each word.
If you want to turn it into a single string with the words separated by spaces, you can call words.join(" ").
EDIT: You could also split on \W (str.split(/\W/)), but that may match more characters than you want.

A: I can't understand why you want to explicitly match, but if your goal is to strip all punctuation, this would work:
var words = "this!is.an?example".split(/\W/);
words = words.join(' ');

\W will match any character except letters, digits and underscore.
If you want to split also on underscores, use this:
var words = "this!is.an?example_with|underscore".split(/\W|_/);

A: If you just want to match:
(\w|\.|!|\?)+

A: If you want to replace all punctuation with a whitespace, you could do this:
var str = str.replaceAll([^A-Za-z0-9]," ");

This replaces all non letters, numerals with a space.

A: /^\W/g means match a string where the first character is not a letter or number
and the string "this!is.an?example" obviously does not begin with a non-letter or non-number.
Remember that ^ means the whole string start with, not what you want to match start with. And also remember that capital \W is everything that is not matched by small \w. With that reminder what you probably want is:
var string="this!is.an?example";
var pattern=/(\w+)/g;                   // parens for capturing

alert(string.match(pattern).join(' ')); // if you don't join,
                                        // some browsers will simply
                                        // print "[object Object]"
                                        // or something like it


text:
Q: Android AspectJ @Around with method args not working In my current Android application I am investigating the use of @AspectJ
I am attempting to "capture" all executions to methods whose signature resembles:-
public void onMethodClicked(com.example.CustomType customType) {}

I have the following POINTCUTS
1) Ignore my Aspect class:
@Pointcut("!within(com.example.aspect)")
public void notAspect() { }

2) Select all "Clicked" methods with customType argument
@Pointcut("execution(* com.example..*.*Clicked(com.example.CustomType)) && args(custom)";)
public void customClicked(CustomType custom) { }

3) My @Around:-
@Around("notAspect() && customClicked()")
public Object selectedClicked(final ProceedingJoinPoint joinPoint, CustomType custom) throws Throwable {
    Log.d(TAG, "Found a clicked method " + custom);
    Object result = joinPoint.proceed();

    return result;
}

When I build my Android Application I get these messages
no match for this type name: CustomType [Xlint:invalidAbsoluteTypeName]

bad parameter to pointcut reference
formal unbound in pointcut

no match for this type name: com.example.aspect [Xlint:invalidAbsoluteTypeName]

the parameter custom is not bound in [all branches of] pointcut
use of ProceedingJoinPoint is allowed only on around advice (arg 1 in (before(extraFlags: 2): (((!within(com.example.aspect+) && execution(* com.example..*.*Clicked(com.example.CustomType)) && args(custom)) && persingleton(com.example.aspect.TraceAspect))->void com.example.aspect.TraceAspect.selectedClicked(org.aspectj.lang.JoinPoint, com.example.CustomType)))

What have I done wrong?
UPDATE
I have fixed one of the error/warning messages by correcting the !within() as follows:-
1) Ignore my Aspect class:
@Pointcut("!within(com.example.aspect.TraceAspect)")
public void notAspect() { }

A: I'm not sure about your problem but you may try changing the POINTCUT like this.
@Pointcut("!within(com.example.aspect.TraceAspect)")
public void notAspect() { }

@Pointcut("execution(* com.example..*.*Clicked(com.example.CustomType)))
public void customClicked() { }

Look I've removed the args(custom) part here which go inside the @Around annotation. And yes, of course I've removed the function parameter argument of customClicked function and the semi-colon by the end of the statement.
Now write your selectedClicked function like this by passing the arguments from here.
@Around("notAspect() && customClicked() && args(custom)")
public Object selectedClicked(final ProceedingJoinPoint joinPoint, CustomType custom) throws Throwable {

    Log.d(TAG, "Found a clicked method " + custom);
    Object result = joinPoint.proceed();

    return result;
}

It should work with no failure.