text:
Q: Create email, save to draft after attachment has uploaded The following code loops through a folder, creates email with attachment and saves to draft.
Public Sub saveFileTodownload()

    Set draftItems = Outlook.Session.Folders("My Email").Folders("Drafts").Items

    strFile = Dir("d:\ga\localsdk\")

    Do While Len(strFile)
        Debug.Print strFile
        Set mail = draftItems.Add("IPM.NOTE")
        mail.Subject = "1downloadme" & Count
        mail.Attachments.Add ("d:\ga\localsdk\" & strFile)
        mail.Save
        strFile = Dir
    Loop

End Sub

I need to wait until the attachment has completely uploaded then call Save.
Is there any way to wait until the attachment has uploaded.
Note: If I debug it and wait a minute after the Attachment.Add line, the attachment has uploaded and Save works.

A: MailItem.Attachments.Add is synchronous; by the time the call returns, the attachment is added to the message. What makes you believe this is not so?

A: user93865
I tested your code and it works for me(No error message). However, it will be gets stuck if there are lots of attachments upload.
You could try this code :
Public Sub saveFileTodownload()
Dim store As Outlook.store
Dim space As Outlook.NameSpace
Dim folder As Outlook.folder
Set space = Outlook.Application.GetNamespace("MAPI")
Set store = space.DefaultStore
Set folder = store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts)
Set Item = folder.Items.Add("IPM.NOTE")
Item.Subject = "1downloadme"
Item.Body = "one"
Dim r As Long
r = 0
Do While r < 100
Item.Attachments.Add ("C:\Users\temp\Desktop\notes\abd.docx")
r = r + 1
Loop
'Item.Display
Item.Save
Item.Close
End Sub


text:
Q: Error:Execution failed for task, finished with non-zero exit value 2 I'm getting this error every time I try to run my project and can't seem to figure out how to fix it. I have tried multiple things to try fix it and still no joy. Any help would be much appreciated.
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2

This is my build.gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

  /*  dexOptions {
        javaMaxHeapSize "4g"
    }*/

    defaultConfig {
        applicationId "com.example.neil.studicom"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.microsoft.azure:azure-mobile-services-android-sdk:2.0.3'
    compile 'com.google.android.gms:play-services:8.3.0'
    compile 'com.android.support:multidex:1.0.1'
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gradle dependency resolution error,
Could not resolve all dependencies for configuration ':runtime'.
Could not resolve      <exclude org: module="l:ame="*" type="*.
Required by:
  :gradle_dep_issue_example:unspecified > org.apache.cxf:cxf-bundle:2.6.13
java.lang.IllegalArgumentException (no error message)

Stopping and starting the gradle daemon has no effect, nor does clearing out the .gradle folder. However, running the war task and passing the --refresh-dependencies option does resolve the issue. Unfortunately, the --refresh-dependencies option must be used every time.
Here is a small build.gradle file which will reproduce the issue when the "downloadRuntimeDeps" task is run.
apply plugin: 'war'

repositories {
  mavenCentral()
}

dependencies {
  compile 'org.apache.cxf:cxf-bundle:2.6.13'
}

task downloadRuntimeDeps(type: Copy){
  from configurations.runtime
  into new File(getBuildDir(), "/runtime-deps/")
}

A: The issue ended up only impacting gradle version 1.10. I tested with versions 1.8 and 1.11, and neither had this problem.
There are no bug fixes included in the release notes for gradle 1.11 that reference an issue like this, so I assume this was fixed while resolving a seemingly unrelated issue.
The solution was to upgrade all my projects to use gradle 1.11


text:
Q: the best way to convert delimited to fixed width What is the BEST way to convert this :
FirstName,LastName,Title,BirthDate,HireDate,City,Region
Nancy,Davolio,Sales Representative,1948-12-08,1992-05-01,Seattle,WA
Andrew,Fuller,Vice President Sales,1952-02-19,1992-08-14,Tacoma,WA
Janet,Leverling,Sales Representative,1963-08-30,1992-04-01,Kirkland,WA
Margaret,Peacock,Sales Representative,1937-09-19,1993-05-03,Redmond,WA
Steven,Buchanan,Sales Manager,1955-03-04,1993-10-17,London,NULL
Michael,Suyama,Sales Representative,1963-07-02,1993-10-17,London,NULL
Robert,King,Sales Representative,1960-05-29,1994-01-02,London,NULL
Laura,Callahan,Inside Sales Coordinator,1958-01-09,1994-03-05,Seattle,WA
Anne,Dodsworth,Sales Representative,1966-01-27,1994-11-15,London,NULL

to this :
FirstName  LastName             Title                          BirthDate   HireDate   City            Region
---------- -------------------- ------------------------------ ----------- ---------- --------------- ---------------
Nancy      Davolio              Sales Representative           1948-12-08  1992-05-01  Seattle         WA
Andrew     Fuller               Vice President, Sales          1952-02-19  1992-08-14  Tacoma          WA
Janet      Leverling            Sales Representative           1963-08-30  1992-04-01  Kirkland        WA
Margaret   Peacock              Sales Representative           1937-09-19  1993-05-03  Redmond         WA
Steven     Buchanan             Sales Manager                  1955-03-04  1993-10-17  London          NULL
Michael    Suyama               Sales Representative           1963-07-02  1993-10-17  London          NULL
Robert     King                 Sales Representative           1960-05-29  1994-01-02  London          NULL
Laura      Callahan             Inside Sales Coordinator       1958-01-09  1994-03-05  Seattle         WA
Anne       Dodsworth            Sales Representative           1966-01-27  1994-11-15  London          NULL

A: I'd create a custom class to hold the information, then do a loop for each line in the CSV file, split on the comma and fill your custom object up. Then throw all of them into a list or IEnumrable and throw it into a repeater / datagrid.
public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public DateTime BirthDate { get; set; }
        public DateTime HireDate { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
    }

    public void Parse(string csv)
    {
        string[] lines = csv.Split( Environment.NewLine.ToCharArray() );
                    List<Person> persons = new List<Person>();

        foreach (string line in lines)
        {
            string[] values = line.Split( ',' );

            Person p = new Person();

            p.FirstName = values[ 0 ];
            p.LastName = values[ 1 ];

                            persons.Add( p );
            //.... etc etc
        }
    }

A: This meets your requirements as stated, and uses LINQ (since your question was tagged LINQ), but is not necessarily best:
class Program
{
    static void Main(string[] args)
    {
        List<string> inputs = new List<string>
        {
            "FirstName,LastName,Title,BirthDate,HireDate,City,Region",
            "Nancy,Davolio,Sales Representative,1948-12-08,1992-05-01,Seattle,WA",
            "Andrew,Fuller,Vice President Sales,1952-02-19,1992-08-14,Tacoma,WA",
            "Janet,Leverling,Sales Representative,1963-08-30,1992-04-01,Kirkland,WA",
            "Margaret,Peacock,Sales Representative,1937-09-19,1993-05-03,Redmond,WA",
            "Steven,Buchanan,Sales Manager,1955-03-04,1993-10-17,London,NULL",
            "Michael,Suyama,Sales Representative,1963-07-02,1993-10-17,London,NULL",
            "Robert,King,Sales Representative,1960-05-29,1994-01-02,London,NULL",
            "Laura,Callahan,Inside Sales Coordinator,1958-01-09,1994-03-05,Seattle,WA",
            "Anne,Dodsworth,Sales Representative,1966-01-27,1994-11-15,London,NULL"
        };

        // TODO: These widths would presumably be configurable
        List<int> widths = new List<int> { 12, 22, 32, 13, 12, 17, 8 };

        List<string> outputs = inputs.Select(s => ToFixedWidths(s, ',', widths)).ToList();

        outputs.ForEach(s => System.Diagnostics.Debug.WriteLine(s));

        Console.ReadLine();
    }

    private static string ToFixedWidths(string s, char separator, List<int> widths)
    {
        List<string> split = s.Split(separator).ToList();

        // TODO: Error handling - what if there are more/less separators in
        // string s than we have width values?

        return string.Join(String.Empty, split.Select((ss, i) => ss.PadRight(widths[i], ' ')).ToArray());
    }
}

In a production scenario though I'd expect to see this data read into an appropriate Person class, as Matt recommended in his answer.

A: The easiest way I know to do this is in PowerShell:

PS >  Import-Csv .\x.csv | Format-Table -AutoSize

FirstName LastName  Title                    BirthDate  HireDate   City     Region
--------- --------  -----                    ---------  --------   ----     ------
Nancy     Davolio   Sales Representative     1948-12-08 1992-05-01 Seattle  WA
Andrew    Fuller    Vice President Sales     1952-02-19 1992-08-14 Tacoma   WA
Janet     Leverling Sales Representative     1963-08-30 1992-04-01 Kirkland WA
...

A: You have two problems here. Consider them separately and you will find a good solution more easily.

*

*Parse your CSV-format input data in to a useful format.

*Present your data in a certain way
Don't write your own CSV parser. The rules are a little tricky, but the format is well-known. Getting it wrong would be bad in the long run. There are existing CSV libraries in the .NET framework you could call on, but I don't know much about them. However, this problem is perfect for the new dynamic feature in C#. Here's one that looks promising: http://tonikielo.blogspot.com/2010/01/c-40-dynamic-linq-to-csvhe.html
I'm assuming that printing the data is a trivial problem and you don't need our help. If not, you'll need to give us some more information, like how you want to decide the widths of the columns.

A: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace StringParsingWithLinq
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var inputs = new List<string>
                             {
                                 "FirstName,LastName,Title,BirthDate,HireDate,City,Region",
                                 "Nancy,Davolio,Sales Representative,1948-12-08,1992-05-01,Seattle,WA",
                                 "Andrew,Fuller,\"Vice President, Sales\",1952-02-19,1992-08-14,Tacoma,WA",
                                 "Janet,Leverling,Sales Representative,1963-08-30,1992-04-01,Kirkland,WA",
                                 "Margaret,Peacock,Sales Representative,1937-09-19,1993-05-03,Redmond,WA",
                                 "Steven,Buchanan,Sales Manager,1955-03-04,1993-10-17,London,NULL",
                                 "Michael,Suyama,Sales Representative,1963-07-02,1993-10-17,London,NULL",
                                 "Robert,King,Sales Representative,1960-05-29,1994-01-02,London,NULL",
                                 "Laura,Callahan,Inside Sales Coordinator,1958-01-09,1994-03-05,Seattle,WA",
                                 "Anne,Dodsworth,Sales Representative,1966-01-27,1994-11-15,London,NULL"
                             };

            Console.Write(FixedWidthHelper.ReadLines(inputs)
                              .ToFixedLengthString());
            Console.ReadLine();
        }

        #region Nested type: FixedWidthHelper

        public class FixedWidthHelper
        {
            private readonly Regex _csvRegex = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
            private readonly List<string[]> _data = new List<string[]>();
            private List<int> _fieldLen;

            public static FixedWidthHelper ReadLines(List<string> lines)
            {
                var fw = new FixedWidthHelper();
                lines.ForEach(fw.AddDelimitedLine);
                return fw;
            }

            private void AddDelimitedLine(string line)
            {
                string[] fields = _csvRegex.Split(line);

                if (_fieldLen == null)
                    _fieldLen = new List<int>(fields.Select(f => f.Length));

                for (int i = 0; i < fields.Length; i++)
                {
                    if (fields[i].Length > _fieldLen[i])
                        _fieldLen[i] = fields[i].Length;
                }

                _data.Add(fields);
            }

            public string ToFixedLengthString()
            {
                var sb = new StringBuilder();
                foreach (var list in _data)
                {
                    for (int i = 0; i < list.Length; i++)
                    {
                        sb.Append(list[i].PadRight(_fieldLen[i] + 1, ' '));
                    }
                    sb.AppendLine();
                }

                return sb.ToString();
            }
        }

        #endregion
    }
}

