text:
Q: System.IO exception? I have Winforms insight have one picture box.  When I double click, my logic writes (using stream class) a picture and then stores one in the system folder.  When I am trying to write, I get an error like "can't access file; it's being processed by another process".
How can I overcome this problem?

A: Make sure to close your stream after each write.

A: A few tips:

*

*Restart your machine, see whether it still has the same problem.

*Try to disable the previous write in your code, see whether it is the previous writes that  locks the file resources.

A: Does it happen when you write the first or the second time? If it's the second time, you have probably forgotten to dispose or close something. If you have loaded an image from that file, you must dispose the image before you can write to its file, sine an image ownd the stream it was loaded from.

A: System folder? Trying to overrite a system file (most likely to be write-locked)?


text:
Q: TWilio-Forward incoming SMS to emails in Rails5 I wanna forward all incoming messsages from my virtual twilio number to email
I am trying to add a webhook from the phone number settings but I didn't find any option in the Messaging service dropdown.
And after adding this how to handle the controller code to forward sms to email.
I am using twilio-ruby gem and RAILS-5

A: Twilio developer evangelist here.
A Messaging Service is a:

higher-level "bundling" of messaging functionality around a common set of senders, features, and configuration. The same settings and feature configuration applies to all of the senders (long code numbers, short codes, toll-free numbers, etc.) in the Messaging Service's pool.

So that is not the setting you are looking for in this case.
To edit the webhook URL, you need to look further down the page. You currently have an ngrok URL set as the webhook when this number receives an incoming message. This is what you should change if you want to update it.

As for receiving the messages in your Rails controller, I recommend reading this blog post on receiving and replying to SMS messages with Rails.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot send session cache limiter, what am i missing? can someone please tell me what Im missing? this simple script
<?
session_start();
?>

displays the following error message:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\test3\index.php:1) in C:\xampp\htdocs\test3\index.php on line 2

thanks.

A: It may be a Byte Order Mark generated by your text editor.

A: Check if there are any whitespaces before <?
If there is any output before session_start() - it will not work

A: session_start(); should be the first thing on  your page. Before any text, or spaces. Nothing should precede it in your page.
<?php

  session_start();

  /* code here */

?>


text:
Q: My app not showing in mobile I am running my App on my mobile through data cable . the app runs fine but does not show in the Apps on the mobile. It shows up in the application manager but no icon and no link to the app in the apps section . what could be the fault here.
kindly update
Manifest file
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.intel.myapplication.alumni2">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application android:allowBackup="true" android:label="My App"
        android:icon="@drawable/ic_launcher" android:theme="@style/AppTheme"
        android:name=".MyApplication">

        <activity android:name=".Welcome">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>

            </intent-filter>
        </activity>
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="meriapp"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>
        </activity>
        <activity android:name=".Registration">
            <intent-filter>
                <action android:name="meriapp"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>
        </activity>
        <activity android:name=".Slider">
            <intent-filter>
                <action android:name="meriapp"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>
        </activity>

        <activity android:name=".Alumni">
            <intent-filter>
                <action android:name="meriapp1"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>

        </activity>

        <activity android:name=".Student">
            <intent-filter>
                <action android:name="merapp1"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>

        </activity>
        <activity android:name=".Authentication">
            <intent-filter>
                <action android:name="merapp1"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>

        </activity>

        <activity android:name=".Register_submit">
            <intent-filter>
                <action android:name="meriapp1"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>
        </activity>
       <!-- <activity android:name=".College_update">
            <intent-filter>
                <action android:name="meriapp1"/>
                <category android:name="android.intent.category.DEFAULT"/>

            </intent-filter>

        </activity>-->

    </application>

</manifest>

A: You need to declare at least one of your activities in the manifest as the main launcher one for it to appear in the apps menu. To do so, add the following to the activity element:
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Notice the all caps LAUNCHER. The manifest you posted has it as Launcher.

A: When you're running you're app in debug mode or in release (via APK for example) it IS shown in you're app list. I'm sure you are looking on the wrong application name, or you missed it.
It just happens.

A: Check your manifest.xml file, weather you have write the below lines or not?
       <activity
            android:name="com.example.restaurent.MainActivity"
            android:label="@string/app_name"  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

A: Add the android:label="My App" tag in your launcher activity, this may help you.


text:
Q: Query not returning expected results group by I am going a little crazy here. I was wondering if may be someone could help me understand why this query is not returning expected results
SELECT
  last_name,
  first_name,
  DATE_FORMAT((tm_date), '%Y-%m-%d') AS dates,
  SUM(tm_hours) total
FROM timecard
LEFT JOIN teachers i
  ON i.ds_id = timecard.ds_id
WHERE tm_notes != 'Lunch Break'
AND tm_date BETWEEN '2018-04-16' AND '2018-04-30'
AND timecard.ds_id = '4'
GROUP BY CONCAT(YEAR(tm_date), '/', WEEK(tm_date)),
         timecard.ds_id
ORDER BY last_name ASC, dates ASC

This query will return the first record as if the week started on 2018-04-20 but it should be 2018-04-16. When I run this query for other users timecard.ds_id the query always returns 2018-04-16 as the first record I don't understand why with this particular user its showing 2018-04-20.
this are the results

this is sample data

Thank you

A: Here's the MySQL documentation for what Terminus specifies. It's worth reading. https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

If ONLY_FULL_GROUP_BY is disabled, a MySQL extension to the standard SQL use of GROUP BY permits the select list, HAVING condition, or ORDER BY list to refer to nonaggregated columns even if the columns are not functionally dependent on GROUP BY columns. This causes MySQL to accept the preceding query. In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic, which is probably not what you want. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Result set sorting occurs after values have been chosen, and ORDER BY does not affect which value within each group the server chooses. Disabling ONLY_FULL_GROUP_BY is useful primarily when you know that, due to some property of the data, all values in each nonaggregated column not named in the GROUP BY are the same for each group.

A: Since it's grouping by week, you may not always get the result you're looking for. If you want the earliest result, then use MIN
DATE_FORMAT(MIN(tm_date), '%Y-%m-%d') AS dates,

A: When selecting a column not included your group by clause and not fed to an aggregate function, MySQL picks an arbitrary tm_date row from the grouped rows. (This is a setting; you can change it and MySQL will throw an exception)
You have to tell MySQL what you want. I think MIN works here.
DATE_FORMAT(MIN(tm_date), '%Y-%m-%d') AS dates,


text:
Q: Number of unique values in columns in two pandas dataframe I have two pd.DataFrame objects (read from .csv file), say,
1, 2
1, 3
2, 4

and
2, 1
1, 2
3, 3

Suppose the DataFrame's are named as data1 and data2. So I can easily count the number of unique values in each column of data1 and data2 individually using
 uniques = data.apply(pd.Series.nunique)

