text:
Q: Flex/Flash Builder - Copy/paste MULTIPLE rows from one dataGrid to another I'm in need of help! Basically I have two mx DataGrids, one that pulls in data from an xml file and the other is blank because I'd like to add to it. I'm trying to select multiple rows from one grid and add them to the other by clicking a button.
Currently I'm successfully able to select, copy and paste one row, but no more. The allowMultipleSelection option is set to true, however when I select multiple rows and try to paste them into the empty dataGrid, it will only paste one row at a time.
Here's the function that I'm using to add the selected row to the empty datagrid.
        public function handleAddRow(event:MouseEvent):void
        {

            summaryGrid.dataProvider.addItem({"Category": offersGrid.selectedItem.category,
                "Program": offersGrid.selectedItem.program,
                "Manufacturer": offersGrid.selectedItem.manufacturer,
                "Products": offersGrid.selectedItem.products,
                "MinimumOrder": offersGrid.selectedItem.minimumOrder,
                "OfferDetail": offersGrid.selectedItem.offerDetail
                });

        }

Thanks in advance!
--Moe

A: use the selectedCells property instead selectedItem. This is a collection of Object which contain all the selected rows.
function handleAddRow(event:MouseEvent):void
{
    for each(var row in offersGrid.selectedCells)
        summaryGrid.dataProvider.addItem({
            "Category": row.category,
            "Program": row.program,
            "Manufacturer": row.manufacturer,
            "Products": row.products,
            "MinimumOrder": row.minimumOrder,
            "OfferDetail": row.offerDetail
         });
}

Try with this and be sure this fields are in your grid.
function handleAddRow(event:MouseEvent):void
{
    for each(var row in offersGrid.selectedCells)
        summaryGrid.dataProvider.addItem({
            category: row.category,
            program: row.program,
            manufacturer: row.manufacturer,
            products: row.products,
            minimumOrder: row.minimumOrder,
            offerDetail: row.offerDetail
         });
}

A: Actually you need to invoke addItem on all the selected items. Here is the code I have tried and it works fine:
public function handleAddRow(event:MouseEvent):void
        {
                var selectedItems:Array = offersGrid.selectedItems;
                if(summaryGrid.dataProvider == null) summaryGrid.dataProvider = new ArrayCollection();
                for each(var item:CategoryObject in offersGrid.selectedItems) {
                    (summaryGrid.dataProvider as ArrayCollection).addItem(item);
                }
        }

You may need to make any minor change as per your requirement. If you face any other issue drop a comment.


text:
Q: clang-format causing compiled object files to change I'm working on a large codebase that needs to be formatted. With many hiccups, it's been formatted with a clean start to finish run of clang-format, and I've moved on to comparing the object files between the original build and the formatted build, as an attempt to check clang-format's work.
Much to my surprise, the compiled binaries are not the same. The only thing that I have fond so far is a difference in immediate offsets in a bunch of mov/add/store instructions:
file format elf64-littleaarch64
430c430
<      628:     52803e63        mov     w3, #0x1f3                      // #499
---
>      628:     52803ac3        mov     w3, #0x1d6                      // #470

The change appears to be consistent across each file (every mov/add in this file changes by 29 base 10), but not across files, another file I've checked has an offset of 10 base 10 between new and old binary.
The only thing I can think of is some sort of string that identifies the file has changed, but I don't see how that would happen, and it's not coming out in the diff of the disassembly.
What could be the cause of this change in offset? The only difference between the two source files is that one had clang-format run on it, with a near default set of rules
Edit: a more detailed example:
 461c466
<     if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
---
>         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
465c470
<     1068:     91220001        add     x1, x0, #0x880
---
>     1068:     91224001        add     x1, x0, #0x890
473c478
<     1088:     91222001        add     x1, x0, #0x888
---
>     1088:     91226001        add     x1, x0, #0x898