A: I just wrote tablign for this exact purpose. Install with
pip install tablign

and
tablign input.dat

will give you
FirstName , LastName  , Title                    , BirthDate  , HireDate   , City     , Region
Nancy     , Davolio   , Sales Representative     , 1948-12-08 , 1992-05-01 , Seattle  , WA
Andrew    , Fuller    , Vice President Sales     , 1952-02-19 , 1992-08-14 , Tacoma   , WA
Janet     , Leverling , Sales Representative     , 1963-08-30 , 1992-04-01 , Kirkland , WA
Margaret  , Peacock   , Sales Representative     , 1937-09-19 , 1993-05-03 , Redmond  , WA
Steven    , Buchanan  , Sales Manager            , 1955-03-04 , 1993-10-17 , London   , NULL
Michael   , Suyama    , Sales Representative     , 1963-07-02 , 1993-10-17 , London   , NULL
Robert    , King      , Sales Representative     , 1960-05-29 , 1994-01-02 , London   , NULL
Laura     , Callahan  , Inside Sales Coordinator , 1958-01-09 , 1994-03-05 , Seattle  , WA
Anne      , Dodsworth , Sales Representative     , 1966-01-27 , 1994-11-15 , London   , NULL

From there, it should be easy to adapt the file to your needs.


text:
Q: How do I trigger an event on jQuery Tabs rotate? I've got a slider that's built with jQuery UI Tabs:

                [Tab Heading]

                [Tab Heading]

                [Tab Heading]

                [Tab Heading]

[Tab Content]

[Tab Content]

[Tab Content]

[Tab Content]

The client wants the tabs to rotate through just the first and second tabs.
I added a function to the show event:
.tabs({
    show: function(event, ui) {
        var selected = $( ".selector" ).tabs( "option", "selected" );
        if (selected == 3) {
            $( "#featured" ).tabs( "option", "selected", 1 );
        }
    }
})

but this did nothing.
Any idea how I could make the slider rotate through just the first and second tab?

A: The selected option only applies to initialization. You could simply trigger a click on the first tab.
$("#featured li.ui-tabs-nav-item:first").trigger("click");


text:
Q: How to setup circular reference in maven modules? I have this problem with building a maven project...
A mvn project parent is set like this:
<groupId>com.company.system.ping</groupId>
<artifactId>system-ping</artifactId>
<name>system-ping</name>
<parent>
    <artifactId>parent_lvl_1</artifactId>
    <groupId>com.company.system</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>

Then I look for said parent's POM and find this:
<groupId>com.company.system</groupId>
<artifactId>parent_lvl_1</artifactId>
<packaging>pom</packaging>
<name>_proj_test</name>
<version>1.0-SNAPSHOT</version>
<parent>
    <artifactId>parent_lvl_0</artifactId>
    <groupId>com.company</groupId>
    <version>1</version>
</parent>

I finally look at the first parent and see this:
<groupId>com.company</groupId>
<artifactId>parent_lvl_0</artifactId>
<packaging>pom</packaging>
<name>_main</name>
<version>1</version>
<description>The whole Projects</description>

Now I check the modules:
<modules>
    <module>../_proj_test</module>

    ...

</modules>

The first parent module is referencing a child! So when I try

mvn install

on '_main' I get this:
[ERROR]   The project com.company.system:_proj_test:1.0-SNAPSHOT (C:\...\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM: The repository system is offline but the artifact com.company:_main:pom:1 is not available in the local repository. and 'parent.relativePath' points at wrong local POM @ line 4, column 10 -> [Help 2]
[ERROR]

I translate this to: you parent requieres a module which requires you back. If I comment out everything in modules I can install everything correctly but this is NOT OK for me! How can I build the parent without building the module dependencies?
Thank you!

A: The config looks very weird to me, mainly because your '_proj_test' which is a child for '_main' is located on the same level.

How can I build the parent without building the module dependencies?

Try mvn -N install.
As for the project structure, I'd do it in such a way:
1) $basedir with '_main' pom.xml which should contain this
<modules>
  <module>_proj_test</module>
</modules>

2) $basedir/_proj_test with '_proj_test' pom.xml which should contain this
<modules>
  <module>system-ping</module>
</modules>

3) $basedir/_proj_test/system-ping with 'system-ping' pom.xml (with correct groupId of parent - com.company.system instead of com.company)


text:
Q: Immutable Array/Dictionary Initialization If I initialize an NSArray as follows:
- (void) myMethod
{
    NSArray *array = [NSArray arrayWithObjects:@"A","B","C",nil];
    // DO SOME STUFF HERE
    return;
}

Is this immutable array initialized at compile time or at run time?  Same with NSDictionary. I'm thinking it must be at compile time but just wondering.

A: No… It would not be created in compile time… It would be created in runtime when the Method is being called.
 By Immutability, it means that You cannot edit size of the array after once initializing it.
refer to this Link for more info about Object Mutability… Let me know if more info needed.. :)

A: No, Method call arrayWithObjects: is not possible at compile time. During compilation, it just check that syntax, unless that variable would be constants or statics. Macros and constants are initialized at compile time. See this example below.
You could initialize directly, if the size is known as below(same example also posted by @simalone)
int num[5] = {2,8,7,6,0};

A: Following code is what you want?
static NSString *strArray[] = {@"A", @"B", @"C"};

To use it with index like this: stringArray[index];


text:
Q: Can't get the proper download url from Firebase Storage I am having a problem getting the url of my image in firebase storage. Basically, each time the url is something like -
com.google.android.gms.tasks.zzu@899c8a
Yes I know people had the same problem yet I couldn't fix it with the answers they approved. I tried the following -
String upload = sRef.child("users/"+uid+"/"+SetModule+"/note-"+randomString).getDownloadUrl().toString();
String upload = taskSnapshot.getMetaData().getDownloadUrl().toString();
String upload = taskSnapshot.getStorage().toString();

but without any success.
I know that getMetaData is deprecated and I should use getStorage but it still didn't work. Uploading to the storage works perfectly.
I am using com.google.firebase:firebase-storage:16.0.1
Below is my code -
                final String randomString = getRandomString(6);
                StorageReference storageReference = sRef.child("users/"+uid+"/"+SetModule+"/note-"+randomString);
                storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                        String upload = sRef.child("users/"+uid+"/"+SetModule+"/note-"+randomString).getDownloadUrl().toString();
                        myRef.child("users").child(uid).child("modules").child(SetModule).child("note-"+randomString).setValue(upload);

                        Log.d("MyTag","Upload Success");
                    }
                });


text:
Q: how to create column in by fluent nhibernat that IDENTITY start from 1000 step 1 I want start identity from 1000 step 1 by fluent nhibernet in c# sample under code but these code don't work.
 Id(c => c.id).GeneratedBy.Identity("int IDENTITY(1,1000)");


text:
Q: Script not loading css properties from external file here are my 2 files
HTML:
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id=myCanvas></canvas>

    <script>
      var c=document.getElementById("myCanvas");
      alert(c.width)
    </script>

  </body>

</html>

CSS:
canvas {
  width:480;
  height:360;
  position:absolute;
  background-color:grey;
}

Clearly, the width of my canvas element would be 480, but for some reason, alert(c.width) returns 300.

A: It's happening because c.width refers to the element's width attribute. If that attribute is not present in the canvas element, you'll get the default value for it, which is 300px. The same would happen for height (150px).
To get the real canvas width, you can use getBoundingClientRect(). Also, don't forget to add 'px' after your CSS numeric values for width and height.

canvas {
  width: 480px;
  height: 360px;
  position:absolute;
  background-color:grey;
}
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id=myCanvas></canvas>

    <script>
      var c = document.getElementById("myCanvas");
      alert(c.getBoundingClientRect().width)
    </script>

  </body>

</html>

A: Try using c.offsetWidth instead of c.width. As @BrunoSdoukos has already mentioned width in the context of how you are trying to use it requires that you set the width as an attribute on the <canvas> element, like this:
<canvas id="myCanvas" width="480"></canvas>

Because there isn't a width attribute set on the HTML element itself, using c.width will return the default width, which is 300px.
Because you have specified the element's width using CSS in order to get the elements width in this case you should use:
c.offsetWidth

Here is what MDN says about HTMLElement.offsetWidth:

Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered). It does not include the width of pseudo-elements such as ::before or ::after.

You can ready more about this property here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth


text:
Q: How do I make the width of content on my web pages 100%? How can I make all static pages display full width in all static pages? For example, in all my static pages, I have content occupy only half of all static pages.
Pages with the url structure /p/sample.html are the only ones affected. These are the contact us, about, policy etc static kind of pages.
Those with /2017/10/samplepage.html are not affected. These are the regular blog posts.
My website is actually hosted on google.com
What I have tried:
I have tried this:
<b:if cond="data:blog.pageType == "static_page"">