data is replaced by data1 and data2 respectively. So I will get 2, 3 for data1 and 3, 3 for data2. Is there a way (other than concatenating the DataFrame's) so that I can get the number of unique values when these two DataFrame's are combined? I want to get 3, 4.

A: I think not. Need concat first:
df = pd.concat([df1,df2]).apply(pd.Series.nunique)
print (df)
a    3
b    4
dtype: int64

A: #use numpy unique to count uninues after combining same columns from both DF.

len(np.unique(np.c_[df1.iloc[:,0],df2.iloc[:,0]]))
Out[1398]: 3

len(np.unique(np.c_[df1.iloc[:,1],df2.iloc[:,1]]))
Out[1399]: 4

A: Another alternative that will work for any number of data frames:
dfs = [df1, df2]
print([
    len(set(np.concatenate([df[colname].unique() for df in dfs])))
    for colname in dfs[0]
])
[3, 4]

Note that this will only work if all the data frames have the same column names.
I think that concat is the best option, unless your data frames already fill your local memory: concatenating will copy


text:
Q: how to use model1 reference in model2 so that changes in model1 reflects in model2 automatically I have two model group model and user model
user model :
var mongoose    =   require('mongoose');
var userSchema  = mongoose.Schema({
     profilePic : String,
     firstName  : String,
     lastName   : String,
     dateOfBirth_DateObject     : {
        type : Date ,
        default : Date(1994-03-18)
     },
     yearOfBirth_Integer : {
        type : Number,
        default : 0
     },
     monthOfBirth_Integer  : {
        type : Number,
        default : 0
     },
     dayOfBirth_Integer : {
        type : Number,
        default : 0
     },
     gender_String  : String
)};
module.exports = mongoose.model('user', userSchema,'user');

group model :
var mongoose       =   require('mongoose');
var groupSchema    =   mongoose.Schema({
   members      :   [{
        id      :   {
           type : mongoose.Schema.Types.ObjectId,
           ref  : 'user'
        },
        firstName   :   String,
        lastName    :   String,
        profilePic :    String

    }]
});

module.exports     =    mongoose.model('group', groupSchema,'group');

so when user uploads new profile pic, url of that pic has been saved in user model but profile pic of that user should also automatically change in group members array.

A: You just need to change your schema into
var groupSchema = mongoose.Schema({members : [{
    id      :   {
       type : mongoose.Schema.Types.ObjectId,
       ref  : 'user'
    },
    otherprop1:   String,
    otherprop2  :   String,

}]});

Then use populate to get user data in find
group.find({}).populate({path:"user", select: "firstName lastName profilePic"})


text:
Q: Identifying signed and unsigned values in assembly I always find this confusing when I am looking at the disassembly of code written in C/C++.
There is a register with some value. I want to know if it represents a signed number or an unsigned number. How can I find this out?
My understanding is that if it's a signed integer, the MSB will be set if it is negative and not set if it is positive. If I find that it's an unsigned integer, the MSB doesn't matter. Is this correct?
Regardless, this doesn't seem to help: I still need to identify if the integer is signed before I can use this informatin. How can this be done?

A: In general, you won't be able to. Many things that happen to integral values happen the same way for signed or unsigned values. Assignment, for example. The only way to tell is if the code happens to be doing arithmetic. You absolutely can't tell by looking at the value; all possible bit patterns are valid either way.

A: In most processors (at least those that use two's complement math), there is no inherent sign-ness for the integers stored in registers or memory. The interpretation depends on the instructions used. A short summary:

*

*Addition and subtraction produce exactly the same bit patterns for signed and unsigned numbers, so usually there is no signed addition or subtraction. (Hovewer, MIPS has separate instructions which cause a trap if the operation overflows).

*Division and multiplication does produce different results for signed vs. unsigned numbers, so if the processor supports it, they come in pairs (x86: mul/imul, div/idiv).

*conditional branches also may differ depending on the interpretation of the comparison result (usually implemented as subtraction). For example, on x86 there is jg for signed greater and ja for unsigned above.
Note that the floating-point numbers (at lease IEEE format) use an explicit sign bit, so the above does not apply to them.

A: Your best bet is too look for comparisons and associated actions/flag usage like a branch. Depending on the type the compiler will generate different code. As most (relevant) architectures provide flags to deal with signed values. Taking x86 for example:
jg, jge, jl, jle = branch based on a signed comparison (They check for the SF flag)
ja, jae, jb, jbe = branch based on a unsigned comparison (They check for the CF flag)

Most instructions on a CPU will be the same for signed/unsigned operations, because we're using a Two's-Complement representation these days. But there are exceptions.
Lets take right shifting as an example. With unsigned values on X86 you would use SHR, to shift something to the right. This will add zeros on on every "newly created bit" on the left.
But for signed values usually SAR will be used, because it will extend the MSB into all new bits. Thats called "sign extension" and again only works because we're using Two's-Complement.
Last but not least there are different instructions for signed/unsigned multiplication/division.
idiv or one-operand imul = signed
div or mul/mulx = unsigned

As noted in the comments, imul with 2 or 3 operands doesn't imply anything, because like addition, non-widening multiply is the same for signed and unsigned.  Only imul exists in a form that doesn't waste time writing a high-half result, so compilers (and humans) use imul regardless of signedness, except when they specifically want a high-half result, e.g. to optimize uint64_t = u32 * (uint64_t)u32.  The only difference will be in the flags being set, which are rarely looked at, especially by compiler-generated code.
Also the NEG instruction will usually only be used on signed values, because it's a two's complement negation.  (If used as part of an abs(), the result may be considered unsigned to avoid overflow on INT_MIN.)


text:
Q: Primefaces datatable is not showing one column header after ajax (the column rows ares showed) The datatable show this column (and others):

        <f:facet name="output"  >
              ...
        </f:facet>
        <f:facet name="input">
              ...
        </f:facet>

ajax update the data table:

but the column header of this column is not showed after ajax updates.
The column rows and footer are showed ok and the headers of columns at right are shifted one column to left.
Before ajax, the html rendered is:
Header Text

But the code after ajax update is:
Header Text

Other columns are ok but they don't have rendered attribute.

A: Put this in your datatable:

This is a header's of your table...after put your columns.
Here there a example: http://www.primefaces.org/showcase/ui/datatableGrouping.jsf
By.


text:
Q: Ошибка при выполнении gitsync При выполнении команды gitsync возникает ошибка: Index was out of range. Must be non-negative and less than the size of the collection. Была старая версия Git 2.21.0, обновление не помогло. Подскажите, как исправить данную проблему?
Версия Git 2.31.1


text:
Q: Unstoppable script Issue I have a script wich uses several mousemoves and, when needed, I press F3 to stop the moves forcing a reload or ESC to stop the moves exiting the app. It works fine with no issues in the regular speed.
The problem is: when I decrease the mousespeed and increase the mousedelay, the script becomes unstoppable: I press the F2, F3 and ESC keys several times (trying to make it stops) but the script ignores it and continues running the mousemoves.
Here's a minimal example of my problem:
SendMode Input

$F1::
SetDefaultMouseSpeed, 50
SetMouseDelay, 30

Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600
Mousemove, 200, 200
Mousemove, 600, 600

SoundPlay, *48
return

$F2:: Pause
$F3:: Reload
$ESC:: ExitApp

Why does it happens and how can I fix it (how can I stop the script even with low speed+high delay)?
ps: F1 key starts the mousemoves sequence.

A: MouseMove with non-zero speed cannot be interrupted by another hotkey inside the same AHK script because Autohotkey is single-threaded internally (it just emulates thread-like behavior) and performs a blocking sleep for each mouse micromovement until it reaches the overall distance you specified.
Solutions:

*

*Check whether a hotkey was pressed after each MouseMove, but it's non-instantaneous;

*Implement your own MouseMove that checks GetKeyState after each 1px movement;

*Use a master script with hotkeys that run/pause/stop the child:
Stopping: trivial, use Process Close
Running: the child should hide tray icon otherwise it'll stay after process close
Pausing: nontrivial but there are solutions (see also the underlying mechanics).


text:
Q: word won't put diacritics before other character is typed I've got a problem with one of the computers I use (running Win7 Pro x64  with Office 2007). Word won't let me type any diacritics (like AltGr+a = ą, AltGr+e = ę, etc) before any other character is typed. Surprisingly typing any other combination of AltGr does work, so i.e. AltGr+r gives the ® symbol etc.
What's more, I'm also unable to put any diacritics once I move cursor to another place in a document, no matter whether the document has been just opened, or just written from the very beginning.
I've tried changing the language settings not only in Office, but also in Windows, but it didn't help. Strange enough, the problem does not occur in any other program, nor in the system itself.
If possible, I'd like to solve this without having to reinstall Office, since I don't have admin rights and the administrator is currently unavailable.
EDIT:
I'm using polish version of Office 2007 with default settings (using polish programmers keybord layout)
And yeah, I mean AltGr, sorry for mistake


text:
Q: MariaDB sort string value with faction I have Linux kernel version like below, want to sort this value from kernel version oldest to latest.
4.18.0-348.7.1.el8_5.x86_64
4.18.0-358.el8.x86_64
4.18.0-305.19.1.el8_4.x86_64
4.18.0-348.12.2.el8_5.x86_64
4.18.0-348.7.1.el8_5.x86_64

Using this query, its not sorting by kernel version. I expect this line 4.18.0-348.12.2.el8_5.x86_64 should come above last line.
select kernel, REGEXP_REPLACE(kernel,'\\.|-|el.*$','') as k from os  group by kernel order by 1;

4.18.0-305.19.1.el8_4.x86_64,4180305191
4.18.0-338.el8.x86_64,4180338
4.18.0-348.12.2.el8_5.x86_64,4180348122
4.18.0-348.2.1.el8_5.x86_64,418034821
4.18.0-348.7.1.el8_5.x86_64,418034871
4.18.0-358.el8.x86_64,4180358

How to make this sql query sort by kernel version?

A: MariaDB in 10.7 had a successful trial of natural_sort_order, soon to be a GA release:
MariaDB [test]> create table v( version varchar(30));
Query OK, 0 rows affected (0.002 sec)

MariaDB [test]> insert into v values ('4.18.0-348.7.1.el8_5.x86_64'),('4.18.0-358.el8.x86_64'),('4.18.0-305.19.1.el8_4.x86_64'),('4.18.0-348.12.2.el8_5.x86_64'),('4.18.0-348.7.1.el8_5.x86_64');

MariaDB [test]> select version from v order by natural_sort_key(version);
+------------------------------+
| version                      |
+------------------------------+
| 4.18.0-305.19.1.el8_4.x86_64 |
| 4.18.0-348.7.1.el8_5.x86_64  |
| 4.18.0-348.7.1.el8_5.x86_64  |
| 4.18.0-348.12.2.el8_5.x86_64 |
| 4.18.0-358.el8.x86_64        |
+------------------------------+
5 rows in set (0.001 sec)

ref: has natural_sort_order

A: How about like this:
SELECT kernel,
       k1, k2, k3,
       CASE WHEN k3 LIKE '%-%' THEN 0
        ELSE SUBSTRING_INDEX(k3,'.',1)+0 END AS k4,
       CASE WHEN k3 LIKE '%-%' THEN 0
        ELSE SUBSTRING_INDEX(k3,'.',-1) END AS k5
FROM
(SELECT kernel,
       SUBSTRING_INDEX(kernel,'-',1) AS k1,
       SUBSTRING_INDEX(SUBSTRING_INDEX(kernel,'-',-1),'.',1) AS k2,
       SUBSTRING_INDEX(SUBSTRING_INDEX(kernel,'.el',1),'.',-2) AS k3
 FROM
    os) V
ORDER BY
  k1, k2, k4, k5
;

With a bunch of SUBSTRING_INDEX() used starting from the subquery. The idea is to separate a few of the parts from the value where I see it's "orderable". The query above will return the following:

kernel
k1
k2
k3
k4
k5

4.18.0-305.19.1.el8_4.x86_64
4.18.0
305
19.1
19
1

4.18.0-338.el8.x86_64
4.18.0
338
18.0-338
0
0

4.18.0-348.2.1.el8_5.x86_64
4.18.0
348
2.1
2
1

4.18.0-348.7.1.el8_5.x86_64
4.18.0
348
7.1
7
1

4.18.0-348.12.2.el8_5.x86_64
4.18.0
348
12.2
12
2

4.18.0-358.el8.x86_64
4.18.0
358
18.0-358
0
0

Demo


text:
Q: local work but hosting on AppHarbor can not query SQL Server So I have my web.config connection string pointing to my SQL Server on appharbor - from local (running Visual Studios) I can login and the memberships works. However from the build that is on the hosting side I get sorry, an error occurred while processing your request.
This is strange because I made a new user from local and check with SQL Server Management Studio whether or not the data has been added to the hosting server and it WORKS.
From my latest build I get the error:

Sorry, an error occurred while processing your request.

which is weird because they both point to the same server...
Anyone have an idea of what I am doing incorrectly?

A: ASP.NET MVC project has the "HandleErrorAttribute" on by default. You should remove it from FilterConfig.cs in App_Start Folder to see the actual error rather than the handled response.
It's located in the RegisterGlobalFilters method where filters.Add(new HandleErrorAttribute()); should be removed.

A: AppHarbor has a FAQ to help you troubleshoot deployment errors like these. In particular, you should inspect the "Errors" interface on AppHarbor and disable customErrors. Please elaborate the question if the FAQ doesn't help you solve the problem.


text:
Q: Meaning of sentence with "vercingetorism" This remark was made on an online forum.  Preliminary online search was of not much help.

(D)id you intend to deal with all this vercingetorism?

This is certainly not a word from one of those obscure domains like psychology, medicine, etc., I hope.
What does the above expression mean?

A: It is probably a word derived from Vercingetorix, the chieftain of the Gallic tribe of the Arverni. Your example could instead read:

... deal with all this formidable opposition.


text:
Q: How to read Inverse Pole Figures (IPF) images When (Electron BackScatter Diffraction) EBSD maps are procesed the output crystallographic orientation is derived into Euler map and three Inverse pole figures (IPF) maps.
In the example there is IPF-Y image of ferrite/cementite structure, large areas are ferritic, the "random pixels" are affiliated with cementite.

My question is, what information I can read from such images?

*

*There are three IPF-x maps, all with colourmap and Miller indices. Miller indices describe position of a plane in respect to crystallographic axes.*

*Can be red-coloured grain assigned to Miller indices of (001) and the Blue ones to (111) directly?

*If the colour is somewhere in the map, say it has coordinates $[r,g,b]=[0.1, 0.3, 0.6]$ can we assume that the miller indices would be:
$$r\cdot(001)+g\cdot(101)+b\cdot(111)=(0,0,1)+(3,0,3)+(6,6,6)=(9,6,10)$$

(*) In X-Ray Diffraction (XRD) the plane conidered is the sample surface or plane parallel to the sample holder. In symmetric crystals, like cubic, the planes (1,0,0), (0,1,0) and (0,0,1) are considered equal and labeled as (1,0,0) only.


text:
Q: Sending email inside a docker container to hosts smtp running postfix On a server I run both docker images and a postfix smtp server. The smtp server is accesible via localhost and is not installed in any sort of container.
The problem is that I can send email via terminal using sendemail outside of any container but I cannot send email via terminal running sendemail inside of any container.
The postfix configuration is the following:
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/letsencrypt/live/ellak.org/fullchain.pem
smtpd_tls_key_file= /etc/letsencrypt/live/ellak.org/privkey.pem

smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = guest8.ellak.gr
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = mail.ellak.org, guest8.ellak.gr, localhost.ellak.gr, localhost

#Virtual alias domains
virtual_alias_domains = ellak.org

# RELAY Options
relayhost = [mail1.ellak.gr]:587
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

smtp_use_tls = yes
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
local_recipient_maps = proxy:unix:passwd.byname $alias_maps
smtp_tls_note_starttls_offer = yes

#Network Access Options

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 172.17.0.0/16
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
relay_domains = *

Inside the container I run:

sendemail -s 172.17.0.1:25 -f no-reply@ellak.org -t
  katanophoros@gmail.com -u Hello -m Hello

And outputs the following error:
Nov 27 19:51:14 7e56b4e22e09 sendemail[1988]: WARNING => The recipient <katanophoros@gmail.com> was rejected by the mail server, error follows:
Nov 27 19:51:14 7e56b4e22e09 sendemail[1988]: WARNING => Received:  454 4.7.1 <katanophoros@gmail.com>: Relay access denied
Nov 27 19:51:14 7e56b4e22e09 sendemail[1988]: ERROR => Exiting. No recipients were accepted for delivery by the mail server.

On the postfix logs I get are:
Nov 27 21:42:54 guest8 postfix/smtpd[14979]: NOQUEUE: reject: RCPT from unknown[172.18.0.5]: 454 4.7.1 <katanophoros@gmail.com>: Relay access denied; from=<no-reply@ellak.org> to=<katanophoros@gmail.com> proto=ESMTP helo=<7e56b4e22e09>
Nov 27 21:42:54 guest8 postfix/smtpd[14979]: lost connection after RCPT from unknown[172.18.0.5]
Nov 27 21:42:54 guest8 postfix/smtpd[14979]: disconnect from unknown[172.18.0.5]
Nov 27 21:46:14 guest8 postfix/anvil[14982]: statistics: max connection rate 2/60s for (smtp:172.18.0.5) at Nov 27 21:42:54
Nov 27 21:46:14 guest8 postfix/anvil[14982]: statistics: max connection count 1 for (smtp:172.18.0.5) at Nov 27 21:42:41
Nov 27 21:46:14 guest8 postfix/anvil[14982]: statistics: max cache size 1 at Nov 27 21:42:41

Do you have any sort of Idea how I will send emails inside docker containers?

A: 172.18.0.5
is not included in
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 172.17.0.0/16
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 172.16.0.0/12
this includes all private 172.16 subnets.


text:
Q: Prettier date formats in Rails? I know I can manually make the date formats however I want with strftime, but are there any easy ways to quickly make dates look nicer than the :short, :long, :long_ordinal formats? The :long_ordinal looks nice but then doesn't have AM/PM, uses military time:
September 11th, 2013 14:00 instead of September 11th, 2013 2:00 PM.
Ideally there's a kind of :long_ordinal_prettier format that has the 2:00 PM mechanism here in America and pretty local dates elsewhere in the world.

A: Create a file like config/initializers/date_formats.rb
Date::DATE_FORMATS.merge!(
  long_date: '%a, %B %e, %Y %l:%M %p',
  short: '%A, %B %e, %Y',
  hyphen: "%Y-%m-%d",
  long_ordinal_prettier: "....."
)

You can use them like this
some_model.created_at.to_formatted_s(:long_ordinal_prettier)


text:
Q: How to create a blob containing an arbitrary octet in Javascript I am trying to understand how the Blob object can be used to programmatically create binary files on a byte by byte level in client-side javascript. As a way of building up my know how I am trying to create a single byte blob that contains the following octet: 00000001. Simple right? Unfortunately, I haven't been able to figure out how to do so. Below is the first iteration of my code:
let downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', function(){
  var myBlob = new Blob([1], {type : "octet/stream"});
  url = window.URL.createObjectURL(myBlob);
  let a = document.createElement('A');
  a.href = url;
  a.download = "testFileOctet";
  a.click();
});