And the relevant assembly from one of the files
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
105c:       f94037e0        ldr     x0, [sp, #104]
1060:       91004c02        add     x2, x0, #0x13
1064:       90000000        adrp    x0, 1000 <pciFindDevice+0x20>
1068:       91224001        add     x1, x0, #0x890
106c:       aa0203e0        mov     x0, x2
1070:       97ffff20        bl      cf0 <strcmp@plt>
1074:       7100001f        cmp     w0, #0x0
1078:       540006a0        b.eq    114c <pciFindDevice+0x16c>  // b.none
107c:       f94037e0        ldr     x0, [sp, #104]
1080:       91004c02        add     x2, x0, #0x13
1084:       90000000        adrp    x0, 1000 <pciFindDevice+0x20>
1088:       91226001        add     x1, x0, #0x898
108c:       aa0203e0        mov     x0, x2

A: If your code uses assert macros, the expansion in DEBUG mode does generate code that depends on line numbering because the macro __LINE__ gets expanded to a different value, which is passed to fprintf to produce the diagnostic with the file name and line number.
You can compare the code generated with assertions disabled.
You should also grep for __LINE__ in the source code and include files to identify other potential uses of the line numbers in custom macros.
From the details in the question update, the differing data is the offset of the string constants for "." and ".." used as arguments for strcmp. The final values for these offsets comes from the link loader after global object code optimisation by LLVM. Most or all string constants in this and other modules may be shifted in the executable, causing the offsets to change in many places in the executable code.
The code posted shows a difference only as a side effect of something else which may be in a different source file.
You can try and identify where this difference starts by loading both executable in a hex editor (eg: qemacs) and search for longer string constants to try and compare the binaries, scanning backwards to find the first difference explaining the shift. If this difference is a string constant that differs between the executables, you will have a good candidate to investigate further.

redpajama_set_name: RedPajamaStackExchange


text:
Q: como formatar variável com jquery mask Galera uso o plugin jQuery Mask Plugin v1.13.4
Tenho uma div onde eu informa um valor da seguinte forma:
$('#v_pg').text('PAGA R$ ' + valor_pago);

Uso Jquery para atualizar o valor dentro da div. Porém queria que ele fosse formatado pelo Mask da seguinte forma:
$('').mask('00.000.000,00', {
    reverse: true
});

Alguém sabe se tem como fazer isso? ou de tem outra forma?

A: Na sua div, tente separar o conteúdo que você quer colocar máscara do texto estático.
Algo assim:

   PAGA R$

Por fim, você pode colocar a máscara da seguinte forma:
$('.valor_pago').mask('00.000.000,00', {
    reverse: true
});

Deve funcionar.
Uma outra alternativa é usar o atributo data-mask no elemento. Eu particularmente nunca testei com elementos que não sejam inputs mas, teoricamente deveria funcionar:

   PAGA R$

Se tiver dúvidas, pode perguntar nos comentários.


text:
Q: Can i use SATA hard drives with IBM servers I am planning to but IBM X 3850 M2 server
http://www-947.ibm.com/support/entry/portal/docdisplay?lndocid=MIGR-5073028
One friend told me that i can only use SAS drives and i can't use SATA Hard drives on it.
I want to know is it true
Also it has 2 PSU. Can i just use one or i have to use both

A: From the red book it looks as if SATA 2 is supported only with the ServeRAID-MR10M card

http://www.redbooks.ibm.com/redpapers/pdfs/redp4362.pdf
  Pages 29-31


text:
Q: MediaSource API using timestampOffset i tried to use MediaSource API for a little player.
this is my code and it work if i use timestampOffset but because video files are not exactly 30 sec (maybe 30 sec and 3 milisecond) there is a gap while playing. it seem using timestampOffset  is not necessary so when i try to remove this line sourceBuffer.timestampOffset += settings.segment_time; player only show first part. what i missed?
;(function ($) {
    $.fn.player = function (options) {
        var settings = $.extend({
            mimeCodec: 'video/mp4; codecs="avc1.640015, mp4a.40.2',
            segment_time: 30,
            download_gap: 60,
            end_on_error: true,
            autoplay: true,
            played: false,
            controls: false,
        }, options);
        if (!('MediaSource' in window && MediaSource.isTypeSupported(settings.mimeCodec)))
            throw 'Unsupported MIME type or codec: ' + settings.mimeCodec;
    this.start = function () {
        this.each(function () {
            if (!settings.hasOwnProperty('segment_id'))
                throw 'Property segment_id is required.';
            var video = this;
            if (settings.controls)
                $(video).attr('controls', '');
            var sourceBuffer = null;
            var mediaSource = new MediaSource();
            var segment_id = settings.segment_id;
            video.src = URL.createObjectURL(mediaSource);
            mediaSource.addEventListener('sourceopen', function () {
                sourceBuffer = this.addSourceBuffer(settings.mimeCodec);
                sourceBuffer.addEventListener('updateend', function () {
                    sourceBuffer.timestampOffset += settings.segment_time;
                    console.log('updateend:');
                    if (!settings.played && video.paused && settings.autoplay) {
                        console.log('play:');
                        video.play();
                        settings.played = true;
                    }
                });
                reader()
            });

            function reader() {
                fetcher(video.currentTime);
                interval(video, setInterval(function () {
                    fetcher(video.currentTime);
                }, settings.segment_time * 1000 / 4))
            }

            function fetcher(currentTime) {
                if (sourceBuffer.timestampOffset - currentTime < settings.download_gap) {
                    if (!sourceBuffer.updating) {
                        console.log('nexting:');
                        fetch('/tv/segments/next/' + segment_id).then(function (response) {
                            return response.json();
                        }).then(function (data) {
                            if (data.status === 200) {
                                fetch(data.result.current.filename).then(function (response) {
                                    return response.arrayBuffer()
                                }).then(function (res) {
                                    segment_id = data.result.next.id;
                                    console.log('appending:');
                                    sourceBuffer.appendBuffer(res);
                                });
                            } else {
                                if (settings.end_on_error)
                                    mediaSource.endOfStream();
                            }
                        });
                    }
                }
            }
        });
    };

    function interval(obj, data) {
        if (data) {
            $(obj).data('interval', data);
        } else {
            return $(obj).data('interval');
        }
    }

    this.stop = function () {
        this.each(function () {
            clearInterval(interval(this));
        });
    };
    return this;
};
}(jQuery));


text:
Q: Rudin's RCA, Theorem $2.18$ These are the definitions which we need for the theorem :

There is the theorem and it's proof:

I don't understand Why is there a regular measure $\mu$ which satisfies the conclusions of theorem $2.17$?
It will  be regular by $2.14$ theorem but I don't understand why does it satisfy the all conclusions of the $2.17$ theorem.
In $2.17$ theorem we have $\sigma$-compact Hausdorff space.
in $2.18$ we have Hausdorff space in which every open set is $\sigma$-compact. Does this implies that $X$ is $\sigma$-compact?
Any help would be appreciated.


text:
Q: data frame filter in R A bit confused about what does sign , mean when filter a data frame, more specifically, this line of code df2 <- df[df$c6 <= 1 & df$c4 > 200,]. I tried to find some online documents, but failed and I think , means no filter on other columns of original data frame. If anyone could comment what , mean when doing filter, it will be great.
I post my code in R, data and results,
Code
df <- read.csv('~/Downloads/sample.csv', sep=',', header=F, stringsAsFactors=FALSE)
names(df) <- c('c1', 'c2', 'c3', 'c4', 'c5')
df$c5 <- as.numeric(df$c5)
df$c6 <- df$c5 *1000 / df$c4
table(df$c2)
df2 <- df[df$c6 <= 1 & df$c4 > 200,]

Data
10321,t1,1,240,0
16123,t1,20,4492,0
19123,t2,3.1,175,0
35321,t1,3,2304,4.608

Results
> df
     c1 c2   c3   c4    c5 c6
1 10321 t1  1.0  240 0.000  0
2 16123 t1 20.0 4492 0.000  0
3 19123 t2  3.1  175 0.000  0
4 35321 t1  3.0 2304 4.608  2
> df2 <- df[df$c6 <= 1 & df$c4 > 200,]
> df2
     c1 c2 c3   c4 c5 c6
1 10321 t1  1  240  0  0
2 16123 t1 20 4492  0  0

A: Data.frames can be referenced by rows or columns.  The format is df[row, column].  If you select a row, you will return all the columns from that row.  That is what you are doing with your examples, i.e. you are filtering the rows  df[ filter condition , ].
Here are some illustrations of the row and column references:
df[3]  #column 3
#1  1.0
#2 20.0
#3  3.1
#4  3.0
class(df[3])
#[1] "data.frame"

df[,3]  #column 3
#[1]  1.0 20.0  3.1  3.0
class(df[,3])
#[1] "numeric"

df[3,]  #row 3
#c1 c2  c3  c4 c5 c6
#3 19123 t2 3.1 175  0  0
class(df[3,])
#[1] "data.frame"

df$c6 <= 1 & df$c4 > 200
#[1]  TRUE  TRUE FALSE FALSE  #Only rows 1 and 2 meet the conditions
all(df[df$c6 <= 1 & df$c4 > 200, ] == df[ c(TRUE, TRUE, FALSE, FALSE),])
#[1] TRUE


text:
Q: What is the best practice to manage stored procedures in C# code? I'm quite new here, so please forgive me if I made any deviation from the rules of this website.
I'm trying to find the best way possible to manage the names of a stored procedure in code.
Currently when I'm calling a stored procedure I'm using this code:
public static DataSet GetKeyTables()
{
    DataSet ds = new DataSet();
    ds = SqlDBHelper.ExecuteMultiSelectCommand("Sp_Get_Key_Tables",
        CommandType.StoredProcedure);
    return ds;
}

But I don't think that stating the name of the stored procedure in code is a wise idea, since it will be difficult to track.
I thought about Enum or app.config solutions, but I'm not sure these are the best ways.
Any idea will be highly appreciated.

A: You can have a class with constant properties having names of the SPs.And have this class in a seperate class library (dll). Also it is not good to have sp_ as start of procedure see the link http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx
public class StoredProcedures
{
    public const string GetKeyTables = "Sp_Get_Key_Tables";
}

A: In the end, it always boils down to the concrete name string of the SP, no matter what you do. You have to keep them in sync manually. - No way around it...
You could use configuration files for that, but that additional effort will only pay when the names change frequently or they need to remain changeable after compilation.

A: You can wrap the calls in a simple gateway class:
public static class StoredProcedures
{
    public static DataSet GetKeyTables()
    {
        return SqlDBHelper.ExecuteMultiSelectCommand(
                "Sp_Get_Key_Tables",
                CommandType.StoredProcedure);
    }

    public static DataSet GetFoobars()
    {
        return SqlDBHelper.ExecuteMultiSelectCommand(
                "Sp_Get_Foobars",
                CommandType.StoredProcedure);
   }
}

Alternatively you can have POCOs that know how to interact with the database:
public class KeyTable
{
   public int Id { get; set; }
   // whatever data you need

   public static List<KeyTable> GetKeyTables
   {
      var ds = SqlDBHelper.ExecuteMultiSelectCommand(
                "Sp_Get_Key_Tables",
                CommandType.StoredProcedure);

      foreach (var dr in ds.Tables[0].Rows)
      {
          // build the POCOs using the DataSet
      }
   }
}

The advantage of this is that not only the SP name is kept in a unique place, but also the logic of how to extract data out of the dataset is in the same place.

A: I don't see a huge issue with what you are doing. You would need to store the SP name somewhere, so either in the query or in another config or helper function.
Depending on the specification, I tend towards a repository for CRUD operations, so I know all data access, including any SP calls, are in the ISomeRepository implementation.

A: When I work with stored procedures in C# I follow the following rules.

*

*Every stored procedure is used only once in the code so that I have
only one place to update. I do hate Magic strings and avoid
them but stored procedures are used in Data Access Layer only once (e.g. Repositories, ReadQueries, etc).

*For CRUD operations the pattern "sp_{Create/Read/Update/Delete}{EntityName}" is used.
If you want to have single place with all your stored procedures, you can create a static class with logic to create stored procedure's names.


text:
Q: decode dictionary into array of codable structs I have JSON as dictionary [String, Anyobject]:
{
  "AED": "United Arab Emirates Dirham",
  "AFN": "Afghan Afghani",
  "ALL": "Albanian Lek",
}

I need to decode it as array of codable structs Currency like:
struct Currency: Codable {
  var code: String
  var name: String
}

Currency(code: "AED", name: "United Arab Emirates Dirham")

A: You can decode the json as Dictionary and map to Array.
let currencies = try? JSONDecoder()
        .decode([String: String].self, from: data)
        .map({ Currency(code: $0.key, name: $0.value) })

A: You need to create a container, for example named "Currencies" to use the single value container.
I share you the example playground:
let str = """
{
  "AED": "United Arab Emirates Dirham",
  "AFN": "Afghan Afghani",
  "ALL": "Albanian Lek",
}
"""

struct Currencies: Codable {
    var values: [Currency]

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let dict = try container.decode([String: String].self)

        values = dict.map({ (key, value) in
            return Currency(code: key, name: value)
        })
    }
}

struct Currency: Codable {
    var code: String
    var name: String

    enum CodingKeys: String, CodingKey {
        case code
        case name
    }
}

let currencies = try JSONDecoder().decode(Currencies.self, from: Data(str.utf8))
print(currencies.values)


text:
Q: Replicated infinispan cache with Wildfly 11 I'm developing a web application distributed on multi nodes with java 8 and java ee7 on wildfly-11.0.0.Final, and i used infinispan cache for share data.
This is the configuration of cache:
<cache-container name="mycache-container" default-cache="my-cache" jndi-name="infinispan/mycache-container">
    <transport lock-timeout="60000"/>
    <replicated-cache name="my-cache" jndi-name="infinispan/mycache-container/my-cache" mode="ASYNC">
        <locking isolation="READ_COMMITTED"/>
        <transaction locking="OPTIMISTIC" mode="NON_XA"/>
        <eviction strategy="NONE"/>
    </replicated-cache>
</cache-container>

And this is the configuration of jgroups subsystem used for replicated cache:
<subsystem xmlns="urn:jboss:domain:jgroups:5.0">
        <channels default="ee">
            <channel name="ee" stack="tcpping" cluster="ejb"/>
        </channels>
        <stacks>
            <stack name="tcpping">
                <transport type="TCP" socket-binding="jgroups-tcp"/>
                <protocol type="org.jgroups.protocols.TCPPING">
                    <property name="initial_hosts">
                        node1[7600], node2[7600]
                    </property>
                </protocol>
                <protocol type="MERGE3"/>
                <protocol type="FD_SOCK"/>
                <protocol type="FD_ALL"/>
                <protocol type="VERIFY_SUSPECT"/>
                <protocol type="pbcast.NAKACK2"/>
                <protocol type="UNICAST3"/>
                <protocol type="pbcast.STABLE"/>
                <protocol type="pbcast.GMS"/>
                <protocol type="MFC"/>
                <protocol type="FRAG2"/>
            </stack>
        </stacks>
    </subsystem>

On the application's startup i load all entity from database and put in the cache.
If i inject cache through container in this way:
@Resource(lookup="java:jboss/infinispan/mycache-container")
EmbeddedCacheManager container;

@PostConstruct
public void init(){
    Cache mycache = container.getCache();
}

the app start and load all objects in cache without problem, but in the other nodes these objects are not replicated also that jgroups cluster is created wihout errors.
Instead if i inject cache directly in this way:
@Resource(lookup="java:jboss/infinispan/mycache-container/my-cache")
Cache myCache;

the app in startup give me this error:
"WFLYCTL0348: Timeout after [300] seconds waiting for service container stability. Operation will roll back. Step that first updated the service; and the server not start"
How should I use the cache to prevent timeout on startup and be able to replicate that objects on all nodes?
Thank you.

A: The reason the 1st approach doesn't work as expected is because you've done nothing to insure that the requisite cache configuration is installed before your call to EmbeddedCacheManager.getCache().
To ensure the requisite cache configuration is installed, you can either:

*

*Inject the cache directly (as you've done in your 2nd approach)

*Add a dependency on the requisite cache configuration to your application, via @Resource or resource-ref.

I always recommend #1, as it is more intuitive, less verbose, and the cache lifecycle is handled by the container.
As to the cause of the "Timeout [...] waiting for container stability", I can't say for sure without seeing the code that loads objects into you cache as well as the relevant stack trace.  Just a guess - are you sure you the transaction mode to be NON_XA?  This means that cache operations are committed via a Synchronization to an active UserTransaction.  This isn't a common requirement.  If you're loading your cache in a @PostConstruct method, and aren't handling transactions correctly, this could prevent your component from starting (leading to a timeout waiting for container stability).
On an unrelated note, I would recommend using the non-deprecated TCPPING configuration.  e.g.
<socket-discovery-protocol type="TCPPING" socket-bindings="node0 node1"/>

... where the socket-bindings reference configured outbound-socket-bindings.
e.g.
<outbound-socket-binding name="node0">
    <remote-destination host="node0" port="7600"/>
</outbound-socket-binding>
<outbound-socket-binding name="node1">
    <remote-destination host="node1" port="7600"/>
</outbound-socket-binding>


text:
Q: Why is comma used while extending tuple by using asterisk in python? In the below code if I don't use comma then only one 0 gets printed while if I use comma 0 gets printed five times, why? Is it something to do with the immutable trait of the tuple?
 food = (0,) * 5  # comma used
 print (*food)

Output: 0 0 0 0 0
 food = (0) * 5  # comma not used
 print (*food)

Output:0

A: It's a syntax thing. What defines the tuple is not the parenthesis, but the presence of the comma:

*

*Parenthesis around a single scalar expression are used to define order of evaluation: (1 + 2) * 3

*A sequence of expressions separated by commas defines a tuple: 1, 2, 3.

*

*This sequence can then be parenthesized if it needs to be embedded in some other expression: (1, 2, 3) * 5 is "the tuple (1,2,3) repeated five times".

*Specifically for a single-item tuple, the syntax requires a trailing comma to differentiate it from a parenthesized expression: 0, is a tuple containing only the element 0; Usually you'd immediately want to parenthesize this expression if you wanted to embed it in a larger expression, e.g. (0,) * 5 ("the tuple consisting of zero, multiplied five times"). Whereas 0 and (0) both mean "the integer zero" (parenthesized in the latter form).

>>> type( (0, ) )
tuple

>>> type ( (0) )
int

So (0) * 5 is "the integer 0 multiplied by 5", giving you 0. There's no tuple involved at any point because the syntax you used does not define a tuple.

A: Because:
>>> (0)
0
>>>

So 0 * 5 is 0, while:
>>> (0,)
(0,)
>>>

Keeps it's type of a tuple.

A: Tuples and Sequences From documentation a tuple with one item is constructed by following a value with a comma

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For Example

>>> t=('hello')
>>> t
'hello'
>>> type(t)
<class 'str'>
>>> t1=('hello',)
>>> t1
('hello',)
>>> type(t1)
<class 'tuple'>
>>>

A: According to: [Python 3.Docs]: Built-in Types - class tuple([iterable]) (emphasis is mine):

*

*Using a trailing comma for a singleton tuple: a, or (a,)

food definition (note that things would be the same without parentheses):

*

*In the 1st case, it's a tuple (as (0,) is a tuple)

*In the the 2nd  case, it's a plain int (0 * 5)

>>> v0 = (0,)
>>> v1 = (0)
>>>
>>> v0, type(v0)
((0,), <class 'tuple'>)
>>> v1, type(v1)
(0, <class 'int'>)
>>>
>>> v0 * 5
(0, 0, 0, 0, 0)
>>> v1 * 5
0

Are you absolutely sure that print(*food) works (as you claim it does) in the 2nd case?


text:
Q: Running manifests (classes) from a task or plan in Puppet Enterprise TL;DR
In Puppet Enterprise, how do I run a manifest (testpp.pp) from a task or plan (not Bolt).
plan base_windows::testplan (
  TargetSpec $targets,
  Optional[String] $contents = undef,
  String $filename,
){
  $apply_prep($targets)
  $apply_results = apply($targets, '_catch_errors' => true) {
    class { 'base_windows::testpp': }
  }
  $apply_results.each | $result | {
    notice($result.report)
  }
}

apply_prep seems to succeed, but apply is failing with the following error:
{
  "msg" : "Evaluation Error: Unknown function: 'report'. (file: /opt/puppetlabs/server/data/orchestration-services/code/environments/development/modules/base_windows/plans/testplan.pp, line: 16, column: 19)",
  "kind" : "bolt/plan-failure",
  "details" : {
    "class" : "Bolt::PAL::PALError"
  }
}

If I change the code to:
plan base_windows::testplan (
  TargetSpec $targets,
  Optional[String] $contents = undef,
  String $filename,
){
  apply_prep($targets)
  $apply_results = apply($targets, '_catch_errors' => true) {
    # Is this how to call a class? I cannot find an example.
    class { 'base_windows::testpp': }
  }
  $apply_results.each |$result| {
    $target = $result.target.name
    if $result.ok {
      out::message("${target} returned a value: ${result.value}")
    } else {
     out::message("${target} errored with a message: ${result.error.message}")
    }
  }
}

The plan tells me it has failed, but there are no errors in the node's report. In fact, there is no entry for the time the plan was executed.
I cannot find any examples on how to call a class from a plan, so the above apply() is a guess, based on this documentation.
I have installed the puppetlabs_reboot module and successfully ran a plan using it, therefore, I conclude my system is set up correctly, it's just my code that is wrong.
Background
I may be going about this all wrong, so here is some background to the problem. Currently, I have a series of manifests that install various packages from the public Chocolatey repository depending on a node's classification. Package definitions are stored in Hiera data and each package' version is set to latest. At the end of the Package{} resource, some manifests include a reboot.
These manifests are used to provision new nodes and keep existing nodes up-to-date with the latest package version.
The Puppet agent is set to run once per hour and if the source package is updated in the Chocolatey repo, on the next Puppet run, the manifest will update the package, rebooting the node, if required.
Goal

*

*New nodes are provisioned with the latest package version.

*Prevent package updates at undetermined times on existing nodes.

*Continue to allow Puppet agent runs every hour.

*Make use of existing manifests.

Ideas
Split out the package{} code from the profile manifest and place them in tasks / plans, allowing packages to be updated out-of-hours.
Specify the actual package version in Hiera. Although this is more declarative and idempotent, it means keeping an eye on over 100 package version. I guess it would be fairly simple to interrogate the Chocolatey repos with code to pull the latest version number, but even so I am no better off.
Create a task with a script that runs choco upgrade all, however, the next Puppet run would revert package versions according to the version defined in Hiera, meaning Hiera still needs to be kept up-to-date.
Problems
As per the main crux of this question, how do I run manifests (classes) from plans? If I understand correctly, tasks are for ad-hoc scripts, whereas plans can run tasks and manifests. As a lot of time has been invested in writing manifests, I would prefer not to rewrite all my manifests as scripts.
I am confused by the Puppet documentation as it seems to switch between PE and Bolt syntax. I am using Puppet Enterprise where Puppet says they don't recommend using Bolt but their examples seem to site Bolt commands.
No errors in the node' report. apply_prep() reports executed successfully, albeit taking far longer to execute than puppetlabs_reboot module, but apply() results in a failure, but nothing is logged in the node's reports.
Using puppetlabs_reboot module as a reference, it appears their plan uses a bunch of tasks. It appears that they don't use apply() to run their reboot{} class. Is this not duplicating the work?

If anyone has any suggestions or ideas, I'd be grateful if you could share.

A: I've got it to work. The class I was trying to run, required parameters that I hadn't provided!
plan base_windows::testplan (
  TargetSpec $targets,
  Optional[String] $contents = undef,
  String $filename,
){

  apply_prep($targets)

  $apply_results = apply($targets, '_catch_errors' => true) {
    class { 'base_windows::testpp':
      filename => $filename,
      contents => $contents,
    }
  }
}

# Output the whole result_set in the PE console
return $apply_results

I found this out using the logs.

*

*Turn on debug level logging in /etc/puppetlabs/puppetserver/logback.xml (root level="debug")

*Tail the following logs:

*

*tail -f /var/log/puppetlabs/bolt-server/bolt-server.log

*tail -f /var/log/puppetlabs/puppetserver/puppetserver.log | grep -B 5 -A 5 'testplan'

*tail -f /var/log/puppetlabs/orchestration-services/orchestration-services.log


text:
Q: Display multiple chart in one page Only one chart is properly displayed. The other one is making a problem.
I want to get the graph work properly. The work I have done is shown here [https://i.stack.imgur.com/Nn98E.png]. I do understand that the problem is because the js is fetched from the same link but how to overcome this problem?
The js code is shown below:

```````````````````````

A: You're calling Highcharts.setOptions twice, but it has to be called only once (it's meant to set the global options, ie those that you want to apply to every chart on the page). Calling it twice is what causes your issue.
You have two options:

*

*if you want the same options for every chart, a single call is enough, and you can therefore remove the second call (see https://jsfiddle.net/Metoule/p9b6n32f/4/)

*if you want different colors for each chart, you can set them per chart by using the chart.colors option (see https://jsfiddle.net/Metoule/p9b6n32f/7/):
Highcharts.chart('CWT_IGW', {
    /*
       THIS can either be set for each chart (like here),
       or for each chart (via the setOptions call)
    */
    colors: Highcharts.map(Highcharts.getOptions().colors, function(color) {
        return {
            radialGradient: {
                cx: 0.3,
                cy: 0.5,
                r: 0.9
            },
            stops: [
                [0, color],
                [1, Highcharts.Color(color).brighten(+0.3).get('rgb')] // lighten
            ]
        };
    }),
    /* other graph options omitted for brevity */
    series: [{
        name: 'Carrier Data',
        type: 'pie',
        data: [
            { name: 'Chrome', y: 61.41 },
            { name: 'Internet Explorer', y: 11.84 },
            { name: 'Firefox', y: 10.85 },
            { name: 'Edge', y: 4.67 },
            { name: 'Safari', y: 4.18 },
            { name: 'Other', y: 7.05 }
        ]
    }]
});


text:
Q: How to enable Inspect function within right-click menu on custom dialog when debugging Google apps script? I'm developing a file picker function in Google sheet, using Google Picker API. Now I'm able to show a custom dialog window to pick files from my Google drive, but the result doesn't fully meet my needs, I would like to debug and find out any wrong script in HTML which shows in the dialog window. However, when I right-click and select Inspect in a new popup window, it's grey and invalid, unable to debug. What's wrong? Does our company's Google manager restrict users to debug?
Here is a screenshot to show my problem:

A: Are you able to click outside of the modal and inspect it?
You can also press F12 to open the developer tools.
Also, ctrl+shift+C  will open the developer tools with the element picker tool selected.


text:
Q: Questions about removing ios photo asset in Swift This source code is a photo app like the iPhone's photo app.
When you launch the app, each Asset that is a CollectionViewCell is shown.
What I would like to ask is the ability to select and delete an image asset. If you look at the iPhone photo app, you can press the select button to select photos and delete and share selected photos. You can choose as many photos as you want rather than just one. I have implemented @IBAction selectButtonPressed.
class PhotoCollectionViewController: UICollectionViewController {

    @IBOutlet weak var sortButton: UIBarButtonItem!
    @IBOutlet weak var selectButton: UIBarButtonItem!
    @IBOutlet weak var actionButton: UIBarButtonItem!
    @IBOutlet weak var trashButton: UIBarButtonItem!

    // MARK:- Properties
    var fetchResult: PHFetchResult<PHAsset>? {
        didSet {
            OperationQueue.main.addOperation {
                self.collectionView?.reloadSections(IndexSet(0...0))
            }
        }
    }
    var assetCollection: PHAssetCollection?

    // MARK:- Privates
    private let cellReuseIdentifier: String = "photoCell"
    private lazy var cachingImageManager: PHCachingImageManager = {
        return PHCachingImageManager()
    }()

    // MARK:- Life Cycle
    deinit {
        PHPhotoLibrary.shared().unregisterChangeObserver(self)
    }

    @IBAction func sortButtonPressed(_ sender: UIBarButtonItem) {

        let fetchOptions: PHFetchOptions = PHFetchOptions()

        if (self.sortButton.title == "In the past") {
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "modificationDate",
                                                             ascending: false)]
            self.fetchResult = PHAsset.fetchAssets(in: assetCollection!, options: fetchOptions )
            self.sortButton.title = "The latest"
        } else if (self.sortButton.title == "The latest") {
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                             ascending: true)]
            self.fetchResult = PHAsset.fetchAssets(in: assetCollection!, options: fetchOptions )
            self.sortButton.title = "In the past"
        }
    }

     @IBAction func seletButtonPressed(_ sender: Any) {
        if (self.sortButton.isEnabled == true) {
            self.sortButton.isEnabled = false
            self.actionButton.isEnabled = true
            self.trashButton.isEnabled = true
        } else if (self.sortButton.isEnabled == false) {
            self.sortButton.isEnabled = true
            self.actionButton.isEnabled = false
            self.trashButton.isEnabled = false
        }

        PHPhotoLibrary.shared().performChanges({
            //Delete Photo
            PHAssetChangeRequest.deleteAssets(self.fetchResult!)
            },
            completionHandler: {(success, error)in
                NSLog("\nDeleted Image -> %@", (success ? "Success":"Error!"))
                if(success){
                }else{
                print("Error: \(error)")
                }
        })
    }
}

extension PhotoCollectionViewController {

    private func configureCell(_ cell: PhotoCollectionViewCell,
                               collectionView: UICollectionView,
                               indexPath: IndexPath) {

        guard let asset: PHAsset = self.fetchResult?.object(at: indexPath.item) else { return }

        let manager: PHCachingImageManager = self.cachingImageManager
        let handler: (UIImage?, [AnyHashable:Any]?) -> Void = { image, _ in

            let cellAtIndex: UICollectionViewCell? = collectionView.cellForItem(at: indexPath)

            guard let cell: PhotoCollectionViewCell = cellAtIndex as? PhotoCollectionViewCell
                else { return }

            cell.imageView.image = image
        }

        manager.requestImage(for: asset,
                             targetSize: CGSize(width: 100, height: 100),
                             contentMode: PHImageContentMode.aspectFill,
                             options: nil,
                             resultHandler: handler)
    }
}

// MARK:- UICollectionViewDataSource
extension PhotoCollectionViewController {

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView,
                                 numberOfItemsInSection section: Int) -> Int {

        return self.fetchResult?.count ?? 0
    }
}

extension PhotoCollectionViewController {

    override func collectionView(_ collectionView: UICollectionView,
                                 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell: PhotoCollectionViewCell
        cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellReuseIdentifier,
                                                  for: indexPath) as! PhotoCollectionViewCell

        return cell
    }

    override func collectionView(_ collectionView: UICollectionView,
                                 willDisplay cell: UICollectionViewCell,
                                 forItemAt indexPath: IndexPath) {

        guard let cell: PhotoCollectionViewCell = cell as? PhotoCollectionViewCell else {
            return
        }

        self.configureCell(cell, collectionView: collectionView, indexPath: indexPath)
    }
}

// MARK:- UICollectionViewDelegateFlowLayout
extension PhotoCollectionViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {

        guard let flowLayout: UICollectionViewFlowLayout =
            self.collectionViewLayout as? UICollectionViewFlowLayout else { return CGSize.zero}

        let numberOfCellsInRow: CGFloat = 4
        let viewSize: CGSize = self.view.frame.size
        let sectionInset: UIEdgeInsets = flowLayout.sectionInset

        let interitemSpace: CGFloat = flowLayout.minimumInteritemSpacing * (numberOfCellsInRow - 1)

        var itemWidth: CGFloat
        itemWidth = viewSize.width - sectionInset.left - sectionInset.right - interitemSpace
        itemWidth /= numberOfCellsInRow

        let itemSize = CGSize(width: itemWidth, height: itemWidth)

        return itemSize
    }
}

extension PhotoCollectionViewController {
    private func updateCollectionView(with changes: PHFetchResultChangeDetails<PHAsset>) {
        guard let collectionView = self.collectionView else { return }

        // 업데이트는 삭제, 삽입, 다시 불러오기, 이동 순으로 진행합니다
        if let removed: IndexSet = changes.removedIndexes, removed.count > 0 {
            collectionView.deleteItems(at: removed.map({
                IndexPath(item: $0, section: 0)
            }))
        }

        if let inserted: IndexSet = changes.insertedIndexes, inserted.count > 0 {
            collectionView.insertItems(at: inserted.map({
                IndexPath(item: $0, section: 0)
            }))
        }

        if let changed: IndexSet = changes.changedIndexes, changed.count > 0 {
            collectionView.reloadItems(at: changed.map({
                IndexPath(item: $0, section: 0)
            }))
        }

        changes.enumerateMoves { fromIndex, toIndex in
            collectionView.moveItem(at: IndexPath(item: fromIndex, section: 0),
                                    to: IndexPath(item: toIndex, section: 0))
        }
    }
}

// MARK:- PHPhotoLibraryChangeObserver
extension PhotoCollectionViewController: PHPhotoLibraryChangeObserver {

    private func resetCachedAssets() {
        self.cachingImageManager.stopCachingImagesForAllAssets()
    }

    func photoLibraryDidChange(_ changeInstance: PHChange) {
        guard let fetchResult: PHFetchResult<PHAsset> = self.fetchResult
            else { return }

        guard let changes: PHFetchResultChangeDetails<PHAsset> =
            changeInstance.changeDetails(for: fetchResult)
            else { return }

        DispatchQueue.main.sync {
            self.resetCachedAssets()
            self.fetchResult = changes.fetchResultAfterChanges

            if changes.hasIncrementalChanges {
                self.updateCollectionView(with: changes)
            } else {
                self.collectionView?.reloadSections(IndexSet(0...0))
            }
        }
    }
}

extension PhotoCollectionViewController {

    // MARK:- Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        PHPhotoLibrary.shared().register(self)

        self.sortButton.title = "In the past"
        self.actionButton.isEnabled = false
        self.trashButton.isEnabled = false
    }
}

AssetCollection can be selected by clicking the select barButtonItem in the upper right corner of the screen, and I want to delete or share selected pictures.

A: You can perfore delete action on phAsset as below:
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
    //Delete Photo
    PHAssetChangeRequest.deleteAssets(delShotsAsset)
    },
    completionHandler: {(success, error)in
        NSLog("\nDeleted Image -> %@", (success ? "Success":"Error!"))
        if(success){

        }else{
            println("Error: \(error)")
        }
})


text:
Q: How to find "missing" rows in a Heroku Postgres database? I keep getting emails that state the following:
"[Your database X] contains 16,919 rows, exceeding the  plan limit of 10,000. INSERT privileges to the database will be automatically revoked in 7 days. This will cause service failures in most applications dependent on this database."
Even though I have limited the number of rows in my single table application to max 10 000, usually hovering at 9999.
I have checked the number of rows and the number of tables by psql and PGAdmin3.
Any idea how Heroku counts the number of rows in a database? Is this a platform bug or am I missing something?

A: Right now it makes estimated counts until you reach a certain threshold at which point it performs accurate counts (this mechanism subject to change). It will never revoke access or email a user without doing an accurate count first (SELECT count(*) FROM table1 + SELECT count(*) FROM table2 etc).
It does not count system tables; it considers all user level tables. Oftentimes people don't realize they have tables that are eating up rows, such as sessions, events or logs.


text:
Q: Creating & intsalling a simple .sublime-syntax file for Sublime Text 3 I'm trying to define a very basic .sublime-syntax syntax-highlight file for Sublime Text 3.
I'm basing it on the first example in the Sublime Text 3 official documentation on Syntax Definitions:
%YAML 1.2
---
name: Z
file_extensions: z
scope: source.c

contexts:
  main:
    - match: \b(if|else|for|while)\b
      scope: keyword.control.c

This file is /Users/justin/Library/Application Support/Sublime Text 3/Packages/User/z.sublime-syntax
(I left the scopes as .c because I thought maybe the ST3 "theme" (e.g. Monokai) wouldn't know how to color "keyword.control.z".)
I restart Sublime Text 3 but in the lower-right language selection, no option for "Z" appears.
What am I doing wrong? Is there a way to ask Sublime if there was a parsing problem? How should I debug this?
Note: I've read this article,
which describes TextMate-based syntax files, but that method is out-dated since ST3.


text:
Q: Windows Authentication on Windows 2008 Prompts for Credentials We're setting up an ASP.NET 4.0 website on Windows Server 2008. The site uses Integrated Windows Authentication for authentication. (It does not use ASP.NET authentication or authorization.)
In IIS, we have only Windows Authentication enabled.
When we browse to the site using localhost as the host header, the site works fine. When we browse to it using the FQDN, the site prompts for username/password but doesn't accept the validly entered credentials.
Some items to note:

*

*IE does have Integrated Windows Authentication enabled

*The site with FQDN is entered in the Intranet zone in IE

*We've tried adding the site to the Trusted sites to no avail

*We did change the Identity on the AppPool from ApplicationPoolIndentity to Network Service with no success

*We verified that IUSR has read and execute access to the directory and files

*We've set NTAuthenticationProviders to both "NTLM" and "Negotiate,NTLM"

What are we missing?
Thanks.

A: We were informed finally that the server is not on the same domain as we had been led to believe so it couldn't authenticate against Active Directory. (We had been testing with a local account.)


text:
Q: Compare lists with column in snowflake using python I have a column in my snowflake table that contain values with space
    select distinct ("power") from "dev"."devtable"."devschema"

    ------------------
     demo1 is good
     what are you doing
     thank you stack

   ----------------------

but would need to compare with a array of list without space and with quotes and comma :
 ["demo1_is_good",
 "thank_you_stack",
 "what_are_you_doing"]

I want to use python with snowflake and the purpose of this comparison is to check that e.g. 'demo1_is_good' (column values) is the same as 'demo1 is good' (list values in array) by first removing the quote and looping for each list to compare with the record in the column.
If any of the list is not in the column , then script will exit and not continue.

A: Code to search string in snowflake table.
Exits when string not found.
import snowflake.connector
con = snowflake.connector.connect(
    user='username',
    password='password',
    account='account_name.region',
    warehouse='warehouse',
    database='dbname',
    schema='PUBLIC'
)
flag_not_exists = 0
tab_array = []
devarray = ['"demo1_is_good"', '"thank_you_stack"','"what_are_you_doing12"']
try:
    cur = con.cursor()
    cur.execute("select DISTINCT power as col1 from devtable;")
    for col1 in cur:
        tab_array.append(col1[0])
finally:
    con.close()

for col1 in devarray:
    for col2 in tab_array:
        if (col2 == col1.replace('_',' ').replace('"','')):
            flag_not_exists = 0
            break
        else:
            flag_not_exists = 1
            continue
    if (flag_not_exists == 1):
        break
    else:
        print ("Pass")


text:
Q: PDO: stripslashes when getting results I am using PDO prepared statements so it's adding slashes when it's needed before inserting into the database.
I was wondering the proper way to get the results and display it on the website without showing the slashes.
Is it as easy as just using echo stripslashes($result->message);?
Here is what my queries look like:
$database->query('INSERT INTO table_name (field1, field2, field3) VALUES (?, ?, ?)', array($value1, $value2, $value3));

Here is my query method:
public function query($query, $bind=null)
{
    global $pdo;

    # Prepare Statment
    $this->statement = $this->pdo->prepare($query);

    # Execute Query
    $this->statement->execute($bind);
}

EDIT: get_magic_quotes_gpc was indeed turned on even though WHM (cPanel) said it was off

A: Prepared statements do not add slashes to your query data. They inject the parameters into the query in the form of placeholder, in such a way that the placeholder is not considered as part of the query, but as part of the data only.
Therefore, no slashed are added, and no need for stripslashes().
If slashes are added for you, make sure you disable prepared statements emulation for your PDO instance:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

A: get_magic_quotes_gpc was indeed turned on even though WHM (cPanel) said it was off


text:
Q: Finding an isomorhpism $A_n \cong \mathbb{Z}/(m,n)\mathbb{Z}$ Let me define $A_n = \{ a \in \mathbb{Z}/m\mathbb{Z} : an = 0 \}$. Could anyone give me a hint as to how to construct an explicit bijection between $A_n$ and $\mathbb{Z}/(n,m)\mathbb{Z}$. I really have no idea how to go about this. Any hint is highly appreciated!

A: Then you simply need to exhibit a homomorphism $\phi:\mathbb{Z}\rightarrow A_n$ for which $\ker\phi = (m,n)\mathbb{Z}.$
Let $(n,m) = d$ with $n = n_1d$ and $m = m_1d$. Then you can easily see that
$A_n = \{a\in\mathbb{Z}/m\mathbb{Z} :an_1=0 \,\text{mod}\, m_1 \}=\{0,m_1,2m_1, ...(d-1)m_1\}=m_1(\mathbb{Z}/d\mathbb{Z}).$ Thus, simply let $\phi(k) = m_1(k\mod{d}).$ This is clearly a homomorphism and $\phi(k) = 0$ if and only if $k\in d\mathbb{Z} = (m,n)\mathbb{Z}$ and the first isomorphism theorem gives the desired isomorphism.


text:
Q: using `lmer` to fit the linear mixed effects models Edit: I know some people vote this question is off-topic since it is more like a Cross Validated question. However, I am not here to ask about the coding thing (but I might word in the wrong way). I put a piece of my code here just in case the mistake is in my code, or I mis-specified the model. But the question is about how to use or adjust the Bayesian Model Selection (BIC) methods in the mixed effects model situation. We know that BIC is not normally used in this situation because of its poor and slow performance. That's why we want to investigate it and improve it. But before we do the improvement we want to reproduce the "poor" performance at first.
Suppose we have the linear mixed effects model (multiple mesurements per subject $i$) as
$$y_{ij}=\begin{pmatrix}1 & x_{ij2} & x_{ij3} & x_{ij4} \end{pmatrix}\begin{pmatrix} \alpha_1 \\ \alpha_2\\ \alpha_3\\ \alpha_4\end{pmatrix}+\begin{pmatrix} 1 & x_{ij2} & x_{ij3} & x_{ij4}
 \end{pmatrix}\begin{pmatrix} \beta_{i1}\\\beta_{i2}\\\beta_{i3}\\ \beta_{i4}\end{pmatrix}+ \epsilon_{ij}$$
where $\alpha=\begin{pmatrix} \alpha_1 \\ \alpha_2\\ \alpha_3\\ \alpha_4\end{pmatrix}$ is the fixed effect and $\beta_i=\begin{pmatrix} \beta_{i1}\\\beta_{i2}\\\beta_{i3}\\ \beta_{i4}\end{pmatrix} \sim N({\bf 0}, {\bf D})$ is the random effects, where ${\bf D}_{44}=0$, i.e. we are forcing $\beta_{i4}=0$. And $\epsilon_{ij} \stackrel{iid}{\sim}N(0,\sigma^2)$. We want to compare these two models:
The full model
$$y_{ij}=\begin{pmatrix}1 & x_{ij2} & x_{ij3} & x_{ij4} \end{pmatrix}\begin{pmatrix} \alpha_1 \\ \alpha_2\\ \alpha_3\\ \alpha_4\end{pmatrix}+\begin{pmatrix} 1 & x_{ij2} & x_{ij3} & x_{ij4}
 \end{pmatrix}\begin{pmatrix} \beta_{i1}\\\beta_{i2}\\\beta_{i3}\\ \beta_{i4}\end{pmatrix}+ \epsilon_{ij}$$
And the reduced model ($\bf \text{which is the true model!}$)
$$y_{ij}=\begin{pmatrix}1 & x_{ij2} & x_{ij3} & x_{ij4} \end{pmatrix}\begin{pmatrix} \alpha_1 \\ \alpha_2\\ \alpha_3\\ \alpha_4\end{pmatrix}+\begin{pmatrix} 1 & x_{ij2} & x_{ij3}
 \end{pmatrix}\begin{pmatrix} \beta_{i1}\\\beta_{i2}\\\beta_{i3}\end{pmatrix}+ \epsilon_{ij}$$
And even simpler models:
$$y_{ij}=\begin{pmatrix}1 & x_{ij2} & x_{ij3} & x_{ij4} \end{pmatrix}\begin{pmatrix} \alpha_1 \\ \alpha_2\\ \alpha_3\\ \alpha_4\end{pmatrix}+\begin{pmatrix} 1 & x_{ij2}
 \end{pmatrix}\begin{pmatrix} \beta_{i1}\\\beta_{i2}\end{pmatrix}+ \epsilon_{ij}$$
and
$$y_{ij}=\begin{pmatrix}1 & x_{ij2} & x_{ij3} & x_{ij4} \end{pmatrix}\begin{pmatrix} \alpha_1 \\ \alpha_2\\ \alpha_3\\ \alpha_4\end{pmatrix}+\begin{pmatrix} 1
 \end{pmatrix}\begin{pmatrix} \beta_{i1}\end{pmatrix}+ \epsilon_{ij}$$
However, when I using lmer in r to fit the model, the BIC always show that the simplest model is the correct one, which is not true.
Here is the code for doing the lmer, where y is the observations for all subjects, and X is the design matrix with first column all 1s. So did I specify my model correctly in lmer?
#Full model
lmer(y ~ X -1 + (0+ X|subject))
#reduced model 1
lmer(y ~ X -1 + (0+ X[,1:3]|subject))
#reduced model 2
lmer(y ~ X -1 + (0+ X[,1:2]|subject))
#reduced model 3
lmer(y ~ X -1 + (0+ X[,1]|subject))

Many thanks!
Edit: In particular, we consider the case where we have 200 subjects, with 8 observations per each. The covariates $x_{ij}=(x_{ij1},...,x_{ij4})^T$ are simulated by fixing $x_{ij1}=1$ and then generating $x_{ijk} \sim \text{Uniform}(-2,2)$ for $k=2,3,4.$ So $X_i$ will look like
$$X_i=\begin{pmatrix}1 & x_{i11} & x_{i12} & x_{i13}\\
1 & x_{i21} & x_{i22} & x_{i23}\\
\vdots & \vdots & \vdots & \vdots \\
1 & x_{i81} & x_{i82} & x_{i83}
\end{pmatrix}_{8 \times 4}$$
And we will choose $\alpha=(1,1,1,1)^T$ and $\sigma^2=1$ in the model with $\beta_i=(\beta_{i1},...,\beta_{i4})^T \sim N(0, D)$, where $$D=\begin{pmatrix} 9 & 4.8 & 0.6 & 0 \\ 4.8 & 4 & 1 & 0 \\ 0.6 & 1 & 1 & 0 \\ 0 & 0 & 0 & 0 \end{pmatrix}_{4 \times 4}$$
Note here, by forcing $D_{44}=0$ and $\mathbb E(\beta_i)={\bf 0}$, we actually force $\beta_{i4}=0$,


text:
Q: Is there a workaround for Postman's bug when content is returned with a 204? Using Postman, when I make a PUT request to an endpoint which returns a 204 with content, Postman is unable to parse the response, and my collection runner stops that iteration, indicating that an error has occurred.
When run outside of the runner, Postman displays the following:

Other people have also had this problem
Unfortunately I cannot fix the non-standard endpoint. Is there a workaround that will let Postman continue without throwing an error, especially when using the collection runner?

A: The 204 (204 NO CONTENT) response from the server means that the server processed your request  successfully and a response is not needed.
More here: https://httpstatuses.com/204
Actually as much as I know, if the server is sending a 204 with a payload response, the endpoint is not developed as it should.
This would be the main reason Postman is not showing a response payload. You will only be able to read response headers.
So if you send a PUT request, and only receive headers, it means everything is ok. If you spect data the server should be responding with a 200 code.
Now, said this, if postman is telling you that "it could not get any response" it means basically the server is not responding any thing. Now try to increase the timeout in the postman settings. It's very probable that the server is taking to much time. Check outside the runner how much time it's taking to response.
I hope this helps you.


text:
Q: GET-запрос. Вывод данных Есть get запрос. В JSON выглядит так:

{
    "_links": {
        "self": {
            "href": "/api/v2/leads?status=20728261",
            "method": "get"
        }
    },
    "_embedded": {
        "items": [
            {
                "id": 1601345,
                "name": "Тест",
                "responsible_user_id": 2600929,
                "created_by": 2600929,
                "created_at": 1531976544,
                "updated_at": 1531985130,
                "account_id": 20728252,
                "is_deleted": false,
                "main_contact": {
                    "id": 4573131,
                    "_links": {
                        "self": {
                            "href": "/api/v2/contacts?id=4573131",
                            "method": "get"
                        }
                    }
                },
                "group_id": 0,
                "company": {},
                "closed_at": 0,
                "closest_task_at": 0,
                "tags": {},
                "custom_fields": {},
                "contacts": {
                    "id": [
                        4573131
                    ],
                    "_links": {
                        "self": {
                            "href": "/api/v2/contacts?id=4573131",
                            "method": "get"
                        }
                    }
                },
                "status_id": 20728261,
                "sale": 1300,
                "loss_reason_id": 0,
                "pipeline": {
                    "id": 1251568,
                    "_links": {
                        "self": {
                            "href": "/api/v2/pipelines?id=1251568",
                            "method": "get"
                        }
                    }
                },
                "_links": {
                    "self": {
                        "href": "/api/v2/leads?id=1601345",
                        "method": "get"
                    }
                }
            },
            {
                "id": 1620709,
                "name": "Тест2",
                "responsible_user_id": 2600929,
                "created_by": 2600929,
                "created_at": 1531985076,
                "updated_at": 1532061092,
                "account_id": 20728252,
                "is_deleted": false,
                "main_contact": {
                    "id": 4614393,
                    "_links": {
                        "self": {
                            "href": "/api/v2/contacts?id=4614393",
                            "method": "get"
                        }
                    }
                },
                "group_id": 0,
                "company": {},
                "closed_at": 0,
                "closest_task_at": 0,
                "tags": {},
                "custom_fields": {},
                "contacts": {
                    "id": [
                        4614393
                    ],
                    "_links": {
                        "self": {
                            "href": "/api/v2/contacts?id=4614393",
                            "method": "get"
                        }
                    }
                },
                "status_id": 20728261,
                "sale": 2300,
                "loss_reason_id": 0,
                "pipeline": {
                    "id": 1251568,
                    "_links": {
                        "self": {
                            "href": "/api/v2/pipelines?id=1251568",
                            "method": "get"
                        }
                    }
                },
                "_links": {
                    "self": {
                        "href": "/api/v2/leads?id=1620709",
                        "method": "get"
                    }
                }
            }
        ]
    }
}

Оттуда надо вытаскивать при обновлении страницы данные "name, account_id, tags, sale" Желательно один лид в одном блоке.
Только начинаю учить PHP.

<?php
$url = '#################';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json['_embedded']['items'] as $item) {
    print $item['name'];
}
?>

В чем ошибка в данном коде? Не хочет работать

A: $obj=Jsone_decode($data);
$obg->нужное поле


text:
Q: Published google sheet with scripts not working From my previous post at Using one script for copying text from cells in a row to another sheet using an icon in a row I have made a great solution for moving a row by marking a checkbox thanks to @Tanaike.
I need this spreadsheet to be published online and anonymous users to mark the checkbox in column A.
When they click the checkbox the text is moved to sheet 2.
The thing is. The script works fine for an anonymous user with a link but not when it is published online.
I have made a test sheet for you to look into. What am I doing wrong?
Sheet with a link for anonymous user that works fine: https://docs.google.com/spreadsheets/d/1z5TGWp3N002z0GNts4NRyspkjXcsN52rxPtx8Pu9D70/edit#gid=0
Sheet with a a published link for anonymous user that doesn't work https://docs.google.com/spreadsheets/d/e/2PACX-1vT7xrS6irhVTHQzsvM-RdBU6rTDyWFGtHlfTMTAGzG3OqxTnL4uoEKfNo5jxrbvHppAox2VXOnev4yP/pubhtml#
Any help is much appreciated.

A: When you publish a file via File > Publish to the web, you make the file contents visible to anyone, but these contents are not the same as the file itself. These published contents cannot be directly updated (the content will be updated if you edit the spreadsheet where the data comes from) and, of course, you cannot fire an Apps Script trigger from there either.
If you want anonymous users to be able to fire the script when they click the checkbox, you should share the file itself via Share > Advanced > Public on the web, and change the access role to Can edit.
Reference:

*

*Make Google Docs, Sheets, Slides & Forms public


text:
Q: Opening SoundCloud from a deep link opens to the Stream tab instead of the Home tab Currently, if you try to open soundcloud://, it opens the app, then redirects to Stream tab. However, if you simply launch the app yourself, it will open on the Home tab.
Is there any reason to it, and can I redirect to Home tab instead if linking from other app?

A:
Is there any reason to it?

Yes, SoundCloud built their universal links this way.  The base URL scheme (soundcloud://) takes you to the Stream tab, because that's what they want.
I've tried experimenting with a few other paths, but it does not look like there are any that take you to the "Home" tab.
As a workaround, any unsupported deep link (such as soundcloud://home will take the user to the "Home" tab, but an error alert will be displayed.  Another workaround would be to take the user to the "Authentication" page (soundcloud://page/authentication), which will present the login view over the "Home" tab.  This is what SoundCloud does on their mobile site.


text:
Q: Can I turn normal speakers into wireless Bluetooth speakers with Bluetooth modules? I want to turn my simple wired speakers with 8mm audio jack to wireless Bluetooth speakers which can be operated from an android Smartphone with Bluetooth module and microcontroller.
(Sorry for my English.)

A: Yes it is possible. The keywords you are looking for are: "Bluetooth Audio Jack"
With the keywords you can find products on the market (ebay).
Or even diy examples to build one like this.


text:
Q: Prove that $C[a,b]$ is a complete metric space. Consider $C[a,b]$ - metric space with $d(f,g) = \int_{a}^{b} |f-g|dx$.
I consider a Cauchy-sequence $\{f_{n}\}$ then consider $f(x)=\lim_\limits{n \to \infty}f_{n}(x)$ then it's obviously that $f(x)$ is continuous. Now consider:
$\forall \epsilon > 0 \exists N : \forall n,m > N : d(f_{n},f_{m}) < \epsilon$, so consider $\int_{a}^{b} |f_{n}-f_{m}| = \lim_\limits{m \to \infty} \int_{a}^{b} |f_{n}-f_{m}| < \int_{a}^{b} |f_{n}-f_{m}| < \epsilon$. Am I right?

A: proof-verification

I consider a Cauchy-sequence $\{f_{n}\}$ then consider $f(x)=\lim_\limits{n \to \infty}f_{n}(x)$ then it's obviously that $f(x)$ is continuous. (Instead of claiming so, one is supposed to show it.)
Now consider:
  $\forall \epsilon > 0 \exists N : \forall n,m > N : d(f_{n},f_{m}) < \epsilon$, so consider
  $$
\int_{a}^{b} |f_{n}-f_{m}| = \lim_\limits{m \to \infty} \int_{a}^{b} |f_{n}-f_{m}| < \int_{a}^{b} |f_{n}-f_{m}| < \epsilon.$$
  (The first equality does not make sense and your proof breaks down here.)
Am I right? (No. Where do you show that the space is complete?)

There is actually nothing to prove because $C[a,b]$ with your metric $d$ is not a complete metric space. Take a look at this answer:
https://math.stackexchange.com/a/156905/9464

A: No, not at all. How do you know that your definition of $f$ makes sense? It may be obvious for you that $f$ is continuous, but not for me. And what's the goal of the final string of inequalities?

A: Obvious is a dangerous word to use. I align my phiolosophy about that word based on two quotes by my professor of calculus:

*

*"dear colleague, the word 'obvious' does not belong to your vocabulary. You are still a couple years off."

*"The only things that you are allowed to call "obvious" are those that have a single line proof. And you should always have the time to write down single line proofs."

Your problems are:
1.I would not consider it obvious that $f$ is continuous.
You should provide a proof of why $f$ is continuous.
2.It is not clear why you define $f$ at all, since you don't use it anywhere else.
What you probably want is to prove that $f$ is the limit of $\{f_n\}$, but you haven't done that yet.
3.The final string of inequalities makes no sense. For example, it is not true that
$$\int_{a}^{b} |f_{n}-f_{m}| = \lim_\limits{m \to \infty} \int_{a}^{b} |f_{n}-f_{m}| $$
because the variable $m$, on the left, is unclear.


text:
Q: Preserving egl context, created via native code I am porting my game to android and decided to go with NativeActivity instead of Java activity and JNI calls (I am not avoiding JNI, just though it would be more convenient to set up callbacks and opengl context creation/destruction purely in c/c++).
I know that GLSurfaceView has a setPreserveEGLContextOnPause function, but that is in Java, not in native app. I create my context with the following code:
EGLConfig config;
EGLSurface surface;
EGLContext context;

EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

eglInitialize(display, 0, 0);

eglChooseConfig(display, attribs, &config, 1, &numConfigs);

eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);

surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);

const EGLint contextAttribs[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
};

context = eglCreateContext(display, config, NULL, contextAttribs);

if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
    ERR("Unable to eglMakeCurrent");
    return -1;
}

I also know that setPreserveEGLContextOnPause is not 100% reliable and I should check if stuff is destroyed manually, but if it's not - I'd like to skip the asset reloading part for the sake of faster loading.
Basically what I want to do is to use setPreserveEGLContextOnPause (or it's equivalent for ndk world). Is it possible? Is GLSurfaceView being instantiated behind the curtains of android's egl calls?

A: GLSurfaceView is a Java-language utility class that sits on top of SurfaceView and GLES.  Nothing is creating or calling into GLSurfaceView from EGL.
The "preserve EGL context" code in GLSurfaceView exists because GLSurfaceView does its own management of the EGL context on the render thread.  The idea was to set things up so the app doesn't have to deal with it if it wants to use GLSurfaceView.  If you want to do your own EGL management, don't use GLSurfaceView; when writing code in Java you'd use SurfaceView or TextureView instead.
You can see multiple examples in Grafika.  The Java-language GLES implementation is a thin wrapper around the native implementation, so the way EGL is used in Grafika closely mirrors how you would use it in native code.
If you manage the EGL context yourself, it will not go away when Activities are torn down and recreated, but it will go away if the process is killed, so it's best to create it on the activity onPause() / onResume().  It's also bad form to continue holding contexts (and their associated textures and buffers) while the app is in the background.  See this article on SurfaceView and Activity lifecycle interaction for some notes about working with surfaces.  (And read the rest of the article if you'd like to understand how the Android graphics architecture works.)


text:
Q: how to convert base 64 encoded public key (.pem) to bytearray? I need to convert a Base 64 encoded public key file in .pem format to byte array using openssl.
Need to convert public key from the below format:
----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxl4aRnRMBB9GZrNgy6sy
seyIA3Ek3a1xg0b8gKrCSgnSjH+lqtBGwtzKqM020piE1q0YrzGpfQxNJ8HPRc0F
OlII7VKuCFGqEuLH2+kFJPUUdRqBr0iN/D8ADp9rLEL2Q4F7qM1t0z0IW6zD

-----END PUBLIC KEY-----

to  this format:
48, -127, -97, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13,...

A: sed -e '/----.*PUBLIC KEY----\|^[[:space:]]*$/d' praj.pem |
    base64 -d |
    hexdump -v -e '/1 "%02d, "' ; echo

This uses sed to remove the blank lines and lines containing the BEGIN and END markers for the public key, then pipes that into base64 -d to decode it, and then pipes that into hexdump with a custom format to print the bytes as comma-and-space separated decimal numbers.
Finally echo is used to make sure the output finishes with a newline (\n).
Output:
48, -126, 01, 34, 48, 13, 06, 09, 42, -122, 72, -122, -9, 13, 01, 01, 01, 05, ...


text:
Q: How to add text to sender ID in kannel I am sending sms using (http:/ myIP:13013/cgi-bin/sendsms?from=XXXX&username=kannel&password=kannel&text=TESTSMS&to=9122222288) in Kannel
I am able to send sms successfully. I receive SMS
as
Sender : - XXXX
sms Body :- TESTSMS
In this case my sender id is XXXX.
Now I want to add my own text to Sender ID eg. XXXX - Welcome TO Kannel
So what changes I need to do in kannel configuration.
Expected SMS:
Sender : - XXXX - Welcome TO Kannel
SMS Body : - TESTSMS

A: Your sender ID is what you've specified in the from parameter in the sendsms URL, i.e., this here: [...]from=XXXX&username=[...]
You don't need to change Kannel configuration to change the sender text, just change the value in the URL. You do have to take into account that:

*

*The value should be URL-encoded.

*It must be between 3-11 alphanumeric characters (letters, numbers and underscore according to the GSM standard.) In practice some other characters also work 99% of the time. In practice also sometimes shorter sender IDs work but it depends on your SMS gateway, recipient operator, and recipient phone.

*Or it can be up to 15 digits if it's numeric, then Kannel will treat it as a phone number in international format (i.e., as if it's a phone number with country code added in front.)

A: You have to alter the sender id outside kannel and then use your common HTTP request with altered sender id. Your sender id mustn't contain whitespaces, you can use "%20" instead.


text:
Q: How to open a Bootstrap modal window using jQuery? I'm using Twitter Bootstrap modal window functionality. When someone clicks submit on my form, I want to show the modal window upon clicking the "submit button" in the form.
<form id="myform" class="form-wizard">

BootStap Wizard Form

    <input type="text" value=""/>
    <input type="submit"/>
</form>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

One fine body…

        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>

jQuery:
$('#myform').on('submit', function(ev) {
    $('#my-modal').modal({
        show: 'false'
    });

    var data = $(this).serializeObject();
    json_data = JSON.stringify(data);
    $("#results").text(json_data);
    $(".modal-body").text(json_data);

    // $("#results").text(data);

    ev.preventDefault();
});

A: Try
$("#myModal").modal("toggle")

To open or close the modal with id myModal.
If the above is not working then it means bootstrap.js has been overridden by some other js file.
Here is a solution
1:- Move bootstrap.js to the bottom so that it will override other js files.
2:- Make sure the order is like below

A: <form id="myform" class="form-wizard">

BootStap Wizard Form

    <input type="text" value=""/>
    <input type="submit" id="submitButton"/>
</form>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

One fine body…

        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>

You can launch the modal with the code below this.
$(document).ready(function(){
    $("#submitButton").click(function(){
        $("#myModal").modal();
    });
});

A: Try This

myModal1 is the id of modal

$('#myModal1').modal({ show: true });

A: Bootstrap 4.3 - more here

$('#exampleModal').modal();

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        Hello world

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

A: Just call the modal method(without passing any parameters) using jQuery selector.
Here is example:
$('#modal').modal();

A: If you use links's onclick function to call a modal by jQuery, the "href" can't be null.
For example:
... ...
Open a Modal by jQuery
... ...
... ...

The Modal can't show.
The right code is :
Open a Modal by jQuery

A: Bootstrap has a few functions that can be called manually on modals:
$('#myModal').modal('toggle');
$('#myModal').modal('show');
$('#myModal').modal('hide');

You can see more here: Bootstrap modal component
Specifically the methods section.
So you would need to change:
$('#my-modal').modal({
    show: 'false'
});

to:
$('#myModal').modal('show');

If you're looking to make a custom popup of your own, here's a suggested video from another community member:
https://www.youtube.com/watch?v=zK4nXa84Km4

A: Here is how to load bootstrap alert as soon as the document is ready. It is very easy just add
 $(document).ready(function(){
   $("#myModal").modal();
});

I made a demo on W3Schools.

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Here is how to load a bootstrap modal as soon as the document is ready

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A:

A: Try to use jQuery instead of $ sign when calling the function, it worked in my case as you can see below.
jQuery.noConflict();
jQuery('#myModal').modal('show');

jQuery.noConflict();  because when jQuery('#myModal').modal('show'); doesn't work, it's caused by having included jQuery twice. Including jQuery 2 times makes modals not to work. and it would resolve the problem in that case, as in my case it is repeating.
Further you can go to this link
Bootstrap Model Window Not Showing by Calling Through JQuery

A: Most often, when $('#myModal').modal('show'); doesn't work, it's caused by having included jQuery twice. Including jQuery 2 times makes modals not to work.
Remove one of the links to make it work again.
Furthermore, some plugins cause errors too, in this case add
jQuery.noConflict();
$('#myModal').modal('show');

A: Check out the complete solution here:
http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_modal_show&stacked=h
Make sure to put libraries in required order to get result:
1- First bootstrap.min.css 2- jquery.min.js 3- bootstrap.min.js
(In other words jquery.min.js must be call before bootstrap.min.js)
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

A: In addition you can use via data attribute
<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>

In this particular case you don't need to write javascript.
You can see more here: http://getbootstrap.com/2.3.2/javascript.html#modals

A: I tried several methods which failed, but the below worked for me like a charm:
$('#myModal').appendTo("body").modal('show');

A: Try this. It's works for me well.

function clicked(item) {
         alert($(item).attr("id"));
        }
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-rtl/3.4.0/css/bootstrap-rtl.css" rel="stylesheet"/>

<button onclick="clicked(this);" id="modalME">Click me</button>

Modal in CSS

        ×

One modal example here.

        Nice!


text:
Q: Looping threads accessing pthread mutex im building this application in which i have a client represented by a thread, running in loop (until it receives the instruction to terminate) trying to access a critical section of data in the server.
When the first client connects to the server, he owns the lock to that mutex. all the subsequent connections are put to a hold. This is the "normal" part of it.
But then, when the first thread unlocks, the loop brings it back to the begining and it should be contending for the lock again. But it's assumed that he still holds the lock and executes the critical section in an almost infinite loop (not infinite because we can terminate the thread, giving the lock away for the other threads).
To resume it all...when the first client connects, it owns the lock forever. The other threads remain in a waiting line until the first thread terminates. Here's some code:
The Server:
int main(int argc, char * argv[])
{
    int servSock;
    unsigned short servPort;
    unsigned int clntLen;

    rcvBuf = (char *)malloc((MAXLINE)*sizeof(char));
    pthreads = (fifo_t*)malloc(sizeof(fifo_t));

    struct sockaddr_in servAddr;
    struct sockaddr_in clntAddr;

    pthread_attr_t custom_sched_attr;

    int fifo_max_prio, fifo_min_prio, fifo_mid_prio;
    struct sched_param fifo_param;

    pthread_attr_init(&custom_sched_attr);
    pthread_attr_setinheritsched(&custom_sched_attr, PTHREAD_EXPLICIT_SCHED);
    pthread_attr_setschedpolicy(&custom_sched_attr, SCHED_FIFO);

    fifo_max_prio = sched_get_priority_max(SCHED_FIFO);
    fifo_min_prio = sched_get_priority_min(SCHED_FIFO);
    fifo_mid_prio = (fifo_min_prio + fifo_max_prio)/2;

    fifo_param.sched_priority = fifo_mid_prio;

    pthread_attr_setschedparam(&custom_sched_attr, &fifo_param);

    if(argc !=2 ){
        fprintf(stderr,"Usage: %s <Server Port>\n",argv[0]);
        exit(1);
    }

    fifo_init(pthreads);

    db  = db_open("DB", O_RDWR, 0666);
    servPort = atoi(argv[1]);

    if((servSock = socket(AF_INET,SOCK_STREAM,0)) < 0){
        perror("Error with Socket()");
        exit(1);
    }

    memset(&servAddr,0,sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servAddr.sin_port = htons(servPort);

    if(bind(servSock,(struct sockaddr*)&servAddr,sizeof(servAddr)) < 0){
        perror("Error with bind()");
        exit(1);
    }

    if(listen(servSock,NUM_THREADS) < 0){
        perror("Error with listen()");
        exit(1);
    }

    for(;;)
    {
        printf("A estabelecer ligaçao!\n");
        clntLen = sizeof(clntAddr);

        if((clntSock = accept(servSock,(struct sockaddr*)&clntAddr,&clntLen)) < 0)
        {
            perror("Error with accept()");
            exit(0);
        }

        printf("Ligação estabelecida!\n");

        pthread_create(&thread,&custom_sched_attr,&HandleTcpClient,(void *)clntSock);

        printf("Continua a execução nesta thread: %d\n",(int)pthread_self());
   }

   exit(0);
}

void * HandleTcpClient(void * data){

   insert(pthreads,(int)pthread_self());

   int sock = (int)data;

   char * key = (char *)malloc(FIELD * sizeof(char));
   char * dados = (char *)malloc(FIELD * sizeof(char));
   char * vendDev = (char *)malloc(FIELD * sizeof(char));
   char * str = (char*)malloc(MAXLINE * sizeof(char));

   memset(key,0,sizeof(key));
   memset(dados,0,sizeof(dados));
   memset(vendDev,0,sizeof(vendDev));
   memset(str,0,sizeof(str));

   while(1)
   {
   start:

       printf("Sem Lock: %d com socket: %d\n",(int)pthread_self(),sock);

       pthread_mutex_lock(&mutexdb);

       printf("Com Lock: %d com socket: %d\n",(int)pthread_self(),sock);
       int i = 0;
       char op;

       if((recvMsgSize = recv((sock),rcvBuf,MAXLINE,0)) < 0)
       {
           perror("Erro na recepção!\n");
           exit(-1);
       }

       rcvBuf[recvMsgSize]='\0';
       str = (char *)rcvBuf;

       op = *str++;

       while(*str!='|' && *str!=0){
           key[i]=*str;
           str++;
           i++;
       }

       key[++i]='\0';
       str++;

       if((int)op==2 || (int)op==3) strcpy(vendDev,str);  // obter o numero de produtos vendidos/devolvidos
       else strcpy(dados,str);

       if(op == 4 || op == 6)
       {
           db_operate(&db,op,key,dados,sock);
           pthread_mutex_unlock(&mutexdb);
           printf("Unlock: %d com socket: %d\n",(int)pthread_self(),sock);
           goto start;
       }
       else
           if(op == 7)
           {
               extract(pthreads);
               pthread_mutex_unlock(&mutexdb);
               close(sock);
               pthread_exit(0);
               break;
           }
           else
               if(op == 1 || op == 2 || op == 3 || op == 5)
               {
                   db_search(&db,op,key,vendDev,sock);
                   pthread_mutex_unlock(&mutexdb);
                   printf("Unlock: %d com socket: %d\n",(int)pthread_self(),sock);
                   goto start;
               }
   }

Can anyone tell me what am i doing wrong here? How can i implement a policy where when the first thread does the unlock the next thread gains it and the said first thread returns to the waiting line, like in a FIFO list?
Thanks ;)

A: There are number of issues with the code as posted:

*

*Thread function allocates memory but never releases it.

*You hold the mutex over blocking socket read - it's never a good idea. Mutex should protect resource shared between threads - the database in your case. Socket is not shared so it doesn't need protection. Worse - waiting on the socket and holding the mutex prevents other threads from accessing the database.

*On the design side - the mutex belongs with the database, not the socket reader. I suggest
 adding the mutex to the db structure, initializing it at database setup time, and hiding lock/unlock calls inside db access functions. Identify the smallest critical section possible and protect that. This gives you better concurrency.

*Doing thread-per-socket only works for very small number of connections. Large-scale design pretty much always involves non-blocking sockets and select/poll/epoll/kqueue tricks.

I didn't really understand the FIFO part of the question, but I hope the points above will guide you into right direction.


text:
Q: Is there any simple automated way of finding out all the source files associated with a Delphi project? I like to backup up the source code set for a project when I release a version.  I use GExperts project backups, which seems to gather up all the files in the project manager into the ZIP file.  You can also add arbitrary files to this file set, but I'm always conscious of the fact that I haven't necessarily got all the files.  Unless I specifically go though the uses clauses and add all the units I have sources for to the project, I'll never be sure of storing all the files necessary to recreate the installable/executable.
I've thought about rolling an app to traverse a project, following all the units used and looking down all the search paths and seeing if there is a source file available for that unit, and building a list of files to back up that way, but hey - maybe someone has already done the work?

A: You should (highly recommend) look into Version Control.
e.g. SVN (subversion), CVS
This will allow you to control revisions of all of your source. It will allow you to add or remove source files, roll back merge and all other nice things related to managing project sources.
This WILL save your a$%# one day.

A: You can interpret your question in two ways:

*

*How can I make sure that I backup at least enough files so I can build the project

*How can I make sure that I backup not too many files so I can still build the project

The first is to make sure you can build the system at all, the second to allow you to clean up unused files.
For both, a version control system including a separate build system is the way to go.
You then - for each new set of changes - can use these steps to assure that both conditions hold:

*

*On your daily development system, check in the new revision of your source code into your version control system.

*On your separate build system, get the latest version of your source control system.

*Build the project on the build system; if this fails, go to Step 1, and add the missing files to your version control system from your development system

*Start removing (one-by-one) files from the project that you suspect are not needed, then rebuild until it fails.

*When the build fails, restore that particular file from the version control system, then continue step 3 with the next candidate

*When the build succeed you have the minimum set of files.

*Now make a difference overview of the files in your version control system, and the build machine.

*Mark the files that are in your version control system but not on your build machine as deprecated or deleted.

Most version control systems have good ways of generating a difference between the files on your development or build system against the files in the version control system (usually fine grained for each historic point in time you added/removed/updated files in your version control system).
The reason you want a separate build system (or two separate development systems) is that you want them to be independent: you use one for developing, and the other for checking if the build is still OK.
This is the first step that in the future you might want to extend this into a continuous integration system (that runs unit tests, automatically creates product setups and much more).
--jeroen

A: I'm not sure if you're asking about version control or how to be sure you've got all the files.
One useful utility I run occasionally is a program that makes a DirList of all of the files in my dcu output folder.  Changing the extensions from .dcu to .pas gives me a list of all of the source code files.
Of course it misses .inc files and other non-.pas files, but perhaps this line of thinking would be helpful to you in some way?
The value of this utility to me is that a second housekeeping utility program then makes a list of all .pas files in my source tree that do not have corresponding .dcu files.  This (after a full compile of all programs) generally reveals some "junk" .pas files that are no longer in use.

A: For getting a list of all units compiled into an executable, you could let the compiler generate a MAP file. This file will contain entries for all the units used.


text:
Q: Cannot change input value while setting default value in jquery I am trying to set default value to an input from another I am entering. However, I can enter data into that box. But I cannot get new value I entered when I submit. Please see my code below:
$('.input1').bind('keyup blur', function(){
    $('.input2').val($(this).val());
});

A: Use on("input", function () { ... }), instead:
$('.input1').on('input', function(){
    $('.input2').val($(this).val());
});

JSFIDDLE

Also, see this thread about the difference between input and change.


text:
Q: How to create a box plot in MS Excel having access to min, max, Q1, Q3 and mean, but not having access to variables? As in title. I want to create a box plot in Excel but I have no access to variables. I just have the values for min, max, Q1, Q3 and mean. How to create a box plot using just that? If that's impossible which tool should I use instead?

A: Arrange your data as Q1, min, max, Q3. Plot as a line chart which gives you four lines and as many points as you have sets of data. Use high-low lines and up/down bars to create the boxes and whiskers. Format as you want them (especially make the high-low lines thicker). Format the original lines to have "no line". Done.
Jon Peltier has some useful info on this in the middle of this article on stock charts (don't try to do this with OOB stock charts!):
https://peltiertech.com/excel-stock-charts/
He also has extensive articles on box plots more generally, although most start from the premise of having other measures such as mean, SD etc, but could still be useful. Also alternatives using column / bar charts which therefore cover horizontal presentation too: https://peltiertech.com/excel-box-and-whisker-diagrams-box-plots/


text:
Q: Dragon Naturally Speaking 10 enters bad characters in certain text editors in Windows XP I use DNS 10 in Win 7 without any problems for dictating in office XP and office 2007. I have installed it too on a computer under WinXP and there, with office XP and office 2003 it enters wrong characters instead of ê, è, à, ù, while it has no problems with é and ç.
For example, it writes
'voilŕ' for 'voilà, 'lŕ-bas' for 'là-bas', 'pčre' for 'père', 'męme' for 'même', 'oů ętes-vous' for 'où êtes-vous'.
This doesn't happen when I dictate here in the internet browser, nor in Wordpad, Notepad, or Open Office.
-- On the other hand, there are problems that appear only in OpenOffice and the internet browser: for example, when dictating a phrase like "Qu'est-ce qu'on peut faire?"("What can we do?) it appears as "quést-ce quón peut faire", while it is always put right in the other editors. --
Can I fix this? - or at least: What the cause might be?

A: It could be a font related problem if it varies across applications. Try changing your fonts in the editor that it doesn't work it to one from an editor that does, and see if that affects the problem.
For the second problem, I believe that the editor automatically substitutes 'e as é and 'o as ó to make typing special characters easier. I don't have a copy of OpenOffice handy, but you should be able to turn off autocorrect somewhere in the preferences dialog.


text:
Q: Row level access control in snowflake I have a customer that owns a carpet cleaning business and we have all of his different franchisee's data in a multi-tenant database model and we would like to move this data into a data warehouse in snowflake. I don't want to have to build a separate database for each customer because then I have to keep each database up to date with the latest data model. I want to use 1 data model to rule them all. I have a tenant ID that I keep with each record to identify the franchisee's data. I want to give a set of credentials to each franchisee to where they can hook up their analytics tool of choice (tableau, power bi, etc.) and only get access to the rows that are applicable to them. Is there a way to secure the rows they see in each table based on their user. In other words some sort of row level access control similar to profiles in postgres. Are there any better methods for handling this type of scenario? Ultimately I want to maintain and manage the least number of elt jobs and data models.

A: This is the purpose of ether Secure Views, or Reader Accounts.
We are using both, and they have about the same technical hassle/setup costs. But we are using an internal tool to build/alter the schema's.

A: To expand on Simeon's answer:
You could have a single Snowflake account and create a Snowflake role & user for each franchisee. These roles would have access to a Secure View which uses the CURRENT_ROLE / CURRENT_USER context functions as in this example from the Snowflake documentation.
You'd have to have a role -> tennant ID "mapping table" which is used in the Secure View to limit the rows down to the correct franchisee.


text:
Q: std::is_trivially_copyable / std::is_trivially_copy_assignable and array wrapping classes I am trying to wrap my head around std::is_trivially_copy_assignable<T> and std::is_trivially_copyable<T>.
As far as I understood, std::is_trivially_copy_assignable<T> checks for a trivial (non-user defined, default) copy operator, whereas std::is_trivially_copyable<T> checks to see if it safe to use memcpy on Type T. By definition, every is_trivially_copyable must be is_trivially_copy_assignable but not other way around. I hope my definitions are correct.
Now I have the following POD type class:
struct Test {
    char data[32];
    int term;
    int dummy[3];
};

When I check the following:
auto isCopyAssignTrivial = std::is_trivially_copy_assignable<Test>::value; //true
auto isCopyTrivial       = std::is_trivially_copyable<Test>::value; //true

auto isArrayCopyAssignTrivial = std::is_trivially_copy_assignable<int[2]>::value; //false
auto isArrayCopyTrivial       = std::is_trivially_copyable<int[2]>::value; //true

I got the above results.
Moreover, when I do the following, I see that anotherTestPod has its elements set correctly and It works without any problems.
Test testPod{};
for(auto &d :testPod.data) {
    d = rand() %100;
}
auto anotherTestPod = testPod;

Even though arrays are not copy assignable themselves, in the case of is_trivially_copy_assignable, how does the trivial copy assignment work?

A: It's important to note that the rules for trivially copyability for standard-defined types (like arrays) are different from those of class types. For standard-defined types, they are trivially copyable by fiat: because the standard says that they are.
An array of elements of the type T is trivially copyable to the extent that T is trivially copyable. An array is not assignable because the standard says that arrays are not assignable. There is no contradiction because neither requires the other.
Any explicit requirement relationship between trivial copyability and assign-ability only exists for class types. And even then, C++14 permits a type to be trivially copyable if its copy assignment operator is deleted, so there isn't even a requirement of assign-ability for class types.


text:
Q: Dreamweaver dialogue windows are huge Good Afternoon, im having a bit of a problem with dreamweaver :/
When opening a dialogue box within dreamweaver CS6, for example the dreamweaver preferences windows, or CSS editor window, it appears very large, almost twice the size of my screen.
For example: Screenshot:

I have checked my systems DPI Settings and they are set to 100%.
Im running windows 8.1. My screen resolution is 1366 x 768
Ive tried changing screen resolutions and different DPI sizes.
Any ideas would be appreciated greatly?

A: I managed to fix this issue by deleting all of my fonts and replacing them with a fresh download from here:
http://www.withsteps.com/2621/windows-8-default-font-download-repair-kit.html


text:
Q: Auto-hiding dock completely disappears on menu bar screen Once I use the auto-hiding dock on the right screen, I am no longer able to use the dock on center screen.  To resurrect the dock on the center screen I first have to use the dock on the laptop. Once I do that, the dock on the center screen magically comes back to life. This cycle is repeatable, without fail.
Here is my monitor arrangement. It has the top of the laptop just slightly under the bottom left corner of center monitor. This depicts the actual physical configuration.

A: While documenting this problem, I stumbled upon the solution -- after two years of fiddling with this. Note the new placement of the laptop in the arrangement below when compared to that in the original post. I had tried swapping monitors, cables, ports on my MBP dock, the menubar location. Nothing helped. And while I was writing up the original post I thought, I wonder if the laptop being at all under the center monitor makes the OS treat the two as one, vertical viewport when it comes to deciding to raise dock.  Now, I don't know if that's accurate or not, but it got me to try moving the arrangement to have the laptop just around the corner on the side, and voila!  No more strange dock behavior. Now I can freely use the dock on any monitor and it does not get stuck. Now, I just have to undo all the strange muscle memory my mouse arm learned while this was still a problem...
If anyone can speak to my supposition about the "one, vertical viewport", I'd be interested and grateful to know the details.


text:
Q: gnu make - assert specific command line tools are available In a makefile, how would I make sure that certain tools like gcov, lcov, g++ are available before executing any other targets?
I want to gracefully fail with

gcov/lcov/g++ not available

.

A: You could try something like:
TOOLS := gcov lcov g++

$(foreach TOOL,$(TOOLS),\
    $(if $(shell command -v $(TOOL)),,\
        $(error Cannot locate $(TOOL) on PATH)))

This assumes you're using a POSIX shell obviously.