.sidebar {display:none;}
#main-content{width: 100%; float: none; margin: 0 auto;}
.main-content .column-center-inner {width: 900px;margin-left: 0px;}
.blog-posts-wrapper {
float: left;
width: 100%;
margin-right: 1.5%;

<b:if cond="data:blog.isMobile == "false"">
.main-content .column-center-inner {width: 100%;}

But it didn't work, I have no idea why. Any input from you will help, please.

A: body {
margin:0;
}

Add margin or you can actually give the display:block; inside the body

A: You need to remove width:300px from .post-outer on pages
Try this
<b:if cond='data:view.isPage'>
  <style>
    .post-outer {
        width: 100%;
        padding: 15px;
        box-sizing: border-box;
    }
  </style>
</b:if>


text:
Q: Windows 7 computer not renewing ip address on start up unless I reset computer I recently reinstalled Windows 7, and I noticed that I do not automatically receive an IP address when I start up the computer.  When I reset, it makes it get an IP address, and I can surf like normal, but when I bring it back down and up again, it loses it.
Now, I at first thought it was my school's network causing problems, since it does have issues, however, when I took my desktop home for break, I ran into the same issue, so the problem is most likely on my machine.
If I try to use ipconfig/renew, I get this error:
The operation failed as no adapter is in the state permissible for this operation.

In my network settings, it is set to automatically get an IP address
I'm on an Ethernet connection.

A: Seems the network-card driver is acting funny and doesn't initialize properly on a cold-boot of the computer.
There could be many reasons for that but usually it's just Windows being confused.
I have outlined the basic troubleshooting procedure for dealing with network-card issues in Windows below.
First go into the BIOS of the computer and do a reset to factory defaults. Then select the "Load optimized defaults" option (if that is available, it depends on the kind of bios you have).
Go into Windows and see if you problem is solved.
If not: open the device manager (Right-click on "My Computer" and select "Manage", then look for the device manager section in the tree-view on the left.)
Find the network adapter among the various pieces of hardware.
Delete the network adapter !
Now reboot the computer.
On the next boot Windows should re-discover the network card, re-install the drivers and refresh all the settings related to the network.
If all this still doesn't help check to see if the manufacturer of the network card has a newer driver.
Still no luck ? In that case the network-card could be faulty: Get yourself a Linux live-CD (or USB stick) and boot the computer from that. If that works OK with the network-card you can be certain that the hardware is OK and the problem is something with your Windows installation, that didn't get solved with the steps above.
If it is Windows and the above didn't help then it will be very hard to fix it. You will have to have someone look at it who can really troubleshoot this hands-on. Or do a full re-install of Windows.


text:
Q: iterate through number of columns, with variable columns For example, let's consider this toy code
import numpy as np
import numpy.random as rnd

a = rnd.randint(0,10,(10,10))
k = (1,2)
b = a[:,k]

for col in np.arange(np.size(b,1)):
    b[:,col] = b[:,col]+col*100

This code will work when the size of k is bigger than 1. However, with the size equal to 1, the extracted sub-matrix from a is transformed into a row vector, and applying the function in the for loop throws an error.
 Of course, I could fix this by checking the dimension of b and reshaping:
if np.dim(b) == 1:
    b = np.reshape(b, (np.size(b), 1))

in order to obtain a column vector, but this is expensive.
So, the question is: what is the best way to handle this situation?
This seems like something that would arise quite often and I wonder what is the best strategy to deal with it.

A: If you index with a list or tuple, the 2d shape is preserved:
In [638]: a=np.random.randint(0,10,(10,10))
In [639]: a[:,(1,2)].shape
Out[639]: (10, 2)
In [640]: a[:,(1,)].shape
Out[640]: (10, 1)

And I think b iteration can be simplified to:
a[:,k] += np.arange(len(k))*100

This sort of calculation will also be easier is k is always a list or tuple, and never a scalar (a scalar does not have a len).
np.column_stack ensures its inputs are 2d (and expands at the end if not) with:
 if arr.ndim < 2:
     arr = array(arr, copy=False, subok=True, ndmin=2).T

np.atleast_2d does
 elif len(ary.shape) == 1:
     result = ary[newaxis,:]

which of course could changed in this case to
 if b.ndim==1:
     b = b[:,None]

Any ways, I think it is better to ensure the k is a tuple rather than adjust b shape after.  But keep both options in your toolbox.


text:
Q: Gitlab CI/CD job that modify files in a repo within the same group How can I have a gitlab CI/CD job modify files of a different repo?
Consider the scenario where we have 2 Gitlab projects (repo1 and repo2). Repo2 uses releases of repo1 by referencing explicitly the version of repo1 it is using.
Now let's assume I am updating repo1 (resulting in a new version/release/build-something).  Naturally I now want to update repo2 such that it is aware of the new version of repo1. But I want to do it automatically with a job being triggered on the repo1 ci/cd pipeline.
How can a job in a ci/cd pipeline of a repo change files for another repo?
If it helps, all considered repos are located in the same Gitlab group and share the same permissions


text:
Q: Capture html5 video event in angular controller <video id="video-player" ng-click="togglePlayer($event)"
       oncontextmenu="return false" autoplay="true" loop
       class="composition-video" ng-src="{{url}}" type="video/mp4"></video>

How can I capture the event for when the video player state changed in the controller in angularjs?

A: Here is a possible way using a directive which add listeners to your video element:
http://plnkr.co/edit/dOm5TnGiSkJAUAtXSFa1?p=preview
.directive('videoEvents', function () {
    return function ($scope, $element) {
      $element[0].addEventListener("loadeddata", function () {
        console.log('loadeddata');
        // you can $rootScope.$broadcast...
      });
      $element[0].addEventListener("playing", function () {
        console.log('playing');
        // you can $rootScope.$broadcast...
      });
      // and so on...
    }
});


text:
Q: AttributeError: module 'pytest' has no attribute 'config' I followed this tutorial (Build DevOps CI/CD pipeline for Python Flask with Azure DevOps).
There is a command line task to execute a functional test which I get an error while running it.
The command line task script is as follows:
pip install selenium && pip install pytest && pytest Tests/functional_tests/ --webAppUrl=$(webAppUrl.AppServiceApplicationUrl) --junitxml=TestResults/test-results.xml

This is the script used for functional test:
import pytest
from selenium import webdriver
import unittest
import os
import sys
import pytest
import time

class FunctionalTests(unittest.TestCase):

def setUp(self):
    options = webdriver.ChromeOptions()
    options.add_argument('--no-sandbox')
    self.driver = webdriver.Chrome(os.path.join(os.environ["ChromeWebDriver"], 'chromedriver.exe'), chrome_options=options)
    self.driver.implicitly_wait(300)

def test_selenium(self):
    webAppUrl = pytest.config.getoption('webAppUrl')
    start_timestamp = time.time()
    end_timestamp = start_timestamp + 60*10
    while True:
        try:
            response = self.driver.get(webAppUrl)
            title = self.driver.title
            self.assertIn("Home Page - Python Flask Application", title)
            break
        except Exception as e:
            print('"##vso[task.logissue type=error;]Test test_selenium failed with error: ' + str(e))
            current_timestamp = time.time()
            if(current_timestamp > end_timestamp):
                raise
            time.sleep(5)

def tearDown(self):
    try:
        self.driver.quit()
    except Exception as e:
        print('tearDown.Error occurred while trying to close the selenium chrome driver: ' + str(e))

I get the following error:
> webAppUrl = pytest.config.getoption('webAppUrl')
    AttributeError: module 'pytest' has no attribute 'config'

The tutorial uses python353x86 in the task prior to this task, to determine the Python version, but I have used Python 3.6.4 x86.
In the other hand, while running command line task, the following settings are printed:
platform win32 -- Python 3.8.3, pytest-5.4.3, py-1.9.0, pluggy-0.13.1

I'm new to pytest, can someone please give a solution for this error? I couldn't find the answer in other stackoverflow pages.

A: pytest.configglobal was deprecated in pytest==4.0 and removed in pytest==5.0. If you want your tests to be compatible with 5.0, you need to pass the config instance via an autouse fixture in order to access it:
class FunctionalTests(unittest.TestCase):

    @pytest.fixture(autouse=True)
    def inject_config(self, request):
        self._config = request.config

    def test_selenium(self):
        webAppUrl = self._config.getoption('webAppUrl')
        ...

This is the same approach that I described in my answer to Pytest fixture for a class through self not as method argument.

A: for me, I just needed to updated pytest-django to the latest, 4.5.2 (as of 05/16/22).


text:
Q: Receiving a trigger error, Illegal assignment from List to Map I am receiving a trigger error, can anyone help as well as explain to me what I did wrong. I have been racking my brain on it for a while.
Purpose of the trigger:
I am trying to populate the name field on a related object (child) record using the Parent Records Name. I cannot override the New button & URL hack it(Lightning). Seemed like a trigger was the only solution.
 trigger PopulateRelatedProductName on ICIX_V1__PP_Relationship__c (before update, before insert){

Set<Id> idCO = new Set<Id>();

    for(ICIX_V1__PP_Relationship__c Rp : trigger.new) {

        if (Rp.Name != null)
        {
            idCO.add(Rp.Id);
        }
    }

    Map<Id,ICIX_V1__PP_Relationship__c > mapPOtoCO = [Select Id, Name FROM ICIX_V1__ICIX_Product__c  WHERE Id IN :idCO];

     for(ICIX_V1__PP_Relationship__c co : trigger.new)
     {
         Co.ICIX_V1__ICIX_Product__c  = mapPOtoCO.get(co.id).Name;
            if( co != null)
            {
                ICIX_V1__PP_Relationship__c.Name = ICIX_V1__ICIX_Product__c.Name;
          }

    }
  }

Thank you.

A: Your code has a number of problems, but I think you're looking for the standard aggregate-query-update pattern, which generically looks like this:
Map<Id, ParentType> parents = new Map<Id, ParentType>();
for(ChildType record: Trigger.new) {
    parents.put(record.ParentField, null);
}
parents.putAll([SELECT FieldFromParent FROM ParentType WHERE Id IN :parents.keySet()]);
for(ChildType record: Trigger.new) {
    if(record.ParentField != null) {
        record.ChildFieldToUpdate = parents.get(record.ParentField).FieldFromParent;
    }
}

I'll leave this up to you to figure out exactly what this means.

As a side note, you can build this same logic in the Process Builder, so you might not even need code at all. Consider trying to use the configuration-based processes before deploying code.


text:
Q: How do i send mail with custom Form Data using WordPress I have a custom HTML form with input types and checkboxes. When I submit this form I want to send a mail will all the form details from the same php. How do I send the email from WordPress? I am pretty new and would thank for ur help.

A: wp_mail is the function you are looking for.
You can take the posted form data ($_POST['email'], for example) and then use it to build and execute the wp_mail function. The example below was taken from https://developer.wordpress.org/reference/functions/wp_mail/#user-contributed-notes
$to = $_POST['email']; //sendto@example.com
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');

wp_mail( $to, $subject, $body, $headers );

Also the above script would need to check for malicious attacks or bad input from the user but the wp_mail function will allow you to send email.
Source:
https://developer.wordpress.org/reference/functions/wp_mail/

A: If you don't want to write your own code (and the mail form), consider a 'contact form' plugin. I use (and recommend) the Contact Form 7 plugin. It allows you to create any form, customize the look/feel/fields, and the mail that is sent out. Very powerful and popular plugin. Lots of other plugins available to add additional fields.
The only minor issue is sparse and sometimes hard-to-find (and sometimes older) technical documentation (like available filters). But I've worked around that.

A: One simple way to post a form is to use a form backend service like https://www.formkeep.com
All you have to do is modify the action tag in your form and backend service will store the data and provide ways to integrate data with the other systems.
Here's a sample for how to modify the form html. You would just replace "example token" with a key provided by the formkeep service
<form accept-charset="UTF-8" action="https://formkeep.com/f/exampletoken" method="POST">


text:
Q: Why can not instantiate an empty Angular app? Why can not instantiate an empty Angular app?
I am following the official docs: https://angular.io/guide/setup-local.
I installed angular first with the command: npm install -g @angular/cli.
Now I am trying to create an empty app by running the: ng new app.
Here is the output I am getting:
my.name@mylaptop MINGW64 ~/source/repos/parentFolder
$ ng new app
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS   [ https://sass-lang.com/documentation/syntax#scss                ]
CREATE app/angular.json (3657 bytes)
CREATE app/package.json (1289 bytes)
CREATE app/README.md (1021 bytes)
CREATE app/tsconfig.json (543 bytes)
CREATE app/tslint.json (1953 bytes)
CREATE app/.editorconfig (246 bytes)
CREATE app/.gitignore (631 bytes)
CREATE app/browserslist (429 bytes)
CREATE app/karma.conf.js (1015 bytes)
CREATE app/tsconfig.app.json (270 bytes)
CREATE app/tsconfig.spec.json (270 bytes)
CREATE app/src/favicon.ico (948 bytes)
CREATE app/src/index.html (289 bytes)
CREATE app/src/main.ts (372 bytes)
CREATE app/src/polyfills.ts (2838 bytes)
CREATE app/src/styles.scss (80 bytes)
CREATE app/src/test.ts (642 bytes)
CREATE app/src/assets/.gitkeep (0 bytes)
CREATE app/src/environments/environment.prod.ts (51 bytes)
CREATE app/src/environments/environment.ts (662 bytes)
CREATE app/src/app/app-routing.module.ts (246 bytes)
CREATE app/src/app/app.module.ts (393 bytes)
CREATE app/src/app/app.component.html (25530 bytes)
CREATE app/src/app/app.component.spec.ts (1089 bytes)
CREATE app/src/app/app.component.ts (208 bytes)
CREATE app/src/app/app.component.scss (0 bytes)
CREATE app/e2e/protractor.conf.js (808 bytes)
CREATE app/e2e/tsconfig.json (214 bytes)
CREATE app/e2e/src/app.e2e-spec.ts (636 bytes)
CREATE app/e2e/src/app.po.ts (262 bytes)
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @types/node@~8.9.4.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of 'app'
npm ERR! notarget

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\my.name\AppData\Roaming\npm-cache\_logs\dateandtime7Z-debug.log
Package install failed, see above.

Of course I can run the npm i @types/node and it works, it installs the @types/node@~13 version for me. But that does not help me to create a project, because after running the npm i @types/node I still do not have an empty angular project.
Help me, please, with this stupid error. It drives me crazy, because it is supposed to be the easiest thing during development - empty project creation. But I stumbled at it seriously as if I have no brains whatever, because I can not do it.
My desired outcome is having an empty default angular project.

A: *

*Install the latest node Js
https://nodejs.org/en/

*Delete the package-lock.json file

*Install the npm using the below command
npm install

A: *

*Install the latest node Js
https://nodejs.org/en/

*Run the below command on CLI
ng new my-app


text:
Q: Multiple Charts in single web page I am trying to replicate something done in a ASP class webpage, but in a ASP.NET MVC webpage using Razor.
basically a SQL call is made to get some data, I use google.visualization.arrayToDataTable to put the data in from SQL, give it a title then draw said chart.
    var chart = new google.visualization.ColumnChart(document.getElementById('topThreeModelNumberST_div'));
    chart.draw(data, options);
...html code emitted for brevity

and that is done a few times. The outcome is about 6 or 7 charts on this one page.
So as a test I made a HomeController
public ActionResult Charts()
{
    List<Models.ModelErrorReports> reports = new List<Models.ModelErrorReports>();
    reports.Add(DAL.DevSQL.GetModelErrorReports("Model1", "efipreQCProError"));
    reports.Add(DAL.DevSQL.GetModelErrorReports("Model2", "eepreQCProError"));

    return View(reports);
}

and In my Charts View
@model List<FailFixLog.Models.ModelErrorReports>

@{
    ViewBag.Title = "Charts";
}

Charts

    @{
        List<Chart> charts = new List<Chart>();

        foreach (var item in Model)
        {
            var myChart = new Chart(485, 300);
            myChart.AddTitle(@item.ModelName);
            myChart.AddSeries(@item.ModelName + "Series",
                xValue: @item.ErrorReports.ErrorDescriptions,
                yValues: @item.ErrorReports.ErrorCounts);
            charts.Add(myChart);
        }

    }

    @foreach (var chart in charts)
    {

                @{@chart.Write();}

    }

now I have tried a few variations to this, but this was my last attempt before I gave up and came here. The result continues to be the same that I only get 1 Chart for Model1. I saw somewhere that I would have to make a view for each of my charts... But that doesn't make sense to me because then I'd have to pass in a List to a Partial view, and seeing as this is my second day writing any sort of web code I cant' wrap my head around that. Just in case you are curious I have a unit test that shows that My List has two ErrorReports, and the data is unique. how do I fix this?


text:
Q: Executing in background, but limit number of executions I have a program that performs some operations on a specified log file, flushing to the disk multiple times for each execution. I'm calling this program from a perl script, which lets you specify a directory, and I run this program on all files within the directory. This can take a long time because of all the flushes.
I'd like to execute the program and run it in the background, but I don't want the pipeline to be thousands of executions long. This is a snippet:
my $command = "program $data >> $log";
myExecute("$command");

myExecute basically runs the command using system(), along with some other logging/printing functions. What I want to do is:
my $command = "program $data & >> $log";

This will obviously create a large pipeline. Is there any way to limit how many background executions are present at a time (preferably using &)? (I'd like to try 2-4).

A: #!/bin/bash
#
# lets call this script "multi_script.sh"
#
#wait until there are less then 4 instances running
#polling with interval 5 seconds

while [ $( pgrep -c program ) -gt 4 ]; do sleep 5; done

/path/to/program "$1" &

Now call it like this:
my $command = "multi_script.sh $data" >> $log;

Your perl script will wait if the bash script waits.
positives:
If a process crashes it will be replaced (the data goes, of course, unprocessed)
Drawbacks:
It is important for your perl script to wait a moment between starting instances
(maybe a sleep period of a second)
 because of the latency between invoking the script and passing the while loop test. If you spawn them too quickly (system spamming) you will end up with much more processes than you bargained for.

A: If you are able to change
my $command = "program $data & >> $log";

into
my $command = "cat $data >>/path/to/datafile";

(or even better: append $data to /path/to/datafile directly from perl )
And when your script is finished that the last line will be:
System("/path/to/quadslotscript.sh");

then I have the script quadslotscript.sh here:

*

*4 execution slots are started and stay until the end

*all slots get input from the same datafile

*when a slot is ready with processing it will read a new entry to process
until the datafile/queue is empty

*no processtable lookup during execution, only when all work is done.

the code:
#!/bin/bash

#use the datafile as a queue where all processes get their input
exec 3< "/path/to/datafile"

#4 seperate processes
while read -u 3 DATA; do "/path/to/program $DATA" >>$log; done &
while read -u 3 DATA; do "/path/to/program $DATA" >>$log; done &
while read -u 3 DATA; do "/path/to/program $DATA" >>$log; done &
while read -u 3 DATA; do "/path/to/program $DATA" >>$log; done &

#only exit when 100% sure that all processes ended
while pgrep "program" &>"/dev/null" ; do wait ; done


text:
Q: Changing NavigationItem title I'm trying to change the title in Product but somehow the navigationItem is different. How come the navigationItem in Container is different compared to the one in Product?
class VC1: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let controller = Container()
        let navigation = UINavigationController(rootViewController: controller)

        navigationController?.pushViewController(navigation, animated: true)
    }
}

class Container: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print(navigationItem)
        navigationItem.title = "test"

        let controller = Product()

        controller.didMove(toParentViewController: self)
        self.addChildViewController(controller)

        view.addSubview(controller.view)
    }
}