I'm not surprised that this doesn't produce the desired bit sequence '00000001' when viewed in a hex editor. I am however surprised that it outputs 00110001 which is the UTF-8 character encoding of '1'. I know that because javascript is weakly typed all numbers are represented as 64-bit floating points so I would have understood if I had a large 64-bit sequence. Or I would have understood if I had specified the MIME type as 'text/plain' instead of 'octet/stream' and had gotten the UTF-8 encoding output.
As it stands, however, I am at a loss... I even attempted some variations where I changed the array being fed into the Blob constructor. Instead of [1] I tried [0x1]. Same result. I tried [0b00000001]. Same result.
So. What am I doing wrong and how is byte-level file creation possible in client-side javascript? Is this a problem with the way I am using the Blob constructor or is it perhaps something to do with the URL encoding that I am using to get the Blob out of the browser? Any help would be much appreciated

A: The Blob() constructor expects a possibly mixed list of Blob-parts, ArrayBuffer or USVStrings.

*

*Blob-parts are other Blob objects.

*ArrayBuffer are either ArrayBuffer objects, or the .buffer property of a TypedArray you would pass in the list.

*USVStrings are more like UTF-8 Strings.

In your case, new Blob([1]) , the Number 1, being neither a Blob, nor an ArrayBuffer or TypedArray will get coerced to the USVString "1".
Just like if you did call new Blob([{}]), then the literal object would get coerced to the USVString "[object Object]".

const obj = new Blob([{}]);
new Response(obj).text().then(v=>console.log('obj', v));

const one = new Blob([1]);
new Response(one).text().then(v=>console.log('one', v));

So how do we set arbitrary bytes?
We use an ArrayBuffer and different views over it.

const buf = new ArrayBuffer(1);
const view = new Uint8Array(buf);
view[0] = 1;
const blob = new Blob([buf]);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'one.bin';
document.body.append(a);
a.click();


text:
Q: How can I format Google Chart Gauge with decimal % on min, max? I know there is an option like min, max (number type) to configure the values but i would like to know if there is possible to set them like...
0.00% to 100.00%
I know there is possible to do on GoogleSheets graph, but im not sure how to do it on javascript or if its possible.
var formatnumbers = new google.visualization.NumberFormat({
  suffix: '%',
  fractionDigits: 2
});
formatnumbers.format(data, 1);

That worked for the middle value only.
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

 var data = google.visualization.arrayToDataTable([
   ['Label', 'Value'],
   ['ALCANCE', 80],
   ['OBJETIVO', 55],
   ['MEDICOS TOP', 68]
 ]);

 var options = {
   width: 600, height: 220,//400,120
   redFrom: 0, redTo: 75,
   yellowFrom:75, yellowTo: 85,
   greenFrom:85 , greenTo:100,
   minorTicks: 5,
   min:0,
   max:100
  };

 var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

    //----------------new--------------//

 var formatnumbers = new google.visualization.NumberFormat({
   suffix: '%',
   fractionDigits: 2
  });
 formatnumbers.format(data, 1);

    //--------------------------------//

 chart.draw(data, options);

 setInterval(function() {
    data.setValue(0, 1, 40 + Math.round(60 * Math.random()));
    chart.draw(data, options);
  }, 13000);
  setInterval(function() {
     data.setValue(1, 1, 40 + Math.round(60 * Math.random()));
     chart.draw(data, options);
  }, 5000);
  setInterval(function() {
     data.setValue(2, 1, 60 + Math.round(20 * Math.random()));
     chart.draw(data, options);
    }, 26000);
  }

A: use the majorTicks ticks option to add the labels...
    majorTicks: ['0.00%', '100.00%'],

see following working snippet...

google.charts.load('current', {
  packages: ['gauge']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['ALCANCE', 80],
    ['OBJETIVO', 55],
    ['MEDICOS TOP', 68]
  ]);

  var options = {
    width: 600, height: 220,//400,120
    redFrom: 0, redTo: 75,
    yellowFrom:75, yellowTo: 85,
    greenFrom:85 , greenTo:100,
    minorTicks: 5,
    majorTicks: ['0.00%', '100.00%'],
    min: 0,
    max: 100
  };

  var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

  var formatnumbers = new google.visualization.NumberFormat({
    suffix: '%',
    fractionDigits: 2
  });
  formatnumbers.format(data, 1);

  chart.draw(data, options);
});


text:
Q: Text label not updating on screen, even though it shows up on `print()` I'm writing an application which has an NSSplitViewController as the main View-Controller. I have it linked-up so that clicking a button in the menubar will trigger an @IBAction which then calls a function in one of the sub-View-Controllers.

if let board = storyboard {
    let imageController = board.instantiateController(withIdentifier: "VC_image_ID") as! VC_image
    imageController.viewDidAppear() // necessary or else I'll get an "Unexpectedly found nil" later on
    DispatchQueue.global().async{imageController.processImage(path)} // path variable was set earlier in the code, but not shown here
}

Inside the sub-View-Controller (named VC_image), I'm trying to change the stringValue of a label by using the following code:

public func processImage(_ path: String) {
    DispatchQueue.main.async {
        self.imageText.stringValue = path
        print(self.imageText.stringValue)
    }
}

Although the imageText.stringValue actually seems to have changed based on the fact that it prints the updated text (through the console), the text in the window never changes. Why is this happening? The reason is probably really obvious to professionals, but I'm still an amateur and can't figure it out. Thanks.


