Q:

Symfony2 cloned routed

I am trying to make 1 resource accessible by 2 different routes:
api_v1:
    type:     rest
    prefix:   /api/v1
    resource: "@AppBundle/Resources/config/routing.yml"

app:
    type:     rest
    prefix:   /
    defaults: { _format: html }
    resource: "@AppBundle/Resources/config/routing.yml"

But forever reason second route overrides the first. When I debug:router I get:
get_products    GET      ANY    ANY  /products.{_format}
post_products   POST     ANY    ANY  /products.{_format}
//etc...

But I am expecting
get_products    GET      ANY    ANY  /api/v1/products.{_format}
post_products   POST     ANY    ANY  /api/v1/products.{_format}
//etc...

get_products    GET      ANY    ANY  /products.{_format}
post_products   POST     ANY    ANY  /products.{_format}
//etc

What could I be doing wrong?

A:

You can't have 2 routes with the same name. In such cases, the second route overrides the previous defined route with the same name, exactly the behaviour you're describing.
It also seems very wrong to have 2 URLs point to exact the same resource. Use a (permanent) redirect to handle such cases.


Q:

How to combine arithmetic expansion and brace expansion?

Can peoples combine arithmetic expansion and brace expansion?
$ for i in {$((1 + 1))..5}; do echo $i; done;
{2..5}
$ echo "bash laughs at me"

A:

See man bash for explanation:

The  order  of  expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and  pathname expansion.

Brace expansion happens before arithmetic expansion, so you can't combine them in the way you tried.
Use seq instead:
for i in $(seq $((a+4)) 12) ; do echo $i ; done


Q:

QGraphicsItem does not show

I wrote a simple application that displays QGraphicsPixmapItems in a QGraphicsScene. The application should be portable without installing Qt on the operating system. I managed to copy only the needed dll files to start the application. Everything works except the QGraphicsItems are not displayed at all, although they are in the scene (wrote a logfile that counts the items).
I figured out that the items are shown correctly, if I copy my "portable" exe file into Qt\Qt5.2.1\5.2.1\mingw48_32\bin folder.
The opposite does not work: If I copy all of the bin-folder to my portable application folder, it does not work. How can I use a QGraphicsItem in a portable Qt application?

A:

I found the reason: I needed to add the folder Qt\Qt5.2.1\5.2.1\mingw48_32\plugins\imageformats to my "portable-app"-folder. In particular, the needed dll was qjpeg.dll.


Q:

SQL query to calculate the sum of previous record in each record

I would like to get the calculated field (previous balance which equal to (sum of all the previous debit) - (sum of all previous credit))  in each row
for example :
for ID =5   , i want to get the previous balance of this record = (sum of debit amount) - (sum of credit amount) from ID=1 to ID =4
any suggestion please ?
i tried the LAG function but still didn't get what i want
thank you

A:

Hi if i understand your wall query and if you have SQL Server version greater or equal than 2008 you can use this query example  ::
Create table #tblVal
(
Id int identity(1,1),
Val int
)
--Inserting Records--
Insert into #tblVal values(720)
Insert into #tblVal values(720)
Insert into #tblVal values(500)
Insert into #tblVal values(720)
Insert into #tblVal values(539)
Insert into #tblVal values(341)

select * from #tblVal

SELECT *, SUM(Val) OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - Val as 'TotalSumPrevious',
     SUM(Val) OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as 'TotalSumCurrent'
FROM #tblVal

drop table #tblVal

AND take look at this link : https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-2017
Code edit with example picture :
Create table #tblVal
(
Id int identity(1,1),
Debit int,
Credit int
)
--Inserting Records--
Insert into #tblVal values(10,0)
Insert into #tblVal values(0,5)
Insert into #tblVal values(20,0)
Insert into #tblVal values(0,30)
Insert into #tblVal values(10,0)
Insert into #tblVal values(0,30)
Insert into #tblVal values(10,0)

select * from #tblVal

SELECT *,
     SUM(Debit - Credit)  OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - (Debit - Credit) as 'PreviousBalance'
FROM #tblVal

drop table #tblVal


Q:

About saturated sets

The above paragraph claims that $C=p^{-1}(D)$ for some $D\subset Y$. I think $D=\{y\in Y| p^{-1}(y)\cap C\ne \emptyset\}$. Is this correct? Even if so, I can't prove it.
Is the converse true? That is, if $C$ is saturated, then $C=p^{-1}(D)$. I think I managed to prove one inclusion. If $y\in D$, then I must prove that $p^{-1}(y)\in C$. Let $x\in p^{-1}(y)$. Then $p(x)=y\in D$ and so $x=p^{-1}(y)$. Since $y\in D$, $x\cap C\ne \emptyset$, and since $C$ is saturated, $x\in C$. This proves $p^{-1}(D)\subset C$

A:

Suppose that $C$ is saturated. I claim that $p^{-1}[p[C]] = C$ and so $C$ is the pre-image of a subset of $Y$, as claimed (so we can take $D = p[C]$).
Note that by definition we always have $p^{-1}[p[C]] \supseteq C$, because $c \in C$ implies $p(c) \in p[C]$ and so $c \in p^{-1}[p[C]]$. Now suppose that $x \in p^{-1}[p[C]]$. This means that $p(x) \in p[C]$ or there is a $c \in C$ such that $p(c) = p(x)$.
So $C$ intersects $p^{-1}[\{p(x)\}$ and by being saturated, $p^{-1}[\{p(x)\}] \subseteq C$ ($C$ contains every fibre it intersects). And in particular, $x \in p^{-1}[\{p(x)\}] \subseteq C$, showing the reverse inclusion.
Reversely it's easy to check that $C = p^{-1}[D]$ is indeed always a saturated subset of $X$.


Q:

fail2ban couriertcpd: LOGIN FAILED not banning

My fail2ban is not banning as I expect.
An example of my log entries are :-
Jul 26 07:11:29 mail couriertcpd: LOGIN FAILED, user=sally, ip=[::ffff:54.191.110.169]
Jul 26 07:13:22 mail couriertcpd: LOGIN FAILED, user=ddos, ip=[::ffff:54.193.13.22]
Jul 26 07:14:45 mail couriertcpd: LOGIN FAILED, user=sally, ip=[::ffff:54.191.110.169]

My courierstmp setting is
more /etc/fail2ban/filter.d/courierlogin.conf
[INCLUDES]
before = common.conf
[Definition]
_daemon = (?:courier)?(?:imapd?|pop3d?)(?:login)?(?:-ssl)?
failregex = ^%(__prefix_line)sLOGIN FAILED, user=.*, ip=\[<HOST>\]$

ignoreregex =

Running a test yields no results.
 fail2ban-regex -v  /var/log/mail.log /etc/fail2ban/filter.d/courierlogin.conf

Running tests
=============

Use   failregex file : /etc/fail2ban/filter.d/courierlogin.conf
Use         log file : /var/log/mail.log

Results
=======

Failregex: 0 total
|-  #) [# of hits] regular expression
|   1) [0] ^\s*(<[^.]+\.[^.]+>)?\s*(?:\S+ )?(?:kernel: \[\d+\.\d+\] )?(?:@vserver_\S+ )?(?:(?:\[\d+\])?:\s+[\[\(]?(?:courier|couriertcpd)?(?:imapd?|pop3d?)(?:login)?(?:-ssl)?(?:\(\S+\))?[\]\)]?:?|[\[\(]?(?:courier|couriertcpd)?(?:imapd?|pop3d?)(?:login)?(?:-ssl)?(?:\(\S+\))?[\]\)]?:?(?:\[\d+\])?:?)?\s(?:\[ID \d+ \S+\])?\s*LOGIN FAILED, user=.*, ip=\[<HOST>\]$
`-

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
|  [296708] MONTH Day Hour:Minute:Second
|  [0] WEEKDAY MONTH Day Hour:Minute:Second[.subsecond] Year
|  [0] WEEKDAY MONTH Day Hour:Minute:Second Year
|  [0] WEEKDAY MONTH Day Hour:Minute:Second
|  [0] Year/Month/Day Hour:Minute:Second
|  [0] Day/Month/Year Hour:Minute:Second
|  [0] Day/Month/Year2 Hour:Minute:Second
|  [0] Day/MONTH/Year:Hour:Minute:Second
|  [0] Month/Day/Year:Hour:Minute:Second
|  [0] Year-Month-Day Hour:Minute:Second[,subsecond]
|  [0] Year-Month-Day Hour:Minute:Second
|  [0] Year.Month.Day Hour:Minute:Second
|  [0] Day-MONTH-Year Hour:Minute:Second[.Millisecond]
|  [0] Day-Month-Year Hour:Minute:Second
|  [0] Month-Day-Year Hour:Minute:Second[.Millisecond]
|  [0] TAI64N
|  [0] Epoch
|  [0] ISO 8601
|  [0] Hour:Minute:Second
|  [0] <Month/Day/Year@Hour:Minute:Second>
|  [0] YearMonthDay Hour:Minute:Second
|  [0] Month-Day-Year Hour:Minute:Second
`-

Lines: 296708 lines, 0 ignored, 0 matched, 296708 missed

I have tried replacing courier with couriertcpd without avail. I am not not sure what else I can do to get this working.

A:

After much searching, I eventually realised that the supplied filter regex was all-things-to-all-people. I didn't need that, so I changed the regex for my specific situation.
# OLD
# failregex = ^%(__prefix_line)sLOGIN FAILED, user=.*, ip=\[<HOST>\]$
# NEW
failregex = couriertcpd: LOGIN FAILED, user=.*, ip=\[<HOST>\]$

That worked and I am happily banning away those pests.


Q:

How to I read several lines in a file faster using python?

As of now I use the following python code:
file = open(filePath, "r")
lines=file.readlines()
file.close()

Say my file has several lines (10,000 or more), then my program becomes slow if I do this for more than one file. Is there a way to speed this up in Python? Reading various links I understand that readlines stores the lines of file in memory thats why the code gets slow.
I have tried the following code as well and the time gain I got is 17%.
lines=[line for line in open(filePath,"r")]

Is there any other module in python2.4 (which I might have missed).
Thanks,
Sandhya

A:

for line in file:

This gives you an iterator that reads the file object one line at a time and then discards the previous line from memory.

A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. However, using seek() to reposition the file to an absolute position will flush the read-ahead buffer. New in version 2.3.

Short answer: don't assign the lines to a variable, just perform whatever operations you need inside the loop.


Q:

Publish MVC Web App to Azure using VSTS

I am learning CI/CD using VSTS and Azure for my MVC Web App.  The build is successful, the deployment (to a specific slot in Azure) is successful, but when I navigate to the web app URL I'm still presented with the default home page.