class Product: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print(navigationItem)
        navigationItem.title = "" // Doesn't remove the title
    }
}

A: I'm just reading the documentation for navigationItem, and it says this:

This is a unique instance of UINavigationItem created to represent the view controller when it is pushed onto a navigation controller.

However, in your case, the embedded VC is not a direct child of a navigation controller.
So, I tried the following code and it worked. The key part is I overrode navigationItem to return the parent's navigation item if there is a parent view controller.
override var navigationItem: UINavigationItem {
    if let parentItem = parent?.navigationItem {
        return parentItem
    } else {
        return super.navigationItem
    }
}


text:
Q: Finding the radius of convergence $\sum_{k=1}^{\infty}\frac{(-5)^k}{(k+1)!}\left(\frac x2\right)^{2k-1}$ How to find the convergence radius of
$$\sum_{k=1}^{\infty}\frac{(-5)^k}{(k+1)!}\left(\frac x2\right)^{2k-1}$$
I guess I should use $R = \lim_{n\rightarrow\infty} \left| \frac{c_n}{c_{n+1}} \right|$, but I have trouble differentiating between $c_k$ - the $k^{th}$ complex coefficient, and
$x$ - the complex variable.

A: Hint: First change the summation index:
$$\sum_{k=1}^{\infty}\frac{(-5)^k}{(k+1)!}\left(\frac x2\right)^{2k-1}=\sum_{k=0}^{\infty}\frac{(-5)^{k+1}}{(k+2)!}\left(\frac x2\right)^{2k+1}$$
Secondly, split $x/2$ from the sum and isolate the power of $x$:
$$\frac{x}{2}\sum_{k=0}^{\infty}\frac{(-5)^{k+1}}{2^{2k}(k+2)!}x^{2k}.$$
Now substitute: $x^2 = u$ and calculate the radius of convergence for:
$$\sum_{k=0}^{\infty}\frac{(-5)^{k+1}}{2^{2k}(k+2)!}u^k.$$
After having evaluated the radius of convergence for $u$ (e.g. by ratio rule) take the square root and you are done. Note, that the $x/2$ does not change the radius of convergence, that is why it is left out (see comment).