text:
Q: jQuery: Can I send and receive an $.ajax response while a longer $.ajax request is pending? Situation:
I'm using an $.ajax() POST to send a request to a php script that inserts about 400,000-500,000 lines into a db.  This consistently takes about 3.5 - 4 minutes. (During this time, the request is PENDING).
Problem:
I need some way to show progress on the page. (such as a %).  I tried using an $.ajax() in a setInterval that checks every 5 seconds or so, but they seem to build up and all come through when the first (longer) $.ajax() is finished.
Question:
Isn't $.ajax() async by default?  Shouldn't this mean requests can be sent out in any order and at any time, and responses should be received in any order and at any time?? Does this even have anything to do with async? Is there a way to periodically send back 'semi-responses' from one request? Or can't I send and receive requests/responses while there is a pending request/response?  (see awesome drawing below)
Thanks in advance!!!
multiple requests http://kshaneb.com/reqres.png

A: Your long-running ajax-call probably opens a session on server, so all next requests are blocked due to a session file lock.

Problem:
  PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.
  The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.
Solution:
  The session file remains locked until the script completes or the session is manually closed. To prevent multiple PHP requests (that need $_SESSION data) from blocking, you can start the session and then close the session. This will unlock the session file and allow the remaining requests to continue running, even before the initial request has completed.

More info here:
http://konrness.com/php5/how-to-prevent-blocking-php-requests/

A: Hope this helps
$(function ()
    {
        var statusElement = $("#status");

        // this function will run each 1000 ms until stopped with clearInterval()
        var i = setInterval(function ()
        {
            $.ajax(
            {
                success: function (json)
                {
                    // progress from 1-100
                    statusElement.text(json.progress + "%");

                    // when the worker process is done (reached 100%), stop execution
                    if (json.progress == 100) clearInterval(i);
                },

                error: function ()
                {
                    // on error, stop execution
                    clearInterval(i);
                }
            });
        }, 1000);
    });

A: Instead of doing an ajax post you can post to an iframe and have php generate incremental output and send it with the flush command.
 // send a hash mark for every 1000 inserts
 $a = 0;
 while ($rec = getDataForNextInsert()){
       $a++;
       // do insert
       if ($a%1000 == 0) { echo '#'; flush(); }
 }

It would also then be possible to poll the contents of the iframe to provide a pretty display for the end user.

A: I hope this will be useful for you
First of all, you need to disable output buffer in your PHP script
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);

Then you need to echo your progress from the PHP during the process, something like that:
for($i=0;$i < 20;$i++){
    echo ($i > 0 ? "#":"").($i/20*100);
    sleep(1);
}

Then, in javascript you need to listen for xhr readystate change event and when this happens, just parse the response text and show the progress as you want to.
listening for event:
$.ajaxPrefilter(function( options, _, jqXHR ) {
                if ( options.onreadystatechange ) {
                    var xhrFactory = options.xhr;
                    options.xhr = function() {
                        var xhr = xhrFactory.apply( this, arguments );
                        function handler() {
                            options.onreadystatechange( xhr, jqXHR );
                        }
                        if ( xhr.addEventListener ) {
                            xhr.addEventListener( "readystatechange", handler, false );
                        } else {
                            setTimeout( function() {
                                var internal = xhr.onreadystatechange;
                                if ( internal ) {
                                    xhr.onreadystatechange = function() {
                                        handler();
                                        internal.apply( this, arguments );
                                    };
                                }
                            }, 0 );
                        }
                        return xhr;
                    };
                }
            });

and sample of ajax request:
$.ajax({
                    url: "test.php",
                    cache: false,
                    onreadystatechange: function( xhr ) {
                        res = xhr.responseText.split("#");
                        $("#id").html(res[res.length-1] + "% done
");
                    }
                }).done(function( data ) {
                        $("#id").append("all done!
");
                    });
            });

tested with jQuery 1.5+


text:
Q: Passing this variable as reference in php In PHP5, I am getting an ugly warning message when passing this variable as reference when running below code..,
<?php
random_string_function($string1, $string2, $p);
echo "Percent: $p%";
?>

any help ??

A: it's configurable in php.ini just do allow_call_time_pass_reference = Off !


text:
Q: Upgrading angular 2.0.0 to 2.4.x I'm trying to upgrade my Angular 2.0.0 application to 2.4.8 i used following link guides https://www.npmjs.com/package/npm-check-updates. but i get some error.
Old dependencies
dependencies": {
"@angular/common": "2.0.0",
"@angular/compiler": "2.0.0",
"@angular/core": "2.0.0",
"@angular/forms": "2.0.0",
"@angular/http": "2.0.0",
"@angular/platform-browser": "2.0.0",
"@angular/platform-browser-dynamic": "2.0.0",
"@angular/platform-server": "2.0.0",
"@angular/router": "3.0.0",
"@types/node": "^6.0.38",
"angular2-platform-node": "~2.0.10",
"angular2-universal": "~2.0.10",
"angular2-universal-polyfills": "~2.0.10",
"aspnet-prerendering": "^1.0.6",
"aspnet-webpack": "^1.0.11",
"bootstrap": "^3.3.7",
"css": "^2.2.1",
"css-loader": "^0.25.0",
"es6-shim": "^0.35.1",
"expose-loader": "^0.7.1",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"isomorphic-fetch": "^2.2.1",
"jquery": "^2.2.1",
"preboot": "^4.5.2",
"raw-loader": "^0.5.1",
"rxjs": "5.0.0-beta.12",
"style-loader": "^0.13.0",
"to-string-loader": "^1.1.5",
"ts-loader": "^0.8.2",
"typescript": "^2.0.0",
"url-loader": "^0.5.7",
"webpack": "^1.12.14",
"webpack-externals-plugin": "^1.0.0",
"webpack-hot-middleware": "^2.10.0",
"webpack-merge": "^0.14.1",
"zone.js": "^0.6.21"
}

New dependencies
"dependencies": {
"@angular/common": "2.4.8",
"@angular/compiler": "2.4.8",
"@angular/core": "2.4.8",
"@angular/forms": "2.4.8",
"@angular/http": "2.4.8",
"@angular/platform-browser": "2.4.8",
"@angular/platform-browser-dynamic": "2.4.8",
"@angular/platform-server": "2.4.8",
"@angular/router": "3.4.8",
"@types/node": "^7.0.5",
"angular2-platform-node": "~2.1.0-rc.1",
"angular2-universal": "~2.1.0-rc.1",
"angular2-universal-polyfills": "~2.1.0-rc.1",
"aspnet-prerendering": "^2.0.3",
"aspnet-webpack": "^1.0.11",
"bootstrap": "^3.3.7",
"css": "^2.2.1",
"css-loader": "^0.26.1",
"es6-shim": "^0.35.1",
"expose-loader": "^0.7.1",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.10.0",
"isomorphic-fetch": "^2.2.1",
"jquery": "^3.1.1",
"preboot": "^4.5.2",
"raw-loader": "^0.5.1",
"rxjs": "5.2.0",
"style-loader": "^0.13.0",
"to-string-loader": "^1.1.5",
"ts-loader": "^2.0.1",
"typescript": "^2.0.0",
"url-loader": "^0.5.7",
"webpack": "^2.2.1",
"webpack-externals-plugin": "^1.0.0",
"webpack-hot-middleware": "^2.10.0",
"webpack-merge": "^3.0.0",
"zone.js": "^0.7.7"
}

app.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent
    ],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
})
export class AppModule {
}

Error Log
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN extract-text-webpack-plugin@1.0.1 requires a peer of webpack@^1.9.11 but none was installed.
npm WARN angular2-universal-polyfills@2.1.0-rc.1 requires a peer of zone.js@~0.6.21 but none was installed.
npm WARN angular2-universal@2.1.0-rc.1 requires a peer of rxjs@~5.0.0-beta.12 but none was installed.
npm WARN angular2-universal@2.1.0-rc.1 requires a peer of zone.js@~0.6.21 but none was installed.
npm WARN Angular2Spa@0.0.0 No repository field.
npm WARN Angular2Spa@0.0.0 No license field.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Users\\ivisual\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v6.9.4
npm ERR! npm  v4.1.1
npm ERR! path C:\Users\ivisual\Documents\Visual Studio 2015\Projects\ng20\ng20\node_modules\.staging\lodash-f67ffa4b\fp\bindAll.js
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall lstat

npm ERR! enoent ENOENT: no such file or directory, lstat 'C:\Users\ivisual\Documents\Visual Studio 2015\Projects\ng20\ng20\node_modules\.staging\lodash-f67ffa4b\fp\bindAll.js'
npm ERR! enoent ENOENT: no such file or directory, lstat 'C:\Users\ivisual\Documents\Visual Studio 2015\Projects\ng20\ng20\node_modules\.staging\lodash-f67ffa4b\fp\bindAll.js'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\ivisual\Documents\Visual Studio 2015\Projects\ng20\ng20\npm-debug.log

A: i changed my package.json as below and it worked.
"dependencies": {
    "@angular/common": "^2.4.5",
    "@angular/compiler": "^2.4.5",
    "@angular/core": "^2.4.5",
    "@angular/forms": "^2.4.5",
    "@angular/http": "^2.4.5",
    "@angular/platform-browser": "^2.4.5",
    "@angular/platform-browser-dynamic": "^2.4.5",
    "@angular/platform-server": "^2.4.5",
    "@angular/router": "^3.4.5",
    "@types/node": "^6.0.42",
    "angular2-platform-node": "~2.0.11",
    "angular2-template-loader": "^0.6.2",
    "angular2-universal": "^2.1.0-rc.1",
    "angular2-universal-patch": "^0.2.1",
    "angular2-universal-polyfills": "^2.1.0-rc.1",
    "aspnet-prerendering": "^2.0.0",
    "aspnet-webpack": "^1.0.17",
    "awesome-typescript-loader": "^3.0.0",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.25.0",
    "es6-shim": "^0.35.1",
    "event-source-polyfill": "^0.0.7",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^2.0.0-rc",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.4",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^2.2.1",
    "json-loader": "^0.5.4",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "^5.0.1",
    "style-loader": "^0.13.1",
    "to-string-loader": "^1.1.5",
    "typescript": "^2.2.1",

    "url-loader": "^0.5.7",
    "webpack": "^2.2.0",

    "webpack-hot-middleware": "^2.12.2",
    "webpack-merge": "^0.14.1",
    "zone.js": "^0.7.6"
  }


text:
Q: Vue nexttick not working for scrollTop inside watcher I have a rather simple question but can't seem to figure it out.
I have a watcher which watches for the route, and when it detects that route, i basically want to navigate to the last scrolled position of the user.
$route(to, from) {
      let currentPath = to.path;
      if (currentPath === "/") {
        this.$nextTick(() => {
          this.$refs.board.scrollTop = this.lastScrollPosition; // fails
        });
      }
    },