2017-11-01T17:25:09.6208009Z ==============================================================================
2017-11-01T17:25:09.6218009Z Task         : Azure App Service Deploy
2017-11-01T17:25:09.6218009Z Description  : Update Azure WebApp Services On Windows, Web App On Linux with built-in images or docker containers, ASP.NET, .NET Core, PHP, Python or Node based Web applications, Function Apps, Mobile Apps, Api applications, Web Jobs using Web Deploy / Kudu REST APIs
2017-11-01T17:25:09.6218009Z Version      : 3.3.19
2017-11-01T17:25:09.6218009Z Author       : Microsoft Corporation
2017-11-01T17:25:09.6218009Z Help         : [More Information](https://aka.ms/azurermwebdeployreadme)
2017-11-01T17:25:09.6218009Z ==============================================================================
2017-11-01T17:25:13.2363661Z Got connection details for Azure App Service:'rsbi'
2017-11-01T17:25:22.3031769Z [command]"C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" -verb:sync -source:package='d:\a\r1\a\myapp-ASP.NET (PREVIEW)-CI\drop\myapp.zip' -dest:auto,ComputerName='https://myapp.scm.azurewebsites.net:443/msdeploy.axd?site=myapp',UserName='********',Password='********',AuthType='Basic' -setParam:name='IIS Web Application Name',value='myapp' -enableRule:AppOffline -enableRule:DoNotDeleteRule -userAgent:VSTS_945126af-40d2-8ab2-c875fd19e0af_release_1_1_1_1
2017-11-01T17:25:23.2157103Z Info: Using ID '8cb6f243-2593-4653-abd3-6666df1d45d4' for connections to the remote server.
2017-11-01T17:25:41.2558582Z Info: Adding ACL's for path (myapp)
2017-11-01T17:25:41.2558582Z Info: Adding ACL's for path (myapp)
2017-11-01T17:25:41.3594685Z Total changes: 2 (0 added, 0 deleted, 2 updated, 0 parameters changed, 0 bytes copied)
2017-11-01T17:25:41.3714688Z Successfully deployed web package to App Service.
2017-11-01T17:25:45.0533462Z Successfully updated deployment History at https://myapp.scm.azurewebsites.net/api/deployments/11509557141986
2017-11-01T17:25:45.0703260Z ##[section]Finishing: Deploy Azure App Service to Slot
2017-11-01T17:25:45.0793254Z ##[section]Finishing: Release

If I look at the Web App debug console in Kudu, I can see all of my content has been deployed:
11/01/2017  05:25 PM    <DIR>          .
11/01/2017  05:25 PM    <DIR>          ..
11/01/2017  02:12 PM    <DIR>          bin
11/01/2017  02:12 PM    <DIR>          Content
11/01/2017  02:12 PM    <DIR>          ExternalAssemblies
11/01/2017  02:12 PM    <DIR>          fonts
11/01/2017  02:12 PM    <DIR>          Scripts
11/01/2017  02:12 PM    <DIR>          Views
11/01/2017  10:31 AM    <DIR>          webapps
11/01/2017  02:11 PM             7,293 ApplicationInsights.config
11/01/2017  02:11 PM            32,038 favicon.ico
11/01/2017  02:11 PM               114 Global.asax
11/01/2017  02:11 PM             6,432 Web.config
               6 File(s)         50,508 bytes
               9 Dir(s)  53,635,162,112 bytes free

D:\home\site\wwwroot>

A:

The reason the home page related to JAVA is that there is webapps folder in wwwroot folder and you specify the Java Version in Application Settings page, more information, you can check There's nothing here yet after deploying Java Web App on Azure thread.
So, you need to remove this folder and turn off Java version.
Regarding java web job, you don’t need to specify Java Version in Application Settings, you can create batch file and set Path environment variable, then call java command, for example (include package folders into zip file, and specify the full name of main class):
set PATH=%PATH%;%JAVA_HOME%/bin
java [package].[main class name]

A related blog: Executing Java Web Jobs on Azure


Q:

Subject.create() Not working in RoR

I'm trying to use the Rails Console to create object instances of my models.
It is possible to create and save an instance to the database using the manual methods like so:
1.9.3p125 :003 > subject = Subject.new
 => #<Subject id: nil, name: nil, position: nil, visible: false, created_at: nil, updated_at: nil>
1.9.3p125 :004 > subject.name = "First Name"
 => "First Name"
1.9.3p125 :005 > subject.position = 1
 => 1
1.9.3p125 :006 > subject.visible = 'true'
 => "true"
1.9.3p125 :007 > subject.save
(0.2ms)  BEGIN
SQL (0.6ms)  INSERT INTO `subjects` (`created_at`, `name`, `position`, `updated_at`, `visible`) VALUES ('2012-06-21 13:28:35', 'First Name', 1, '2012-06-21 13:28:35', 1)
(20.4ms)  COMMIT
 => true
1.9.3p125 :008 > subject.id
 => 1
1.9.3p125 :009 > subject.new_record?
 => false

I'm totally new to RoR so I've got no idea where to begin trouble shooting this error:
1.9.3p125 :010 > subject = Subject.create(:name => "Second name", :position => 2)
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: name, position from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security.rb:230:in `sanitize_for_mass_assignment'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/base.rb:498:in `initialize'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/persistence.rb:44:in `new'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/persistence.rb:44:in `create'
from (irb):10
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Here is my Subject model:
class Subject < ActiveRecord::Base
  attr_accessible :title, :body, :name, :position
end

Thanks!
Things I've tried so far:

Exiting and reentering rails c.
Typing "reload!" into rails c
Reopening terminal

A:

You need to add
attr_accessible :name, :position

To your Subject model so you can create this in one step. Its a thing of security. You can read about this here:
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible
hf,..


Q:

постоянно крашится Unreal Engine 4.25.1

Скачал недавно Unreal Engine 4. Как только создаю или открываю проект (даже пустой) (для разработки игр) открывается нормально не лагает, но через несколько секунд/минут (даже когда я ничего не делаю) он виснет. Сначала виснет сам анриал а потом и весь ноут так что даже диспетчер не открывается, приходится перезагружать кнопкой Power. Ноут по параметрам подходит (12 оперативки, geforce 1050, i5-8300H 2.3 GHz)
Что пробовал:

Менял IDE по умолчанию (думал может вижуалка грузит)
Запускал от админа (и не от админа тоже). + Савил галку отключить оптимизацию на весь екран как в гайдах в гугле.
Переустанавлявал
Ставил раннюю версию (Может попробовать скачать более более ранние? но качать и так уже надоело все равно не работает)
Ставил галку чтобы принудительно запускалось через видюху
Обновлял дрова
Нажимал проверить в лаунчере епиков

A:

Проблема решилась при открытии редактора не на полный экран


Q:

Run jQuery slideDown complete function only after last item has completed

I understand that you can pass a function to slideUp/slideDown that will run once the transition has completed:
$('li').slideUp({
    complete: function(){
        alert('done');
    }
});

With this HTML an alert is shown 3 times.

[content here]

[content here]

[content here]

Is there some way to have the complete function fire only once, when the last list item has completed the slideUp? (fiddle)

A:

You can "redo" your selector and check if this is the last :
$('li').slideUp({
    complete: function(){
        if($('li:last').is(this)){
            alert('done');
        }
    }
});

Fiddle : http://jsfiddle.net/5NQsU/
Caching your selector would be even better :
var $li = $('li');
$li.slideUp({
    complete: function(){
        if($li.last().is(this)){
            alert('done');
        }
    }
});


Q:

SSH vs/and Password

I have a VPS that I am logging to root via SSH keys.
Now, I created another user user1 with the command adduser and I assigned a password to it. However, whenever I try to login to the server via winSCP using user1 I still get the error that I need to enter the private key and can't login using the password for user 1.
My questions are as follows:

Can a user have the possibility to login via the 2 methods? That is, using the SSH keys and a password?
If SSH is used, are all the users of the system bound to use the keys to login?

A:

You can add rules for that particular user on the /etc/ssh/sshd_config file like the example at the end of this answer. But before be warned, allowing password login via SSH is somewhat unsafe in terms of brute-force attempts possible to the server. So the safest way to go is to create another SSH key on the VPS or another Linux machine with the following line. best is to switch to user1 on that machine before you start using the following commands with su - user1. (Note: you should change into the directory where you want the key-pair to be created as the -f has a hard time with paths):
ssh-keygen -t rsa -C "user1_email@example.com" -f user1_key

The user can change the passphrase himself later by copying his key-pair for a short time onto the VPS or on another Linux machine with:
ssh-keygen -p -f user1_key

Then give the private key (user1_key) to user1 and place the public key (user1_key.pub) in the users home directory under ~/.ssh/authorized_keys on the VPS then change ownership to user1 or you do su - user1 before doing that to prevent undesired wrong ownership inside the home directory of user1.
mkdir -p /home/user1/.ssh
cat user1_key.pub >> /home/user1/.ssh/authorized_keys
# The next line is only needed if you have done the two above as 'root'
chown -Rv user1:user1 /home/user1/.ssh

The key-pair creation process can be done on Windows too using WinScp, see here for reference. You might then want to make sure the public and the private key have the right permissions set, which is 0600 for the users private key and 0644 for the users public key. (Note: copying the key to a windows formatted USB stick or drive lets the key loose its set permissions, so you want to double check on that.
If you however really want to make this user able to log in via password, you can change the following line in /etc/ssh/sshd_config:
AllowUsers mainuser user1

And add the following at the end:
For enabling password only:
Match User user1
    PubkeyAuthentication no
    PasswordAuthentication yes

For enabling both:
Match User user1
    PubkeyAuthentication yes
    PasswordAuthentication yes

For enabling ssh only you can remove that part or set it to:
Match User user1
    PubkeyAuthentication yes
    PasswordAuthentication no

More reading material which might not necessarily related to the question but to SSH in general you can find here, just be aware that some information is specified for digital-ocean but still useful. See as well the manpage for the ssh-keygen command and the manpage for the ssh command.
Thanks to @Eliah-Kagan for proofreading and suggesting corrections and additions.


Q:

How can I customize the CSS generated by LESS to include Font Awesome?

I want to customize Bootstrap's CSS by layering in Font Awesome as a replacement for Bootstrap's default Glyphicons.
How can I customize the CSS generated by LESS to include Font Awesome in a way that won't break if I update the core Bootstrap files? Note: Font Awesome suggests altering the core Bootstrap 'bootstrap.less' file to replace @import "sprites.less"; with @import "path/to/font-awesome/less/font-awesome.less";, but this change would get overwritten if the Boostrap core were to be replaced (by a version upgrade, for example).
Similar to my earlier question ("How can I customize Twitter Bootstrap's CSS using LESSCSS variables?"), we can assume I have this file structure:
/html
    /bootstrap
       ...etc...
       /js
       /less
    /Font-Awesome
       /css
       /font
       /less
       ...etc...
    /MyApp
       ...etc...
       /common_files
          /less
             style.less

A:

Following the pattern suggested in Font Awesome's "getting started" section, edit the MyApp/common_files/less/style.less file to

import the font-awesome/less/font-awesome.less file, then
define the LESS variable '@fa-font-path' (for Font Awesome 4+) or '@FontAwesomePath' (for Font Awesome < 4)

So, given the directory structure in the question:
@import "../../../bootstrap/less/bootstrap.less";
@import "../../../bootstrap/less/responsive.less";
/* include the Font Awesome CSS */
@import "../../../Font-Awesome/less/font-awesome.less";

/* define path to Font Awesome 4's font folder*/
@fa-font-path:   "../../../Font-Awesome/fonts";

Or
/* or define path to Font Awesome 3's font folder*/
@FontAwesomePath:   "../../../Font-Awesome/font";


Q:

How to avoid specific paths in allShortestPath function?

The graph is supposed to represent a system similar to github, with commits (commit1, commit2, commit3 and commit4), documents (d1, d2) and changes on those documents (green nodes).
I am trying to use CYPHER to get all the documents values at a specific commit. In other words, I am trying to find the shortest path between the specific commit and each of the documents on my graph, but avoiding some paths.
Imagine if I am on commit4, d1 should be equal to foo2 and d2 should be equal to spain. This could be solved with the following CYPHER query:
MATCH (c:Commit {id: 'commit4'})-[:FOLLOWS|CHANGED*]->(:Value)<-[:EQUALS]-(d:Document), p = allShortestPaths((c)-[*]-(d))
RETURN p

This would give the following response:

Now, imagine that I want to be get the values on commit3. The request should not return any changes from the commit4. However, if I use the allShortestPaths function the way I do, it will go through commit4 since it is actually the shortest path to d1 and return the exact same response than if my starting node was commit4.
MATCH (c:Commit {id: 'commit3'})-[:FOLLOWS|CHANGED*]->(:Value)<-[:EQUALS]-(d:Document), p = allShortestPaths((c)-[*]-(d))
RETURN p

How could I avoid the allShortestPath function to go through a [:FOLLOWS]->(c) relationship and solve my problem?

A:

From what you explained, I understand that you don't want to traverse the FOLLOWS edge in the opposite direction of the edge. To do so you can use cypher projection in algo.shortestPath:
MATCH (start:Commit {name:'commit4'})
MATCH (end:Document)
CALL algo.shortestPath.stream(start, end, null,{
nodeQuery:'MATCH (n) RETURN id(n) AS id',
relationshipQuery:'MATCH (n)-[r:FOLLOWS|CHANGED]->(p) RETURN id(n) AS source, id(p) AS target UNION MATCH (n)-[r:EQUALS]-(p) RETURN id(n) AS source, id(p) AS target',
graph:'cypher'})
YIELD nodeId, cost
WITH end as document, algo.asNode(nodeId) AS value WHERE "Value" in labels(value)
return document, value

Replace "commit4" with any other commit name.


Q:

git log --since date string parsing

I was looking through some logs in a submodule today (somewhat furiously) and typed some errors into the dates in the command
git log --since="2019-12-31" --oneline | wc -l
      90

and instead of typing that I typed,
git log --since="2019-12=31" --oneline | wc -l
    2147

I was alarmed by the difference is count which is why I was able to notice the error immediately. However, I'm unclear as to what the behavior is in this case. Is this a bug or is this expected behavior for git log?
I would expect an error in parsing but it looks like the logs go back to January or February of 2019.

A:

It appears that Git's date parsing just stops when it gets to a part it can't understand.  For example "2015-13" is understood as "2015", as is "2015-4444".
In your case, it's treating "2019-12=31" as "2019".  And then a second weird "feature" kicks in: --since 2019 does not mean --since 2019-01-01, it means "since today's date in 2019".  So the meaning of your --since 2019-12-31 will actually change throughout each year when you run it!
What seems to be happening is:

Generate the current date-time (in your time zone).
Replace the parts you specified in --since, ignoring the month and day part if the parser cannot decide how to parse it.

Note that even the simple and "obviously correct" git log --since 2019-12-31 does not really do what one might expect, because it shows commits since the current time on that day, not since midnight.  So unless you specify a full date-time string, there will always be some dependency on the time when the command is executed.


Q:

Son, eres or es: which one to use with "the boys"?

We use 'eres' for 'are' with you in Spanish. We use 'es' with usted for 'are'. If we have to use 'are' with boys, what would we use: son, eres or es?
What would be the appropriate tense for "The boys."?

A:

Yo soy
Tu eres
Él es
Nosotros somos
Ustedes son
Ellos son

which of these pronouns do you think fit "the boys" best?
As to the translation- any dictionary can help you with that.

A:

When you use the usted form you use the conjugation of the third person, not the second, even if usted is used as a polite version of tú (thus, second person singular) and ustedes  as a polite version of vosotros (thus, second person plural).

Tú eres / Vosotros sois [Second person]
El (o ella) es / Ellos Son [Third person]
Usted es / ustedes son [second person that used third person conjugation]

We do this when directly addressing someone, as a way of being polite, not when we describe certain collectives. It doesn't matter if is boys or cars. What matters is if you want to be super-polite when addressing someone you are talking to.
It is unlikely that you would address a group of boys de usted but not impossible. For example if you were their teacher and wanted to be extremely formal you could address the as usted.
So with boys or kids or teenagers most likely you will use the tú form, so use the second person of whichever verb you are using. If you are not addressing them directly you have no need for the usted form.
Nevertheless, being boys a plural you are going to use third person.

Ese chico está solo. Esos chicos están jugando.


Q:

two query results in 1 $variable

I'm trying to use codeigniter activerecords to pull some records from two tables that have the same structure.  For example I have a MARKET table with two fields (name, name_spanish) and I have an APPLICATION table with the same two fields (name, name_spanish).
Can I create a $data variable and put the results of each query into it?  Then I'd want to check the results like this psuedocode $spanish = $data['name_spanish'] where $data['name'] = "Hello"
Can this be accomplished?

A:

This sounds like a UNION query.
SELECT * FROM table1 WHERE foo = 1
  UNION SELECT * FROM table2 WHERE bar = 3 AND baz = 3

I don't think CodeIgniter's ActiveRecord supports union queries, so use the query method.


Q:

How to refresh/update select in Javascript (vanilla) with Materialize?

I am attempting to update options in a select-widget by using Javascript (vanilla) with Materialize. I have I guess it is related to "dynamically generated select elements", but I am not sure what to do?
According to Materialize I may need to consider to implement: "In addition, you will need a separate call for any dynamically generated select elements your page generates.". Unfortunately, I am not sure (did not found) how I can "dynamically generated select elements" as to update/refresh the select-widget?
Here are my related codes:
HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

        <button id = "btn" class="waves-effect waves-light btn-small">person_addAdd</button>

        <button id = "btnRemove" class="waves-effect waves-light btn-small">deleteRemove</button>

          <select id="voteNoList" onchange="PersonInfo()" required>
            <option value="">Vote Number?</option>

            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
          </select>

Javascript (Vanilla)
  //------------
  // AUTO
  //------------
  // Select
  document.addEventListener('DOMContentLoaded', function() {
    var el = document.querySelectorAll('select');
    var instances = M.FormSelect.init(el);
  });

  // Button - Add
  document.getElementById("btn").addEventListener("click", PersonInfo);

  // Button - Remove
  document.getElementById("btnRemove").addEventListener("click", PersonDelete);

  function PersonInfo(){

    debugger;
    var selectobject = document.createElement("option");
    selectobject.text = "Text55";
    selectobject.value = "myvalue55";
    var selectList = document.getElementById("voteNoList");
    selectList.appendChild(selectobject);
    debugger;
    return;
  }

  function PersonDelete(){

    debugger;
    var selectobject=document.getElementById("voteNoList");
    for (var i=0; i<selectobject.length; i++){
      if (selectobject.options[i].value == "2"){
         selectobject.remove(i);
        break;
      }
    }
    debugger;
    return;
  }

My expectation was to have a select-widget which can increase and decrease in options depending on how the buttons have been pressed. (Observe that for simplicity, I hard-coded to only be able to add the same option and delete the option that is equal to "2".)
Although I could not find a solution in Javascript (vanilla), I was able to find a jQuery solution as seen in
link.
My codes are also available in CodePen, where one can see in debug mode that the different number options of selectList change when pressing the buttons.

A:

Apparently, the solution to my case was to add M.FormSelect.init(selectList); before return. The codes with the update/solution are available in CodePen.


Q:

Java has-a relationship

Would the below be correct for the following statement. "A man has a best friend who is a dog."
public class Mann {
     private BestFriend dog;
     //etc
}

A:

I'd say it would be more correct to write:
public class Man extends Entity {
     private Entity bestFriend = new Dog(); // Where Dog extends Entity
     //etc
}

Why? Let's say you have a bunch of different entities, say Man, Cat, and Dog. It would then make sense to have them each extend an Entity class, that specifies various attributes every entity should have. Each one, then, could have a bestFriend attribute, that could be any other Entity.
However, as pointed out in the comments, it would be even more correct to allow for specifying a bestFriend in the constructor:
public class Man extends Entity {
    private Entity bestFriend;

    public Main(Entity bestFriend) {
        this.bestFriend = bestFriend;
    }
    //etc
}

...

Dog bobDog = new Dog();
Man bob = new Man(bobDog);

A:

Looks like Dog should by type, because man can have other "type of best friend":
public class Mann {
     private Dog bestFriend;
     //etc
}

Update
Most close to real-live implementation will look like:
public interface Friend {}

public class Man implements Friend {}

public class Dog implements Friend {}

public class FriendRelationship {
    private Friend first;
    private Friend second;

    public FriendRelationship(Friend first, Friend second) {
        this.first = first;
        this.second = second;
    }
}

Man aPerson = new Man();
Dog aBog = new Dog();
FriendRelationship bestFriends = new FriendRelationship(aPerson, aDog);

This way one can express friend relationships between any entities. Common base class is not required. You only need implement Friend interface.


Q:

Eclipse Juno, neverending Android toolkit update

I haven't done any Android development for a while. During this while I updated my Galaxy Nexus (the first version) to Android 4.2.2. Yesterday I wanted to work on my game and I connected my mobile. I wrote some code, clicked run and the device appeared in the device selector, but instead of the familiar "Samsung Galaxy Something" I got some seemingly random number (it was probably a serial code for something) and the device was marked as offline, and it was not selectable for deploy and debug. Interestingly, the device itself was enabled for USB debug, the little monster was clearly visible in the upper left corner of the screen and everything seemed fine.
I tried to switch USB debug off and on again, with no success.
I tried to kill and restore the ADB server.
I tried to change the USB cable; I learned that there are A and B cables and in some cases it may be important to use the right one (I left the Samsung cable in another continent).
I tried to update the Android SDK with the Android update manager; after doing this the device when connected would prompt me to accept USB debug requests, so after all something has changed in a way. However, the device name still would not show up in the device manager and the status was still offline. Then, Eclipse started complaining that with the new SDK the Android Development Toolkit should be updated to version 21.
I ran the Eclipse update manager and it is still hanging at "Contacting Software Sites" at 50% after several hours.
I tried to add -Declipse.p2.mirrors=false at the end of eclipse.ini, but it doesn't seem to be faster.
I'm especially aware of this and this, and nothing of what they said there helped.
Edit
Still at 50%, after one hour. I'll also try some of these at some point.
Edit
Cool, it finally started downloading the updates and after a while it crashed.
An error occurred while collecting items to be installed
session context was:(profile=epp.package.java, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,com.android.ide.eclipse.adt,21.1.0.v201302060044-569685
No repository found containing: osgi.bundle,com.android.ide.eclipse.base,21.1.0.v201302060044-569685
No repository found containing: osgi.bundle,com.android.ide.eclipse.ddms,21.1.0.v201302060044-569685
No repository found containing: osgi.bundle,com.android.ide.eclipse.gldebugger,21.1.0.v201302060044-569685
No repository found containing: osgi.bundle,com.android.ide.eclipse.hierarchyviewer,21.1.0.v201302060044-569685
No repository found containing: osgi.bundle,com.android.ide.eclipse.traceview,21.1.0.v201302060044-569685
No repository found containing: osgi.bundle,overlay.com.android.ide.eclipse.adt.overlay,21.1.0.v201302060044-569685
No repository found containing: org.eclipse.update.feature,com.android.ide.eclipse.adt,21.1.0.v201302060044-569685
No repository found containing: osgi.bundle,com.android.ide.eclipse.adt.package,21.1.0.v201302060044-569685
No repository found containing: org.eclipse.update.feature,com.android.ide.eclipse.ddms,21.1.0.v201302060044-569685
No repository found containing: org.eclipse.update.feature,com.android.ide.eclipse.gldebugger,21.1.0.v201302060044-569685
No repository found containing: org.eclipse.update.feature,com.android.ide.eclipse.hierarchyviewer,21.1.0.v201302060044-569685
No repository found containing: org.eclipse.update.feature,com.android.ide.eclipse.traceview,21.1.0.v201302060044-569685

A:

I also faced the same problem when i updated my sdk took kit and tried to update ADT , For downloading ADT 21.1 you need Helios 3.62 version or Higher I guess .
The best way is to download the Desire update using zip and then update using that zip file.
I saved my day using this method only. Remove the internet connection while updating using local zip file
This might Help :)


Q:

Pure CSS onclick event checkbox hack problem

So i have a robot drawn in HTML+CSS, colored via "background-color" and i want his parts to change color onclick. I know it can be done(probably) in several easy quick lines of JS\Jquery, but i want a pure CSS solution.
I've been trying to implement the checkbox hack, but failed miserably(see "#recolor:checked > .torso" section in CSS part).
Code included.

body{
 background-color: rgba(0, 0, 0, 0.788);
}

h1 {
 text-align: center;
 font-family: 'Roboto', sans-serif;
 margin-left: 50px;
 color: whitesmoke;
}

.robots {
 display: flex;
 flex-flow: column wrap;
 justify-content: center;
 align-items: center;
 margin-left: 100px;
}

nav{
 position: fixed;
 top: 75px;
 left: 20px;
 margin: 0px 50px 0px 20px;
        width: 300px;
 color: blanchedalmond;
}

ul{
 list-style: none;
}

.head,
.left_arm,
.torso,
.right_arm,
.left_leg,
.right_leg {
 background-color: #5f93e8;
}

#recolor:checked > .torso {
 background-color: chartreuse;
}

.head {
 width: 200px;
 margin: 0 auto;
 height: 150px;
 border-radius: 200px 200px 0 0;
 margin-bottom: 10px;
}

.eyes {
 display:flex;
}

.head:hover {
 width: 300px;
    transition: 1s ease-in-out;
}

.upper_body {
 width: 300px;
 height: 150px;
 display: flex;
}

.left_arm, .right_arm {
 width: 40px;
 height: 125px;
 border-radius: 100px;
}

.left_arm {
 margin-right: 10px;
}

.left_arm:hover {
 -webkit-transform: rotate(120deg);
    -moz-transform: rotate(120deg);
    -o-transform: rotate(120deg);
    -ms-transform: rotate(120deg);
    transform: rotate(120deg);
}

.right_arm {
 margin-left: 10px;
}

.torso {
 width: 200px;
 height: 200px;
 border-radius: 0 0 50px 50px;
}

.lower_body {
 width: 200px;
 height: 200px;
 margin: 0 auto;
 display: flex;
}

.left_leg, .right_leg {
 width: 40px;
 height: 120px;
 border-radius: 0 0 100px 100px;
}

.left_leg {
 margin-left: 45px;
}

.left_leg:hover {
 -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
 transform: rotate(20deg);
}

.right_leg:hover {
 -webkit-transform: rotate(-20deg);
    -moz-transform: rotate(-20deg);
    -o-transform: rotate(-20deg);
    -ms-transform: rotate(-20deg);
 transform: rotate(-20deg);
}

.right_leg {
 margin-left: 30px;
}

.left_eye, .right_eye {
 width: 20px;
 height: 20px;
 border-radius: 15px;
 background-color: white;
}

.left_eye {
 position: relative;
 top: 100px;
 left: 40px;
}

.right_eye {
 position: relative;
 top: 100px;
 left: 120px;
}
<!DOCTYPE html>

 <title>RoboPage</title>
 <link rel="stylesheet" type="text/css" href="style.css">
 <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Robot Friend

Usage tutorial

Hover over robot's left arm for him to greet you!

Click and hold on bot's body for him to change color

Hover over bot's legs for him to make a tap dance

   <input type="checkbox" id="recolor">

A:

You're selecting #recolor:checked > .torso, which means any .torso that's a direct child of a checked #recolor. That would mean something like this:
<input type="checkbox" id="recolor">

</input>

But that's not your structure, and it's also invalid (input can't have children). You have the input, then right next to it, you have a .head, then an .upper_body and a .torso inside of it.
Your selector should be: #recolor:checked ~ .upper_body > .torso.
That means any .torso that's a direct child (>) of an .upper_body that's a sibling (~) of the checked input.
In this case you have to use ~ instead of + because .upper_body is a sibling of the input, but it's not right next to it.


Q:

How to drive together JTA (Bitronix) and XADisk

We have a J2SE application (we deploy it as a standalone JAR) which is a Jetty-powered web service, making use of JPA (EclipseLink) and JTA (Bitronix, UserTransaction). As you can guess, the main purpose of this app is to receive REST requests, process, store and provide data to the http clients.
While processing a request, sometimes we generate files on the fs. Sadly, this process is out of the scope of our JTA configuration. I have a task to bind file generation to the JTA transaction, eg. upon utx.rollback() I have to rollback file processing, and upon succesfull utx.commit() I have to commit the fs changes, too.
My senior advised me to use XADisk ( http://xadisk.java.net/ ). Seems very promising! I did some example-reading but I'm still a bit confused on how to introduce this into our app.
So my question: can anyone provide me some guidelines on how to implement this lib into a JTA application? Thanks!

A:

Going forward on docs hunting, I found some bits of info:
Tracking issue
XADisk User Guide
The latter contains a chapter titled "Enlisting XADisk into JTA Transactions"


Q:

Is Lazy Loading required for nHibernate?

It took me a long time but I finally got nHibernate's Hello World to work.  It worked after I did "lazy loading."  Honestly, I couldn't tell you why it all worked, but it did and now I am reading you don't need lazy loading.  Is there a hello world that anyone has that is bare bones making nHibernate work?  Do you have to have lazy loading?  I ask because I would like to use nHibernate but I need to understand how things are working.
Thank you.
Do you know of a hello world that doesn't have so much overhead?
Is it better to use lazy loading?
EDIT:  I am using asp.net 3.5.  Web Application Project.

A:

I don't understand what you mean with "I did lazy loading". Lazy loading is a feature, it is turned on by default and you can turn it off if you don't like it.
There are two kinds of lazy loading: for references to other entities and for lists.
Given this entity:
class Entity
{
  // pk
  int id { get; private set; }

  // reference to another entity
  User MyUser { get; set; }

  // list to other entities
  IList<Comments> MyComments { get; set; }
}

Lazy loading on the reference to User
If you have lazy loading on the User, you need to define all members of the User class virtual. NHibernate will create a so called proxy. The proxy is a classed defined at runtime which derives from User. Your code is accessing it as User and is not aware that is is a subclass. But when you access one of its members the first time, the properties are loaded from the database.
If you want to turn off lazy loading on the User class, you need to do this in its mapping:
<class name="User" lazy="false"> ...

Then NHibernate creates always instances of type User, no proxies. You don't need to have anything virtual.
Lazy loading on the list of comments
If you use lazy loading on the list of comments, it is the list itself that implements the lazy loading. If you access the list the first time, it is loaded from the database. NHibernate uses a list that implements IList, but is not List.
If you want to turn off lazy loading in the list, you do this in the mapping of Entity:
<class name="Entity">
    <bag name="MyComments" lazy="false" >
        ...

Usually, lazy loading is a good thing, and you application does not have to care about it much. But there are some risks. For instance, if you serialize a instance, and it is a proxy, you get a not initialized proxy instead of anything useful. Lazy loading only works as long as the session is open. It is not always faster to use lazy loading. If you need to load all the data anyway, its faster to load it in one piece.
So the configuration needs to be done carefully.

Edit:
To answer your original question: Is lazy loading required for NHibernate? No. But: Is lazy loading required in my application? Most probably yes.
I think, only small and rather trivial applications don't need lazy loading. If you have a system with many persistent classes, you'll need lazy loading.

A:

If you're using hbm.xml files for you mapping simply adding a lazy="false" to the <class> element will get you non-lazy loading for all simple properties.  Foreign entities will still be lazy by default.  To make them eager add lazy="false" to the mapping element.  One benefit of eager loading is you will no longer need virtual properties on your entity classes.
Edit:
If you really want to find out what's going on behind the scenes, NHibernate logs everything using log4net. Adding
<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  <!-- Rest of config sections here -->
</configSections>
<log4net>
  <appender name="SQLFileAppender" type="log4net.Appender.RollingFileAppender, log4net">
    <param name="File" value="C:\Logs\SQL.log" />
    <param name="AppendToFile" value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <logger name="NHibernate.SQL" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="SQLFileAppender" />
  </logger>
</log4net>

inside <configuration> in your web.config will spit all the SQL NHibernate generates the file c:\logs\sql.log


Q:

grunt globbing except a file

I have a list of files:
 'app/scripts/module.js',
 'app/templates/templates.js',
 'app/scripts/**/*.js'

This will load app/scripts/module.js, app/templates/templates.js and then all the files under app/scripts/**/*.js except the one that was loaded before (module.js).
Now I want it to load another file located in app/scripts/a.js at the end of the list.
The problem is that when app/scripts/**/*.js is loaded, it already load app/scripts/a.js.
I want to write something like app/scripts/**/*.js (!a.js) - load all except a.js.
It this possible?

A:

You want to load 'a.js', but after the other scripts?
How about this, (pulled from the docs)
['app/scripts/**/*.js', '!app/scripts/**/a.js', 'app/scripts/**/a.js' ]

If you don't wish to load 'a.js', then just remove the last entry in the array.
['app/scripts/**/*.js', '!app/scripts/**/a.js']

http://gruntjs.com/configuring-tasks#globbing-patterns


Q:

Angular 2 RC1: Get parameters from the initial URL used

Some users enter my web app via invitations. so they would have a link that looks something like this: https://example.com/invitaion/12345 where 12345 is their unique invitation number.
When users click the link, and my AppComponent is initialized on the client side by the framework, how do I get the fact that the URL used was "invitation/*" and how do I get the invitation number?

A:

You'll want to use RouteParams to access that variable, and use it within your Component.
// let's assume you labeled it as `path : '/invitation/:id'` in your @Route setup.

@Route([
    { path : '/invitation/:id', component : MyComponent }
])

Now within the Component itself:
import { RouteParams } from '@angular/router';

// Now simply get the ID when injecting RouteParams within your constructor

class MyComponent {
    id: string;
    constructor(_params: RouteParams) {
        this.id = _params.get('id');
    }
}


Q:

MySQL JOIN to JSON array

I'm building a HTTP API and this part should return a JSON list of posts and their attached photos, like this:
[
    {
        "id": "788",
        "content": "Foo bar! Foo foo, bar bar.",
        "photos": [181, 282, 182]
    },
    ...
]

And this is my PHP code handling the request:
// get all the posts and their photos
$st = $db->prepare ('SELECT * FROM `posts` ' .
                    'LEFT JOIN `photos` ON `photo_post` = `post_id`');
$st->execute ();

// init our results array
$posts = array ();

// get the first post (plus it's JOINed photo)
$row = $st->fetch (PDO::FETCH_OBJ);
// if there's more left
while (false !== $row) {
    // init our post array
    $post = array (
        'id' => $row->id,
        'content' => $row->content,
        'photos' => array ()    // to fill with the photos
    );
    do {
        // don't add a `null` if there's no photos
        if (null !== $row->screenshot)
            $post ['photos'] [] = $row->photo_id;
    // get the row, repeat if it's another photo
    } while (false !== ($row = $st->fetch (PDO::FETCH_OBJ)) &&
             $row->id === $post ['id']);

    // add this post to the list
    $posts [] = $post;
}

// and send it back
echo json_encode ($posts);

Pretty simple JOIN parsing job, right?  But the code is anything but nice or simple!
How can I parse MySQL's JOIN results elegantly into the JSON heirarchy that I need?

A:

This is not vastly different but you might think its a little easier to read and follow and probably therefore debug.
With this code everything can be done within a single loop rather than the more complex multiple loop while/do that you originally used.
This also makes use of the stdClass provided by PHP to generate an array of objects as per your requirement, where your code was creating an array of arrays.
// get all the posts and their photos
$st = $db->prepare ('SELECT * FROM `posts` ' .
                    'LEFT JOIN `photos` ON `photo_post` = `post_id`');
$st->execute ();

// init our results array
$posts = array ();

$lastPostId = NULL;

// get the first post (plus it's JOINed photo)
while ( $post = $st->fetch (PDO::FETCH_OBJ) ) {

    if ( $lastPostId != $post->id ) {
        if ( $lastPostId !== NULL ) {
            // add this obj to the post array
            $posts[] = $tPost;
        }
        // start a new temp object
        $tPost          = stdClass();
        $tPost->id      = $post->id;
        $tPost->content = $post->content;
        $tPost->photos  = array();
    }

    // Add photo_id to current tPost obj
    $tPost->photos[] = $post->photo_id;

    $lastPostId = $post->id;
}

// and send it back
echo json_encode($posts);

A:

You can make use of MySQL's GROUP_CONCAT function which will return a comma separated list of photoIds. e.g. 1,2,3,4,5
If there are no photos, an empty string is returned. Explode returns an empty array if passed an empty string.
// get all the posts and their photos

$st = $db->prepare ('
    SELECT `posts`.post_id as id, `posts`.content, GROUP_CONCAT(`photos`.id) AS photoIds
    FROM `posts`
    LEFT JOIN `photos` ON `photo_post` = `post_id`
    GROUP BY `posts`.post_id
');

$st->execute ();

// init our results array
$posts = [];

$rows = $st->fetchAll (\PDO::FETCH_ASSOC);

foreach ($rows as $row) {
    $row['photos'] = explode(',', $row['photoIds']);
    $posts[] = $row;
}

// and send it back
echo json_encode ($posts);


Q:

Three diodes in series rectifier

So, I want to make AC 220V to DC 220v rectifier. Can I use two or three diodes in series, because the reverse voltage maximum of one diode is about 60 volts?

A:

220 V AV does not give you 220 V DC after rectification. The Peak voltage of 220 Vrms AC is 1.414 * 220 V = 311 V DC
Your diodes and smoothing capacitors should be able to handle that 311 V DC. Also the mains is only typically 220 V AC, at times 240 V AC or more is possible.
In practice you would use 400 V DC (or higher) rated components for a mains bridge rectifier and smoothing capacitors.
As mentioned in hatsunearu's answer using multiple diodes in series to get to the required reverse voltage rating is a bad idea. There will always be one diode in the series chain that is the weakest and at some point it will break through and that will also kill the other diodes. It is just not good practice.
Diodes with a high enough reverse voltage rating are available so use those.


Q:

Developing TypeScript without an installed IDE or editor

I work in a place that restricts me from downloading and installing any applications, regardless of job roles. I have several web apps that I want to migrate to Angular 2 with TypeScript. I'm a C# developer in my own time and TypeScript is very appealing as it's statically typed and just compiles down to JavaScript.
How can I develop with TypeScript without having access to an installed IDE or code editor? Are there any online environments that allow the use of TypeScript definition files that provide code help/intellisense?

A:

How can I develop with TypeScript without having access to an installed IDE or code editor

I am hoping you can do npm install typescript. If you can just run npm install typescript -g and then run typescript as tsc -w -p tsconfig.json in your code directory. This will allow you to run the compiler in the background leaving you free to use even notepad if you have to.
Alternatively you can just download the zip file from : https://github.com/Microsoft/TypeScript/releases and if you have node you can run node ./bin/tsc etc from the extracted directory.

A:

Use Codenvy:
It needs some manual tweaks but somebody figured them out already: https://groups.google.com/a/codenvy.com/forum/#!topic/codenvy/R4myXA9MygA


Q:

Best way to implement server side cache in Node JS

I'm trying to implement the server-side cache in Node JS, I've read about express-redis-cache, but how would this solution work with load balanced node servers? I might use something like AWS Redis Service, but it loses the whole purpose of using Redis on some external server as it increases latency. Can you suggest the best approach for this?
PS - I have some .md & .json files using which I generate the .html files and return. So, instead of doing this, I want to have some caching which will store this generated .html files. I'll update the cached content only when my .md & .json files are updated.

A:

I've read about express-redis-cache, but how would this solution work
  with load balanced node servers?

It wouldn't be a problem because all your load balanced node servers would connect to the same Redis host, which is fine.

I might use something like AWS Redis Service, but it loses the whole
  purpose of using Redis on some external server as it increases latency

It depends how you architect your app. If you are fully hosted on AWS, Elasticache is designed for this, latency would be minimal as connection will be  within the VPC which is fast. If you need to connect to elasticache from a client on premise, you still have options: VPN (not ideal) or DirectConnect which would be much faster than a VPN.
Having said that, if you are looking to cache  .html files
probably then look at CloudFront instead of a bespoke caching solution using Redis.


Q:

How to make Thymeleaf to process URL expressions in HTML comments

I've started to use Thymeleaf and came across following problem.
In my HTML template I have this piece of code:
  <!-- Thymeleaf -->
  <script src="../js/vendor/modernizr.js" th:src="@{js/vendor/modernizr.js}"></script>
  <!--[if lt IE 9]>
        <script src="../js/vendor/jquery-1.11.min.js" th:src="@{js/vendor/jquery-1.11.min.js}"></script>
        <script src="../js/helpers/polyfills.js" th:src="@{js/helpers/polyfills.js}"></script>
    <![endif]-->

When I open this in a browser, Thymeleaf is replacing URLs correctly for the first line, while for the part in [if lt IE 9], nothing is processed. Please compare:
<!-- Thymeleaf -->
  <script src="js/vendor/modernizr.js"></script>
  <!--[if lt IE 9]>
        <script src="../js/vendor/jquery-1.11.min.js" th:src="@{js/vendor/jquery-1.11.min.js}"></script>
        <script src="../js/helpers/polyfills.js" th:src="@{js/helpers/polyfills.js}"></script>
    <![endif]-->

How to solve this problem?

A:

You must use the Conditional Comments Extras Dialect.
You just add org.thymeleaf.extras.conditionalcomments.dialect.ConditionalCommentsDialect to your template engine and it will work out of the box!


Q:

ASP.net error INSERTING INTO SQL table

Okay I've come to an point where I have no idea what to do anymore, I've posted a question before and the result was a -3 in votes to close down the question, and in fear of that happening again kept me searching the  googleing till snapped... I've tried numerous code and every single time i get an error...
I've created a database about 6/7 times today and kept changing the connection string...
I've got a database with 3 tables, 1 table is called Company, now what I wanna do is I want to use 2 textboxes representing CompName and password and a dropdownlist representing businesstype.
I want to use these to enter information into the table, can someone please help me
Here's my code:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CompanyLogin : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        string ConnectionString =     System.Configuration.ConfigurationManager.ConnectionStrings["MyConncetionString"].ConnectionString;

        string sql = "INSERT INTO company (CompName, BusinessType, Pword) VALUES('" + txtCompName.Text + "','" + DropDownList1.Text + "', '" + txtPassword + "')";
        using (SqlConnection sqlconn = new SqlConnection(ConnectionString))
        {
            sqlconn.Open();

            using (SqlCommand command = new SqlCommand(sql, sqlconn))
            {
                command.ExecuteNonQuery();
            }
        }
    }
}

Error:

System.NullReferenceException: Object reference not set to an instance of an object.

on line:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConncetionString"].ConnectionString;

web.config:
<?xml version="1.0"?>
<configuration>
  <connectionStrings>
     <add name="Varsity_College.tempsConnectionString"
          connectionString="Data Source=JAUN-   PC\SQLEXPRESS;Initial Catalog=Varsity_College.temps;Integrated Security=True"
          providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
       ...... (irrelevant) ......
  </system.web>
  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

My error keeps POINTING TO

Line 17:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;*

A:

You have mismatch
MyConncetionString => replace with MyConnectionString
You can use
   cmd.CommandText =  "insert into company(CompName, BusinessType, Pword) Values(@CompName,@BusinessType,@Pword);"

    cmd.Parameters.AddWithValue("@CompName", txtCompName.Text);
    cmd.Parameters.AddWithValue("@BusinessType",DropDownList1.Text);
    cmd.Parameters.AddWithValue("@Pword",txtPassword );

    cmd.ExecuteNonQuery();


Q:

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

What does this error mean?, I keep getting this error, it use to work fine and it just started throwing this error.... any help?
img1.ImageUrl = ConfigurationManager.AppSettings.Get("Url").Replace("###", randomString)
 + Server.UrlEncode(((System.Web.UI.MobileControls.Form)Page.FindControl("mobileForm")).Title);

An exception of type 'System.NullReferenceException' occurred in
  MyProject.DLL but was not handled in user code
Additional information: Object reference not set to an instance of an
  object.

A:

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.
Given your statement:
img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString)
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.
You could easily break this out into multiple statements to solve the problem:
var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}


Q:

Testing for float equality in C

i have following code which gives strange output
#include<stdio.h>
void main()
{
 float a, x;
 a=6.7;
 if(a==6.7)
  printf("1\n");
 else
  printf("2\n");

 x=8.5;
 if(x==8.5)
  printf("1\n");
 else
  printf("2\n");

}

output
$ ./a.out
2
1

if i suffix numbers with f e.g. "6.7f" in if condition then i get proper output, I don't get why is this strange behavior?

A:

float has less precision than double, which would be the default type used for floating point literals. Since 6.7 cannot be represented with a finite number of binary digits, the less precise float representation does not equal the double representation.

A:

6.7 is a double, so when you say a=6.7 you're truncating a double to a float.
Because floating point numbers are stored in base 2, not base 10, it's impossible to represent 6.7 with complete precision. So when being truncated to a float, you lose a bit of information in this case. The same does not happen with 8.5, because 8.5 CAN be stored with complete precision in base 2.
Then, when you compare (a==6.7), you're comparing the different representations, which - as explained above - are not equal.

A:

Unsuffixed floating point literals are of type double, not of type float.
6.7    /* double */
6.7f   /* float  */


Q:

Tool for building intelligent agent?

Suggest me any open source based platform/IDE/framework/toolkit for developing intelligent agent. I don't have any background in this area, would like to use a tool or any tutorial in building intelligent agent.

A:

If you don't have any background at all, I suggest you start with something simple.
I had quite a good experience with dmangame, a simple Python engine where you can script the behaviour of agents.
The good point is that the installation is very simple, you know where to code your Python scripts for AI, there is a nice API for it. And you've got a nice graphical interface to see directly what you code.
Edit : By the way, look at this similar question


Q:

How can I use apply properly in R in this dataframe column?

I have a dataframe  column with NA, I want to how can I use  apply (or lapply, sapply, ...) to the column.
I've tried with apply and lapply, but it return an error.
The function I want to apply to the column is:
a.b <- function(x, y = 165){
  if (x < y)
    return('Good')
  else if (x > y)
    return('Bad')
}

the column of the dataframe is:
   data$col = 180 170  NA  NA 185 185
When I use apply I get:
apply(data$col, 2, a.b)
 Error in apply(data$col, 2, a.b) :
   dim(X) must have a positive length

I have try dim(data$col) and the return is NULL and I think it is because of the NA's.
I also use lapply and I get:
lapply(data$col, a.b)
Error in if (x < y) return("Good") else if (x > y) return("Bad") :
  missing value where TRUE/FALSE needed

This is for a course of R for beginners that I am doing so I am sorry if I made some mistakes. Thanks for taking your time to read it and trying to help.

A:

apply is used on a matrix, not a vector. Try:
a.b <- function(x, y = 165){
  if (is.na(x)){
    return("NA")
  } else if (x < y){
    return('Good')} else if (x > y){
    return('Bad')}
}
data$col=sapply(data$col,a.b)


Q:

Translation of 何かにつけて

父は何かにつけて、若いころ外国で過ごした思い出を語る。

Is this sentence best translated as "My father would sometimes talk about his memories as a young man travelling abroad".
If yes, what is the difference between 何かにつけて and something simpler like 時々、時に etc.?

A:

Is this sentence best translated as "My father would sometimes talk about his memories as a young man travelling abroad."?

I would definitely have to say NO.  The word choice of "sometimes" does not reflect the meaning and nuance of 「何かにつけて」 at all.
That translation basically says "Someone does something at a certain frequency."  It sounds very neutral and it is that neutrality that is the problem here because the expression 「何かにつけて」 is not neutral.  It is indeed fairly negative.
「何かにつけて～～する」 means "to never miss a chance (to do something)", "to take every opportunity (to do something)", etc.
This father speaks about his memories more often than his family want to listen.  That is the nuance of the original Japanese sentence and the expression 「何かにつけて」
.


Q:

How to change in Gradle time to live for artifact caches?

I am interesting in reducing time between refresh of SNAPSHOT versions of dependencies in Gradle.
How can I configure it and what is the default value?

A:

Snapshots treated in Gradle as changing modules.
There is an explanation available how to configure it in the Gradle documentation


Q:

Backing up an Oracle 10G Express on Windows 2000 Server

Oracle 10G Express installed on Windows 2000 Server Enterprise Edition.
I am trying to automate backups and on Oracle's website I have found the following documentation.
http://docs.oracle.com/cd/B25329_01/doc/admin.102/b25107/backrest.htm
Activate Archive Log

SQLPLUS -> CONNECT SYS/password AS SYSDBA
SHUTDOWN IMMEDIATE
STARTUP MOUNT
ALTER DATABASE ARCHIVELOG;
ALTER DATABASE OPEN;

Backup the Database
Then using the backup.bat file provided by Oracle: D:\oraclexe\app\oracle\product\10.2.0\server\BIN\BACKUP.BAT, I can backup the database either manually or with Scheduled tasks
Using a test server, I have been able to backup and restore the database using the backup.bat and restore.bat files provided.  I have not seen anything however about recycling those backups.
Questions:

Does Oracle provide a script to cleanup backup files that are no longer needed?
or What can I do to avoid filling up the D: drive with backup files?
Is there a better method to backup Oracle 10G Express?

Thank you

A:

I don't have the 10g version of Express Edition installed, but if it is like the 11g version, then your first question is answered in the comments section of the Backup.bat file itself.
For 11g this means the comments indicate that No cleanup script is needed because the script automatically keeps two backups in the Flash Recovery Area.  Whether there is a better method or not will depend on what your recovery requirements are.


Q:

Eastpak backpack as small luggage with Ryanair?

The dimensions permitted for Ryanair's small hand luggage are 35x20x20. An Eastpak backpack is about 45x38x11. Will it be allowed on board?
Please refer your personal experiences on this subject.
EDIT: What if I carry it nearly empty and folded into 2 parts, so that it'll fit? (I really need to take a backpack with me, but there's no room in my other luggage, that's why I'm asking these questions)

A:

45x38x11 cm is above the size that Ryanair say they will definitely allow in the cabin (35x20x20 cm) but below the maximum size of hand luggage (55x40x20 cm) so if it's your only piece of hand luggage you might be allowed to take it on, and if not it will be carried in the hold for free.
In my experience, when they insist that passengers gate check their luggage they are mainly looking for the big wheely suitcases which just fit in the cage at all. The main limitation is on overhead locker space, so if your bag looks like it will fit under the seat in front of you then you're probably OK.


Q:

Read one file name "Only" and skip to next directory - PHP

I have the following code which reads all filnames from each directory, but I want it to read one filename "only" and skip to the next directory.
<?php
$dir = "/images/";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
      echo "filename:" . $file . "<br>";
    }
    closedir($dh);
  }
}
?>

How can I read only one filename, then skip to the next directory to read "only" first filename and so on.  Please let me know if you require any more information.

A:

if it doesn't matter which file you read then just put a break; in your while loop or don't even go in a loop just take the $file = readdir($dh);
PS: In linux OS be aware of . and .. Also look up scabdir() function


Q:

OP_RETURN with bitcoind not working

I have created a raw transaction with the following hexstring which decodes to:
{
   "lock_time":0,
   "size":248,
   "inputs":[
      {
         "prev_out":{
            "index":1,
            "hash":"2fb04bcfcc164fbb9d5ad740c891e2599d904920386ab4e7f39bc1c87431218e"
         },
         "script":"483045022100c727a635fbd5e689888e60a10c6ce45855abb7ceeb2235004d815edae2555abb022059839448cdd52733280b6fdde09ee87b06ba090357e50fea178d8fe41d811ba9012103f515b50b5e7693b4d8fe3d5d25346f989b42ab43f65a0106808f844deff55f08"
      }
   ],
   "version":1,
   "vin_sz":1,
   "hash":"096328dc269ea7a060eb1c16ce8629cf81a5cff5766eb3f2ec97d81344854327",
   "vout_sz":3,
   "out":[
      {
         "script_string":"OP_DUP OP_HASH160 98ac2448db3e1a08cce87052513280cb20bafbf5 OP_EQUALVERIFY OP_CHECKSIG",
         "address":"1EvFvmzhiFWhaRfvvZupxxQvTMHJ79GGdb",
         "value":1,
         "script":"76a91498ac2448db3e1a08cce87052513280cb20bafbf588ac"
      },
      {
         "script_string":"OP_DUP OP_HASH160 f3223f468b6b81b4104b5b880d23b246c9c76711 OP_EQUALVERIFY OP_CHECKSIG",
         "address":"1PAaE9hEh1RNpoGuSJ6fw6wajziLptJSVv",
         "value":99998,
         "script":"76a914f3223f468b6b81b4104b5b880d23b246c9c7671188ac"
      },
      {
         "script_string":"OP_RETURN 68656c6c6f20776f726c64",
         "value":0,
         "script":"6a0b68656c6c6f20776f726c64"
      }
   ]
}

When I enter the command
bitcoind sendrawtransaction <hex-string>

I get the following message:
error: {"code":-26,"message":"64: dust"}

Will this be anything to with standard transactions? I am currently using 0.9.3 branch of the bitcoin client.

A:

The issue is this output:
  {
     "script_string":"OP_DUP OP_HASH160 98ac2448db3e1a08cce87052513280cb20bafbf5 OP_EQUALVERIFY OP_CHECKSIG",
     "address":"1EvFvmzhiFWhaRfvvZupxxQvTMHJ79GGdb",
     "value":1,
     "script":"76a91498ac2448db3e1a08cce87052513280cb20bafbf588ac"
  },

See the "value":1? That means that the output is worth 1 satoshi. It's worthless, because it would cost more to spend this than it's worth. See this answer for more.
To solve this, remove that output.


Q:

SQL Server Select from a table returned by a query as list of table names

If I have these tables below:
PLAYERS
ID    Name
==    ===========
1     Mick
2     Matt

COACHES
ID    Name
==    ===========
1     Bill
2     Don

And I have a script below to find all tables that has a column called "Name":
SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'

Which returns the following:
table_name
===========
PLAYERS
COACHES

How can I select all the rows from both tables returned by the query above?

A:

You will have to use dynamic sql, try something like this:
declare @t table( tablename varchar(50))
declare @sql varchar(max)
set @sql = ''

insert into @t
SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'

select @sql = @sql + 'Select * From ' + tablename + ' union ' from @t

--remove the trailing 'union'
Select @sql = substring(@sql, 1, len(@sql) - 6)

exec (@sql)

The above script creates and executes the following sql
select * from coaches
union
select * from players

Since we are using union here, it is important that all your tables that have name as column is of same structure.
See more about dynamic sql from http://msdn.microsoft.com/en-us/library/ms188001.aspx


Q:

What are the differences for left handed person when playing electric cello?

If I decide to buy an electric cello, should I look for a special one for left handed people, or I will even have to order a custom one?

A:

Short answer: for an electric cello, there is no basic difficulty in playing left-handed apart from the bridge and the nut, if you have already learned the cello left-handed.
Most electric cellos feature a wood bridge, and its arc shape and groves correspond to the fingerboard's shape and string gauges. The main custom thing you will need is the bridge but you might need a custom nut as well (depends on models). Any good luthier can fit you a new left-handed bridge for a reasonable fee. He or she might even like the challenge of doing something unusual. If your electric cello vendor can make it for you on order, its probably a good solution too, because he will know a few things about interaction with the amplification system. Having the right-handed bridge could be helpful if you want to sell it later.
Long answer
Orchestral string instruments such as violin, viola, cello, double bass are not symmetrical but this fundamental asymmetry is not seen at first glance and is mainly concerned with the acoustic properties of the cello body which are almost irrelevant for an electric cello.
I expand on this subject because at least one answer to this question is really misleading.

When you have a cello in front of you, the traditional setting has the bass side (C-String) on the left and the treble side (A-string) on the right.

Inside the cello, you have a soundpost on the right side blocked between the table and the back, and a so called bass bar (image taken from http://www.nowakviolins.co.uk/) glued on the table. These two devices are essential to enhance the resonance and amplification of the string vibrations by the cello body.

The fingerboard can be asymmetrical (one possibility is the Romberg shape, with a angled cut on the side of the C string) and with a varying scoop. You can have an idea of this shape here. Unfortunately, the Strad magazine is not online at this moment but there are many subtleties about fingerboard shaping that have been explained in its articles.
The bridge usually follows the ending shape of the fingerboard but not always (it is often asymmetrical in violins and violas, for ease of play and compensation of the position of the wrist, palm and fingers around the neck). It is anyway asymmetrical because the strings have different diameters and you have to be careful on the size of the groves they have to lie in.
The bridge transversal shape itself is asymmetrical. You cannot simply turn it by 180° with the same results.
The nut (that part of the cello just before the fingerboard where the strings pass just after the pegbox) has groves with size matching the string diameters. A damaged or badly fitting nut can cause parasitic sound on the strings. This is more dramatic on electric cello which are amplified.
Of course the pegbox and the position of the pegs is asymmetrical but the use of a given peg for a given string is more a matter of common sense and convention, not a problem when changing string order for left-hand playing.

So true left-handed cellos are different in many respects, and this is not only a matter of changing the string order. They are rarer than ordinary right-handed cellos but I do not like this terminology, because string playing requires as much ability and coordination from the two hands, and it is not always clear that a left-handed person might benefit in using its right hand for the fingerboard.  Anyway this is clearly a problem when playing in orchestra to play with the bow in the left-hand.


Q:

What is the difference between "Bisphosphate" and "Diphosphate" in biochemistry?

I have often found bisphosphate compounds ( e.g. RuBP, RuBisCO, 2,3-BPGA etc.) and diphosphate compounds (e.g. ADP, GDP etc.) in biochemistry. They are commonly seen and are important compounds in both animals and plants but what is the basic difference between a bisphosphate and a diphosphate?

A:

[Source:Wikipedia]
As you can see in the above structure of ADP(Adenosine di-phosphate), the two phosphate groups in the compound are directly attached to one another. So it is named as di-phosphate. [Source] You can see this table for more examples.

[Source:Wikipedia]
In this structure of RuBP(Ribulose-1,5-bisphosphate), the two phosphate groups in the compound are not directly attached to one another, they are attached to first and fifth carbon, meaning they are attached to different atoms. Therefore, it is named as bis-phosphate. [Source](2nd comment)


Q:

Conditional Stack Variables

Given the following function, will each of the local variables be declared on the stack?
std::string reallyCoolFunction(unsigned int a)
{
   if( a < 20 )
   {
     std::string result1 = "This function is really cool";
     return result1;
   }

   if( a >=20 && a <= 40 )
   {
     std::string result2 = "This function is kind of cool";
     return result2;
   }

   if( a > 40 )
   {
     std::string result3 = "This function is moderately cool";
     return result3;
   }

 std::string result4 = "This function really isn't that cool";
 return result4; // remove warning

}

In this situation, only one std::string is actually required, do all 4 get allocated on the stack, or does only 1 get allocated?

A:

The decision is up to the compiler: since the automatic variables go out of scope before the next one comes in scope, the compiler can re-use their memory. Keep in mind that "stack" variables are actually variables with automatic storage duration according to the C++ specification, so they may not be on the stack at all.

A:

On most compilers only one string will be allocated. Keep in mind though std::string uses dynamic memory so most of its content will still be allocated on the heap.

A:

Most probably 0 or maybe 1 (in Release) and certainly 4 (in Debug).
This is called the RVO: Return Value Optimization.
The compiler is actually allowed to elide the copy entirely and build the std::string directly in the slot provided by the caller. This is ABI specific, and as all optimizations only applies if a number of criteria are met; in your case it's probable that it will apply.
If you want to check, you can try to peruse the output of the compiler at various stages of its translation/optimization pipeline; it might be hard though depending on your toolchain.


Q:

Matrix / vectors notation

Is there any standard to represent Matrix / vectors symbols like using bold fonts, bar, underline or arrow notation?

A:

Different fields use different conventions. For instance, mathematicians frequently use lower case italic letters for vectors and upper case italic letters for matrices.
For physics and chemistry, IUPAP and IUPAC recommend (some journal guidelines are in agreement with this recommendation) a number of symbols for quantities that can be found in the following document:
E R Cohen et al., "Quantities, Units and Symbols in Physical Chemistry", IUPAC Green Book, 3rd Edition, 2nd Printing, IUPAC & RSC Publishing, Cambridge, 2008
In particular, the document recommends to typeset matrices and vectors with a bold italic font.


Q:

Understanding multiple instanton contributions to vacuum tunneling in a double potential well

I'm trying to understand the method of calculating the transition probability of one vacuum state to another in a double well potential, using instantons. The reference I am following is Sidney Coleman's book "Aspects of symmetry".
The approach uses the path integral formulation of QM and we look at the semi-classical limit of small $\hbar$. In this limit our path integral is dominated by the stationary points of the (euclidean) action. Solving the equation of motion I find an infinite number of single instanton solutions (each different by a shift of the time origin of the instanton) starting at one vacuum and ending at the other.

For example, if I took a potential of the form
$V = \lambda(x^2-a^2)^2~~~$   and define $~~~\omega^2 = 8\lambda a^2$
our solution to the E.O.M with $~x(-\infty) = -a~$ and $~x(\infty) = a~$  would be
$x(t) = a\tanh\left(\frac{\omega}{2}(t-t_c)\right)$
where $t_c$, the center of the instanton is arbitrary.

Coleman then introduces other "approximate stationary points" which are effectively instanton/antiinstanton chains which start at one vacuum and end at the other. Coleman then continues in his analysis by adding up all of these approximate stationary point contributions to the original single instanton stationary point term.
My question is the following: in what sense are these multiple instanton/antiinstanton solutions "approximate stationary points"? (Is there some limit I can take where it becomes exact, or could someone explain why these paths don't have a negligible contribution to the path integral unlike other paths?)

A:

The reason why classical solutions add a "lot" to the path integral is that their action (phase) is stationary i.e. almost the same phase as the action (phase) in their reasonably large vicinity of the configuration space; one gets positive interference as a consequence. More generic paths cancel with the adjacent ones whose phases are different and random.
The exact stationarity of the action means that one has classical solutions. One may also consider approximate solutions – configurations that solve the equations of motion up to relatively small errors – and for these approximate solutions, one still gets positive interference with nearby solutions but a less perfect one. The action is approximately stationary around these approximate solutions; $\delta S$ contains not only terms of order $[\delta x(t)]^2$ and higher powers but also $a\cdot \delta x(t)$ but the coefficients $a$ are very very small so that for certain purposes, it must be OK to approximate $a\sim 0$ and consider these things solutions (or stationary points).
For the instanton/antiinstanton chains, the error in these approximate solutions goes to zero if the instantons and antiinstantons are separated from each other by an infinite distance (by distance, I mean the $t$ direction in your purely-temporal example of kinks). When these chains of instantons and antiinstantons are really widely separated, the solution is almost exact: $x(t)$ almost completely reaches the ultimate stable points $\pm a$.
When the instantons and antiinstantons are closer to each other, the error by which this configuration fails to be a solution gets larger because the configuration forces $x(t)$ to revert the direction well before it reaches $x(t)=\pm a$ which means that some "additional acceleration" (violating the original equations of motion) had to be added. When the distance between the pieces of the chain gets infinite, one instanton in the chain is used almost in its full length and $x(t)$ gets almost as constant as it does for $|t-t_c|\to\infty$ for an antiinstanton which means that one may glue the instanton and antiinstanton.
Clearly, the approximation in which the chains are "solutions" is only good if $\omega\Delta t\gg 1$. We may replace $\gg$ by $\gt$ to define a convention of which configurations we allow. However, we must realize that there's no unique, systematic procedure to deal with these chains-of-instantons contributions. The importance of these chain configuration is that they're there and they surely do contribute something to the path integral while they're missed by all the perturbative terms; and missed by the single-instanton terms, too. So they're important for those processes for which they're important and for which the perturbative and one-instanton terms don't contribute much. The previous sentence is a tautology; but it's also meant as an encouragement to think because when one thinks a little bit, he may determine what kind of processes are sensitive to such things.


Q:

use code behind to pop aspx confirmation message

I need to return a confirmation message to OnClientClick event. The problem is I have to get the message from stored procedure, and I don't seem to call my function right.
 <asp:ImageButton
OnClientClick="return confirm(<%# GetConfirmExportMessage()%>);"
OnClick="btnExportRed_Click"
runat="server"
ImageUrl="~/Images/excel_red.gif"
ID="btnExportRed"
AlternateText="Export all records!"/>

My code behind:
public string GetConfirmExportMessage()
    {
        string xmlFilterForExport = Parameters.ToString().Split('+')[4].Trim();
        string alertMessage = companiesSearcher.GetAlertMessage(xmlFilterForExport, 1, null, null, IdSegment, 1, Convert.ToInt32(RoDB2004.BLL.clsUsers.UserID));

        return alertMessage;
    }

A:

Try using equal sign instead of pound (and don't forget your single quotes).
OnClientClick="return confirm('<%= GetConfirmExportMessage()%>');"

However, if you're ImageButton is located inside a DataGrid or GridView, the server-side code will not be evaluated and will yeield an alert saying <%= GetConfirmExportMessage()%> instead of the real message.
To get around this problem (and to increase performance, throughput, etc.), output your message once to a variable, then alert the contents of the variable.
<script language="JavaScript">
    var myMessage = '<%= GetConfirmExportMessage()%>';
</script>

Later, in the GridView...
OnClientClick="return confirm(myMessage);"

You save throughput by repeating a small variable name like "myMessage" and avoid repeating some big message.  Also note, that the method GetConfirmExportMessage isn't called dozens of times increasing performance.
If your message is specific to data within a current row and not static like "Are you sure?", then I suggest you perform this operation inside the GridView's RowDataBound event.  You'll have full access to the ImageButton and to the data the current row is binding to, which makes it very easy to setup server-side.  Check out the FindControl() method, or if you know the exact location, just reference it and unbox the object.
protected void gvMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ImageButton ibtn = (ImageButton)e.Row.FindControl("btnExportRed");
        if(ibtn != null)
        {
            ibtn.ClientClick = "return confirm('" + GetConfirmExportMessage() + "');";
        }
    }
}

As an alternative solution, maybe you should look into WebMethods, AJAX and jQuery.  This solution is probably the better one because the data is not sent to the client and only retrieved when necessary.


Q:

On delete cascade is not working

I have two table: users and 'bills'. In bills as a foreign key to users.
I want to automatically delete rows from the bills table when I delete from the users table. For that I alter table with following query, still it doesn't delete entry from bills table.
My alter statement is:
ALTER TABLE bills
ADD CONSTRAINT fk_pid
FOREIGN KEY (pid)
REFERENCES users(id)
ON DELETE CASCADE

here pid is foreign key in bills table, whereas id primary key in users table
Please help me to resolve above issue, thank you in advance.

A:

Use create instead of alter,Otherwise your syntax is ok
Create TABLE bills(
Your columns details
------
------
ADD CONSTRAINT fk_pid
FOREIGN KEY (pid)
REFERENCES users(id)
ON DELETE CASCADE
)

Try this..
If it's doesn't work then try for this thing as well.
if your both tables having mismatch primary key and foreign key problem then you cannot add Delete Cascade.For that you need to fix that key problem.like you don't have primary key value in your user table and you are using that same id in your bills table as a foreign key then you cannot add cascade in bills table.For that remove that key from bills table and then try your adding cascade script with Alter.I had same problem but i use this way and it worked.Hope it will work for you as well.Thanks


Q:

Android layout поверх другого

как можно наложить один layout поверх другого с итемами, чтобы первый перекрывал собой все, что есть?
<Button
    android:id="@+id/button_Inner"
    android:layout_width="150dp"
    android:layout_height="50dp"
    android:layout_below="@+id/textView_InnerClass"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:background="@drawable/button"
    android:onClick="goToNextActivity"
    android:text="Начать"
    android:textAllCaps="false"
    android:textSize="@dimen/text_size" />

<TextView
    android:id="@+id/textView_InnerClass"
    android:layout_width="268dp"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:lineSpacingExtra="3pt"
    android:textSize="@dimen/text_size" />

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"></RelativeLayout >

пробовал так поставить, но в итоге кнопка вылазит все равно, хотя textview с посаженным белым текстом не отображается

A:

Если задача в том, чтобы RelativeLayout покрывал все элементы до него (предполагаем, что внешний элемент для всех трех view - FrameLayout), то в целом, все работает правильно, что и показывает TextView, который прячется под RelativeLayout как нужно. Исключение составляет Button, почему он показывается поверх и как это исправить можно найти тут. Если кратко, нужно добавить строку к Button в XML:
android:stateListAnimator="@null"


Q:

Instance method, named_scope or association extension

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships

  def moderators
    # relationship_id is in the memberships table
    self.users.find(:all, :conditions => ['relationship_id = ?', 1])
  end
end

Given the above code, is this the best way to implement the moderators method?  My goal is to be able to find all the users with a "moderator" relationship within a given group.  Right now I can use the method to iterate over all the moderators
# ...
@group.moderators

I considered an association extension which makes sense to use here because I'm asking for a subset of users that meet a condition.  But the syntax seems redundant to ask for users that are moderators
# Association extension - seems redundant
@group.users.moderators

I considered a named_scope but I couldn't figure out how to implement it without errors.  Even if I could the named_scope will return all the moderators across all the groups which isn't what I want.
# named_scope: returns all the moderators across all the groups
moderators = Group.moderators

I'm wondering what the best practice here is and why I might want to us an association extension (or named_scope) over the instance method given that it allows for a more concise syntax?

A:

Add an association on Group class:
class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships

  has_many :moderators, :source => :user, :through => :memberships,
                :conditions => ['relationship_id = ?', 1]
end

Now you can do the following:
 @group.moderators
 @group.moderators.size
 @group.moderators.find_by_city(..)


Q:

I need a list of AdMob Functions SWIFT

I've looked all over google's AdMob site, I just want a list of all the inbuilt functions I can use for banners and interstitials.
eg. adViewDidReceiveAd() interstitialDidDismissScreen()
If anyone knows where I can find this, please let me know.

A:

This is bannerView functions where you have to implement GADBannerViewDelegate to be able to use it (don't forget to set the delegate for your banner as myBanner.delegate = self so they will be called).
func adViewDidReceiveAd(bannerView: GADBannerView!) {

}
func adViewDidDismissScreen(bannerView: GADBannerView!) {

}
func adViewWillDismissScreen(bannerView: GADBannerView!) {

}
func adViewWillPresentScreen(bannerView: GADBannerView!) {

}
func adViewWillLeaveApplication(bannerView: GADBannerView!) {

}
func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) {

}

And for interstitial delegates you will need to implement GADInterstitialDelegate to able to use it.(don't forget to set the delegate for your interstitlal as interstitial.delegate = self so they will be called).
func interstitialDidReceiveAd(ad: GADInterstitial!) {

}
func interstitialDidDismissScreen(ad: GADInterstitial!) {

}
func interstitialWillDismissScreen(ad: GADInterstitial!) {

}
func interstitialWillPresentScreen(ad: GADInterstitial!) {

}
func interstitialWillLeaveApplication(ad: GADInterstitial!) {

}
func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {

}

Implement these after class declaration, ex: class test:GADInterstitialDelegate {}


Q:

use macro enabled Excel file in OneDrive

I've created login_form that appears before worksheet and gets data (username or code) from login_form then filters inside Excel. Now I want to use this Excel file (.xlsm ) in OneDrive, that login_form will appear and users can use it on web (online). Is it possible?
And when users open this file in local, asks "enable macros" and "enable editing". Is there function that VBA automatically enables macros and editing in this file? Thanks in advance

A:

"Is it possible?"
Not really clear what you exactly mean by "use it on web (online)".
But fact is you need Excel to open an Excel file and use macros. Therefore you cannot do this online, but the users need to (temporarily) download that file and open it locally then.
"enable macros" and "enable editing"
These messages are for security reason! So nobody can run evil code on your computer without permission.
There is no way that you can enable macros at your users site.  But you can sign your code digitally with a certificate which …

… is generated by a trusted certificate authority (not free, need to pay).
… is generated by yourself (free).
But then your users need to trust that certificate once on their computer.

If the macros are digitally signed and the certificate is trusted you won't get the message to enable the macros.


Q:

How do I make curl ignore the proxy?

How do I make curl ignore the proxy?
Setting $NO_PROXY doesn't seem to work for me.

A:

If your curl is at least version 7.19.4, you could just use the --noproxy flag.
curl --noproxy "*" http://www.stackoverflow.com

From the manual.

A:

I ran into the same problem because I set the http_proxy and https_proxy environment variables. But occasionally, I connect to a different network and need to bypass the proxy temporarily. The easiest way to do this (without changing the environment variables) is:
curl --noproxy '*' stackoverflow.com

From the manual: "The only wildcard is a single * character, which matches all hosts, and effectively disables the proxy."
The * character is quoted so that it is not erroneously expanded by the shell.

A:

I assume curl is reading the proxy address from the environment variable http_proxy and that the variable should keep its value. Then in a shell like bash, export http_proxy=''; before a command (or in a shell script) would temporarily change its value.
(See curl's manual for all the variables it looks at, under the ENVIRONMENT heading.)


Q:

How to prevent image disappear when another image is dropped on it

I want to create page where I can move images between divs. I can move images over other divs and back. The problem is that if I move one image over another, the "another" image disappear. I am looking for some way to prevent this.

    function allowDrop(event)
    {
        event.preventDefault();
    }
    function drag(event)
    {
        event.dataTransfer.setData("text", event.target.id);
    }

    function drop(event)
    {
        event.preventDefault();
        var imgData = event.dataTransfer.getData("text");
        event.target.appendChild(document.getElementById(imgData));
    }

CodePen here
I expect that if I move image over another image, it will not move but stay in div where it is currently located.
Thank you for your time.

A:

You need to clone the original element and create a new node, otherwise it will just moved over.
function allowDrop(event)
{
  event.preventDefault();
}
function drag(event)
{
  event.dataTransfer.setData("text", event.target.id);
}

function drop(event)
{
  event.preventDefault();
  var imgData = event.dataTransfer.getData("text");
  var newNode = document.getElementById(imgData).cloneNode(true);

  clearChildren(event.target);
  event.target.appendChild(newNode);
}

function clearChildren(el) {
  while (el.firstChild) {
    el.removeChild(el.firstChild);
  }
}