A: Every time you increase $k$, you multiply the current term by $-5\left(\dfrac x2\right)^2$ and divide it by $k+2$. As soon as $k+2$ exceeds $\dfrac{5x^2}4$, the absolute series becomes bounded by a geometric series of common ratio less than $1$, and converges.


text:
Q: Null safety in Kotlin for MutableMap with MutableList I am trying to run this example
fun main() {
    val mlist: MutableList<String> = mutableListOf<String>()
    val mapp: MutableMap<Int, MutableList<String>> = mutableMapOf(1 to mlist)
    println(mapp)
    mapp[1].add("a") // Correct is mapp[1]?.add("a")
    println(mapp)
}

at Online Kotlin Compiler.
The compiler is complaining about  Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type MutableList<String>?.
Although I have defined MutableList<String> why the compiler says something about MutableList<String>?.
What does the compiler understand more than me?! What am I missing here?

A: The compiler does not say: '... something about MutableList<String>?.' What the compiler is saying, is, that mapp[1] could return null.
 mapp[1]       // this is the short notation for:
 mapp.get(1)

Both return in your case a MutableList<String>?. Why is this return value nullable? It could be that mapp does not contain an element with the key 1. And then get(1) will return null.
If you are absolutely sure, that the element with key 1 is present in mapp use !!, if not use ? and add("a") will not be executed.

A: in mutableMap, value can be added or removed, the compiler has no guarantee that the value is still present or has been changed before accessing the value in mutableMap types


text:
Q: Create a TextView link in Android I've the following convenience method:
public static void createLink(TextView textView, String linkText, String linkHRef) {
    String htmlLink = "%s";
    Spanned spanned = Html.fromHtml(String.format(htmlLink, linkHRef, linkText));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setHighlightColor(ContextCompat.getColor(textView.getContext(), android.R.color.holo_green_light));
    textView.setText(spanned, TextView.BufferType.SPANNABLE);
}

I'm using that method to create a clickable link inside a textview, given the textview itself, the text link and the url.
Now I would to show a "click effect" when the user tap on that text.
How can I achieve this?
Thank you very much!

UPDATE
I was able to obtain what I mean in this way:
public static void createLink(TextView textView, String linkText, String linkHRef, @ColorRes int linkColorStateList) {
    String htmlLink = "%s";
    Spanned spanned = Html.fromHtml(String.format(htmlLink, linkHRef, linkText));
    textView.setTextColor(ContextCompat.getColorStateList(textView.getContext(), linkColorStateList));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(spanned, TextView.BufferType.SPANNABLE);
}

And defining a color state list xml file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true" android:state_pressed="false" android:color="@color/green" />
   <item android:state_focused="true" android:state_pressed="true" android:color="@color/green_dark" />
   <item android:state_focused="false" android:state_pressed="true" android:color="@color/green_dark" />
   <item android:color="@color/green" />
</selector>

Now the color of the text contained in the TextView changes when I press on it.
The only things that I don't understand is why the TextView background color changes too, becoming bright blue. My code doesn't do that, I think. Anyone maybe knows that?

A: Just add android:autoLink="web" to your .xml file, inside your TextView

A: protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
                         String description = "Your Description http://stackoverflow.com/";

                         Spannable spannable = new SpannableString( description );
                         Linkify.addLinks(spannable, Linkify.WEB_URLS);
                         URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
                         for (URLSpan urlSpan : spans) {
                            LinkSpan linkSpan = new LinkSpan(urlSpan.getURL());
                            int spanStart = spannable.getSpanStart(urlSpan);
                            int spanEnd = spannable.getSpanEnd(urlSpan);
                            spannable.setSpan(linkSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannable.removeSpan(urlSpan);
                        }

                 txt_textview.setMovementMethod(EnhancedLinkMovementMethod.getInstance());
                 txt_textview.setText(spannable, BufferType.SPANNABLE);

        }
    //if you want to open in app web

         private class LinkSpan extends URLSpan {
                    private LinkSpan(String url) {
                        super(url);
                    }

                    @Override
                    public void onClick(View view) {
                        String url = getURL();
                        //Toast.makeText(getApplicationContext(), ""+url, Toast.LENGTH_SHORT).show();
                        Intent webIntent = new Intent(this,Web.class);
                        webIntent.putExtra("url", url);
                        startActivity(webIntent);
                    }
                }

    public class EnhancedLinkMovementMethod extends ArrowKeyMovementMethod {

        private static EnhancedLinkMovementMethod sInstance;

        private static Rect sLineBounds = new Rect();

        public static MovementMethod getInstance() {
            if (sInstance == null) {
                sInstance = new EnhancedLinkMovementMethod();
            }
            return sInstance;
        }

        @Override
        public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
            int action = event.getAction();

            if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {

                int index = getCharIndexAt(widget, event);
                if (index != -1) {
                    ClickableSpan[] link = buffer.getSpans(index, index, ClickableSpan.class);
                    if (link.length != 0) {
                        if (action == MotionEvent.ACTION_UP) {
                            link[0].onClick(widget);
                        }
                        else if (action == MotionEvent.ACTION_DOWN) {
                            Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]));
                        }
                        return true;
                    }
                }
                /*else {
                    Selection.removeSelection(buffer);
                }*/

            }

            return super.onTouchEvent(widget, buffer, event);
        }

        private int getCharIndexAt(TextView textView, MotionEvent event) {
            // get coordinates
            int x = (int) event.getX();
            int y = (int) event.getY();
            x -= textView.getTotalPaddingLeft();
            y -= textView.getTotalPaddingTop();
            x += textView.getScrollX();
            y += textView.getScrollY();

            /*
             * Fail-fast check of the line bound.
             * If we're not within the line bound no character was touched
             */
            Layout layout = textView.getLayout();
            int line = layout.getLineForVertical(y);
            synchronized (sLineBounds) {
                layout.getLineBounds(line, sLineBounds);
                if (! sLineBounds.contains(x, y)) {
                    return -1;
                }
            }

            // retrieve line text
            Spanned text = (Spanned) textView.getText();
            int lineStart = layout.getLineStart(line);
            int lineEnd = layout.getLineEnd(line);
            int lineLength = lineEnd - lineStart;
            if (lineLength == 0) {
                return -1;
            }
            Spanned lineText = (Spanned) text.subSequence(lineStart, lineEnd);

            // compute leading margin and subtract it from the x coordinate
            int margin = 0;
            LeadingMarginSpan[] marginSpans = lineText.getSpans(0, lineLength, LeadingMarginSpan.class);
            if (marginSpans != null) {
                for (LeadingMarginSpan span : marginSpans) {
                    margin += span.getLeadingMargin(true);
                }
            }
            x -= margin;

            // retrieve text widths
            float[] widths = new float[lineLength];
            TextPaint paint = textView.getPaint();
            paint.getTextWidths(lineText, 0, lineLength, widths);

            // scale text widths by relative font size (absolute size / default size)
            final float defaultSize = textView.getTextSize();
            float scaleFactor = 1f;
            AbsoluteSizeSpan[] absSpans = lineText.getSpans(0, lineLength, AbsoluteSizeSpan.class);
            if (absSpans != null) {
                for (AbsoluteSizeSpan span : absSpans) {
                    int spanStart = lineText.getSpanStart(span);
                    int spanEnd = lineText.getSpanEnd(span);
                    scaleFactor = span.getSize() / defaultSize;
                    int start = Math.max(lineStart, spanStart);
                    int end = Math.min(lineEnd, spanEnd);
                    for (int i = start; i < end; i++) {
                        widths[i] *= scaleFactor;
                    }
                }
            }

            // find index of touched character
            float startChar = 0;
            float endChar = 0;
            for (int i = 0; i < lineLength; i++) {
                startChar = endChar;
                endChar += widths[i];
                if (endChar >= x) {
                    // which "end" is closer to x, the start or the end of the character?
                    int index = lineStart + (x - startChar < endChar - x ? i : i + 1);
                    //Logger.e(Logger.LOG_TAG, "Found character: " + (text.length()>index ? text.charAt(index) : ""));
                    return index;
                }
            }

            return -1;
        }
    }

A: TextView textView = (TextView) view.findViewById(R.id.textview);
SpannableString linkText= new SpannableString("linkText");
linkText.setSpan(new UnderlineSpan(), 0, linkText.length(), 0);
textView.setText(linkText);
This above code will make your textview have underline like link . Now Using implicit intent.
Intent i= new  Intent(this,Intent.ACTION_VIEW);
i.setData(Uri.parse("your http url"));
startActivity(i);

A: try this :
textView.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v)
            {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(textView.getText().toString()));
                startActivity(browserIntent);
            }
         });


text:
Q: PHP parsing on includes I'm including a file init.php which defines path constants. So if I include init.php in a file (index.php) and then in another file (layout/header.php)... is init.php parsed before being added to these files or is it added to the parent file and then the parent file is parsed as a whole?
EDIT: Why this is important is because init.php defines path variables relative to location of where it is parsed.

A: Actually include and require are identical in all except require will fail with E_ERROR while include will issue a warning. Also both of the statements are only activated when they actually executed inside script. So the following code will always work:
<?php
echo "Hello world";
if (0) require "non_existing.php";

The answer to your question is that index.php will be parsed first and executed. Then when include "init.php" encountered the file init.php is parsed and executed within current scope. The same for layout/header.php - it will be parsed first.
As already noted init.php will be parsed and executed each time include / require is called, so you probably will want to use include_once or require_once.

A: Think of it as being copy-pasted into the file at the position where it was included. Use require_once or include_once if you don't want your stuff redefined.