This doesn't seem to work for me although I came across a few posts that recommend it. (VueJs doesnot update ScrollTop, Vue method scroll div to top)
However, setting a timeout of >= 100ms seems to work.
$route(to, from) {
      let currentPath = to.path;
      if (currentPath === "/") {
        setTimeout(() => {
          this.$refs.board.scrollTop = this.lastScrollPosition; // works
        }, 100);
      }
    },
  },

I'm hoping to find a way in which this.$nextTick should work. Thanks in advance for the guidance!


text:
Q: Fizz Buzz Boolean return total I have a FizzBuzz Assignment thatcounts from 1 to 1000
if a number is divisible by 3 its fizz
if its divisible by 5 its buzz
and if its divisible by both is fizzbuzz
I managed to make the project already, my problem is I'm trying to return the number total of Fizz, Buzz and Fizzbuzz respectively in the end. And return statements dont work for me, any help please?
My code:
using System;

namespace FizzBuzz
{
    public class Class1
    {
        public static void Main(string[] args)
        {
            for (int i = 1; i <= 1000; i++)
            {
                //Declaration of Fizz and Buzz as Boolean
                bool fizz = i % 3 == 0;
                bool buzz = i % 5 == 0;
                //Fizzbuzz declared to be conditional if its both
                bool fizzbuzz = fizz && buzz;
                if (fizzbuzz)
                {
                    Console.WriteLine("FizzBuzz");
                }
                else if (fizz)
                {
                    Console.WriteLine("Fizz");
                }
                else if (i % 5 == 0)
                {
                    Console.WriteLine("Buzz");
                }
                else
                {
                    Console.WriteLine(i);
                }
            }
        }
    }
}

A: Try this:
using System;

namespace FizzBuzz
{
    public class Class1
    {
        public static void Main(string[] args)
        {
                int fizzCount = 0;
                int buzzCount = 0;
                int fizzbuzzCount = 0;
                for (int i = 1; i <= 1000; i++)
                {
                    //Declaration of Fizz and Buzz as Boolean
                    bool fizz = i % 3 == 0;
                    bool buzz = i % 5 == 0;
                    //Fizzbuzz declared to be conditional if its both
                    bool fizzbuzz = fizz && buzz;

                    if (fizzbuzz)
                    {
                       fizzbuzzCount++;
                       Console.WriteLine("FizzBuzz");
                    }
                    else if (fizz)
                    {
                        fizzCount++;
                        Console.WriteLine("Fizz");
                    }
                    else if (buzz)
                    {
                        buzzCount++;
                        Console.WriteLine("Buzz");
                    }
                    else
                    {
                        Console.WriteLine(i);
                    }
                }
                Console.WriteLine("Fizz count: " + fizzCount.ToString());
                Console.WriteLine("Buzz count: " + buzzCount.ToString());
                Console.WriteLine("FizzBuzz count: " + fizzbuzzCount.ToString());
            }
        }
    }


text:
Q: PHP require files I am currently working on a website and the nav looks like this

I have primarilly made a page template that is shared by all the pages.The picture follows shows how i tried to break down the template into different pieces.

now I have to keep all files in the main directory. I can't put related pages for example all listing pages in listing folder or all download pages in download folder etc because it can't access the require files. I have tried using .. operator but the template is so nested that it is not helping either.
My question is what strategy do I use so that I can use template pieces yet all related files can be grouped in folders rather than keeping all files in the main directory. That looks really messy
Thank you.

A: You should not put all files in your main directory which will look messy and confusing.
Better you put required files in their respective folders and call them properly.
In index.php-> its okay how you have included files.
But in init.php -> you don't need to write folder name "core" as init.php is already inside core folder.
So simply use
require('connect.php');

Similarly in header.php
 require('logo.php');

And in footer.php
require('counter.php');

If you have any problem, plz let me know.


text:
Q: Models that can learn incrementally I want to implement a multinomial text classifier for my 3 classes 'A', 'B' and 'C'. This classifier should be open, in the sense that it should be extensible with new data.
Using the hashing trick it is possible to avoid being bounded by the original text (modulo collisions).
Is it possible to successfully train such a classifier if the number of classes is not known in advance? I am thinking of a streaming data case, where is not possible to look at the data before training.
For example some classifiers in scikit-learnimplement implement the  partial_fit method, but they seem to require the number of total classes.


text:
Q: Is it of any drawback if a table has many (20+) foreign key constraints? Let's says I have a table which has many fields linked to values from other "value tables". Naturally, I declare foreign key constraints on each and evary of them to enforce integrity.
What if I finally get the number of such fields in the range of 20-30? Will it somehow "slow" table operations or not really?
ADDED: Value tables are expected to have only few records, normally 5-10 or something. The database is SQL Server 2008.

A: When you insert a row into your child table, the DB engine will look up if the corresponding values in the parent tables exist - that will use up some CPU and some logical reads. If your parent tables are small, they will most likely be in the cache, so you would not expect many slow physical reads as soon as your cane is warm.
What would concern me more is if you are ever going to delete from your parent tables: if you don;t have a corresponding index on your child table, the whole child table will be locked and scanned. On the other hand, if you do have corresponding indexes for all your foreign keys, then you may end up with up to 20-30 additional indexes on your child table, which is a considerable slowdown.
You might want to run your own benchmarks and see for yourself.

A: Having one foreign key slows down insert / update operations versus having zero foreign keys - just because database has to check that foreign key value actually exists. Having 30 foreign keys will be slower then having none.
That said, just how much slower it'll be depends on many things, including size of your value tables / database engine you're using / indexes / etc... and may be virtually negligible under best case scenario.

A: Yes, there is some performance penalty on inserts and updates as all the relevant constraints are checked, but it is unlikely to cause any issues unless you are trying to insert data at a high rate.  It is usually more important for data to be maintained correctly rather than quickly, so the penalty is well worth incurring.
If you perform an UPDATE of a few columns, only the constraints on those columns need to be checked, and most DBMSs will only check those constraints.
SELECT statements will not be slowed down at all of course, and in some (probably rare) cases could even benefit from the optimizer being aware of the foreign key relationship between 2 tables that are being joined.

A: Of the 20-30 fields, how many rarely get used? Maybe some other table could be built. Makes it tougher to have to update two tables from a coding perspective, but would speed things up if you can omit updating the second table most of the time.
I deal with a 3rd party app that has main tables with corresponding 'custom' tables where we can setup our own fields. Unfortunately, we use the 'custom' fields all the time and rarely can get away with just dealing with the main table.

A: I think it's going to depend on if your queries use any of the contraints. If your query is going to need to check another table because of a constraint, then you'll see a performance hit. If your query doesn't reference any columns in the contraints, the performance hit will probably be negligible.

A: Like most everything database design related, this 'depends.' If your application does heavy inserting, updating and deleting you will run into performance issues. This could be a case where de-normalizing could be justified, especially if the 'value' tables are not changing.


text:
Q: Java Object selection during runtime I am relatively new to Java and am trying to overcome a problem..
I have a base class, for this example lets call it a box, and I have 3 more box classes inheriting the base box class. The reason for this is that each of these 3 boxes have different characteristics that differentiate them from each other. Lets pretend that:
Box01 can ONLY be made out of cardboard and be between 15 and 30cm long.
Box02 can ONLY be made out of aluminium and be greater than 30cm in length.
box03 can ONLY be made out of plastic and be less than 100cm in length.
In the program in question the user cannot select the type of box specifically but alternatively must supply their requirements and the program must respond saying if the product is possible. So a plastic box of 120cm is not possible, neither is a 50xm cardboard box.
My current solution is to use if statements such as:
if(boxType == 'cardboard' && length >= 15 && length <= 30){
    Box = new box01(boxType, length);
else if(boxType == 'aluminium' && length >= 30){
    Box = new box02(boxType, length);
}

I know in this simplified example it appears unnecessary to have the additional box classes but assume that in the real version that the boxes have many more unique characteristics which would reflect in the classes attributes and constructor.
Now to my question. This particular method looks ok here with only 2 tests and a few ifs but my program has considerably more attributes and many many more tests. Is there another more sophisticated way for my program to detect what kind of box my program should make besides the ifs.
Thank you for anybody who takes the time to read this, understand it and post a reply. I'm sure the solution is much simpler than I am making it out to be.

A: A good approach for this would be to structure your application like this:

*

*Use an interface or an abstract class with a basic implementation for de:
public interface BoxType(){ //Or BoxFactory or smth like that

    public boolean isApplicable(int userInput1, String userInput2...);        /// If you have more than 1-2 user input elements, create a special object (something like `UserInput`) with the user input/requirements and just pass it.

    public Box buildBox(int userInput1, String userInput2...);
    ...
}

*Implement each box type, defining it's applicability conditions in the isApplicable() Method and how to build it in the buildBox() method.

*Wherever you need to check which box type is, just cycle through the existing (registered) Box types and check which one is applicable and build it.

A: This is what I was talking about:
import java.util.Arrays;
import java.util.List;

enum Material {
    CARDBOARD, ALUMINIUM, PLASTIC
}

class BoxProperties {
    public Material material;
    public double length;
}

abstract interface RuleSet {
    public boolean isSatisfiedBy(BoxProperties props);
}

class MyRuleSet implements RuleSet {
    private final Material material;
    private final double[] length;

    public MyRuleSet(Material mat, double minLength, double maxLength) {
        this.material = mat;
        this.length = new double[] {minLength, maxLength};
    }

    @Override
    public boolean isSatisfiedBy(BoxProperties props) {
        if (props.material != material) return false;
        if (props.length < length[0] || props.length > length[1]) return false;
        return true;
    }

}

public class Box {
    private static final List<? extends RuleSet> rules;
    public final Material material;
    public final double length;

    private Box(BoxProperties props) {
        this.material = props.material;
        this.length = props.length;
    }

    public static Box createBox(BoxProperties props)
            throws IllegalArgumentException {
        for (RuleSet rs : rules) {
            if (rs.isSatisfiedBy(props)) {
                return new Box(props);
            }
        }

        //XXX This should probably be made a checked exception
        throw new IllegalArgumentException(
                "No supported box type can fullfil the requests");
    }

    static {
        rules = Arrays.asList(
                new MyRuleSet(Material.CARDBOARD, 15, 30),
                new MyRuleSet(Material.ALUMINIUM, 30, Double.POSITIVE_INFINITY),
                new MyRuleSet(Material.PLASTIC, 0, 100)
                );
    }
}

If you determine that you need different Box subclasses, then you might make Box abstract, and add a createBox method to the RuleSet interface, which is implemented to return a custom implementation. Also, you might need to pass some extra parameter to the Box constructor, which wasn't in the request, so it's likely that you'll want to add that.
Anyway, I repeat that I don't think you should subclass, because the client class would still see a Box. In order to determine if it can be wrapped, it should make something like
if (returnedBox instanceof MaybeWrappableBox && ((MaybeWrappableBox)returnedBox).isWrappable()) {
    ...
}

Then, you'd better add isWrappable() to all your boxes, and just return false if the box is never wrappable. That would simplify caller code, while not particularly complicating callee code.


text:
Q: Google REST API - message in an RFC 2822 formatted and base64url encoded string I try the use the - try it of Google REST API - Users.messages: send .
There is there a required parameter - raw -

The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when
  the format=RAW parameter is supplied.

I checked about RFC 2822 format and seems it should displayed as the sample here , then I encoded it the base64URL with this encoder and paste it the raw field of the try it and I get  - Invalid value for ByteString: http://ostermiller.org/calc/encode.html .
Can you provide me a correct RFC 2822 format and its corresponding base64URL which it would work in the above try it ?

A: An example mail could look like this:
From: sender@gmail.com
To: receiver@gmail.com
Subject: Subject Text

The message text goes here

Open up the Developer Tools in your browser and Base64 encode it and replace all + with -, replace all / with _, and remove the trailing = to make it URL-safe:
btoa(
  "From: sender@gmail.com\r\n" +
  "To: receiver@gmail.com\r\n" +
  "Subject: Subject Text\r\n\r\n" +

  "The message text goes here"
).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

This will give you the following data:
RnJvbTogc2VuZGVyQGdtYWlsLmNvbQ0KVG86IHJlY2VpdmVyQGdtYWlsLmNvbQ0KU3ViamVjdDogU3ViamVjdCBUZXh0DQoNClRoZSBtZXNzYWdlIHRleHQgZ29lcyBoZXJl
Use this string above as your raw-parameter in the API Explorer to send the mail.

A: you can use this in node REPL or online node compiler and get the json
function createMessageJson(){
    const messages = [
        'From: NAME <foo@email.com>',
        'To: Name <foobar@email.com>',
        'Content-Type: text/html; charset=utf-8',
        'MIME-Version: 1.0',
        'Subject: Re: SUBJECT',
        '',
        'BODY_TEXT',
        '',
    ];

    function encodedMessage (){
        return Buffer.from(messages.join('\n'))
            .toString('base64')
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=+$/, '');
    }

  return JSON.stringify({
            raw: encodedMessage()
    });
}

console.log(createMessageJson())


text:
Q: Bash script not working with double quotation When I run the script below it works fine but I have to enter the PublicDNS in the script. This script has single quotes.
          sh '''
    ssh -o StrictHostKeyChecking=no \
        -i my-key.pem \
        ec2-user@ec2-xxx-xxx.amazonaws.com \
        "sudo yum update -y && \
        sudo yum install docker -y && \
        sudo systemctl start docker && \
        sudo docker pull image/test:be && \
        sudo docker run -d -p 8080:8080 image/test:be"
'''

However, when I try to add a variable for DNS in the second script and as a result change the script to double quotations then error shown below is thrown
sh """
    ssh -o StrictHostKeyChecking=no \
        -i my-key.pem \
        ec2-user@$DNS \
        "sudo yum update -y && \
        sudo yum install docker -y && \
        sudo systemctl start docker && \
        sudo docker pull image/test:be && \
        sudo docker run -d -p 8080:8080 image/test:be"
"""

Error:
/var/jenkins_home/workspace/script.sh: 3: sudo yum update -y &&         sudo yum install docker -y &&         sudo systemctl start docker &&         sudo docker pull image/test:be &&         sudo docker run -d -p 8080:8080 image/test:be: not found
Any idea what I am doing wrong? Thanks

A: 100% Working
Simply just use heredoc instead:
sh <<EOF
    ssh -o StrictHostKeyChecking=no \
        -i my-key.pem \
        ec2-user@$DNS \
        "sudo yum update -y && \
        sudo yum install docker -y && \
        sudo systemctl start docker && \
        sudo docker pull image/test:be && \
        sudo docker run -d -p 8080:8080 image/test:be"
EOF

A: Use a here-document:
sh <<EOF
ssh -o StrictHostKeyChecking=no \
    -i my-key.pem \
    ec2-user@$DNS \
    "sudo yum update -y && \
    sudo yum install docker -y && \
    sudo systemctl start docker && \
    sudo docker pull image/test:be && \
    sudo docker run -d -p 8080:8080 image/test:be"
EOF


text:
Q: Ways to implement Google Pub Sub I found these 3 ways for implementing messaging with Google Pub Sub:

*

*with client libraries
https://cloud.google.com/pubsub/docs/publisher

*with spring integration message channels and PubSubTemplate API
https://dzone.com/articles/spring-boot-and-gcp-cloud-pubsub

*without message channels but with PubSubTemplate API
https://medium.com/bb-tutorials-and-thoughts/gcp-how-to-subscribe-and-send-pubsub-messages-in-spring-boot-app-b27e2e8863e3
I want to understand the differences between them / when each is best to use and which would be useful for my case.
I have to implement a single Topic and a single Subscription to get the queue functionality. I think I'd rather not use Spring message channels if not needed , they seem to intermediate the communication between Pub Sub topic and the subscription and I don't want that. I want things simple , so I think the option 3 would be best but I am also wondering about option 1.

A: Option 1, client libraries, is universal. You don't need Spring to run it, you can use this library in Groovy or in Kotlin also.
Option 2, it's deeply integrated to Spring. It's quite invisible but if you have special thing to do, it's tricky to override this implementation
Option 3, it's a light spring integration. PubSubTemplate (the client in fact) is loaded automatically for you at startup, as any bean and you can use it easily in your code. It's my preferred option when I use Spring.

A: Google Cloud Pub/Sub Using Client Libraries :

*

*Using Google Cloud Pub/Sub with Client libraries is one of the standard and easiest way to implement Cloud Pub/Sub.

*A producer of the data publishes messages to Pub/Sub topic, a subscriber client then creates a subscription to that topic and consumes messages.

*You need to install the client libraries. You can follow this setup and tutorial for further information.

*Here you won't require Spring integration, you can directly use the client library to publish messages and pull it from subscription.

Spring Integration using spring channels :

*

*This use case involves intensive integration of Spring Boot Application with Google Cloud Pub/Sub using Spring Integration to send and receive Pub/Sub messages. ie. Pub/Sub acts as intermediate messaging system

*Here The Spring Application sends messages to Cloud Pub/Sub topic utilizing spring channels and the Application further receives messages from Pub/Sub through these channels.

Pub/Sub message in Spring-Boot App :

*

*This use case is a simple and valid example of integrating Cloud Pub/Sub with Spring boot application.

*The use case demonstrates how to subscribe to a subscription and send message to topics using Spring Boot Application

*Message is published to the topic, queued in the respective subscription and then received by the subscriber Spring Boot Application


text:
Q: How to test if two samples are distributed from the same Gaussian process Given a sequence $\mathbf{x} = (x_1,x_2,\dots,x_n)$ which is sampled from some Gaussian process $GP(\mu_1,\Sigma_1)$ and a "target" sequence $\mathbf{y} = (y_1,y_2,\dots,y_n)$ sampled from another Gaussian process $GP(\mu_2,\Sigma_2)$, does anyone know of a test of whether $\mathbf{x}$ and $\mathbf{y}$ come from the same distribution?  I guess I'd like to know the probability $\mathbf{x}$ and $\mathbf{y}$ are from the same distribution (is that even well posed?).
I am not assuming any of $\mu_1,\mu_2,\Sigma_1$ or $\Sigma_2$ are known.  Also, I'm okay with assuming the GPs are stationary (but not centered) if that helps.

A: This sounds like an application for the two-sample KS test, which evaluates whether two samples were taken from the same continuous probability distribution. For more information, you might want to start here, which explains it in some detail: http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm.

A: Let the null hypothesis be that $\mathbf x$ and $\mathbf y$ have the same distribution. Let $\mathbf z = \mathbf x - \mathbf y.$ Under the null, $\mathbf z$ will have a mean of zero and be symmetric. Test the hypothesis that $\mathbf z = \mathbf 0$ using the traditional test. If you reject, you are done.
If you fail to reject, then divide the $x_i - y_i$ into two subsets: those realizations less than zero and those greater than zero. Now use the two-sample KS test on the two halves of your data.
You will need to use your judgment for high dimensions since you are performing a multitude of tests, but at least this deals with the potential dependence.


text:
Q: Expression of unitary group , the discrete subgroups and invariants Let $$G=U(3),$$ be the unitary group. Here we consider $G$ in terms of the fundamental representation of U(3). Namely, all of $g \in G$ can be written as a rank-3 (3 by 3) matrices.

*

*What is the convenient way to parametrize the rank-3 matrix in terms of a 9 degrees of freedom (for 9 generators)?

*Can we find some subgroup of Lie group,  $$k \in K \subset G= U(3) $$  such that

$$
k^T \{R_1, R_2\} k =\{R_1, R_2\} .
$$
  This means that set $\{R_1, R_2\}$ is invariant under the transformation by $k$. Namely, both cases are allowed:
  $$
k^T R_1  k =R_1,\;\;\;  k^T R_2 k =R_2 .
$$
  $$
k^T R_1  k =R_2,\;\;\; k^T R_1 k =R_2 .
$$

Here $k^T$ is the transpose of $k$.
What is the full subset (or subgroup) of $K$?
Here we define:
$$
R_1 =
\left(
\begin{array}{ccc}
 0 & 1 & 0 \\
 -1 & 0 & 0 \\
 0 & 0 & 0 \\
\end{array}
\right),\;\;\;\; R_2 =-R_1=
-\left(
\begin{array}{ccc}
 0 & 1 & 0 \\
 -1 & 0 & 0 \\
 0 & 0 & 0 \\
\end{array}
\right).$$
This means that $k^T R_a k=R_b$ which may transform $a$ to a different value $b$, where $a,b \in \{1,2 \}$. But overall the full set $ \{R_1, R_2\}$ is invariant under the transformation by $k$.
There must be a trivial element $k=$ the rank-3 identity matrix. But what else can it allow? In particular, I can see an SU(2) and an additional $\mathbb{Z}_2 \times \mathbb{Z}_2$ structure in $K$.

How could we determine the complete $K$?

Edit: More clarifications. Simplified the problem.

A:
Question. Let $R_1=\begin{pmatrix} 0 & 1 & 0 \\ -1 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix}$. Find the subgroup $K$ of $U(3)$, where
  $$
K=\{k\in U(3)\mid k^TR_1k=R_1\text{ or }-R_1\}
$$
Answer. Denote by $SU(2)\rtimes\mathbb{Z}_2$ the group of $2\times2$ unitary matrices with determinant $\pm1$. Then
  $$
\begin{align*}
K &= \Bigl\{ \begin{pmatrix} \alpha & \mp\bar\beta & 0 \\ \beta & \pm\bar\alpha & 0 \\ 0 & 0 & \gamma \end{pmatrix} \in U(3) \mid \alpha,\beta,\gamma\in\mathbb{C},\,|\alpha|^2+|\beta|^2=|\gamma|=1 \Bigr\} \\
&\cong (SU(2)\rtimes\mathbb{Z}_2)\times U(1)
\end{align*}
$$

Solution. Let us find $k=(k_{ij})$ such that $k^TR_1k=R_1$ or $-R_1$. It implies the following three equations
$$
k_{11}k_{23} = k_{13}k_{21}, \quad
k_{12}k_{23} = k_{13}k_{22}, \quad
k_{11}k_{22} - k_{12}k_{21} = \pm1 \tag{*}
$$

Claim 1. $k_{13}=0$ and $k_{23}=0$.
Proof. If $k_{13}\neq 0$, then by the Gaussian elimination
  $$
k=\begin{pmatrix} k_{11} & k_{12} & k_{13} \\ k_{21} & k_{22} & k_{23} \\ k_{31} & k_{32} & k_{33} \end{pmatrix} \sim \begin{pmatrix} k_{11} & k_{12} & k_{13} \\ k_{21}-k_{11}(\frac{k_{23}}{k_{13}}) & k_{22}-k_{12}(\frac{k_{23}}{k_{13}}) & k_{23}-k_{13}(\frac{k_{23}}{k_{13}}) \\ k_{31} & k_{32} & k_{33} \end{pmatrix} \sim \begin{pmatrix} k_{11} & k_{12} & k_{13} \\ 0 & 0 & 0 \\ k_{31} & k_{32} & k_{33} \end{pmatrix}
$$
  $k$ is singular which contradicts to $k\in U(3)$. In the same way, we can prove that $k_{23}=0$ too.

Now the three equations in (*) are reduced to only one equation
$$
k_{11}k_{22} - k_{12}k_{21} = \begin{cases} +1 & \text{if $k^TR_1k=R_1$} \\ -1 & \text{if $k^TR_1k=-R_1$} \end{cases} \tag{**}
$$

Claim 2. $k_{31}=k_{32}=0$.
Proof. Since $k\in U(3)$,
  $$
k^\dagger k=\begin{pmatrix} * & * & \bar k_{31} \\ * & * & \bar k_{32} \\ 0 & 0 & \bar k_{33} \end{pmatrix} \begin{pmatrix} * & * & 0 \\ * & * & 0 \\ k_{31} & k_{32} & k_{33} \end{pmatrix} = \begin{pmatrix} * & * & * \\ * & * & * \\ k_{31}\bar k_{33} & k_{32}\bar k_{33} & k_{33}\bar k_{33} \end{pmatrix} = I
$$
  where $k^\dagger$ denotes the conjugate transpose of $k$.
  From $k_{33}\bar k_{33}=|k_{33}|^2=1$, we have $\bar k_{33}\neq0$ so that $k_{31}=k_{32}=0$.

Now we have $k=\begin{pmatrix} k_{11} & k_{12} & 0 \\ k_{21} & k_{22} & 0 \\ 0 & 0 & k_{33} \end{pmatrix}\in U(2)\times U(1)$ where $|k_{33}|=1$, and the equation (**) implies that the determinant of the sub-matrix $\begin{pmatrix} k_{11} & k_{12} \\ k_{21} & k_{22} \end{pmatrix}\in U(2)$ is $\pm1$.
On the contrary, it is easy to check this form of $k$ satisfies $k^TR_1k=R_1$ or $-R_1$.
Note. For the first question, I do not know any convenient way to parametrize $U(3)$.


