text:
Q: Laravel - Add column to existing pivot table and add MUL key I have a Laravel pivot table which contains multiple primary keys: "order_id", "product_id", "variation_id".
I need to add a new column called "id" to this table which I do as follows:
public function up()
    {
        Schema::table('order_product', function (Blueprint $table)
        {
            $table->integer('id')->unsigned()->after('variation_sku');
        });
    }

My original migration file looks as follows:
public function up()
    {
        Schema::create('order_product', function (Blueprint $table)
        {
            $table->integer('order_id')->unsigned()->index();
            $table->foreign('order_id')->references('order_id')->on('orders')->onDelete('cascade');
            $table->integer('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('product_id')->on('products')->onDelete('cascade');
            $table->integer('variation_id')->unsigned()->index()->nullable();
            $table->jsonb('variation')->nullable();
            $table->integer('qty');
            $table->string('variation_status')->default('bakery');
            $table->timestamps();
            $table->softDeletes();
            $table->primary(['order_id', 'product_id', 'variation_id']);
        });
    }

This migration includes my 3 composite keys.
I now need to add the new column "id" and add this column to the composite keys.
I cannot find anything in the Laravel documentation and have a suspicion that this may not be possible as it may affect past records in this table.

A: You could drop the primary key then create a new one:
public function up()
{
    Schema::table('order_product', function (Blueprint $table)
    {
        $table->integer('id')->unsigned()->after('variation_sku');
        $table->dropPrimary();
        $table->primary(['id', 'order_id', 'product_id', 'variation_id']);
    });
}


text:
Q: Create subdomain, IIS, AWS VM i have an aws vm with a dns record pointing to it. my aws vm is running IIS.
i want to create a sub domain, sub.domain.com
both websites are on the same box+iis but stored in different folders..
i have tried creating a binding for the subdomain but i cant get it working..
im assuming the only changes needed are in IIS because the VM is the endpoint for that dns record and IIS should handle the rest?
Given the current configuration, what do i need to do the make this work?

A: You should create two CNAME records pointing to this VM. Then configure IIS sites to use the respective sub-domains.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use same branch more than once I am new to git, and I am assuming that if I can use only one branch for all project. After I commit my code into a branch -- subBranch, and merge it into the master. Then I did some other change. May I commit them into the subBranch again and merge into the master, or I have to make a new branch?

A: You need read some materials about [git branch model, or git workflow. The following two links will be a good start.
git wokflow
git branch model
You need not creating new branch for your case as you described in your question, but if you have needs to work on multiple new features, or interrupted by certain hot fix request, a new branch will be a help.

A: It is common to use reuse the same branch in this way.
For example, suppose you have a 'dev' branch and a 'maintenance' branch. You may do lots of commits on the 'dev' branch, and periodically merge 'dev' into 'maintenance'. After merging, you can do more commits on 'dev'.

A: You don't have to create branch every time you want push your change into the master branch.. use the branch for divide the tasks for your project.. for this issue.. you can use the same branch..


text:
Q: How can I fasten the "histc" Matlab function I need to fasten this part of my Matlab code :
 double(sum(histc(windows, 0:1:255),2)')

It is applied on every pixel of a large image, it is for calculating the local histogram (within 'windows') so it is very quite consuming.
Do you have any suggestion to fasten the computing ?
Thanks a lot.

A: You can exploit the overlap between adjacent pixels. Lets say you us a window of size 3x3 and have calculated the histogram for a pixel I(x,y), then the histogram for pixel I(x+1,y) will contain 6 of the same pixels. So you need only subtract 3 values and add 3.
Your code looks wrong. histc returns bin counts and then you sum the counts which should always add up to the size of your window. Do you want to calculate the sum of pixel intensities within the window? Then you should just use the sum function directly.


text:
Q: Java Batch job in cluster environment We have a cluster with 2 JBOSS nodes.  We have a batch job which loads all users details from a active directory to a DB.  This job is run everyday.  It was run before in a non clustered environment and hence we designed it as a singleton.
Now we have a clustered environment and I do not know what is best way to achieve the same result.  I want batch job to be run only once a day.  We use spring and hibernate and I looked at Spring batch.  I could not get any concise answer to my question.
Can anybody please let me know if you had implemented batch in cluster environment?  What would be the best solution in this scenario?

A: We implemented this by triggering and starting the jobs externally via MQ ( an http request to start the job would work as well).  The scheduler puts a message on the queue and even though we have 'n' nodes listening to the queue, one node will receive the message and based on it's contents, start the job.  You can do this with HTTP as well.
The real 'solution' to this is to schedule the batch job 'externally' and not via an internal cron trigger.  The actual start mechanism is secondary to that.

A: Consider also https://github.com/willschipp/spring-batch-cluster that features

*

*write-behind for the Batch Job Repository

*HA for batch in a cluster (automatic stop and failover of executing jobs)

A: In general, it's sometimes a good idea to externalize/isolate batch jobs from transactional systems, so they don't interfere with availability or performance.  That being said, if there are good reasons for embedding a batch job in a clustered application (simplicity, code reuse, etc.), then aside from solutions already mentioned, ShedLock is a great option.
Note for whatever its worth, a blog post about batch jobs in clustered environments.


text:
Q: Strange keywords for documents with "CLF" I'm using fts and observed strange behavior when the text contains a string "clf". For some reason keywords created for documents with "clf" string behave differently then almost identical documents with some other string in place of "clf". Bellow is code to recreate described behavior
CREATE TABLE [dbo].[test1](
    [id] [int] NOT NULL,
    [data] [nvarchar](max) NULL,
 CONSTRAINT [PK_test1] PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE FULLTEXT CATALOG test_catalog;

CREATE FULLTEXT INDEX ON [dbo].test1
(
    data
)
KEY INDEX [PK_test1] ON test_catalog

insert into dbo.test1 values (1, N'17 12 CLF'), (2, N'17 13 bbb'), (3, N'17 129 CLF'), (4, N'17 139 aaa')

Then when we query keywords created
SELECT * FROM sys.dm_fts_index_keywords_by_document( DB_ID('db_name'), OBJECT_ID('dbo.test1') )

we can see that keywords created for document with "clf" are different then with "aaa" and "bbb". For example for document 4 there is keyword "139" but for document 3 there is not "129" and there is only "17 129 clf".
What is the reason for this behavior? Is there a simple way to force fts to behave the same way for strings with and without "clf"?

A: Using fulltext search on technical values could be challenging.
The stop-word-list and the dictionary language affect the search.
I disabled in my project the stoplist (off) and set the language to neutral.
When you are searching with "contains" and you are using "*" in the words, then remember this:
SQL-Server could only do a prefix search!
see here:
https://technet.microsoft.com/en-us/library/ms187787%28v=sql.105%29.aspx
with neutral language and no stoplist it looks equal:
document 3:
129
17
17 129
clf
nn129
nn17
nn17129

document 4:
139
17
17 139
aaa
nn139
nn17
nn17139


text: Q: Synaptics touchpad not responding after kernel update I did a software update from my 3.13 Ubuntu kernel, and it took away my Intel 3460 wifi drivers so I didnt have internet anymore.. I then had to install the newer 4.04 kernel, and after the reboot the wifi came back but now my SynPS/2 laptop touchpad isnt working.. On xinputI see my pointer as SynPS/2 with id 12 as a slave pointer (2), however I also see a DLL06F0 UNKNOWN slave pointer which on doing xinput -list-props 15 shows a change on every key press so it looks like the keyboard ? Ive been trying to fix this forever now and either wifi fix on 3.13 or mouse fix on 4.04 would be truly appreciated!


text:
Q: Update iOS 5 to 7.0.6 from copied .ipsw file to phone I've recently downloaded .ipsw file (firmware 7.0.6) and want to update my apple 4s 32 gig phone (ios 5).
but when I tried to to use iTunes (holding shift key in windows 7 + press update button in iTunes -> choose .ipsw file for update) I got the error below :

http://support.apple.com/kb/TS4451
What does this error mean and how can I fix it?
I've downloded iTunes 11.2 (latest version)

Extra questions:
I am certainly sure there is no problem about my internet or hosts file.
I turned my anti virus & firewall off and after that still got that error.
Is it possible to transfer .ipsw file to my phone and run it from there?
If yes, where should I copy that file and how can I run it?
If no what is the solution and how can i fix that error?


text:
Q: OS X .dictionary format information Who knows where can I find information about .dictionary format and how to manually read from it?
I know that .dictionary is a directory but I have no idea on how to handle it contents.
I would like to read it manually.


text:
Q: WPF DatagridComboboxcolumn not in combobox style This has been a long problem of mine, and even though there are a lot of solutions out there, none has seemed to work for me.
How do I make the DataGridComboBoxColumn display as Combobox when it is not focused?
I tried using DataGridTemplateColumn and I've almost been successful in it except that when trying to identify the selected item in the Combobox, the value returns back to previous data, and honestly made it a lot harder for me to work on this compared to just using DataGridComboBoxColumn.
How can I do this without using DataGridTemplateColumn?
The DataGrid is found in a UserControl which is dynamically added to the MainWindow.
XAML
<!-- This is my preferred way-->
<DataGridComboBoxColumn Header TagType x:Name="TagTypeCombo" SelectedValueBinding="{Binding TagType}"/>

<!--This is similar to all of solutions that I've seen-->
<DataGridTemplateColumn Header="Tag Type" x:Name="ComboTemplate">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox Width="135" x:Name="Tagger" ItemsSource="{Binding tagType,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" SelectedItem="{Binding Tags}" SelectedValuePath="TagType"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Code-Behind
public int counter;
List<Tags> tags = new List<Tags>();
public event EventHandler SaveButtonClicked;
public List<string> tagType = new List<string>() { "Modbus Coil(0x)", "Discrete Input(1x)", "Input Register(3x)", "Holding Register(4x)" };
public ModbusCard2()
{
    InitializeComponent();
}
public class Tags
{
    public int TagAddress { get; set; }
    public string TagType { get; set; }
    public string TagID { get; set; }
}
private void DeleteButton_Click(object sender, RoutedEventArgs e) => ((WrapPanel)this.Parent).Children.Remove(this);
private void Tagger_Loaded(object sender, RoutedEventArgs e)
{
    var cx = sender as ComboBox;
    cx.ItemsSource = tagType;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    for (int i = 1; i <= counter; i++)
    {
        tags.Add(new Tags() { TagAddress = 0, TagID = $"M{i}", TagType = "Discrete Input(1x)" });
    }
   DevTags.ItemsSource = tags;
}

private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    SaveButtonClicked?.Invoke(sender, e);
}

private void EditButton_Click(object sender, RoutedEventArgs e) => DevTags.IsReadOnly = false;

//For the SaveButtonClicked found in MainWindow
private void SaveButtonClicked(ModbusCard2 d)
{
    foreach (var a in d.DevTags.Items.OfType<Tags>().ToList())
    {
        if (a.TagType == d.tagType[1])
        {
            a.TagID = $"M{DICount}";
            DICount++;
        }
        if (a.TagType == d.tagType[2])
        {
            a.TagID = $"R{AICount}";
            AICount++;
        }
        d.DevTags.Items.Refresh();
    }
    d.DevTags.IsReadOnly = true;
}

A: Try this with your ComboBox that's currently inside your TemplateColumn.
It adds logic in your binding to update your source trigger, while also removing your SelectedValuePath tag. I'm assuming based on your lack of a DisplayMemberPath tag that your ComboBox ItemsSource is a string collection. If this is the case the SelectedValuePath can actually wreck your bindings (I have no idea why though).
<ComboBox Width="135" x:Name="Tagger" ItemsSource="{Binding tagType,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" SelectedItem="{Binding Tags, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Let me know if you still have binding update issues after, and will go from here.


text:
Q: Does the work I do with a Live USB Drive or Live DVD leave any trail (eg: tmp files) on my machine? I want to know how Live DVD and USB drive work.

*

*Do they use the disk of my PC at all?

*If so, do they delete everything after I shut down the PC?

*If so, are the tmp files deleted securely? Or they can be recovered?

I'm thinking of a Live DVD like BackTrack, which is used for security tests, etc.

A: They usually mount tmpfs to /tmp, which is an in-memory filesystem (like a ramdisk on steroids). So, it is as secure as your memory is.


text:
Q: Drupal email wraps path I am sending an email from my Drupal website using the hook_mail().
My problem is that the folder where the report is saved into has spaces in its name "to keep folder" and the email's body wraps exactly in the middle of the name of that folder EX:
Please visit \\folder1\folder2\to keep
folder to see the report.

I was asked to make the "\folder1\folder2\to keep folder" internal path a link if possible or to at least force the whole path to stay on one line.
I tried the url() function like this:
$message['body'][] = 'Please visit ' . url('\\\\folder1\folder2\to keep folder') . ' to see the report.';

but still it will not show up as a link.
Here is my entire hook_mail() function:
/**
 * Implements hook_mail().
 */
function my_module_mail($key, &$message, $params) {
  switch ($key) {
    case 'email_success':
      $message['headers']['Bcc'] = 'my_email@mydomain.com';
      $message['subject'] = 'Successfully generated the report';
      $message['body'][] = 'The daily budget report has been generated.';
      $message['body'][] = 'Please visit ' . url('\\\\folder1\folder2\to keep folder') . ' to see the report.';
      break;

    case 'email_fail':
      // Build the other email
      break;
  }
}

Any ideas ?

A: Your emails are probably being sent in plain text. Try contrib module Mime Mail allowing you to receive emails in HTML.
Via configuration > system > mimemail, choose your preferred E-mail format & try your hook_mail again.


text:
Q: How can I make the default Nav Menu into a Responsive toggle navigation menu? I have working on a site( http://sitepreview.net63.net/ ). But I want to make it a responsive site. So I want to make the navigation menu( which comes from the Wordpress Menu Bar ) a toggle navigation menu in the small screens. I am giving an image link here, where you can check what I want, please go to this link: http://sitepreview.net63.net/wp-content/uploads/2013/10/responsive-nav-menu.jpg .

A: You will need to use media queries to disable the nav and show the mobile nav. You then can use some jQuery to know if the screen size is this size to add click function to the nav.
Something like this
HTML

home

About

Blah Blah

home

About

Blah Blah

CSS
.fullNav {
  /*Code goes here */
}
.mobileNav {
  /*Code goes here */
    display: none;
}

Media Query
@media only screen and (max-width: 680px) {
    .fullNav {
      display: none;
    }
    .mobileNav {
      display: block;
    }
}

jQuery
if ($(window).width() < 680) { // if statement is not 100% needed
  $('.mobileNav').on('click', function() {
     $(this).children().slideToggle();
  }
}

Header tag
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0;">


text:
Q: Django - Register App Model in Custom AdminSite I have a django project with three apps: website, blog, and customauth. The customauth app implements a custom user and AdminSite. The blog app has a Post model. I am trying to register the Post model with the custom AdminSite and I receive the following error:
NoReverseMatch at /my_admin/
Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$']
Request Method: GET
Request URL:    http://127.0.0.1:8000/my_admin/
Django Version: 2.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$']

Here is customauth/admin.py:
class MyAdminSite(admin.AdminSite):
    site_title = "Custom Administration Area"
    site_header = 'Custom Administration Area'

    def get_urls(self):
        urls = super(MyAdminSite, self).get_urls()
        my_urls = [
            url(r'^my_view/$', self.my_view, name='my_view'),
        ]
        return my_urls + urls

    def my_view(self,request):
        value = "You're looking at the new admin view."
        context = dict(
           # Include common variables for rendering the admin template.
           self.each_context(request),
           # Anything else you want in the context...
           key=value,
        )
        return TemplateResponse(request, "website/admin.html", context)

admin_site = MyAdminSite(name='myadmin')
# Now register the new UserAdmin...
admin_site.register(MyUser, UserAdmin)

And here is blog/admin.py:
from django.contrib import admin
from customauth.admin import admin_site
# Register your models here.
from .models import Post

class PostAdmin(admin.ModelAdmin):
    pass

admin_site.register(Post,PostAdmin)

Here is the website/urls.py:
from django.contrib import admin
from django.urls import include, path
from customauth.admin import admin_site

from . import views

urlpatterns = [
    path('admin/',       admin.site.urls,            name='admin'),
    path('my_admin/',    include('customauth.urls'), name='custom_admin'),
    path('',             views.index,                name='index'),
    path('latest_news/', include('blog.urls'),       name='latest_news')
]

And here is the customauth/urls.py:
from . import views
from .admin import admin_site

urlpatterns = [
    path('', admin_site.my_view, name='custom_admin'),
]

What am I doing wrong?

A: I figured out what I did wrong.
The problem is the way I configured the urls.
In website.urls I changed:
path('my_admin/',    include('customauth.urls'), name='custom_admin'),

to
path('my_admin/',    admin_site.urls,      name='custom_admin'),

And that solved the problem. I no longer need the customauth.urls file.


text: Q: notation "interior to" I am writing out some notes as review, and a thing I often say is "z is a point interior to C". I was wondering if there is a common shorthand to write this before I make one up for myself. C is a contour if that makes a difference


text:
Q: How to change the preferred mode on xrandr? I have a dual monitor setup, a laptop monitor and an external VGA monitor. The preferred mode should be 1920x1080 on laptop and 1600x900 on external monitor.
That's how it was but I installed (and then uninstalled) some nvidia drivers for other reasons. When I reinstalled the nouveau drivers the preferred modes on both monitors were 1024x768.
As you can see below on xrandr output the monitors have two preferred modes! Only that when using the --preferred flag it uses the undesirable 1024x768.
I am currently using a half fix by running on start up:

xrandr --output eDP1 --mode 1920x1080 --output VGA1 --mode 1600x900 --left-of eDP1 --primary

instead of running as before:

xrandr --output eDP1 --preferred --primary --output VGA1 --left-of eDP1 --preferred

The problem is that the display manager (slim) is still displayed on 1024x768 resolution and I have to log in for the preferred resolutions. Also in case I plug in a different monitor I would have to manually run xrandr with the correct resolution.
Is there a way to disable 1024x768 as a preferred resolution?
xrandr output http://pastebin.com/xuPEFMrH

Also, here is the xorg.conf in case it is needed: http://pastebin.com/8DemF0qi
I am not exactly certain how the xorg.conf regarding the monitors is interacting. I tried to change all 1024x768 to 1920x1080 but it didn't change anything.


text:
Q: Binding "Highcharts" events in rails I'm trying to bind a function in the load event of Highchart (In Rails).
raw "options.chart.events.load = abc();"

I have an alert in the function abc(), which gets fired but, the graph is not rendered with following error:
Uncaught TypeError: Cannot set property 'load' of undefined

Function defination:
function abc(){
  alert('Hi');
}

What mistake am I doing?

A: I encountered the same problem and found this solution
<%= high_chart("some_id", LazyHighCharts::HighChart.new('column') do |f|
    f.options(
          chart: {
            :events => {
              :load => "function(){ return false; }".js_code
            }
          }
      )
<% end %>


text:
Q: Reading value from XML file Throws an error - FAKE F#MAKE I am trying to read value from XML file from FAKE , But I am getting an error i.e.
.fsx(9,16) : eror FS000: Incomplete structurd construct at or before this
 point in expression. Expected '->' or other token.

Below is my code , I am using XMLHelper.XMLRead to read values from xml file .
#r "./packages/FAKE/tools/FakeLib.dll"
open Fake
open Fake.XMLHelper
Target "BuildMain" (fun _ ->
    for s in XMLHelper.XMLRead true "D:/test/Version.Config" "/version/major/minor"
        trace s)
"BuildMain"
RunTargetOrDefault "BuildMain"

Below is my XML File :
<version>
  <major number="2">
    <minor>1</minor>
    <build>1</build>
    <revised>1</revised>
  </major>
</version>

Here I am trying to read value from minor version , and moreover can I store this value in a variable so that I can use this later ??

A: The for ... in construct requires either do or an arrow -> before the body:
for s in XMLHelper.XMLRead true "D:/test/Version.Config" "/version/major/minor" do
    trace s

You use do if the body is another loop or just side-effecting code, as in:
for x in 1..5 do
   printfn "%d" x

You use arrow -> to have the body produce a value, which then becomes part of the resulting list or sequence, as in:
let evenNumbers2to10 = [for x in 1..5 -> x*2]

The arrow -> can be viewed as a shortcut for do yield:
let evenNumbers2to10 = [for x in 1..5 do yield x*2]


text:
Q: Sequelize do not work when I use Op.and and Op.ne I use Sequelize to query my database.
I use Op.and and Op.ne in my query :
const Op = require('sequelize');
let subLevels = await SubAchievement.findAll({
    where: {
        [Op.and]: [
            { upLevel: level.id, },
            {
                level: {
                    [Op.ne]: 2
                }
            }
        ]
    }
});

when I run my program. i get this error:
(node:72806) UnhandledPromiseRejectionWarning: Error: Invalid value { upLevel: 1 }

and I can not find Op.ne in Op, but Op.and can be found.
why?

A: const Op = require('sequelize');
let subLevels = await SubAchievement.findAll({
    where: {
        [Op.and]: [
            { upLevel: { [Op.eq]: level.id, } }, // [Op.eq] is added
            { level: { [Op.ne]: 2 } }
        ]
    }
});


text:
Q: Расположение объектов по математической функции в цикле (оптимизация) Доброго времени суток.
У меня есть некоторый список объектов, и их нужно расположить по полуокружности относительно некоего центра:

Количество объектов всё время разное и варьируется от 0 до 5. Точки расположения объектов указаны зелёными кружочками; порядок расположения - справа налево.
И, в принципе, мне понятно, какие условия надо проверять, чтобы задать позицию для объекта. Вопрос вот в чём: как оптимизировать ?
for (int i = 0; i < gameObjects.Count; i++)
{
    while (x != x_center || y != y_center || x != x_center + deltaX || x != x_center - deltaX)
    {
        x -= 0.01f;
        y = y_center + (float)Math.Sqrt(radius * radius - x * x);
    }
    gameObjects[i].transform.position = new Vector3(x, 0, y);
    x -= 0.01f;
    y = y_center + Mathf.Sqrt(radius * radius - x * x);
    if (x < (x_center - radius)) { break; }
}

Программа зависает, так и не выдавая результата, что абсолютно очевидно: через отладку я посмотрел, что цикл while идёт слишком долго. Что можно предпринять? Может, стоит использовать Math.Round() и пренебречь дробными разрядами и точностью? Или есть способ быстро пробегать по математической функции?
Заранее спасибо за ответ.

A: В общем, я понял, что надо задавать условия в цикле while с погрешностями. Отдельное спасибо Александру, который ответил мне в комментариях.
Если возникнут проблемы - напишу сюда; если нет - тема закрыта.


text:
Q: KVM + Cloudmin + IpTables I have a KVM virtualization on a machine. I use Ubuntu Server + Cloudmin (in order to manage virtual machine instances).
On a host system I have four network interfaces:
ebadmin@saturn:/var/log$ ifconfig
br0       Link encap:Ethernet  HWaddr 10:78:d2:ec:16:38
    inet addr:192.168.0.253  Bcast:192.168.0.255  Mask:255.255.255.0
    inet6 addr: fe80::1278:d2ff:feec:1638/64 Scope:Link
    UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
    RX packets:589337 errors:0 dropped:0 overruns:0 frame:0
    TX packets:334357 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:753652448 (753.6 MB)  TX bytes:43385198 (43.3 MB)

br1       Link encap:Ethernet  HWaddr 6e:a4:06:39:26:60
    inet addr:192.168.10.1  Bcast:192.168.10.255  Mask:255.255.255.0
    inet6 addr: fe80::6ca4:6ff:fe39:2660/64 Scope:Link
    UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
    RX packets:16995 errors:0 dropped:0 overruns:0 frame:0
    TX packets:13309 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:2059264 (2.0 MB)  TX bytes:1763980 (1.7 MB)

eth0      Link encap:Ethernet  HWaddr 10:78:d2:ec:16:38
    UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
    RX packets:610558 errors:0 dropped:0 overruns:0 frame:0
    TX packets:332382 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:1000
    RX bytes:769477564 (769.4 MB)  TX bytes:44360402 (44.3 MB)
    Interrupt:20 Memory:fe400000-fe420000

lo        Link encap:Local Loopback
    inet addr:127.0.0.1  Mask:255.0.0.0
    inet6 addr: ::1/128 Scope:Host
    UP LOOPBACK RUNNING  MTU:16436  Metric:1
    RX packets:239632 errors:0 dropped:0 overruns:0 frame:0
    TX packets:239632 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:50738052 (50.7 MB)  TX bytes:50738052 (50.7 MB)

tap0      Link encap:Ethernet  HWaddr 6e:a4:06:39:26:60
    inet6 addr: fe80::6ca4:6ff:fe39:2660/64 Scope:Link
    UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
    RX packets:17821 errors:0 dropped:0 overruns:0 frame:0
    TX packets:13703 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:500
    RX bytes:2370468 (2.3 MB)  TX bytes:1782356 (1.7 MB)

br0 is connected to a real network, br1 is used to create a private network shared between guest systems.
Now I need to configure iptables for network access.
First of all I allow ssh sessions on port 8022 on the host system, then I allow all connections in state RELATED, ESTABLISHED.
This is working ok.
I install another system as guest, it's IP address is 192.168.10.2, and now I have two problems:

*

*I want to allow the access from this host to the outside world, cannot accomplish this. I can ssh from the host.

*I want to be able to ssh to the guest from the outside world using 8023 port. Cannot accomplish this.
Full iptables configuration is following:
ebadmin@saturn:/var/log$ sudo iptables --list
[sudo] password for ebadmin:
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8022
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
LOG        all  --  anywhere             anywhere             LOG level warning

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
LOG        all  --  anywhere             anywhere             LOG level warning

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
LOG        all  --  anywhere             anywhere             LOG level warning
ebadmin@saturn:/var/log$ sudo iptables -t nat --list
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DNAT       tcp  --  anywhere             anywhere             tcp spt:8023 to:192.168.10.2:22

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination

The worst of all is that I don't know how to interpret iptables logs. I don't see the final decision of the firewall.
Need help urgently.

A: Set up a second virtual NIC for the guest which is bridged to br0 on the host.

A: Try using the power of SSH! Edit your config:
vi ~/.ssh/config

Host saturn
    HostName saturn.yourdomain.com # little shortcut

Host guest1
    ProxyCommand ssh -q saturn nc -q0 guest1.internal.name 22 #(or SSH port)

Then, from the outside world, you could do:
ssh myuser@guest1

And the host will sling you straight in. Don't muck about with iptables for this.


text:
Q: Compiling XPath expression in C# leads to 'invalid token' exception I am trying to compile an XPath expression in C# but I keep getting the below exception
'max(//*[local-name()="acc"][accdetails/accgroupid="2" and accdetails/status="N"]/acchistory/count(ah[position()<=3 and (self::ah/@pay>following-sibling::ah[1]/@pay)]))' has an invalid token.

   at MS.Internal.Xml.XPath.XPathParser.CheckToken(LexKind t)
   at MS.Internal.Xml.XPath.XPathParser.ParseMethod(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParsePrimaryExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseFilterExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParsePathExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseUnionExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseUnaryExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseMultiplicativeExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseAdditiveExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseRelationalExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseEqualityExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseAndExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseOrExpr(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseExpresion(AstNode qyInput)
   at MS.Internal.Xml.XPath.XPathParser.ParseXPathExpresion(String xpathExpresion)
   at System.Xml.XPath.XPathExpression.Compile(String xpath, IXmlNamespaceResolver nsResolver)
   at System.Xml.XPath.XPathNavigator.Compile(String xpath)

The above exception comes from the below code
public object ParseCreditReportResponse(XmlDocument document)
{
    var navigator = document.CreateNavigator();
    var expr = navigator.Compile("max(//*[local-name()=\"acc\"][accdetails/accgroupid=\"2\" and accdetails/status=\"N\"]/acchistory/count(ah[position()<=3 and (self::ah/@pay>following-sibling::ah[1]/@pay)]))");

    return expr;
}

Can someone help identify the problem with the XPath statement. The problem appears to revolve around /acchistory/count(ah[position()<=3 and (self::ah/@pay>following-sibling::ah[1]/@pay)])

A: Function invocation in path step is not supported in XPath 1.0 i.e /acchistory/count(...) in your XPath. There might be a solution to accomplish what you wanted to accomplish in one XPath, but the XPath will likely become complicated then, as it is quite complex to start with.

A: It's possible that you need to escape the angle bracket. Replace < with <.

A: Maybe you should add a '@' symbol before your xpath like that:
@"max(//*[local-name()=\"acc\"][accdetails/accgroupid=\"2\" and accdetails/status=\"N\"]/acchistory/count(ah[position()<=3 and (self::ah/@pay>following-sibling::ah[1]/@pay)]))"


text:
Q: How do I include the text of a file in my Java code? It seems that Java is not set up to do what I have previously done in C++ (no big surprise there). I've got a set of rules that are generated from another application (a series of if-then checks). These rules change from time to time, so in C++ I would do this:
double variableForRules=1;
bool condition=false;
#include "rules.out";
if(condition) //do something

Essentially the if-then checks in rules.out would use the "variableForRules" (and several other variables) to decide whether condition should be set to true. If it gets set to true after the eval of the rules, the program does something.
Is there a similar way to do this in Java? Or is my only option to have rules.out actually be an entire class that needs to be instantiated, etc.?
Thanks!

A: Since you're autogenerating that rules.out, you could autogenerate your Java function as well.  Hopefully it's not too painful to add that functionality.

A: Since there is no preprocessor in Java, you can't do this. Like you said, you have to implement your logic inside a class.

A: Maybe you could use scripting for that. You could take a look at the Java Scripting Programmer's guide.

A: In Java, it would be common for the other application to save the rules into an .xml or .properties file, and then have Java read in that file.

A: rules.out actually has to be an entire class that needs to be instantiated for code to be executed.
Since rules.out is generated by third-party application, best thing would be to write your own CppToJavaTransformer that reads file rules.out as input and generates Rules.java. This assumes rules.out is available before compile time and Rules.java will be used at compile time. Drawback of this is that there is an extra transformation required.
Alternately you can write code that interprets rules.out and execute required instructions using introspection. This is hard way but rules.out can be changed at runtime as well.

A: Even if could include the rules file it would be of no help. Your rule are dynamic as you said. Looks like you java code needs to change for a different scenario.

A: You could try using reflection (See: Creating New Objects and Invoking Methods by Name)
First generate a Rules.java in the manner in which you currently build rules.out and compile it.
Then load the class file into your app at runtime in the manner in which JDBC drivers were traditionally loaded.
Class clazz = Class.forName("com.mydomain.Rules");

If your app runs for long periods of time (longer then the lifetime of a single Rules.class file) then you would have to create your own ClassLoader in order to swap out the underlying class during a single runtime.


text:
Q: Finding the only multiple zero of a quadratic function I don't know how to figure this problem out. Can someone please help?
For what value of $\;b\;$ will $\;f(x)=x^2 + bx + 400\;$ have $\;-20\;$ as its only zero?

A: The number $\;-20\;$ is a zero of the function $\;f(x)=x^2+bx+400\;$ if and only if $\;f(-20)=0\;.$
$(-20)^2+b(-20)+400=0\;,$
$400-20b+400=0\;,$
$-20b=-800\;,$
$20b=800\;,$
$b=\dfrac{800}{20}=40\;.$
Moreover, if $\;b=40\;,\;$ then it results that $\;f(x)=x^2+40x+400=(x+20)^2\;,$
consequently,
$f(x)=(x+20)^2=0\iff x+20=0\iff x=-20\;,$
so $\;-20\;$ is the only zero of $\;f(x)\;.$
Hence, the value of $\;b\;$ such that $\;f(x)=x^2+bx+400\;$ has $\;-20\;$ as its only zero, is
$b=40\;.$
Another way to solve the exercise:
$f(x)=x^2+bx+400\;.$
$x^2+bx+400=0\;,$
and, by applying the quadratic formula's determinant,
$\Delta=b^2-4ac=b^2-4\cdot1\cdot400=b^2-1600\;.$
$f(x)=x^2+bx+400\;$ has only a zero if and only if $\;\Delta=0\;.$
$b^2-1600=0\;,$
$b^2=1600\;,$
$b=\pm\sqrt{1600}=\pm40\;.$
If $\;b=-40\;,\;x=\dfrac{-b\pm\sqrt{\Delta}}{2a}=\dfrac{40\pm0}{2}=20\;.$
If $\;b=40\;,\;x=\dfrac{-b\pm\sqrt{\Delta}}{2a}=\dfrac{-40\pm0}{2}=-20\;.$
Hence, the value of $\;b\;$ such that $\;f(x)=x^2+bx+400\;$ has $\;-20\;$ as its only zero, is
$b=40\;.$

A: For a quadratic equation having one root, its discriminant is zero, i.e.
$$b^2- 4\cdot 400=0$$
which leads to $b=\pm40$. Check to determine that $b=40$ from the given root $-20$.


text:
Q: Strange double subtraction result in .NET I'm aware of the inaccuracies of floating point operations but the results of the below code seem rather odd to be. Can anybody please explain it?
This is with .NET Framework 4.8 on Windows 10. The code was compiled with csc.exe and no other options.
Thanks!
using System;
class Test {

    public static void Main() {
        double f1 = Math.Exp(Math.Log(10));
        double f2 = 10;
        double f3 = 10;

        Console.WriteLine(f1);
        Console.WriteLine(f1-10.0);
        Console.WriteLine(f2-f3);
    }
}

The results are:
10
1.77635683940025E-15
0

An inspection of the generated code with ildasm shows:
  IL_0001:  ldc.r8     10.
  IL_000a:  call       float64 [mscorlib]System.Math::Log(float64)
  IL_000f:  call       float64 [mscorlib]System.Math::Exp(float64)
  IL_0014:  stloc.0
  IL_0015:  ldc.r8     10.
  IL_001e:  stloc.1
  IL_001f:  ldc.r8     10.
  IL_0028:  stloc.2
  IL_0029:  ldloc.0
  IL_002a:  call       void [mscorlib]System.Console::WriteLine(float64)
  IL_002f:  nop
  IL_0030:  ldloc.0
  IL_0031:  ldc.r8     10.
  IL_003a:  sub
  IL_003b:  call       void [mscorlib]System.Console::WriteLine(float64)
  IL_0040:  nop
  IL_0041:  ldloc.1
  IL_0042:  ldloc.2
  IL_0043:  sub
  IL_0044:  call       void [mscorlib]System.Console::WriteLine(float64)

I can't see any obvious explanation for the difference so what might I be missing?
Thanks!

A: Try with "G" format specifier (precision of 15 for doubles).
Update: In .NET Framework (as opposed to .Net Core/5) G or G15 doesn't help. We need to use R (round-trip format specifier).
Console.WriteLine(f1.ToString("R"));
Console.WriteLine((f1-10.0).ToString("R"));
Console.WriteLine((f2-f3).ToString("R"));

This produces:
10.000000000000002
1.7763568394002505E-15
0

Since 1.77635683940025E-15 rounds up to 0.000000000000002 it all seems fine.


text:
Q: Why aren't merged answers tagged in their titles? I came across this question which was recently merged: https://stackoverflow.com/questions/4551090/codegolf-find-the-unique-paths
It's not marked as closed in the title and as such there is no indication from seeing it in a list of questions why it has 0 votes and 0 answers (for reference the main copy has 11 votes and 8 answers). Is this a bug, missing feature or by design?

A: It's not closed. It's locked.* And locked questions don't get anything appended to their titles.
*Ok, so this isn't obvious either... Merge-source questions are automatically locked - it's implicit in the "merged" indicator following the question, and explicitly noted in the question's revision history.

A: This one should have been deleted anyway, so your question is moot.
I've deleted it.


text:
Q: TypeError: AWS.S3 is not a constructor I am trying to create a NPM package but before I do that, I am testing it using the
yarn link command and then importing the node_module into another project.
This is what my package.json for the NPM package looks like
{
  "name": "qa-data-tool",
  "version": "1.0.0",
  "description": "AWS uploads to S3 to support testing of invoicing PYCMA accounts",
  "main": "dist/cjs/index",
  "types": "dist/cjs/index.d.ts",
  "type": "module",
  "exports": {
    ".": {
      "require": "./dist/cjs/index.js",
      "import": "./dist/esm/index.js"
    }
  },
  "files": [
    "/dist"
  ],
  "scripts": {
    "tsc": "tsc",
    "test": "jest",
    "test typescript": "tsc ./src/testing.ts && node ./src/testing.js",
    "build": "rm -rf dist/ && prettier --write src/ && npm run build:esm && npm run build:cjs",
    "build:esm": "tsc",
    "build:cjs": "tsc --module CommonJS --outDir dist/cjs"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": ""
  },
  "devDependencies": {
    "@babel/core": "^7.18.10",
    "@babel/preset-env": "^7.18.10",
    "@babel/preset-typescript": "^7.18.6",
    "@types/jest": "^28.1.7",
    "@typescript-eslint/eslint-plugin": "^5.17.0",
    "@typescript-eslint/parser": "^5.17.0",
    "babel-jest": "^28.1.3",
    "esbuild": "^0.14.54",
    "eslint": "^8.12.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-airbnb-typescript": "^17.0.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-typescript": "^2.7.0",
    "eslint-plugin-import": "^2.25.4",
    "eslint-plugin-json": "^3.1.0",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.29.4",
    "jest": "^28.1.3",
    "prettier": "^2.6.1",
    "ts-node": "^10.9.1",
    "typedoc": "^0.22.13",
    "typescript": "^4.7.4"
  },
  "dependencies": {
    "@types/json2csv": "^5.0.3",
    "aws-sdk": "^2.1200.0",
    "csv": "^6.2.0",
    "csv-parser": "^3.0.0",
    "dayjs": "^1.11.5",
    "dotenv": "^16.0.1",
    "json2csv": "^5.0.7"
  },
  "jest": {
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts)$",
    "moduleFileExtensions": [
      "ts",
      "js"
    ]
  }
}

This is the folder sturcture of my project:

I am initializing the S3 bucket like so:
import * as dotenv from 'dotenv';
import * as path from 'path';
import * as fs from 'fs';
import * as util from 'util';
import * as AWS from 'aws-sdk';

dotenv.config({ path: path.resolve('.env') });
const readFile = util.promisify(fs.readFile);

const s3 = new AWS.S3({
  region: process.env.REGION,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
});

/**
 * Uploads a file to the specified S3 bucket
 * @param filePath - relative path of the file you would like to upload e.g src/uploads/filename.txt
 * @param bucketName - the name of the bucket you would like to upload to e.g aspiration-galileo-staging-sftp-all/2023/09/
 */
export async function s3Upload(
  filePath: string,
  bucketName: string,
): Promise<void> {
  const fileData = await readFile(filePath);
  let extractFileName = filePath.split('/');
  const uploadFile = s3
    .putObject({
      Bucket: bucketName, //bucket name to upload your file too
      Key: extractFileName[extractFileName.length - 1], //name of the file will be the last element in the array
      Body: fileData,
    })
    .promise();
  uploadFile
    .then((data) => {
      console.log(`File uploaded to s3 bucket: ${bucketName} successfully`);
    })
    .catch((err) => {
      console.log(err);
    });
}

Now when I try to use these modules in my simple node.js package I get the following error:
const s3 = new AWS.S3({
           ^

TypeError: AWS.S3 is not a constructor

can someone point me in the right direction on how to solve this error message?

A: had to change my code to
import * as dotenv from 'dotenv';
import * as path from 'path';
import * as fs from 'fs';
import * as util from 'util';
import S3 from 'aws-sdk/clients/s3.js';

dotenv.config({ path: path.resolve('.env') });
const readFile = util.promisify(fs.readFile);

const s3 = new S3({
  region: process.env.REGION,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
});

/**
 * Uploads a file to the specified S3 bucket
 * @param filePath - relative path of the file you would like to upload e.g src/uploads/filename.txt
 * @param bucketName - the name of the bucket you would like to upload to e.g aspiration-galileo-staging-sftp-all/2023/09/
 */
export async function s3Upload(
  filePath: string,
  bucketName: string,
): Promise<void> {
  const fileData = await readFile(filePath);
  let extractFileName = filePath.split('/');

  s3.upload(
    {
      Bucket: bucketName, //bucket name to upload your file too
      Key: extractFileName[extractFileName.length - 1], //name of the file will be the last element in the array
      Body: fileData,
    },
    (err, data) => {
      if (err) {
        console.log('There was an error uploading your file: ', err);
      }
      console.log('Successfully uploaded file.', data);
    },
  );
}


text:
Q: How do I make a svg icon and a select input box vertically align in a div? Here is the code:
http://jsfiddle.net/jj9gLxta/1/
#wrapper {
  vertical-align:middle;
  display:inline-table;
}
#wrapper select {
  margin-left:5px;
}

I'd like to make the svg icon and select box vertically aligned.
BTW the svg icon and the select input may be in other sizes, so I need some css to make it applicable to different designs.
Thanks,

A: This fiddle should have the desired effect. I removed styling from the wrapper element, and made these changes:
#wrapper select {
  display:inline-block;
  margin-left:5px;
}
#icon {
  display:inline-block;
  vertical-align: middle;
}

A: You could also use something like
display: table;

and also:
display: table-cell;

Like the following example:
http://jsfiddle.net/aq8gv4hj/1/
Better explained here:
https://css-tricks.com/centering-in-the-unknown/


text:
Q: sql server conditional where select * from table where category=@categoryid

I'm not sure how easy is this but I couldn't get my head around it. I want to be able to change where clause on above query so that if use 0 instead of 1-2-3 or 4 as @categoryid it would select all categories. i don't have any category with 0 in database.

A: Simple.
select * from table where (category=@categoryid) OR (@categoryid = 0)

A: This should probably be divided into 2 separate queries unless you actually want the same execution plan of a full clustered index scan to be used both in the case that @categoryid=0 and @categoryid<>0
By dividing into 2 separate queries you will potentially allow the ones where @categoryid is not zero to be satisfied by an index seek rather than the full scan.
If the table is small or @categoryid is not very selective it might not be an issue however.

A: You can set it to NULL when you want to select all categories an just modify select like this
select * from table where category= ISNULL( @categoryid, category )

A: select * from table where
category BETWEEN @mincategoryid AND @maxcategoryid

Min and max will one of

*

*both be 1 (or 2 or 3 or 4)

*respectively 0 and a high number

This will use an index too..

A: This is SQL not PL/SQL.
You need to test the value before sending the request you can not ask to SQL test it for you.


text:
Q: Split file and line in error message using regex I get string like
main.c:11: error: 'qz' undeclared (first use in this function)

like parameter to function. I need to use regex and split name of file ( main.c ), line (11) and message ( 'qz' undeclared (first use in this function) ).
I wrote regex like this
private static Pattern patern=Pattern.compile("([a-zA-Z0-9_-]+\.c:)([0-9]+:)(.)*");

but it doesn't split. Can anybody tell me what regex to use ?

A: You at least need to escape that \. Try
"([a-zA-Z0-9_-]+\\.c:)([0-9]+:)(.)*"

instead.
Here is a demo:
import java.util.regex.*;

public class Test {

    public static void main(String[] args) {
        String input = "main.c:11: error: 'qz' undeclared (first use in this function)";

        Pattern p = Pattern.compile("([^:]+\\.c):(\\d+):(.*)");
        Matcher m = p.matcher(input);

        if (m.matches()) {
            System.out.println("File: " + m.group(1));
            System.out.println("Line: " + m.group(2));
            System.out.println("Message: " + m.group(3));
        }
    }
}

Prints:
File: main.c
Line: 11
Message:  error: 'qz' undeclared (first use in this function)

Another option would just be to do input.split(":").

A: I'd do it like this:
^(.*?):(\d+):\s(error|warning):\s(.*?)

This will get you the filename as first result, the line number as second and the error message as the fourth match. Also, it captures warnings of the same format, too.
Edited to capture line number.


text:
Q: laravel/codeception : test if json response contains only certain keys I have a json array coming from my api as response:
{
  "data": [
    {
      "id": 1,
      "name": "abc"
    }
}

I am using laravel for api and laravel-codeception for testing.
public function getAll(ApiTester $I)
    {
        $I->sendGET($this->endpoint);
    }

I have to test if the response contains only id and name key (not any other key) example this response should fail the test.
{
      "data": [
        {
          "id": 1,
          "name": "abc",
          "email":"abc@xyz"
        }
    }

I have found $I->seeResponseContainsJson(), but it checks if JSON is present or not. It does not check if JSON response contains only specified keys.
Thanks.


text:
Q: Cost of using weak references in Java Has anyone researched the runtime costs involved in creating and garbage collecting Java WeakReference objects?  Are there any performance issues (e.g. contention) for multi-threaded applications?
EDIT:  Obviously the actual answer(s) will be JVM dependent, but general observations are also welcome.
EDIT 2:  If anyone has done some benchmarking of the performance, or can point to some benchmarking results, that would be ideal.  (Sorry, but the bounty has expired ...)

A: I implemented a Java garbage collector once, so whatever I was able to accomplish is a (weak :) lower bound on what is possible.
In my implementation, there is a small constant amount of additional overhead for each weak reference when it is visited during garbage collection.
So the upshot is: I wouldn't worry about it, it's not a big problem unless you are using zillions of weak references.
Most importantly, the cost is proportional to the number of weak references in existence, not the size of the overall heap.
However, that's not to say that a garbage collector that supports weak references will be as fast as one that does not. The presumed question here is, given that Java supports weak references, what is the incremental cost of using them?
Mine was a simple "stop the world" mark/sweep garbage collector. During garbage collection, it makes a determination for every object whether that object is live or not and sets a LIVE bit in the object header. Then it goes through and frees all the non-live objects.
To handle weak references you just add the following:

*

*Ignore weak references when setting LIVE bits (i.e., they don't cause the LIVE bit on the referenced object to be set).

*During the sweep step, add a special check as follows: if the object you're visiting is LIVE, and it's a WeakReference, then check the object that it weakly references, and if that object is not LIVE, clear the reference.

Small variations of this logic work for soft and phantom references.
Implementation is here if you're really curious.

A: cache using weak references may significantly slow down your app if it's rebuild on demand e.g. in getters:
public Object getSomethingExpensiveToFind() {
    if(cache.contains(EXPENSIVE_OBJ_KEY)) {
        return cache.get(EXPENSIVE_OBJ_KEY);
    }

    Object sth = obtainSomethingExpensiveToFind(); // computationally expensive
    cache.put(EXPENSIVE_OBJ_KEY, sth);
    return sth;
}

imagine this scenario:
1) app is running low on memory
2) GC cleans weak references, thus cache is cleared too
3) app continues, a lot of methods like getSomethingExpensiveToFind() are invoked and rebuild the cache
4) app is running low on memory again
5) GC cleans wear references, clears cache
6) app continues, a lot of methods like getSomethingExpensiveToFind() are invoked and rebuild the cache again
7) and so on...
I came upon such problem - the app was interrupted by GC very often and it compeletly defeated the whole point of caching.
In other words, if improperly managed, weak references can slow down your application.

A: WeakReferences have negative impact on CMS garbage collector. As far as I can see from behavior of our server it influences parallel remark phase time. During this phase all app threads are stopped so it's extremely undesirable thing. So you need to be careful with WeakReferences.


text:
Q: Link won't show using the_permalink(); Inside my loop, I'm trying to have a link show and it won't I'm not sure why
Here is the code:
<?php the_title('
<a href="<?php the_permalink(); ?>"', '
'); ?>

I understand this is maybe because of the '' quotations instead of "", but how would I achieve this general thing with just PHP and not by wrapping the_title(); in an a tag.

A: You can't nest these functions. Change your code to

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

A: because the_title() expects a string for the $before and $after args, you need to use the string version of the permalink, in a string concatenation;
<?php the_title('
', '
');  ?>
you also had a missing >.
https://developer.wordpress.org/reference/functions/get_permalink/

A: 23 seconds too late.
I think the issue is that you have a double  open/close statement.
Without seeing your code, I would suggest you to edit your line of code as

<a href="<?php the_permalink(); ?>"><?php echo get_the_title(); ?>


text:
Q: Fancytree jQuery plugin - select node I have difficulties in selecting a given node from fancytree plugin.
So, I have tried something like:
$("#tree").fancytree("getTree").visit(function(node){
    node.select(n);
});

where "n" is any number representing the node id, but it doesn'work, even if the select() function exists in documentation
Could someone help?

A: var tree = $("#tree").fancytree("getTree");
var node = tree.getNodeByKey(n);
node.setSelected(true);


text:
Q: How to set 2 spaces indent in javascript-mode in Emacs? This is similar question as this How do I change indent in php-mode to 2 spaces in Emacs? but for javascript-mode, I've try the same
(setq c-basic-offset 2)

but it don't work.

A: Found this as well
(setq js-indent-level 2)


text:
Q: Always select a row sql I have a case statment (see below) but I always want to return a value even if nothing matches the WHERE clase. Is that possible? Thanks
SELECT
    CASE
        WHEN COUNT(*) > 10 THEN 1
        ELSE 0
    END
FROM
fldt_QueryDSLAM lastDay
WHERE AccountID = @acc
    AND lastDay.DSL = @dsl
GROUP BY lastDay.DSL

A: If the WHERE clause returns one row (or one group more precisely), remove the GROUP BY. Then you'll always have one row in the output.
I assume it will (return one group) because you have GROUP BY on a filter column, and AccountID isn't mentioned in either SELECT or GROOUP BY
SELECT
    CASE
        WHEN COUNT(*) > 10 THEN 1
        ELSE 0
    END
FROM
    fldt_QueryDSLAM lastDay
WHERE
    AccountID = @acc AND lastDay.DSL = @dsl

For why, see this: Does COUNT(*) always return a result?

A: You can wrap the select within an isnull;
SELECT ISNULL((
    SELECT
        CASE
            WHEN COUNT(*) > 10 THEN 1
            ELSE 0
        END
    FROM
    fldt_QueryDSLAM lastDay
    WHERE AccountID = @acc
        AND lastDay.DSL = @dsl
    GROUP BY lastDay.DSL
), -99 /*no match*/)


text:
Q: What is the value of Va,Vb and Vc by using nodal analysis?
Can i directly put the Vb value as 12v or is there any supernode in there? I tried applying KCL at Va,Vb (which i put as 12v) and Vc but got the wrong answer.

A: We'd all like to see your work when you post. Please include your prior efforts when you write here.
Often, the problem is as simple as an incorrect sign and the work is otherwise just fine. But it could be more serious. If you don't expose your work, there's no way to know.
Here's how to set up the equations. You can check them against your own work. But what I'm providing here will resolve into the correct answers for you. Let's do the schematic first:

simulate this circuit – Schematic created using CircuitLab
You'll notice that I swapped the series positions of \$R_3\$ and \$V_1\$. There is no harm in that and it slightly simplifies the equations:
$$\begin{align*}
\frac{V_a}{R_1}+\frac{V_a}{R_2}+I_\text{P}&=\frac{V_b}{R_2}\\\\
\frac{V_b}{R_2}+\frac{V_b}{R_3}+\frac{V_b}{R_4}&=\frac{V_a}{R_2}+\frac{V_1}{R_3}+\frac{V_c}{R_4}\\\\
\frac{V_c}{R_4}+\frac{V_c}{R_5}&=\frac{V_b}{R_4}+I_\text{Q}
\end{align*}$$
I've placed the outflowing currents on the left side and the inflowing currents on the right side. (Clearly, they must be equal to each other.) Very simple to follow and it will solve out correctly.
Compare this with your own work. Chances are, you'll see the problem. (If not, then you probably have still more remedial work ahead of you.)

If you have Sage and sympy installed you can do something along the following lines:
var('r1 r2 r3 r4 r5 va vb vc v1 ip iq')
eq1=Eq(va/r1+va/r2+ip,vb/r2)
eq2=Eq(vb/r2+vb/r3+vb/r4,v1/r3+vc/r4+va/r2)
eq3=Eq(vc/r4+vc/r5,iq+vb/r4)
ans=solve([eq1,eq2,eq3],[va,vb,vc])
for item in ans: ans[item].subs({v1:12,ip:400e-6,iq:8e-3,r1:5e3,r2:5e3,r3:20e3,r4:4e3,r5:4e3})


text:
Q: Unable select Javafx combobox items programmatically which uses objects In the JavaFx ComboBox which uses a class object list .I want to select items in the ComboBox programmatically using getSelectionModel().select(object or index). i am not getting the desired result Although the value is set but it is something like this main.dao.Company.Company.CompanyTableData@74541e7b.
The code is somewhat like this.
ComboBox<CompanyTableData> company = new ComboBox<>();
company.setItems(GetCompany.getCompanyTableData());//where Observable list is set..

GetCompany.getCompanyTableData() returns observablelist of CompanyTableData class.
The ComboBox Looks as follows.

The CompanyTableData Class is as.
public class CompanyTableData {
private SimpleStringProperty itemCompanyId;
private SimpleStringProperty itemCompanyName;
private SimpleStringProperty createBy;
private SimpleStringProperty createdOn;

public CompanyTableData(CompanyData companyData){
    this.itemCompanyId = new SimpleStringProperty(companyData.getItemCompanyId());
    this.itemCompanyName = new SimpleStringProperty(companyData.getItemCompanyName());
    this.createBy = new SimpleStringProperty(companyData.getCreatedBy());
    this.createdOn = new SimpleStringProperty(companyData.getCreatedOn());
}

public String getItemCompanyId() {
    return itemCompanyId.get();
}

public SimpleStringProperty itemCompanyIdProperty() {
    return itemCompanyId;
}

public void setItemCompanyId(String itemCompanyId) {
    this.itemCompanyId.set(itemCompanyId);
}

public String getItemCompanyName() {
    return itemCompanyName.get();
}

public SimpleStringProperty itemCompanyNameProperty() {
    return itemCompanyName;
}

public void setItemCompanyName(String itemCompanyName) {
    this.itemCompanyName.set(itemCompanyName);
}

public String getCreateBy() {
    return createBy.get();
}

public SimpleStringProperty createByProperty() {
    return createBy;
}

public void setCreateBy(String createBy) {
    this.createBy.set(createBy);
}

public String getCreatedOn() {
    return createdOn.get();
}

public SimpleStringProperty createdOnProperty() {
    return createdOn;
}

public void setCreatedOn(String createdOn) {
    this.createdOn.set(createdOn);
}

}
The Cell Factory is set
company.setCellFactory(param -> new CompanyCell());

And the CompanyCell
public class CompanyCell extends ListCell<CompanyTableData> {
@Override
protected void updateItem(CompanyTableData item, boolean empty) {
    super.updateItem(item, empty);
    if (empty || item == null || item.getItemCompanyName() == null) {
        setText(null);
    } else {
        setText(item.getItemCompanyName());
    }
}

}
After all this when i try to set the items programmetically as
company.getSelectionModel().select(getSelectedCompanyIndex());

The getSelectedCompanyIndex() function is as follows.
public static CompanyTableData getSelectedCompanyIndex(){
    CompanyTableData c = null,i;
    Iterator<CompanyTableData> itr = GetCompany.getCompanyTableData().iterator();
    while (itr.hasNext()){
        i = itr.next();
        if (i.getItemCompanyName().equals(Element.getItemTableData().getCompany())){

            c = i;
        }
    }
    return c;
}

And the result i am getting is

And

At the end it should select a name or item in the list but it has set some type of object i think.
Now what should i do. Is there any type of string conversion required.

A: The buttonCell used to display the item when the combobox popup is not shown is not automatically created using the cellFactory. You need to set this property too to use the same cell implementation:
company.setCellFactory(param -> new CompanyCell());
company.setButtonCell(new CompanyCell());


text:
Q: Creating columns for each category in column I am new to SQL. I have a table with data for different companies.
For example :
Company type count
--------------------
St1    sync    20
St2    async   30
St3    async   40
St3    sync    100
St1    async   90
St2    sync    65

Here, I'd like to print a report with sync and async as separate columns.
Company  sync   async
----------------------
St1      20     90
St2      65     30
St3      100    40

I've tried different queries, but can't really get the logic to implement it.
SELECT Company,
(CASE WHEN type='async' THEN count END) as async,
(CASE WHEN type='sync' THEN count END) as sync,
FROM table
GROUP BY Company;

Included a query I've tried above.

A: Use a pivot query:
SELECT
    Company,
    MAX(count) FILTER (WHERE type = 'sync')  AS sync,
    MAX(count) FILTER (WHERE type = 'async') AS async
FROM yourTable
GROUP BY
    Company
ORDER BY
    Company;

Demo


text:
Q: Where are the default Unity lenses stored? I want to create a home build lens for the 12.04 dash and liked to use one of the default lenses as example. I'm thus for looking where I can find the files of these lenses.

A: There are three essential files that compose a lens.

*

*A .lens file stored in /usr/share/unity/lenses. This details the name, icon, and D-Bus address of a lens for Unity.

*A .service file stored in /usr/share/dbus-1/services. This points to the location of a lens' query executable; D-Bus will see this executable and act as IPC between it and Unity.

*Finally, the executable of your lens may be placed anywhere in the filesystem (you specify where in the .service file), but canonically these are located in /usr/lib.
Look at /usr/share/unity/lenses/video/video.lens, /usr/share/dbus-1/services/unity-lens-video.service, and /usr/lib/unity-lens-video/unity-lens-video for a concrete example of how these files work together.


text:
Q: php mail headers for outlook - the email arrives empty to outlook, and great to gmail to yahoo mail($to, $subject, $message, $headers);

the $header is:

From: from-me@mymail123.com
Reply-To: from-me@mymail123.com
Content-Type: text/html; charset=iso-8859-1
X-Mailer: PHP/5.2.5
MIME-Version: 1.0

I built $header with those line and I changed the order in every way, putting the Mime in the beginning, at the end, moving the from and reply around adding and deleting the X-mailer line. The results are the same. Gmail and yahoo are fine and the email is an empty attachment when set to outlook 2003.
Any thoughts?
sdfor

A: thanks for the thoughts. I tried phpMailer and got stuck on a "Could not instantiate mail function" error. I posted a question about that too.
But I figured out the problem. Outlook requires a doctype and that the HTML be correct. gmail will take almost anything. \
The following works!
//the message:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

HTML EMAIL

//the headers
$headers = "From: $from\n"
$headers .= "Reply-To: $replyto\n"
$header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";

// the mail call
mail($to, $subject, $message, $headers);

A: Personnally, i prefer using phpmailer, available on sourceforge. It offers a much more robust mailing solution.  I use it to send our email newsletter. Very reliable.

A: Try adding  to the end of 'From: ...'.  This email should be an actual email address on the server.   Try checking your spam folder with what you have.


text:
Q: Rotating a Axe Model in Roblox So, For Context im trying to emulate kind of like throwing an axe, when you throw an axe it spins and spins and spins vertically.However, I got the spinning part right but the axis that is at, is not right the axe it should be facing vertically not facing you, i will post a gyazo link just so u can see how it spins right now. https://gyazo.com/99eaa8c1b5b3ce22205148509e115b14
Ive tried a couple things, ive tweend it, i thought that would work, as tweening it i can do it infinitley, But the result was it being still. I also tried pivoting it, But because of my courtine. Sometimes it wouldnt even go through
Heres The roblox code
local function ZodiacMove(plr,Mouse)
    local TestingCourotine = coroutine.create(function(Handle)
        while true do RunService.Stepped:Wait()
            print(Handle)

            Handle.CFrame = Handle.CFrame * CFrame.Angles(0,0,math.rad(10))
            if Handle.Parent == nil then break end
        end
        print('the axe has vanished :sob:')
    end)
    local ZodiacProjectile = game:GetService("ReplicatedStorage").Axe:Clone()
    local Handle = ZodiacProjectile:FindFirstChild("Blade")["Blade Tip"]
    print(Handle)
    local ZodiacProjectilePivot = ZodiacProjectile:GetPivot()
    ZodiacProjectile:PivotTo(ZodiacProjectilePivot * CFrame.new(math.rad(10),0,0))
    coroutine.resume(TestingCourotine,Handle)
    ---TweenInfoGoals.CFrame = Handle.CFrame * CFrame.Angles(0,0,math.rad(360))
    --local ZodiacProjectileTween = TweenService:Create(Handle, tweenInfo,TweenInfoGoals)
    --ZodiacProjectileTween:Play()
    local OverParams = OverlapParams.new()
    OverParams.FilterType = Enum.RaycastFilterType.Blacklist
    OverParams.FilterDescendantsInstances = {workspace.Baseplate, plr.Character, plr.Character:GetChildren()}
    local HumanoidRootPart = plr.Character:WaitForChild("HumanoidRootPart")
    local BV = Instance.new("BodyVelocity")
    BV.Parent =  Handle
    ZodiacProjectile.Parent = HumanoidRootPart
    BV.Velocity = HumanoidRootPart.CFrame.LookVector * 100
    BV.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
    ZodiacProjectile:PivotTo( HumanoidRootPart.CFrame * CFrame.new(0, 0, -1))
    Debris:AddItem(ZodiacProjectile,2)
end```


text:
Q: Sybase ASE 15 : Creating an index on multiple columns which values are inequally discriminating I have a table mytable of 5 million records and a query that looks like
select *
from mytable
where column1 = 'value1' and column2 = 'value2' and column3 = 'value3'

So I thought about creating an index based on the 3 columns but my problem is that I have no best column to put in the first position of the index because there is no column that is really discrimating compared to the others.
Therefore I would like to build something similar to the hash tables with a hash code based on these 3 columns. I tried a function-based index based on the concatenation of those 3 columns but it's taking so long to create that I never got it created and I believe it's the wrong way to achieve what I want. What is the correct way to achieve this ?

A: Just create an index with three columns:
create idx_mytable_col1_col2_col3 on mytable(col1, col2, col3)

You have equality comparisons.  The order of the columns in the index does not matter in this case.
Let the database do the work for you.

A: ASE's indexes are generally stored as b-trees, and while there's some hashing 'magic' that takes place during index searching, there's still a bit of traversal/searching required; if the first column of an index is not very selective then you can see some degradation in index search performance when compared to an index where the more selective column(s) is listed first; the difference in performance is really going to depend on the selectivity of the column(s) in question and the sheer size of the index (ie, number of index levels and pages that have to be read/processed).
If you're running ASE 15.0.3+, and you're running ASE on linux, you may want to take a look at virtually-hashed tables. In a nutshell ... ASE stores the PK index as a hash instead of the normal b-tree, with the net result being that index search times are reduced.  There are quite a few requirements/restrictions on virtually-hashed tables so I suggest you take a look at your Transact-SQL User's Guide for more details.
Obviously (?) there's a good bit more to table/index design than can be discussed here; certainly not something that can be addressed by looking at a single, generic query. ("Duh, Mark!" ?)


text:
Q: Haskell: encoding a generic schema To begin with, some motivation: I want to take configuration from multiple places - command line arguments, possibly config files, some other service. I don't have any particular care for the format of these sources. What I would like to do is describe a schema for that configuration and have pluggable sources generate parsers/writers for that config as necessary. The schema should also encode things such as help text, possibly completion options, etc.
Here's the basis of what I have so far:
data Name =
    LongName String
  | ShortName Char

data OptionDefault a = OptionDefault (Maybe a) (Maybe (a -> String))

data OptionDescr = OptionDescr {
    odNames :: [Name]
  , odSummary :: String
  , odDetail :: String
}

data Option a = Option {
    oReader :: Monad m => String -> m a
  , oDefault :: OptionDefault a
  , oDescr :: OptionDescr
}

The thing I'm not sure how to do is compose these - e.g. to define a config section as being, say, three options of types Option Foo, Option Bar and Option Baz as well as a function f :: Foo -> Bar -> Baz -> FBBSection. This is a different question to composing the Parsers, which should be done at a later date by a generator for the specific format.
The only thing I can think of is to store the options as some kind of HList, and force some kind of fold composition for f - any other ideas?

A: If you have an Applicative instance for Option:
foo :: Option Foo
bar :: Option Bar
baz :: Option Baz
f :: Foo -> Bar -> Baz -> FBBSection

fbbSection :: Option FBBSection
fbbSection = f <$> foo <*> bar <*> baz

Now, the trouble is in writing the Applicative instance.  First of all, you need a Functor instance, but you can't really provide one: OptionDefault is an invariant functor because its type parameter a occurs in both a positive position Maybe a and in a negative position Maybe (a -> String).  The Functor typeclass in Haskell is only for covariant functors.
You might re-examine your data to see if you can make it covariant.  There might be an equivalent for Applicative that is invariant though I'm not sure; I'm not sure how currying works for isomorphisms, if it does at all, and Applicative is actually rather dependent on currying, from a categorical perspective.
After you got though all of that, you'd need to define how your Applicative combined OptionDescr values.


text:
Q: Table indexes and constraints needlessly recreated when generating migrations in Typorm NestJs In Package.json script tag i have added
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
then for migration:
generation i use
npm run typeorm migration:generate -- -n <migration name>
to run migration:
npm run typeorm migration:run
nest version: 8
orm: Typeorm
database: PostgreSQL
Table indexes and constraints needlessly recreated when generating migrations in Typorm NestJs.
is there any solution to stop this?


text:
Q: Where do I find the ca certificates for mosquitto_sub and pub? In this article mosquitto_sub with TLS enabled I understand that you need to provide a capath or cafile option to mosquitto_sub (and pub) but I am having trouble figuring out where those files/paths come from.
Back in October I was able to run mosquitto_sub -h mymosquitto.com -p 8883 -v -t 'jim/#' -u <u> -P <pw> --capath ssl/certs from my desktop computer (running Mint 19).  That no longer works.  I did an apt install ca-certificates and found the .crt files in /usr/share/ca-certificates/mozilla/ but when I used that path, it still gave me: Error: A TLS error occurred.
This is a Ubuntu 18.04 server running Let'sencrypt.  I tried to point the --cafile to the chain.pem file which came from:
allow_anonymous false
password_file /etc/mosquitto/pwfile

listener 1883

listener 8883
certfile /etc/letsencrypt/live/mymosquitto.com/cert.pem
cafile /etc/letsencrypt/live/mymosquitto.com/chain.pem
keyfile /etc/letsencrypt/live/mymosquitto.com/privkey.pem

But that didn't work either.  Can someone please help me understand what I should be doing?

A: From the mosquitto_sub man page:

--capath
Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication.
For --capath to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash [path to
capath]" each time you add/remove a certificate.

If you want to use a directory of certs you will have to make sure the openssl rehash command mentioned has been run on that directory.
If you want use a file from the letsencrypt --cafile with the fullchain.pem file

A: I have rethought my situation.  Since my certs get regenerated every 3 months or so I'm going to have to redo my apps using the new files so I decided to just go back to rolling my own.  I did that using this site: http://www.steves-internet-guide.com/mosquitto-tls/ and I'm back to where I was in October.Thanks to hardillb for the advise.
Jim.


text:
Q: Non differentiable, continuous functions in metric spaces. Take the metric space $(C([0,1]),d)$ with $C([0,1])$ the set that contains all continuous functions $f: [0,1] \to \mathbb{R} $ and the metric $d(f,g) = \sup \{|f(x)-g(x)| : x \in [0,1]\}$.
Now, I was wondering that if we take a non differentiable, continuous function $f$ in this metric space, are there any differentiable functions in the set $B(f,\varepsilon) = \{ g \in C([0,1]) : d(f,g) < \varepsilon \}$?
I do think that this is true but that is just my intuition, can someone help me find a solution?

A: Your question is equivalent to asking

*

*Is it possible to approximate a continuous function uniformly with a differentiable one, or

*Is the set of differentiable function dense in $C([0,1])$.

Both is true and stays true if you replace "differentiable" by differentiable infintely often and can be seen by convolution with mollifiers.

A: That is true. In fact, one may even take the function $g$ to be a polynomial. See the Stone-Weierstrass approximation theorem.


text:
Q: Is this transformation symmetric? Let $V = \mathcal{P}(\mathbb{R})$ with the inner product defined as $\langle u,v \rangle = \int_{-1}^{1}u(t)v(t)dt$
And let T be a transformation such that
$$T:V\rightarrow V$$
$$p\mapsto T[p](x) = p(-x)$$
Is T going to be symmetric?
Well, I know that for a transformation to be symmetric it has to obbey the following statement:
$$\langle T[p](x), y \rangle = \langle x, T[p](y) \rangle \quad (1)$$
or in other words
$$\langle p(-x), p(y) \rangle = \langle p(x), p(-y) \rangle$$
First problem: I don't think I understand the notation. Let's say I have a basis $B=(1,x,x^2,...)$. If I take $p(1)$ and apply the transformation will I have $T[p](1) = p(-1) = -1$? And if I take $p(x)$ and apply the transformation will I have $T[p](x) = p(-x) = -x$?
Second problem: If the above is right, what I have to do is plug different vectors and test whether or not $(1)$ applies?
Any help or guidance will be appreciated!

A: $\langle x, Ty \rangle = \int_{-1}^1 x(t) y(-t) dt  = \int_{-1}^1 x(-s) y(s) ds = \langle Tx, y \rangle  $. Hence $T^* = T
Addendum:
Using the substitution $s=-t$ we have
$\int_{-1}^1 x(t) y(-t) dt = \int_1^{-1} x(-s) y(s) (-1)ds = \int_{-1}^1 x(-s) y(s) ds$.


text:
Q: How can I only pull 5 tweets from this array? How can I only pull an exact number of tweets such as 5? I have tried to use the count function but it's not working? Any suggestions would be appreciated, thank you :)
$stwt = array('HarbourBridge','SyndeyBridge','bridgeclimb');

for($n = 0; $n < count($stwt); $n++){
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = "?q=#'$stwt[$n]'&result_type=recent";
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$data=$twitter->setGetfield($getfield)
              ->buildOauth($url, $requestMethod)
              ->performRequest();
$phpdata = json_decode($data, true);
 //Loop through the status updates and print out the text of each
foreach ($phpdata["statuses"] as $status) {
    echo("<p>" . $status["text"] . "</p>");
    stwitter1 = (string)$status["text"];
    $stwt = "SELECT * FROM STweets ";
    mysqli_query($mysqli,"INSERT INTO STwitter(STweets)
                          VALUES ('$stwitter1')");

}
}
?>


text:
Q: Формирование std::tuple в C++11 Доброго времени суток, уважаемые.
У меня следующий вопрос:
Пусть есть шаблонный класс вот такого вида:
template <class... Ts> class MyClass
{
public:
      using TupleT = std::tuple<Ts...>;
      ...
private:
      TupleT m_tuple;
};

и есть шаблонный класс
template <size_t I, class TupleT> WrapperT { ... };

Хочется сделать следующее: изменить тип m_tuple внутри MyClass с указанного выше на тип TupleWrappedT таким образом, что WrapperT будет выбирать по индексу элемент из TupleT и оборачивать его в себя.
Вопрос, собственно, в том, как такой тип определить. Я придумал только
template <size_t... Is> using TupleWrappedT = std::tuple<WrapperT<Is, TupleT>...>;

возможно ли обойтись без приставки template <size_t... Is>? С учетом того, что элементы Is должны быть последовательны в диапазоне от 0 до sizeof...(Ts), а значит, известны на этапе компиляции.
Заранее благодарю за ответ.

A: Держите :)
#include <tuple>

template <size_t I, class TupleT> struct WrapperT {};

template <class Tuple, size_t... Is>
static std::tuple<WrapperT<Is, Tuple>...> wrap_impl(std::index_sequence<Is...>);

template <class Tuple>
static auto wrap() -> decltype(wrap_impl<Tuple>(std::make_index_sequence<std::tuple_size<Tuple>::value>()));

template <class... Ts> class MyClass
{
public:
      using TupleT = std::tuple<Ts...>;
      using TupleWrappedT = decltype(wrap<TupleT>());
private:
      TupleT m_tuple;
};

int main() {
    static_assert(std::is_same<MyClass<int, float>::TupleT, std::tuple<int, float>>::value, "!");
    static_assert(std::is_same<MyClass<int, float>::TupleWrappedT, std::tuple<WrapperT<0, std::tuple<int, float>>, WrapperT<1, std::tuple<int, float>>>>::value, "!");
    return 0;
}

A: Возможно я чего-то не понял, но разве std::tuple_element и std::get не решают задачу? Пример:
template <size_t I, class TupleT> class WrapperT
{
    using Element = typename std::tuple_element<I, TupleT>::type;
    Element mElement;

    public: WrapperT(const TupleT& tuple)
        : mElement{std::get<I>(tuple)}
    {
    }
};


text:
Q: Akka-Cluster: indirectly connected member does not receive UnreachableMember event about himself There's something I'm trying to understand about failure detection and the gossip of the detection.
A multi-jvm test I wrote seems to show that a member that has been detected as failed but still reachable via other nodes will not receive an UnreachableMember(self) event, telling him that he has been detected as unreachable by some member.
The test went as follows:
In a 3 node cluster, node2 detects node3 as unreachable, node3 detects node2 as unreachable. Then node1 receives the information that node2 and node3 are unreachable (through gossiping). However, node2 and node3 never receive the fact that they were themselves detected as unreachable.
After some digging in the GossipSpec I found out that the "falsely" unreachable member will reach convergence even though it is noted as Unreachable (see the test "not reach convergence when unreachable").
Is that the reason why I'm not seeing the UnreachableMember(self) event?
The ultimate goal I'm trying to get at is to detect that a member has been falsely found unreachable since it is unreachable from that given member due to a faulty channel between both.


text:
Q: C# How a winform capture server sent event How to subscribe a desktop client to server sent event. so whenever something will be pushed from server side my winform application should be able to capture and show that message. just a looking for a example code. i got some relevant links.
Here i am highlighting a sample code where a javascript side and ASP.Net MVC talking to each other by server sent event.
<input type="text" id="userid" placeholder="UserID" /><br />
<input type="button" id="ping" value="Ping" />

<script>
    var es = new EventSource('/home/message');
    es.onmessage = function (e) {
        console.log(e.data);
    };
    es.onerror = function () {
        console.log(arguments);
    };

    $(function () {
        $('#ping').on('click', function () {
            $.post('/home/ping', {
                UserID: $('#userid').val() || 0
            });
        });
    });
</script>

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace EventSourceTest2.Controllers {
    public class PingData {
        public int UserID { get; set; }
        public DateTime Date { get; set; } = DateTime.Now;
    }

    public class HomeController : Controller {
        public ActionResult Index() {
            return View();
        }

        static ConcurrentQueue<PingData> pings = new ConcurrentQueue<PingData>();

        public void Ping(int userID) {
            pings.Enqueue(new PingData { UserID = userID });
        }

        public void Message() {
            Response.ContentType = "text/event-stream";
            do {
                PingData nextPing;
                if (pings.TryDequeue(out nextPing)) {
                    Response.Write("data:" + JsonConvert.SerializeObject(nextPing, Formatting.None) + "\n\n");
                }
                Response.Flush();
                Thread.Sleep(1000);
            } while (true);
        }
    }
}

i want to communicate between a web api and winform by server sent event. so please show me how a winform can communicate subscribe to server sent event ?
if any small example would be added....will be great help. thanks

A: I wrote a basic implementation using the TcpClient.
Variables:

*

*Host: 127.0.0.1

*Port: 5000

*Method: GET

*Url: /home/message

Listener
private static async Task ConnectEventStreamAsync(CancellationToken token)
{
    var client = new TcpClient();
    try
    {
        await client.ConnectAsync("127.0.0.1", 5000);
        if (!client.Connected)
            throw new Exception("Unable to connect the host");

        var encoding = Encoding.UTF8;
        var stream = client.GetStream();
        var connectBytes = encoding.GetBytes(
            "GET /home/message HTTP/1.1\r\n" +
            "Host: 127.0.0.1\r\n" +
            "Content-Length: 0\r\n\r\n"
        );
        await stream.WriteAsync(connectBytes, 0, connectBytes.Length, token);
        var buffer = new byte[4096];
        while (!token.IsCancellationRequested)
        {
            var readCount = await stream.ReadAsync(buffer, 0, buffer.Length, token);
            if (readCount > 0)
            {
                var message = encoding.GetString(buffer, 0, readCount);
                using (var stringReader = new StringReader(message))
                {
                    string line;
                    while ((line = await stringReader.ReadLineAsync()) != null)
                    {
                        //--try to read the next chunk
                        if (!int.TryParse(line, NumberStyles.HexNumber, null, out var bytes))
                            continue;
                        var data = await stringReader.ReadLineAsync();
                        Console.WriteLine($">>New Event ({bytes} bytes)\r\n{data}");
                    }
                }
            }
            await Task.Delay(500, token);
        }
    }
    finally
    {
        client.Dispose();
    }
}

EDIT: Here is other solution using the HttpClient. I added more code to parse the text-eventstream messages. You can read more here to make improvements.
private static async Task ConnectEventStreamAsync(CancellationToken token)
{
    var client = new HttpClient
    {
        Timeout = Timeout.InfiniteTimeSpan
    };
    try
    {
        var response = await client.GetAsync(
            "http://127.0.0.1:5000/home/message",
            HttpCompletionOption.ResponseHeadersRead,
            token
        );
        if (!response.IsSuccessStatusCode)
            throw new Exception("Unable to connect the stream");

        var isTextEventStream = response.Content.Headers.ContentType.MediaType == "text/event-stream";

        if (!isTextEventStream)
            throw new InvalidOperationException("Invalid resource content type");

        var stream = await response.Content.ReadAsStreamAsync();
        var buffer = new byte[4096];
        while (!token.IsCancellationRequested)
        {
            var readCount = await stream.ReadAsync(buffer, 0, buffer.Length, token);
            if (readCount > 0)
            {
                var data = Encoding.UTF8.GetString(buffer, 0, readCount);
                await ParseDataAsync(data);
            }

            await Task.Delay(500, token);
        }
    }
    finally
    {
        client.Dispose();
    }

    async Task ParseDataAsync(string data)
    {
        using (var stringReader = new StringReader(data))
        {
            string line;
            while ((line = await stringReader.ReadLineAsync()) != null)
            {
                if (line.StartsWith("event:"))
                {
                    var eventText = line.Substring("event:".Length);
                    Console.WriteLine($">>Event ({eventText.Length} bytes)\r\n{eventText}");
                    continue;
                }

                if (line.StartsWith("data:"))
                {
                    var dataText = line.Substring("data:".Length);
                    Console.WriteLine($">>Data ({dataText.Length} bytes)\r\n{dataText}");
                    continue;
                }

                if (line.StartsWith("id:"))
                {
                    var eventId = line.Substring("id:".Length);
                    Console.WriteLine($">>Event ID ({eventId.Length} bytes)\r\n{eventId}");
                    continue;
                }

                if (line.StartsWith("retry:"))
                {
                    var retryValue = line.Substring("retry:".Length);
                    Console.WriteLine($">>Retry ({retryValue.Length} bytes)\r\n{retryValue}");
                    continue;
                }

                if (line.StartsWith(":"))
                {
                    Console.WriteLine($">>Comment ({line.Length - 1} bytes)\r\n{line.Substring(1)}");
                }
            }
        }
    }
}

The server part using Asp.Net Core (very similar to the one displayed by the user who asks).
...
private static ConcurrentQueue<PingData> pings = new ConcurrentQueue<PingData>();

[HttpGet]
public void Ping(int userID)
{
    pings.Enqueue(new PingData { UserID = userID });
}

[HttpGet]
public void Message()
{
    Response.ContentType = "text/event-stream";
    Response.WriteAsync($":Hello {Request.Host}\n");

    const int intervalMs = 1000;
    do
    {
        if (pings.TryDequeue(out var nextPing))
        {
            Response.WriteAsync($"event:Ping\n");
            Response.WriteAsync($"retry:{intervalMs}\n");
            Response.WriteAsync($"id:{DateTime.Now.Ticks}\n");
            Response.WriteAsync($"data:{JsonConvert.SerializeObject(nextPing)}\n\n");
        }

        Thread.Sleep(intervalMs);
    } while (Response.Body.CanWrite);
}

public class PingData
{
    public int UserID { get; set; }
    public DateTime Date { get; set; } = DateTime.Now;
}
...


text:
Q: why a click event in javascript is removing a list item on second clik only trying to remove a list item with a button click event but list is only deleted after the second click.

life11

life2

life3

    <button onclick="lostLives()">Remove list item</button>

and the javascript function looks like
let lostLives = function() {
    let lives = document.getElementById('lives');
    lives.removeChild(lives.lastChild);
};

A: lastChild will give you text nodes or comment nodes, not just element nodes. In this case, it's giving you a text node corresponding to the whitespace after the last
.
You want lastElementChild, which only gives you elements.

let lostLives = function() {
    let lives = document.getElementById('lives');
    lives.removeChild(lives.lastElementChild);
};

life11

life2

life3

  <button onclick="lostLives()">Remove list item</button>

A: change the .lastChild to .lastElementChild and your function will work.  The last child is a text node with the spaces tabs and carriage returns, the last element is what you want.

A: Try the below one

let lostLives = function() {
  let lives = document.getElementById('lives');
  lives.removeChild(lives.lastElementChild);
};

life11

life2

life3

  <button onclick="lostLives()">Remove list item</button>

A:
lastChild is not element but text node. You should be using lastElementChild as you are trying to remove li element node.

let lostLives = function() {
  let lives = document.getElementById('lives');
  lives.removeChild(lives.lastElementChild);
};

life11

life2

life3

  <button onclick="lostLives()">Remove list item</button>

A: In order to demonstrate why there is a deletion on every second key press, change your script to this:
let lives = document.getElementById('lives');
console.log(lives);
let lostLives = function() {
    lives.removeChild(lives.firstElementChild);
};

If you view your page in a browser and open up the console, you then can view the child nodes as follows:

You will notice that there are 7 nodes, not the expected 3 because the text and the element nodes are children of ul#lives. Starting at the bottom, there is a text node first so this will be deleted when the button is pressed, followed by the li element, then text etc. which is exactly what you see.
As a further example, if you change your html to be as follows:

life11

life2

life3

    <button onclick="lostLives()">Remove list item</button>

Then you will find that there are only 3 child nodes and your function will work as you expected it to work.
I hope this helps.

A: Try this

var lostLives = document.getElementById("lostLives");

lostLives.addEventListener("click", function(){
    var el = document.getElementById('lives');
    if (el.children.length > 0) {
       el.removeChild(el.lastElementChild);
    }else{
        alert("All items have been deleted");
    }
});

life11

life2

life3

    <button id="lostLives">Remove list item</button>


text:
Q: c++11 variadic templates and std::endl I tried to do logger using C++11 variadic templates, but it doesn't work for std::endl, because std::endl is template function and the compilator doesn't know what specialization of std::endl to select. Is there any way how i can force to always select std::endl<char, std::char_traits<char>>? If possible, i want to use directly std::endl.
EDIT: it looks like it is not currently possible with C++11 and and best way is to use #define or what vsoftco answered.
#include <iostream>
#include <string>

class Logger {

public:

    template<typename T>
    void log(T val);

    template <typename T, typename ...Args>
    void log(T val, Args... args);

};

// explicit specialization not working
template<>
void Logger::log(std::basic_ostream<char, std::char_traits<char>> (*modifier) (std::basic_ostream<char, std::char_traits<char>>)) {

    std::cout << modifier;

}

template<typename T>
void Logger::log(T val) {

    std::cout << val;

}

template<typename T, typename ...Args>
void Logger::log(T val, Args... args) {

    log(val);
    log(args...);

}

int main(int argc, char* argv[])
{
    Logger log;

    log.log("Nazdar ", "bazar ", "cau", std::endl, "kik"); // ERROR: cannot determine which instance of function template "std::endl" is intended
    log.log("Nazdar ", "bazar ", "cau", std::endl<char, std::char_traits<char>>, "kik");

    std::cin.get();

    return 0;
}

A: A simpler option to achieve the same goal:
// global or class member
enum MyEndl { my_endl };

// class member function
void log(MyEndl x) { std::cout << std::endl; }

usage:
log.log("Nazdar ", "bazar ", "cau", my_endl, "kik");

A: I came up with this, basically re-defining std::endl via a custom wrapper my_endl taking default template parameters. Not the most elegant, but it does the job. Of course, for more such manipulators, one should write a specialized wrapper, but I guess even this can somehow be possible by a more clever implementation.
#include <iostream>
#include <string>
#include <type_traits>

class Logger {

public:

    template<typename T>
    void log(T val);

    template <typename T, typename ...Args>
    void log(T val, Args... args);
};

template<typename T>
void Logger::log(T val) {
    std::cout << val;
}

template<typename T, typename ...Args>
void Logger::log(T val, Args... args) {

    log(val);
    log(args...);

}

template< class CharT = char, class Traits = std::char_traits<CharT> >
inline std::basic_ostream<CharT, Traits>& my_endl( std::basic_ostream<CharT, Traits>& os )
{
    return std::endl(os);
}

// or, use the excellent (and better) suggestion by 0x499...,
// auto manip = std::endl<char, std::char_traits<char>>;
// log.log(..., manip)

int main(int argc, char* argv[])
{
    Logger log;

    // log.log("Nazdar ", "bazar ", "cau", std::endl, "kik"); // ERROR: cannot determine which instance of function template "std::endl" is intended
    log.log("Nazdar ", "bazar ", "cau", my_endl<>, "kik");

    std::cin.get();

    return 0;
}


text:
Q: Sampling continuous function in Matlab I'm new to matlab, and in this academic exercise they asked us to do a sampling from a continuous function.
My original functions are:
x = sin(pi * t);
y = cos(2 * pi * t / 3);
z = x + y - 2;

In the interval
t = -8:0.001:8;

Then they asked us to make a sampling, z(n), of z with a period of Ts=0.01 seconds.
My idea was to save in a new vector the values of z, jumping through z ten by ten positions:
n = numel(z);
Zd = z(0:10:z);

This idea came from the fact that 0.01 seconds is ten times less accurate then the first 'continuous' interval t. But matlab says that this is not possible and gives me the error:
??? Subscript indices must either be real positive integers or logicals.

Can somebody give me some hint on this?

A: As 2 @Memming said, matlab indexes start at 1 and not 0, and that was my problem.
Thanks.


text:
Q: numpy randint arguments exclusive In the official NumPy documentation,
numpy.random.randint has an exclusive second argument.
random.randint(low, high=None, size=None, dtype=int)
    Return random integers from low (inclusive) to high (exclusive).

Then, I thought random.randint(1, 5) returns values 1, 2, 3, or 4,
but it actually gives values among 1, 2, 3, 4, and 5.
What went wrong?

A: You're conflating numpy.random.randint with Python's random.randint (from the random module in the standard library), the latter of which has an inclusive upper bound.


text:
Q: How replace a navigation icon with a navigation title in xamarin forms I trying to add a navigation title icon to my app in one of the page and the code that i have used is:
For iOS:
NavigationPage.SetTitleIcon(this, "icon.png");

For Android in the ToolBar.axml I have added a ImageView as shown below:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <ImageView
        android:id="@+id/titleicon"
        android:src="@drawable/UstNameIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.v7.widget.Toolbar>

The issue is that, I want my Navigtion icon to get disabled in my next Page and put a title instead of icon.
For that, I tried
For iOS:
NavigationPage.SetTitleIcon(this, null);

NavigationPage.Title="Title";

For Android, How can i achieve the change of Navigation title?

A: In MainActivity.cs
[Activity (Label = "Todo.Android.Android", MainLauncher = true, Icon="@android:color/transparent")]

For Title, you can set Title property in xaml or c#

A: To change text you just simple need to find that element by id, and set up a title:
var toolbar =
    FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); // it may be simplifed
    SetSupportActionBar(toolbar);
    toolbar.Title = "title";

And image is under toolbar.Logo, so you can just try:
toolbar.Logo = null;

If you have some data in resources which you want to put in, you can use also:
toolbar.SetTitle();
toolbar.SetLogo();