There is no difference between including a .php or a .txt. You can include php in a .txt file and it will get parsed as long as you have the <?php openning tag.

A: It depends if you use include or require. With include the text content of the included file is added to the parent and then the whole thing is parsed. With require the included file is first parsed and its content made available to the runtime, then processing continues with parsing the rest of the containing file.
If you want to make sure that the init file is only loaded once in a runtime of a request, then use require_once to make sure that it is only parsed once regardless of how many times you call it. Its a good idea to try to load your init file everywhere you need its constants, but use require_once to make sure you don't parse it more times then needed.


text:
Q: Maven - dynamic pom file? I'm using the Maven plugin was6-maven-plugin to deploy to websphere. When installing an application, there's a configuration value named "updateExisting" that should be false if I am installing a new application, and true if I am updating an existing application. I don't like having to manually toggle this value if I am fresh-installing/updating the application.
The way I see it, I can either add an uninstallApp goal to always uninstall the application before installing it, but this seems a rather silly way to do it.
I've noticed that this plugin also has a goal wsListApps that outputs all applications installed on the server. The output looks like this:

[INFO]   [wsadmin] WASX7209I: Connected to process "server1" on node 1234Node02 using SOAP connector;  The type of process is: UnManagedProcess
[INFO]   [wsadmin] DefaultApplication
[INFO]   [wsadmin] IBMUTC
[INFO]   [wsadmin] MyApplicationEAR
[INFO]   [wsadmin] ivtApp
[INFO]   [wsadmin] query

Is it possible for Maven to scan this output for the string "MyApplicationEAR" and set "updateExisting" to "true" if it is found, and leave it "false" otherwise?

A: What you need is to be able to update a maven property during the life-cycle, before the phase binded with your was6-maven-plugin. (and using this property as a value for <updateExisting>)
Unfortunately, maven properties are static and cannot be changed at runtime. So at first sight it's impossible to do.
But, there is a plugin : properties-maven-plugin you can use to define new properties at runtime. The value of the property can be defined by a groovy script. Now the question is more about how can you write a groovy script telling if your app is already there or not.
Honestly, I don't know if it's a good idea to use it. I think running the uninstall goal everytime with failOnError set to false is probably the simplest way (and so probably the best, but maybe I am missing something ?)


text:
Q: Script to hardware inventory- Solace Appliances We have bunch of solace appliance in our environment and I want write a script to collect hardware detail from all of them, is it feasible? More like, I want  "show hardware" command output.
Cheers,
Ram

A: You can use SEMP to pull that information from each Appliance, you will need to have access to a Mangement Username for each Appliance you need to query for information.
With an http POST call to your appliance you can get that information on an XML response, in this case I'm using curl command to send the POST:
> curl -X POST -d @[SEMP_FILE] -u [username:password] http://[APPLIANCE_IP_OR_HOST:ADMIN_PORT]/SEMP

Example values:
> curl -X POST -d @show-hardware-details.semp -u admin:admin http://10.0.0.102:80/SEMP

Where the show-hardware-details.semp file contains the command you want to send to the Appliance on an XML form:
<rpc>
    <show>
        <hardware>
            <details></details>
        </hardware>
    </show>
</rpc>

This will return an XML response with all the output you normally get from the "show hardware details" command on the Solace CLI.
For more details on how SEMP and SEMPv2 work:
https://docs.solace.com/SEMP/SEMP-Get-Started.htm
https://docs.solace.com/SEMP/Using-Legacy-SEMP.htm


text:
Q: cron has trouble running an R script I have an R script that runs just fine from inside R or from the command line.  Its operation is pretty straightforward.  It just takes some regularly updated data, does some analysis, makes some plots, and saves them to disk.  I want to run it automatically somewhat in sync with the data updates, so I am trying to run it under a cron job.  It does everything just fine until it gets to writing the images to disk.  Then it tells me it can't open the first image, and fails.  I have tried all the stuff I can think of: checking permissions in the run directory, making sure cron is running as me, switching my cron command from "R CMD BATCH" to "Rscript".  Nothing has worked.  Again, the script runs just fine from inside R or from the command line.  Anyone have any ideas about what else I can do?  (BTW, I did find a similar question to this on this site, but the answers given there didn't help in my particular case.)
The offending code seems to be:
png(file=nd_pic_image_names[1],height=720,width=720)