text:
Q: Button click issue in continuously changing data I am creating one table,in which data is updating continuously.In each row there is one button.We have add one popup on click event of button.Some how that button is blinking due to change in data. and not able to click the button.
I have tried @ViewChild(https://angular.io/api/core/ViewChild) ,but it does not work for me.

    <button onload="loadBtn(runner.id)"  id="book-match-{{runner.id}}"   runat="server"  (click)="showAlert(runner)"  class="button rounded-full-btn cancel-btn custom-button">Book</button>
    {{runner.back2 | round}}
{{runner.backValue2 | round}}
    {{runner.back1 | round}}
{{runner.backValue1 | round}}

Below code is in ts file and running on 200ms
  if(JSON.parse(message.body).fancy!=null){
  this.fancy = JSON.parse(message.body).fancy;
  }
  this.fancyRunners = this.fancy.runners;

I just want to button to be click.that button should be rendered first time ,other than that only other data should be change.

A: Because of this reassignment this.fancyRunners = this.fancy.runners; the rows are getting rerendered and your button is blinking.
Don't reassign every time to 'fancyRunners', write a logic to assign for 1st time and then for next time update the array(fancyRunners).


text:
Q: Using javascript filtering when having 2 arrays to check or compare I have some problems using the filtering method in javascript when I have two large objects and have to compare them in a filtering process.
For simplicity, I created an example, where we have two arrays: array_1 and array_2.
Array_2 should be filtered based on the id that exists in array_1. (These id's are the same in each array)
let array_1 = [
    { id: '_i23455szq', description: 'text' },
    { id: '_h6yf2uk1n', description: 'text' }
]

let array_2 = [
    { id: '_h6yf2uk1n', description: 'text', capacity: 2 },
    { id: '_465324423', description: 'text', capacity: 4 },
    { id: '_i23455szq', description: 'text', capacity: 0 },
    { id: '_54234gfgd', description: 'text', capacity: 0 },
]

As you see, in array_2 we have a capacity set. I'm trying to filtering based on capacity, I want to filter array_2 so after the filtering, it includes every object that has a capacity (higher than 0, but also include those that matches the once in array_1)
How can this be done, if you should make a nice solution without too many for loops?
Is this even possible in 1-2 lines?
Have tried with a filtering and a forEach inside, but can't seem to create a solution that is simply a don't take up so much space.
array_2 = array_2.filter(function (i) {
    array_1.forEach(j => {
        if (j.id == i.id) {
            console.log("ID matches")
            // How to return??
        }
    })
})

The output should be the following objects:
{ id: '_h6yf2uk1n', description: 'text', capacity: 2 },
{ id: '_465324423', description: 'text', capacity: 4 },
{ id: '_i23455szq', description: 'text', capacity: 0 },

A: Probably best to make a Set of array_1's ids in advance (Set lookup is much faster than any other sort of .some / indexOf array lookup). Then, you just need to .filter, extracting the id and capacity properties from array2, and check to see if the id is in the Set of ids, or if the capacity is greater than 0. This has a complexity of O(N), while using array methods like .some inside the .filter would have O(N^2):

let array1 = [
    { id: '_i23455szq', description: 'text' },
    { id: '_h6yf2uk1n', description: 'text' }
]

let array2 = [
    { id: '_h6yf2uk1n', description: 'text', capacity: 2 },
    { id: '_465324423', description: 'text', capacity: 4 },
    { id: '_i23455szq', description: 'text', capacity: 0 },
    { id: '_54234gfgd', description: 'text', capacity: 0 },
]

const ids = new Set(array1.map(({ id }) => id));
console.log(
  array2.filter(({ id, capacity }) => ids.has(id) || capacity > 0)
);

A: You're looking for a logical OR (||) of two conditions in your filter. Check the capacity first so that you don't need to search array_1 if capacity > 0. If capacity isn't greater than 0 then youcan search for an object with the same id in array_1.

const array_1 = [
    { id: '_i23455szq', description: 'text' },
    { id: '_h6yf2uk1n', description: 'text' }
]

const array_2 = [
    { id: '_h6yf2uk1n', description: 'text', capacity: 2 },
    { id: '_465324423', description: 'text', capacity: 4 },
    { id: '_i23455szq', description: 'text', capacity: 0 },
    { id: '_54234gfgd', description: 'text', capacity: 0 },
]

const result = array_2.filter( obj =>
  obj.capacity > 0 || array_1.some( ({ id }) => id === obj.id )
);

console.log( result );

A: array_2 = array_2.filter(i => i.capacity || array_1.some(j => i.id == j.id));


text:
Q: Using jQuery slideToggle() without display:none? I'm trying to use jQuery's slideToggle function to show or hide a panel which has been hidden using CSS position, rather than display:none (as this causes issues with a Google Map in one of my panels).
At the moment I'm just hiding and showing the panels like so, but some animation would be nice:
$('.panel').addClass('hidden');
$('.head > span').addClass('closed');

$('.head').click(function() {
    $(this).next('.panel').toggleClass('hidden');
    $(this).children('span').toggleClass('open');
});

Any ideas?

A: slideToggle() is an alternative to toggle(), which shows/hides the selected items depending on its current visible state.
You needn't worry about the classes at all if you are simply trying to get the animation to work.
So, just try the following to see what you get:
$(this).next('.panel').slideToggle();

A: slideToggle animates height of the element in question apart from visibility. Not sure how exactly you have used CSS position to show/hide your panels. Based on that you have to build you own animation using animate function. Another quick way could be to
For showing element:

*

*Hide the element (using jquery hide())

*Apply your class to show element
(i.e. to adjust its position)

*Now apply slideDown
For hiding content:

*

*Apply slideUp - use callback function to do steps 2 & 3

*Apply your class to hide element
(i.e. to adjust its position outside window)

*Show the element (using jquery show())
Edit: Illustrative code goes below (assuming that 'hidden' classes will do CSS positioning to hide the element):
function customSlideToggle(e)
{
   var show = e.hasClass('hidden');
   if (show) {
     e.hide();
     e.removeClass('hidden')
     e.slideDown('slow');
   }
   else
   {
     e.slideUp('slow', function() {
        e.addclass('hidden');
        e.show();
     });
   }
}

A: Try this Pezholio
 $('.head').click(function() {
    $(this).next('.panel').slideToggle('slow', function() {
        $(this).toggleClass('hidden')
    });
    $(this).children('span').slideToggle('slow', function() {
        $(this).toggleClass('open')
    });
});

you can combine few more effect slideUP,slideDown,slideToggle and with easing plugin you have even add some smoothness to animation
Here is an example
Html

    test one

    test one

    test one

    test one

    test one

show

javascript
$(document).ready(function() {
    $('span.more').click(function() {
        $('p:eq(0)').slideToggle();
        $(this).hide();
    });
});

CSS
.text{display:none}

live demo
http://jsfiddle.net/gB6np/


text:
Q: instr function in VBA Kindly help need your assistance please,
Description:
I have designed a VBA code where I want to compare a string with FileName in a directory.In this case I have used Instr function, this helps me in 3 cases only but not dynamicaly.
Explaination:
if the str=4567 and compairing with filename, where filename can be:
1.xs1234567.pdf
2.4567.pdf
3.4567(1).pdf
4.updated 4567(2).pdf
so the code i have created help to find all the files, but this is not correct. It should exclude first file name ie:xs1234567.pdf
This is the following code:
Dirfname = finDir
fName = Mid((Dirfname), 1, (InStr(1, (Dirfname), ".") - 1))
fileExt = Mid((Dirfname), (InStr(1, (Dirfname), ".") + 1), 3)

**If (InStr(1, fName, wkvalue) > 0 And wkvalue <> "") Then ** 'checking lookup val in instr
        If (Trim(UCase(fileExt)) = "PDF" Or Trim(UCase(fileExt)) = "TIF") Then
                                Cells(recnum, 2).Value = "Yes"
                                'col = col + 1
                                ws.Hyperlinks.Add Anchor:=Cells(recnum, (col + 1)), _
                                Address:=SourceFolderName & "\" & Dirfname
                                col = col + 1
                                'Else: Cells(recnum, 2).Value = "No"
        End If
  End If

Please advice what can be done for this case.

A: You could use Regular Expressions to assist you. Im not very proficient with it yet but this is a relatively simple case. Here is a function adapted from tmehta.com/regexp that you could use in conjunction with an iteration of the filenames in a folder:
Function RegExpFind(FindIn, FindWhat As String, _
                    Optional IgnoreCase As Boolean = False) As Variant

    Dim i As Long
    Dim rslt() As String

    '// Using Late Binding here, use the commented types if you've added
    '// the "Microsoft VBScript Regular Expressions" reference
    Dim RE As Object 'RegExp
    Dim allMatches As Object 'MatchCollection
    Dim aMatch As Object 'Match

    '// Use "Set RE = New RegExp" if using the VBScript reference
    Set RE = CreateObject("vbscript.regexp")

    RE.Pattern = FindWhat
    RE.IgnoreCase = IgnoreCase
    RE.Global = True
    Set allMatches = RE.Execute(FindIn)

    '// check if we've found anything, if not return a single element array
    '// containing an empty string. If we've found something return at least
    '// at least a single element array containing the matched expressions
    If allMatches.Count = 0 Then
        ReDim rslt(0 To 0)
        rslt(0) = ""
    Else
        ReDim rslt(0 To allMatches.Count - 1)
        For i = 0 To allMatches.Count - 1
            rslt(i) = allMatches(i).Value
        Next i
    End If

    RegExpFind = rslt

End Function

You would need to pass in the file name as the FindIn parameter and the regexp pattern "^4567" in the FindWhat parameter. Using it this way will return 4567 (as the first element in the return array) only if it occurs at the start of the search string. This function could be easily recycled for use with other searches down the road if you need to.

A: Assuming that your criteria for a match is that the character preceeding 4567, if any, is a space
i = InStr(1, fName, wkvalue)
if i > 0 and wkvalue <> "" Then
    ch = " "
    if i > 1 then
        ch = mid(fName, i - 1, 1)
    end if
    if ch = " " then
        ...

A: You don't describe why the first filename should be rejected, but I assume it's because it has a digit (0-9) before and/or after wkvalue, such that "4567" is not the entire number. In such a case, this will work:
    charBefore = ""
    charAfter = ""
    pos = InStr(fName(i), wkvalue)
    If pos = 1 Then
        ' It's at the beginning of the filename.
        ' Get character after the number.
        charAfter = Mid(fName(i), pos + Len(wkvalue), 1)
    ElseIf pos > 1 Then
        ' It's not at the beginning of the filename
        ' Get characters before and after the number.
        charBefore = Mid(fName(i), pos - 1, 1)
        charAfter = Mid(fName(i), pos + Len(wkvalue), 1)
    Else
        ' Number not found.
    End If
    ' Could add another ElseIf to check if it's at the end of the filename.

    If pos > 0 And wkvalue <> "" _
        And Not charBefore Like "#" And Not charAfter Like "#" Then
            ' Number found and not preceded or followed by a digit (0-9).
            ' Do your thing.
    End If


text:
Q: trace of VoIP packet delay I am interested about packet delays due to network jitter in voip calls. The distribution of the delay should be something similar to a Gaussian distribution with heavy tail to the right of the peak, and truncated to the left. Does anyone know where I can find a trace to download of packets sent during a voip call?

A: Why don't you simply install 2 free VoIP clients and make a Wireshark trace yourself ?
For H.323 you could use Spranto or X-Lite for SIP.


text:
Q: how to create initialcontext to connect to sql server I am having difficulty connecting my java code to sql server database.  I can connect from App server just fine..but now I want to try to connect with app server out of the picture and using InitialContext with some env properties. So a stand alone java class connecting to sql server using InitialContext
I have mssqlserver.jar in my projects libraries. Do I need some other jar as well?
I looked around for some code sample but dont know what to put in Context.INITIAL_CONTEXT_FACTORY
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "what do i put here?");
env.put("java.naming.factory.initial",
"what do i put here?");
...
what other properties would I need?

on the App server I have following properties.
datasourceName = mydb
user = myuser
port = 1433
password = mypwd
databaseName = mydb
servername = localhost

A: You are not on the right track here. InitialContext is strictly about the application server. In order to connect to the database directly without the application server you have to create your own JDBC connection to the database, or use a different JDBC connection pool implementation.

A: You may find it helpful to consult the JDBC tutorial, you'll see that you can use a DriverManager to get your connection. The JNDI approach you are familiar with is a nice, general abstraction for giving access to all manner of services provided in an AppServer environment. For stand-alone apps one usually just uses the raw APIs.


text:
Q: How to return the response of a post request in qraphql I'm developing an app using GraphQL in the backend and I want to implement a face comparison method. I am using the facepp npm package, which gives me an API to perform the comparison. The problem I am having is that when my resolver runs, it finishes before it gets a response from facepp. How can I make it return the response from facepp?
    module.exports = {
      Mutation: {
         checkFace: async () => {
           console.log("Checking.....");

        let confidence;

        var parameters = {
          image_url1: "link to image 1",

          image_url2: "link to image 2",
        };

        facepp.post("/compare", parameters, function (err, res) {
            if (!err) {
                confidence = res.confidence;
              //return res.confidence doesn't work
            } else {
                confidence = "There was an error"
            }
        });

        return confidence
    },
},

};

A: After a couple of trials and researches, I came up with a working solution. The problem in my original code was that I didn't correctly handle the asynchronous handler of the facepp.post method. In case if someone runs into the same issue, below is a working implementation of my code.
module.exports = {
    Mutation: {
        checkFace: async () => {
            let confidence;
            const callCheck = () => {
                return new Promise((resolve, reject) => {
                    var parameters = {
                        image_url1: "link to image 1",
                        image_url2: "link to image 2",
                    };
                    facepp.post("/compare", parameters, function (err,
                  res) {
                        if (!err) {
                            confidence = res.confidence;
                            resolve();
                        } else {
                            confidence = "error";
                            reject();
                        }
                    });
                });
            };
            await callCheck();
            return confidence;
        },
    },
};


text:
Q: how create frontend and backend structure for modules in yii2? The structure im looking for is like:
modulesName
   frontend
     controllers
     models
     views
     web

   backend
     controllers
     models
     views
     web

is that possible ?
we should use basic or advance ?

A: Yes you can. But if you need this kind of structure it is good to use Yii2-advanced template. Or if you want you can use also starter kit by trntv here is link. It has lots of features that will easy your development.
What if you want it as module, you need basic template but you will not have separate web folders. Just use Gii to create module. Instructions how to work and create modules are given here.


text:
Q: Styling off after JQuery Append I have a weird problem that happens in all browsers except for Firefox. The Show More button losses its padding when I do an ajax request and append data to the table...
On first load (non-ajax) the button displays properly in all browsers. When I click the Show more button which sends a request to get more data (rows) back, the button losses it's bottom padding.
If I open up Chrome's or IE's development tool and click on the  or  tag element for the button it brings back the padding. It's almost like the DOM needs a refresh or something to trigger the padding to be shown.

                    Record Data

Show More

    #table { position: relative; width: 800px; height: 470px; overflow-y: scroll; padding: 10px;  }
    #showData { display: block; padding-top: 10px; }

Returned Data
The ajax call just returns a bunch of table rows. There are no classes or id's on any of the returned html.
example of data returned by a call

some returned data 1

some returned data 2

some returned data 3

A: Try with:
#showData {
    display: block;
    ...
}

An you forgot to close
:

Show More

A: "the button loses it's bottom padding"...
Your CSS has padding-bottom set to 0px. Try increasing it? Or remove it outright so that it doesn't overwrite the implied 10px from padding which immediately precedes it.
#showData { display: block; padding: 10px; padding-bottom: 0px; }


text:
Q: MYSQL - Select based on a dynamic value I'm looking for a way to select something in one column based on another column's data. I have 2 tables:
input_table - has a column called "year_of_birth"
result_table - has a column called "notes"

you see, that "notes" column might contain a year in there, something like "1980". I need to be able to select rows where the notes field contains a match to the year_of_birth field. I have my statement written like this so far:
select inp.year_of_birth, res.notes, res.result
from order_input inp join order_result res on inp.order_id = res.order_id
where res.result !='no match'
and res.notes like '%' + inp.year_of_birth + '%'

right now i'm getting an error thta says "conversion failed when converting the varchar value '%' to data type int. I'm not sure what i'm doing wrong because I have a similar statement i'm using that has this type of string in it that works...

A: You need to use CONCAT instead of +
res.notes like CONCAT('%', inp.year_of_birth, '%')

A: Try this:
select inp.year_of_birth, res.notes, res.result from order_input as inp join order_resultas res on inp.order_id = res.order_id where res.result <> 'no match' and res.notes like CONCAT('%', inp.year_of_birth, '%')


text:
Q: What's the difference between simple past and present prefect? I quite have a doubt with the below statements. Do they convey the same meaning? Do these two convey the same meaning? And if not, what's the difference?

*

*Judy had visited Thailand in 2014

*Judy visited Thailand in 2014

A: Past perfect is not used in single simple sentences. Since it refers intrinsically to a second past time, prior to some other past event, a clause using the past perfect construction must have some other close clause or sentence to refer to.
Consequently,

*

*Judy had visited Thailand in 2014
all by itself, is a very strange sentence. Why did the speaker use past perfect? What else happened later?
The past perfect pops up in narratives to place events in sequence:

*

*Judy had visited Thailand in 2014, but when she returned last year she found a lot of changes.
But it doesn't occur by itself.