The error returned is:
Error in X11(paste("png::", filename, sep = ""), g$width, g$height, pointsize,  :
unable to start device PNG
Calls: png
In addition: Warning message:
In png(file = nd_pic_image_names[n], height = 720, width = 720) :
 unable to open connection to X11 display ''
Execution halted

I don't understand the "X11" stuff.  I don't have a reference to X11() anywhere in the code and I am not trying to plot prior to opening (or trying to open) my PNG file.  Thanks.

A: Start simple:

*

*Add a cronjob that simply executes a single command, maybe format(Sys.time()), via an Rscript file -- mostly to demonstrate (to yourself) that you can run an R script

*Convert your existing code into an R script you can run at the command-line.  Make sure you have no dependencies on environment variables etc pp

*Add your script as a cronjob.  If it fails, do it piecemeal by adding to the script created in 1.


text:
Q: WordPress error: This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php I have some WordPress websites server with root access, and at the time of creating the server, everything was fine and WordPress itself and plugins and themes were updating without any issues, but I'm not sure why recently I get an error indicates usually permission error (at least I see permissions are fine).
Error when updating WordPress:

This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php

These are what I did to investigate the problem:
ls -ld /home
drwx--x--x 26 root root 4096 Mar 9 20:03 home
ls -ld /home/my_user
drwx--x--x 26 my_user my_user 4096 Mar 9 20:03 /home/my_user/
ls -ld /home/my_user/public_html
drwxr-x--- 26 my_user nobody 4096 Mar 9 20:03 /home/my_user/public_html/

Also all of the files inside public_html permissions are 0644, and all directories are 0755.
cd /home/my_user/public_html/
find . -type f -exec chmod 644 {} \; && find . -type d -exec chmod 755 {} \;
find . -type f -exec chown my_user:my_user {} \; && find . -type d -exec chown my_user:my_user {} \;

So till now, there's nothing wrong with permissions and ownership in my opinion.
Checking wp-admin, wp-admin/includes and wp-admin/includes/update-core.php permissions and ownership was fine and had no problem, but I'm not sure why WordPress cannot install any plugin, theme or itself.
I use CentOS 7, and my_user's website uses PHP 7.3, PHP-Handler is suphp (I also ran tried cgi and lsapi), Apache has below configurations:
MPM: mod_mpm_prefork
Apache modules (some of them):
mod_cgi
mod_lsapi
mod_mpm_prefork
mod_suexec
mod_suphp

lsattr /home/my_user/public_html/wp-admin/includes/update-core.php
-------------e-- /home/my_user/public_html/wp-admin/includes/update-core.php

I should add that I can add any file as media, no matter whether it's extension is zip, jpg, etc. But I cannot update WordPress itself, or I cannot update/install any theme or plugin. For theme/plugin I get Could not copy file error.
Would you please help me what is causing the issue and how may I solve it?


text:
Q: php mysql insert image BLOB field i had a table with 6 fields students_id, customer_id, firstname, lastname, image_name, image this image field is BLOB type, image_name field image filename and extension. i know how to get stored image from blob field and display to my webpage, i tested it with uploading image via phpmyadmin... my question is how can i store image in my image field.?
this is what i use for my other fields..
<?php
public function addStudents($data) {
     $this->db->query("INSERT INTO " . DB_PREFIX . "students SET customer_id = '" .
 (int)$this->customer->getId() . "', firstname = '" . $this->db->escape($data['firstname']) .
 "', lastname = '" . $this->db->escape($data['lastname']) . "'");
}
?>

its my HTML image upload section
<input type="file" name="image" />

anyone please help me? if anyone can answer with edit my source code its very helpful...
thanks...

A: Well, you can check http://www.mysqltutorial.org/php-mysql-blob/, it is clearly explained


text:
Q: Converting circular object to normal object that can be stringified without losing data from it Can we Stringify a circular object without losing data from it, I tried Flatted and other libraries but they remove data from object in which I need them.
Anyone knows a way to do it please?

A: In my opinion, The best way to do this would be to use JSON.stringify but with a custom replacer function. Extending tarkh's answer, Here's how you can stringify a circular object:

// Circular object creator
function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Print string
// You can see in the result, that circular
// property have **ref** link as it's value
console.log('circular one:', circular);

var cache = [];
const stringified = JSON.stringify(circular, (key, value) => {
  if (typeof value === 'object' && value !== null) {
    // Duplicate reference found, discard key
    if (cache.includes(value)) return;

    // Store value in our collection
    cache.push(value);
  }
  return value;
});
cache = null; // Enable garbage collection

console.log('Stringified one', stringified);

When we create a circular object it repeats one property again and again which causes the predefined replacer function of JSON.stringify to malfunction and cause Max Call Stack error internally. So, We define a custom replacer function which we can use in order to stringify our object. Removing the Circular Property from object's child. This solution is good if you don't have more children object property. If you want it to work perfectly with children object properties too. Then, You have to add an identifier to your Circular Property. Which you can use as a condition in your custom replacer function.

Check this thread of Circular JSON structure for more information.

Also do check out this blog by mozilla on Cyclic/Circular JSON Structure to learn more about this problem.

A: Circular object have some property, that refers to object itself, that's why it is circular. So it can't be like JSON string:

// Circular object creator
function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Print string
// You can see in the result, that circular
// property have **ref** link as it's value
console.log(circular);

So to handle this ref properly you need to introduce your custom logic, which will recreate this instance after you load this string back from localstorage. This is pretty complex and maybe changing your app logic is the better way.
You can flatten regular objects and store them as JSON strings in localstorage, and this is the standard way:

// Regular (non circular) object with key-value structure
const browsers = [
  { name: 'Chrome', company: 'Google' },
  { name: 'Firefox', company: 'Mozilla' },
  { name: 'Safari', company: 'Apple' },
  { name: 'Edge', company: 'Microsoft' }
];

// Stringify to JSON string format
const str = JSON.stringify(browsers);

// Result
console.log(str);

But if you try to do the same thing with circular object, you'll get error:

// Circular object creator
function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Try to JSON.stringify()
const res = JSON.stringify(circular);

** Hack time **
You can try to use third-party libraries for this, like Cycle.js, but this may work unstable and not in all cases... So at your own risk:

function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Use of Cycle.js lib
const str = JSON.decycle(circular);
const json = JSON.stringify(str);

// Test
console.log(`Stringified and pushed to JSON circular object:`);
console.log(json);

// Here you store it in localstorage
// ...

// Then load back
const loadedStr = JSON.parse(json);

// Then use Cycle.js again
const recreatedCircular = JSON.retrocycle(loadedStr);

// Test
console.log(`Recreated circular object:`);
console.log(recreatedCircular);
<script>
/*
    cycle.js
    2021-05-31

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    This code should be minified before deployment.
    See https://www.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

// The file uses the WeakMap feature of ES6.

/*jslint eval */

/*property
    $ref, decycle, forEach, get, indexOf, isArray, keys, length, push,
    retrocycle, set, stringify, test
*/

if (typeof JSON.decycle !== "function") {
    JSON.decycle = function decycle(object, replacer) {
        "use strict";

// Make a deep copy of an object or array, assuring that there is at most
// one instance of each object or array in the resulting structure. The
// duplicate references (which might be forming cycles) are replaced with
// an object of the form

//      {"$ref": PATH}

// where the PATH is a JSONPath string that locates the first occurance.

// So,

//      var a = [];
//      a[0] = a;
//      return JSON.stringify(JSON.decycle(a));

// produces the string '[{"$ref":"$"}]'.

// If a replacer function is provided, then it will be called for each value.
// A replacer function receives a value and returns a replacement value.

// JSONPath is used to locate the unique object. $ indicates the top level of
// the object or array. [NUMBER] or [STRING] indicates a child element or
// property.

        var objects = new WeakMap();     // object to path mappings

        return (function derez(value, path) {

// The derez function recurses through the object, producing the deep copy.

            var old_path;   // The path of an earlier occurance of value
            var nu;         // The new object or array

// If a replacer function was provided, then call it to get a replacement value.

            if (replacer !== undefined) {
                value = replacer(value);
            }

// typeof null === "object", so go on if this value is really an object but not
// one of the weird builtin objects.

            if (
                typeof value === "object"
                && value !== null
                && !(value instanceof Boolean)
                && !(value instanceof Date)
                && !(value instanceof Number)
                && !(value instanceof RegExp)
                && !(value instanceof String)
            ) {

// If the value is an object or array, look to see if we have already
// encountered it. If so, return a {"$ref":PATH} object. This uses an
// ES6 WeakMap.

                old_path = objects.get(value);
                if (old_path !== undefined) {
                    return {$ref: old_path};
                }

// Otherwise, accumulate the unique value and its path.

                objects.set(value, path);

// If it is an array, replicate the array.

                if (Array.isArray(value)) {
                    nu = [];
                    value.forEach(function (element, i) {
                        nu[i] = derez(element, path + "[" + i + "]");
                    });
                } else {

// If it is an object, replicate the object.

                    nu = {};
                    Object.keys(value).forEach(function (name) {
                        nu[name] = derez(
                            value[name],
                            path + "[" + JSON.stringify(name) + "]"
                        );
                    });
                }
                return nu;
            }
            return value;
        }(object, "$"));
    };
}

if (typeof JSON.retrocycle !== "function") {
    JSON.retrocycle = function retrocycle($) {
        "use strict";

// Restore an object that was reduced by decycle. Members whose values are
// objects of the form
//      {$ref: PATH}
// are replaced with references to the value found by the PATH. This will
// restore cycles. The object will be mutated.

// The eval function is used to locate the values described by a PATH. The
// root object is kept in a $ variable. A regular expression is used to
// assure that the PATH is extremely well formed. The regexp contains nested
// * quantifiers. That has been known to have extremely bad performance
// problems on some browsers for very long strings. A PATH is expected to be
// reasonably short. A PATH is allowed to belong to a very restricted subset of
// Goessner's JSONPath.

// So,
//      var s = '[{"$ref":"$"}]';
//      return JSON.retrocycle(JSON.parse(s));
// produces an array containing a single element which is the array itself.

        var px = /^\$(?:\[(?:\d+|"(?:[^\\"\u0000-\u001f]|\\(?:[\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*")\])*$/;

        (function rez(value) {

// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.

            if (value && typeof value === "object") {
                if (Array.isArray(value)) {
                    value.forEach(function (element, i) {
                        if (typeof element === "object" && element !== null) {
                            var path = element.$ref;
                            if (typeof path === "string" && px.test(path)) {
                                value[i] = eval(path);
                            } else {
                                rez(element);
                            }
                        }
                    });
                } else {
                    Object.keys(value).forEach(function (name) {
                        var item = value[name];
                        if (typeof item === "object" && item !== null) {
                            var path = item.$ref;
                            if (typeof path === "string" && px.test(path)) {
                                value[name] = eval(path);
                            } else {
                                rez(item);
                            }
                        }
                    });
                }
            }
        }($));
        return $;
    };
}

</script>


text:
Q: Partitioning best-practices for SSD+regular HDD with multi-boot I have a (couple of) regular HDDs on my machine , and I'm about to buy an SSD, probably 128GB, for it.
I would like the machine to be a Dual-Boot Linux (3.x kernel) + Windows 7. My question has two parts.
First, suppose I completely ignore my current partition structure. How would I best partition my drives?
Second, my current partition structure has a bunch of NTFS partitions, one 49GB ext4 partition on one of the drives, and a 4.5GB swap partition. What would you recommend so I don't need to do a lot of shuffling-around of files and partitions?
Notes:

*

*I have an Intel Z77 board, with Smart Response Technology, I'd like to utilize that

*I'm quite open to using LVMs

*I don't have HDDs which are the same, so no RAID-0/1'ing I guess (correct me if I'm wrong).

*I have 8GB of RAM; if you think a RAM drive is relevant (I've heard it suggested), I can consider that as well.

A: I currently own a 128 GB SSD and have both Windows and Linux running. I've split them 50:50 and and put the operating systems and swap drives on the SSD. After a few months I realized that I had more stuff in my home directory than I could store, so I moved that onto another, bigger, non-SSD drive.
Recommended partition setup:

*

*100 MB UEFI boot drive

*~20 GB Linux

*~40 GB Windows

*2x RAM Linux swap

*2x RAM Windows swap

Also remember to move your Windows temp and download directory to a different drive because they will fill up quite quickly. You may also want to set your Windows swap file to a fixed size.
If you are worried because of your SSD write cycle limit move your Windows swap- and temp file to a non-SSD drive. If you however have sufficient RAM (like me) your swap file will almost never be used anyway.
Update: As for SRT, you could alternatively use your large drive as the primary one and only use the SSD for caching via SRT. The same partitioning can apply here, maybe leave a bit more space for Windows since it tends to be disk-hungry. If you have a disk larger than 2 TB you absolutely must boot using UEFI, which may be a pain to set up if you have for example a SuperMicro BIOS. (That's why I chose to boot from the SSD.)
When setting up SRT, pay attention to the mode to set it to. Enhanced mode offers more data security, while maximized offers more speed at the expense of data security. Do not use maximized mode unless you have frequently tested UPS if your data is the least bit precious.
In summary: I found my 128 GB SSD to be a bit small for two OS', so that may be a compelling reason to use SRT. However, the technology itself is a very advanced form of RAID. In the server world everybody fears data loss and therefore nobody dares to use a RAID controller that has no barebone recovery instructions. SRT may be perfectly safe, but I urge you (quite independently of SRT actually) to do your backups.


text:
Q: How do I add a custom column to my CSV.generate endpoint in Rails app? I followed this example but I'm having issues with a nil value showing up in each row (in between the original values and the additional value I'm adding.
Here's my controller endpoint:
def daily_grocery_carts_overview_export
  @data = DailyRetailerShop.all.order("start_date ASC")
  respond_to do |format|
    format.html { redirect_to root_path }
    format.csv { send_data @data.to_csv, filename: "DailyGroceryCarts-#{Time.now.strftime("%Y%m%d%H%M%S")}.csv" }
  end
end

Here's my model:
class DailyRetailerShop < ActiveRecord::Base

  def self.to_csv
    # generate site abbreviations & name to add to CSV file
    site_abbreviations = {}
    Partner.all.each do |p|
      site_abbreviations[p[:site_abbreviation]] = p[:name]
    end

    CSV.generate do |csv|
      # remove certain columns
      export_columns = column_names - %w(id site_abbreviation created_at updated_at)
      # add custom column header
      headers = export_columns << 'Website'
      # add to csv file
      csv << headers
      all.each do |item|
        row = item.attributes.values_at(*export_columns).insert(-1, site_abbreviations[item.site_abbreviation])
        csv << row
      end
    end
  end

end

When I download the CSV file and open it up I see a blank value followed by the custom value I appended in each row. If I read the downloaded CSV file, here's what I see in the first few rows:
data = CSV.read("downloaded_file.csv")
puts data[0..3]
=> [["start_date", "grocery_retailer", "retailer_shops", "Website"], ["2019-10-15", "walmart", "25", nil, "Website1"], ["2019-10-15", "walmart", "24", nil, "Website2"], ["2019-10-15", "instacart", "23", nil, "Website3"]]

Notice there is a nil value for each row (not in the headers). If I exclude my custom header name and then append values as I did above those nil values (blanks when I open the file) are no longer there.
So, it appears the custom header creating a nil value for each row. How do I get rid of that?

A: I never found out why those nil values are being included in each row but I figured out how to restrict them from showing up. Here's how I modified the function within my model:
class DailyRetailerShop < ActiveRecord::Base

  def self.to_csv
    # generate site abbreviations & name to add to CSV file
    site_abbreviations = {}
    Partner.all.each do |p|
      site_abbreviations[p[:site_abbreviation]] = p[:name]
    end

    CSV.generate do |csv|
      # remove certain columns
      export_columns = column_names - %w(id site_abbreviation created_at updated_at)
      # add custom column header
      headers = export_columns << 'Website'
      # add to csv file
      csv << headers
      all.each do |item|
        # exclude the last item before inserting site name (custom header)
        row = item.attributes.values_at(*export_columns)[0..-2].insert(-1, site_abbreviations[item.site_abbreviation])
        csv << row
      end
    end
  end

end

Hope this helps someone in the future!


text:
Q: How to require a file other than the npm main file in node? package.json:
...
"name": "mypackage",
"main": "src/index.js"
...

Directory structure:
|- src/
|--- index.js
|--- other.js

I can require src/index.js with require('mypackage');, but how can I require src/other.js?
If the answer is require('mypackage/src/other');, is there a way to make it so I can require it with require('mypackage/other'); (i.e. teaching node what the source file directory is of your module?

A: I'm currently looking into the exact same thing.
Package.json has a property called 'files':
http://blog.kewah.com/2014/npm-as-a-front-end-package-manager/
https://docs.npmjs.com/files/package.json

The "files" field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder.

But I have yet to find how to do a import/require of such a file.
I don't really see another point in listing these files other then to be able to import/require them?

I was able to import a file from a package if it was listed in this files array.
{
    "name": "local-ui-utilities",
    "version": "0.0.1",
    "description": "LOCAL UI Utilities",
    "main": "index.jsx",
    "author": "Norbert de Langen",
    "license": "none",
    "dependencies": {
    },
    "files": [
       "/colors/sets/variables.css"
    ]
}

I'm able to import the css file from the package using postcss-import:
@import "local-ui-utilities/colors/sets/a.css";

This probably isn't your use-case, but postcss-import just uses npm under the hood. So This should work for your use-case as well, I would think.
This question and accepted answer seem related:
Node/NPM: Can one npm package expose more than one file?

A: You'll have to explicitly expose the file in the root folder, but many projects (including older versions of lodash) do this as part of a pre-publish step. In fact there's a package that does exactly what @Creynders suggests, adding module.exports = require('./path/to/file') files in your root folder. A while back I wrote up a guide on getting started, but the gist is pretty simple.
Install
npm install --save-dev generate-export-aliases
Configure
{
  "name": "my-package",
  "scripts": {
    "prepublish": "generate-export-aliases"
  },
  "config": {
    "exportAliases": {
      "other": "./src/other"
    }
  }
}

Use
const other = require('my-package/other')
DISCLAIMER: I'm the author of the package

A: AFAIK You'll have to explicitly expose it in the root:
Directory structure:
|- src/
|--- index.js
|--- other.js
|- other.js

Then in /other.js
module.exports = require('src/other.js');

Now you can do require('mypackage/other')

A: Edit
Don't use prepublish anymore. Instead, use prepublishOnly.
My own approach to the solution:
As no one has an idea of how to perform the desired behaviour, we can't stand still, the best answer now is:
Solution 1:
From Patrick solution, and his package generate-export-aliases: we can add some npm scripts to automate the whole publish process.
Either you write your code directly in commonjs inside ./src/ subdirectory or you used some new shining ES feature transpiled in ./dist, you will have your module files to be exposed, so add npm scripts:
"scripts": {
  "expose": "generate-export-aliases",
  "prepublishOnly": "npm run expose",
  "postpublish": "git reset --hard HEAD"
}

Or a more save scripts
"scripts": {
  "expose": "generate-export-aliases",
  "prepublishOnly": "git ceckout -b prepublish-expose && npm run expose",
  "postpublish": "git add . && git stash && git stash drop && git checkout master && git branch -d prepublish-expose"
}

Solution 2: Without generate-export-aliases
You can use gulp task runner (transpile if needed and put the files directly in the root dir, no need to copy or move again).
Indeed, this is the exposing step, you can keep prepublishOnly and postpublish scripts unchanged and just change the expose script. Save time and build in the root dir directly.

A: From node 12.7.0 there is the [exports][1] property of the package.json that can help you.
{
  "main": "./main.js",
  "exports": {
    ".": "./main.js",
    "./other": "./src/submodule.js"
  }
}```

If you have a lot of submodules and you want to export all files you can use a [subpath pattern][1]:

```//package.json
{
  "exports": {
    "./*": "./src/*.js"
  },
}```

  [1]: https://nodejs.org/api/packages.html#subpath-patterns

A: just import it as a simple file.
const otherfile = require('./node_modules/other_package/other_file.js');


text:
Q: How to get the total of column values in sqflite in flutter? I want to get the total of the price column values and save it in a variable and return it...I have gone through other posts one of which is the question which i am asking but it was in android native and i am new to sqflite so i couldnt figure out how to write the code. So please help me with suggestions.
this is my code of the columns i am using
void _onCreate(Database db, int version) async {
await db.execute(
    "CREATE TABLE Cart(id INTEGER PRIMARY KEY,name TEXT, price TEXT,category
TEXT,images TEXT)");
print("DB created");
}

I am trying to do this
Future calculateTotal() async{
var dbClient = await db;// couldnt figure out after this
var cursor = dbClient.rawQuery("SELECT SUM(price) as Total FROM Cart",
null);
if(cursor.move)
}

A: According to https://www.techiediaries.com/flutter-sqlite-crud-tutorial/ this should do:
Future calculateTotal() async {
  var dbClient = await db;
  var result = await dbClient.rawQuery("SELECT SUM(price) as Total FROM Cart");
  print(result.toList());
}

int _total;

void _calcTotal() async{
  var total = (await db.calculateTotal())[0]['Total'];
  print(total);
  setState(() => _total = total)
}

@override
Widget build(BuildContext context) {
  ...
  Text(_total != null ? _total : 'waiting ...', ... )

A: Future<List> calculateTotal() async {
  var dbClient = await db;
  var result = await dbClient.rawQuery("SELECT * FROM Cart");
  return result.toList();
}

int _total = 0;
List priceList;

void _calcTotal() async{
   priceList = await db.calculateTotal();
   priceList.forEach((price){ _total = _total + price['price'];});
   print(_total);
   setState(() => _total = total);
}

@override
Widget build(BuildContext context) {
   ...
   Text(_total != null ? _total : 'waiting ...', ... )


text:
Q: How can I trigger custom emails to be sent in wordpress? My goal is to use a user's answers to a few questions to trigger custom emails being sent to them with filtered content on my wordpress website. It seems like this is a common need, but can't find anything that allows it, or even is the right base to build a custom solution.
There are 3 main features I'm needing to do:  First, the signup form lets users choose a few criteria via selection boxes.
Next, the captured information triggers an email being sent that matches the content they chose.  For example, if the user says they're interested in waterskiing, the email that is auto sent would show the most recent posts in the water-skiing category.
Finally, the user responses would need to be saved to trigger actions at a later time if the content is not available yet. So for example, if they are interested in bowling, but there are no entries on bowling, nothing happens.  However, once a post gets entered in this category, they are automatically emailed with that recent entry.
Any clarity you can provide here on plugins, software, etc that would lend to this functionality is much appreciated!!


text:
Q: NonEmpty set in Haskell Is there an equivalent of Data.Lists.NonEmpty for sets?
I know there is NonNull from mono-traversable, but I'm wondering if there's anything else out there.

A: Not in base, but there does seem to be a package that includes nonempty versions of a few data structures, such as Maps and Sets.
http://hackage.haskell.org/package/non-empty-0.3


text:
Q: Text auto-format command/shortcut in Dymola Is there a auto-format command/short-cut in the Dymola text editor that will take care of the proper tab spacing?
Example:
Original
model test
    Real tabCorrecet;
        Real tabIncorrect;
equation
    for i in 1:m loop
ImTabbedWrong=moveMe;
        end for; //me too!!!
end test;

Fixed via One Button Click/hotkey
model test
    Real tabCorrecet;
    Real tabIncorrect;
equation
    for i in 1:m loop
        ImTabbedWrong=moveMe;
    end for; //me too!!!
end test;

A: Highlight what you want formatted, or ctrl+A for the entire file, and then press ctrl+shift+L or right click and select Reformat Selection.


text:
Q: hasManyThrough polymorphic relation I have a student model,a favorite model and media models eg music,video etc. I want to implement hasManyThrough ploymorphic relation in which the through model is favorite and then stores these favorites in favorite table in my case mongoDB. Am using loopback3 and its documentation isn't clear about this topic.Any lead?

A: Your models would look like this:
common/models/student.json
{
  "name": "Student",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "favorites": {
      "type": "hasMany",
      "model": "Favorite",
      "foreignKey": "studentId"
    },
    "videos": {
      "type": "hasMany",
      "model": "Video",
      "foreignKey": "studentId",
      "through": "Favorite",
      "keyThrough": "favoriteId"
    },
    "musics": {
      "type": "hasMany",
      "model": "Music",
      "foreignKey": "studentId",
      "through": "Favorite",
      "keyThrough": "favoriteId"
    }
  },
  "acls": [],
  "methods": {}
}

common/models/video.json
{
  "name": "Video",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "favorites": {
      "type": "hasMany",
      "model": "Favorite",
      "foreignKey": "videoId"
    },
    "students": {
      "type": "hasMany",
      "model": "Student",
      "foreignKey": "videoId",
      "through": "Favorite",
      "keyThrough": "studentId"
    }
  },
  "acls": [
  ],
  "methods": {}
}

common/models/favorite.json
{
  "name": "Favorite",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "student": {
      "type": "belongsTo",
      "model": "Student",
      "foreignKey": "studentId"
    },
    "video": {
      "type": "belongsTo",
      "model": "Video",
      "foreignKey": "videoId"
    },
    "music": {
      "type": "belongsTo",
      "model": "Music",
      "foreignKey": "musicId"
    }
  },
  "acls": [],
  "methods": {}
}

Then, you simply need to POST a new Favorite item with the attributes studentId and videoId to add the new relation.
EDIT: Added music.json
common/models/music.json
{
  "name": "Music",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "favorites": {
      "type": "hasMany",
      "model": "Favorite",
      "foreignKey": "musicId"
    },
    "students": {
      "type": "hasMany",
      "model": "Student",
      "foreignKey": "musicId",
      "through": "Favorite",
      "keyThrough": "studentId"
    }
  },
  "acls": [
  ],
  "methods": {}
}


text:
Q: Proof of $A \cup B = A \cup C \implies B = C$ How could I prove $A \cup B = A \cup C \implies B = C$?
Thank You!

A: It is not true, in general.
E.g., suppose $$B\subset A,\;C \subset A$$  Then $A\cup B = A\cup C =A$
As a concrete example, suppose $$A = \{1, 2, 3, 4\},\; B=\{1, 2\}, \;C=\{3, 4\}$$
Then $A = A\cup B = A \cup C$, but $B\neq C$.


text:
Q: How to make a bar chart not group things by day I've got the following table

What I want do is create a bar chart and to have 5 different bars, each one with a height of 2. The issue is that, because there are 2 items that are on the 04/01/2022 then my chart groups them together. Is there a way to make Excel say "Separate that single bar into 2 because the times are different?
This is what Excel currently creates for me

I know that this type of chart doesn't make much sense right now but it does on the bigger project that I'm working on.

A: I suggest creating a pivot table, it will look like this: