text:
Q: How do I include 'System.Runtime.Serialization.Json' namespace in my VSCode project on Mac OS X? I was hoping to use System.Runtime.Serialization.Json in a simple Visual Studio Code console app on my Mac OS X but I am running into this compile error:
The type or namespace name 'Json' does not exist in the namespace 'System.Runtime.Serialization' (are you missing an assembly reference?)
Based on this post - Where is the System.Runtime.Serialization.Json namespace?, I added "System.ServiceModel.Web": "1.0.0" to my project.json file but that did not help. I added 1.0.0 since that's the only version I found in nuget - https://www.nuget.org/packages/System.ServiceModel.Web/
As an alternative, I tried using https://www.nuget.org/packages/Newtonsoft.Json/6.0.8 by adding the following in my project.json - "Newtonsoft.Json": "6.0.8" but then adding the reference of using Newtonsoft.Json; again gives a compile error of - The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)

Ultimately I would like to derserialize a json stream from my VSCode console app, so hoping to get pointers on how that can be done?

A: System.Runtime.Serialization.Json is not going to get ported to .Net Core; you did the right thing by going to Newtonsoft.Json.
Unfortunately, you added it only to the dnxcore50 section; you need to add it to the framework-agnostic dependency section:
{
  "version": "1.0.0-*",
  "dependencies": {
    "System.ServiceModel.Web": "1.0.0",
    "Newtonsoft.Json": "6.0.8"
  },
  "commands": {
    "run": "run"
  },
  "frameworks": {
    "dnx451": {},
    "dnxcore50": {
      "dependencies": {
        "System.Console": "4.0.0-beta-*",
        "System.ServiceModel.Web": "1.0.0"
      }
    }
  }
}


text:
Q: Generating CMOV instructions using Microsoft compilers In an effort to eke out some cmov instructions on an intel core 2 running windows 7 pro I wrote the code below. All it does is take a string from the console as input, apply some shift operations to generate a random seed, and then pass that seed on to srand, for the generation of a small array of pseudorandom numbers. The pseudorandom numbers are then evaluated for whether they satisfy the predicate function ( more arbitrary bitshuffling ), and output a '*' or a '_'. The purpose of the experiment is to generate cmov instructions, but as you can see in the disassembly below, there are none.
Any tips on how to change the code or the cflags so that they'll be generated?
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>

bool blackBoxPredicate( const unsigned int& ubref ) {
   return ((ubref << 6) ^ (ubref >> 2) ^ (~ubref << 2)) % 15 == 0;
}

int main() {
   const unsigned int NUM_RINTS = 32;
   unsigned int randomSeed = 1;
   unsigned int popCount = 0;
   unsigned int * rintArray = new unsigned int[NUM_RINTS];
   std::string userString;

   std::cout << "input a string to use as a random seed: ";
   std::cin >> userString;

   std::for_each(
      userString.begin(),
      userString.end(),
      [&randomSeed] (char c) {
         randomSeed = (randomSeed * c) ^ (randomSeed << (c % 7));
   });

   std::cout << "seed computed: " << randomSeed << std::endl;

   srand(randomSeed);

   for( int i = 0; i < NUM_RINTS; ++i ) {
      rintArray[i] = static_cast<unsigned int> (rand());
      bool pr = blackBoxPredicate(rintArray[i]);
      popCount = (pr) ? (popCount+1) : (popCount);

      std::cout << ((pr) ? ('*') : ('_')) << " ";
   }

   std::cout << std::endl;

   delete rintArray;
   return 0;
}

And used this makefile to build it:
OUT=cmov_test.exe
ASM_OUT=cmov_test.asm
OBJ_OUT=cmov_test.obj
SRC=cmov_test.cpp
THIS=makefile

CXXFLAGS=/nologo /EHsc /arch:SSE2 /Ox /W3

$(OUT): $(SRC) $(THIS)
   cl $(SRC) $(CXXFLAGS) /FAscu /Fo$(OBJ_OUT) /Fa$(ASM_OUT) /Fe$(OUT)

clean:
   erase $(OUT) $(ASM_OUT) $(OBJ_OUT)

And yet when I went to see whether any had been generated, I saw that microsoft's compilers had generated the following assembly for that last for loop:
; 34   :       popCount = (pr) ? (popCount+1) : (popCount);
; 35   :
; 36   :       std::cout << ((pr) ? ('*') : ('_')) << " ";

  00145 68 00 00 00 00   push    OFFSET $SG30347
  0014a 85 d2        test    edx, edx
  0014c 0f 94 c0     sete    al
  0014f f6 d8        neg     al
  00151 1a c0        sbb     al, al
  00153 24 cb        and     al, -53            ; ffffffcbH
  00155 04 5f        add     al, 95         ; 0000005fH
  00157 0f b6 d0     movzx   edx, al
  0015a 52       push    edx
  0015b 68 00 00 00 00   push    OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout
  00160 e8 00 00 00 00   call    ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@D@Z ; std::operator<<<std::char_traits<char> >
  00165 83 c4 08     add     esp, 8
  00168 50       push    eax
  00169 e8 00 00 00 00   call    ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> >
  0016e 46       inc     esi
  0016f 83 c4 08     add     esp, 8
  00172 83 fe 20     cmp     esi, 32            ; 00000020H
  00175 72 a9        jb  SHORT $LL3@main

For your reference, here are my cpu id strings and compiler version.
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 6 Model 58 Stepping 9, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=3a09

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86

A: It is extremely difficult, if not downright impossible, to get Microsoft's 32-bit C/C++ compiler to emit CMOVcc instructions.
What you have to remember is that conditional moves were first introduced with the Pentium Pro processor, and while Microsoft had a compiler switch that would tune the generated code for this 6th generation processor (the long-deprecated /G6), they never emitted code that would run exclusively on this processor. The code still needed to run on 5th generation processors (i.e., Pentium and AMD K6), so it couldn't use CMOVcc instructions because those would have generated illegal instruction exceptions. Unlike Intel's compiler, global dynamic dispatching was not (and is still not) implemented.
Also, it is worth noting that no switch was ever introduced to target exclusively 6th generation processors and later. There's no /arch:CMOV or whatever they might call it. Supported values for the /arch switch go straight from IA32 (the lowest common denominator, for which CMOV would be potentially illegal) to SSE. However, the documentation does confirm that, as one might expect, enabling SSE or SSE2 code generation implicitly enables the use of conditional-move instructions and anything else that was introduced before SSE:

In addition to using the SSE and SSE2 instructions, the compiler also uses other instructions that are present on the processor revisions that support SSE and SSE2. An example is the CMOV instruction that first appeared on the Pentium Pro revision of the Intel processors.

Therefore, in order to have any hope of getting the compiler to emit CMOV instructions, you must set /arch:SSE or higher. Nowadays, of course, this is no big deal. You can simply set /arch:SSE or /arch:SSE2 and be safe, since all modern processors support these instruction sets.
But that's only half of the battle. Even when you have the right compiler switches enabled, it is extremely difficult to get MSVC to emit CMOV instructions. Here are two important observations:

*

*MSVC 10 (Visual Studio 2010) and earlier virtually never generate CMOV instructions. I've never seen them in the output, no matter how many variations of source code I've tried. I say "virtually" because there might be some crazy edge case that I missed, but I very much doubt it. None of the optimization flags have any effect on this.
However, MSVC 11 (Visual Studio 2012) introduced significant improvements to the code generator, at least in this aspect. This and later versions of the compiler now seem to be at least aware of the existence of the CMOVcc instructions, and may emit them under the right conditions (i.e., /arch:SSE or later, and use of the conditional operator, as described below).

*I've found that the most effective way to cajole the compiler into emitting a CMOV instruction is to use the conditional operator instead of a long-form if-else statement. Although these two constructs should be completely equivalent as far as the code generator is concerned, they are not.
In other words, while you might see the following translated to a branchless CMOVLE instruction:
int value = (a < b) ? a : b;

you will always get branching code for the following sequence:
int value;
if (a < b)    value = a;
else          value = b;

At the very least, even if your use of the conditional operator doesn't cause a CMOV instruction (such as on MSVC 10 or earlier), you might still be lucky enough to get branchless code by some other means—e.g., SETcc or clever use of SBB and NEG/NOT/INC/DEC. This is what the disassembly you've shown in the question uses, and although it is not quite as optimal as CMOVcc, it's certainly comparable and the difference is not worth worrying about. (The only other branching instruction is part of the loop.)

If you truly want branchless code (which you often do when hand-optimizing), and you're not having any luck getting the compiler to generate the code you want, you'll need to get more clever in how you write the source code. I've had good luck with writing code that computes the result branchlessly using bitwise or arithmetic operators.
For example, you might wish that the following function generated optimal code:
int Minimum(int a, int b)
{
    return (a < b) ? a : b;
}

You followed rule #2 and used a conditional operator, but if you're using an older version of the compiler, you'll get branching code anyway. Outsmart the compiler using the classic trick:
int Minimum_Optimized(int a, int b)
{
    return (b + ((a - b) & -(a < b)));
}

The resulting object code is not perfectly optimal (it contains a CMP instruction that is redundant since SUB already sets the flags), but it is branchless and will therefore still be significantly faster than the original attempt on random inputs that cause branch prediction to fail.
As another example, imagine that you want to determine whether a 64-bit integer is negative in a 32-bit application. You write the following self-evident code:
bool IsNegative(int64_t value)
{
    return (value < 0);
}

and will find yourself sorely disappointed in the results. GCC and Clang optimize this sensibly, but MSVC spits out a nasty conditional branch. The (non-portable) trick is realizing that the sign bit is in the upper 32 bits, so you can isolate and test that explicitly using bitwise manipulation:
bool IsNegative_Optimized(int64_t value)
{
    return (static_cast<int32_t>((value & 0xFFFFFFFF00000000ULL) >> 32) < 0);
}

In addition, one of the commentators suggests using inline assembly. While this is possible (Microsoft's 32-bit compiler supports inline assembly), it is often a poor choice. Inline assembly disrupts the optimizer in rather significant ways, so unless you're writing significant swaths of code in inline assembly, there is unlikely to be a substantial net performance gain. Furthermore, Microsoft's inline assembly syntax is extremely limited. It trades flexibility for simplicity in a big way. In particular, there is no way to specify input values, so you're stuck loading the input from memory into a register, and the caller is forced to spill the input from a register to memory in preparation. This creates a phenomenon I like to call "a whole lotta shufflin' goin' on", or for short, "slow code". You don't drop to inline assembly in cases where slow code is acceptable. Thus, it is always preferable (at least on MSVC) to figure out how to write C/C++ source code that persuades the compiler to emit the object code you want. Even if you can only get close to the ideal output, that's still considerably better than the penalty you pay for using inline assembly.

Note that none of these contortions are necessary if you target x86-64. Microsoft's 64-bit C/C++ compiler is significantly more aggressive about using CMOVcc instructions whenever possible, even the older versions. As this blog post explains, the x64 compiler bundled with Visual Studio 2010 contains a number of code-quality improvements, including better identification and use of CMOV instructions.
No special compiler flags or other considerations are necessary here, since all processors that support 64-bit mode support conditional moves. I suppose this is why they were able to get it right for the 64-bit compiler. I also suspect that some of these changes made to the x86-64 compiler in VS 2010 were ported to the x86-32 compiler in VS 2012, explaining why it is at least aware of the existence of CMOV, but it still doesn't use it as aggressively as the 64-bit compiler.
The bottom line is, when targeting x86-64, write the code in the way that makes the most sense. The optimizer actually knows how to do its job!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add new columns to excel file from multiple datasets with Pandas in Google Colab I'm trying to add some columns to a excel file after some data but I'm not having good results just overwriting what I have. Let me give you some context: I'm reading a csv, for each column I'm using a for to value_counts and then create a frame from this value_counts here the code for just one column:
import pandas as pd

data= pd.read_csv('responses.csv')

datatoexcel = data['Music'].value_counts().to_frame()

datatoexcel.to_excel('savedataframetocolumns.xlsx') #Name of the file

This works like this ...

And with that code for only one column I have the format that I actually need for excel.
But the problem is when I try to do it with for to all the columns and then "Append" to excel the following dataframes using this formula:
for columnName in df:
    datasetstoexcel = df.value_counts(columnName).to_frame()
    print(datasetstoexcel)
    # Here is my problem with the following line the .to_excel
    x.to_excel('quickgraph.xlsx') #I tried more code lines but I'll leave this one as base

The result that I want to reach is this one:

I'm really close to finish this code, some help here please!

A: How about this?
Sample data
df = pd.DataFrame({

    "col1": [1,2,3,4],
    "col2": [5,6,7,8],
    "col3": [9, 9, 11, 12],
    "col4": [13, 14, 15, 16],
})

Find value counts and add to a list
li = []

for i in range(0, len(df)):
    value_counts = df.iloc[:, i].value_counts().to_frame().reset_index()
    li.append(value_counts)

concat all the dataframes inside li and write to excel
pd.concat(li, axis=1).to_excel("result.xlsx")

Sample output:


text:
Q: Nginx If statement executed before location? I'm confused why nginx is executing my If statement "before" the location statement.
More precise, why is nginx not executing the return statement and then stops processing?
I would expect if I open /xyz to get a 200 with "hello world" even if $http_x_forwarded_host is not www.acme.com because the if statement is located down the location statement. But nginx just ignor the location statement and ran into the if clause. Any ideas? I tried break; with no luck.
    server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;
    index   index.html index.htm index.php;

        location /xyz {
          return 200 'hello world';

        }

        if ($http_x_forwarded_host != "www.acme.com") {
                return 301 https://www.acme.com$uri;
        }

    }

A: You are right, all directives from the ngx_http_rewrite_module are executed before the location selection mechanism took its place. Using the break directive means breaking the execution of those directives from the rewrite module and immediately force the request execution according to the best matching location. This happened because although nginx configuration in general is declarative, rewrite module evaluates its instructions imperatively. This is always a source of confusion for every nginx novice. You can read more about the rewrite module internal implementation here.
Being that said, you can't implement that sort of behavior with your configuration. It doesn't mean you can't achieve what you want at all, one of possible solutions is to use the regex negative lookahead feature:
    if ($http_x_forwarded_host != "www.acme.com") {
        # do the redirect only if the URI doesn't start with '/xyz'
        rewrite ^(?!/xyz) https://www.acme.com$uri permanent;
    }
    location /xyz {
        return 200 'hello world';
    }

If you want to do some complex request processing instead of redirection, you can use an internal location:
    if ($http_x_forwarded_host != "www.acme.com") {
        # in case you will need an original URI later, you can save its value
        # set $original_uri $uri;
        # process the request with the special location only if the URI doesn't start with '/xyz'
        rewrite ^(?!/xyz) /special;
    }
    location /xyz {
        return 200 'hello world';
    }
    location /special {
        internal;
        ... # any custom processing here, for example 'return 403;'
    }

It should be obvious that for such a locations you should choose an URI prefix than can't interfere with your existing site in any ways.

A:
I think it is because after the redirection it reaches your site again. Maybe the redirection is pointing to the same host as the location?


text:
Q: Tensorboard is not populating graph on windows I have written simple python program to multiply two values and expected to populate the tensorboard graph.
I am using Windows - CPU machine.
Then after executing my program it generated required graph event file in the log directory path with the name events.out.tfevents.1504266616.L7
I use the below command to start tensorboard:
tensorboard --logdir C:\\Users\\SIMBU\\python_pgm\\TensorFlow\\graph --host 127.0.0.1 --port 5626

However, there is no graph under http://127.0.0.1:5626/#graphs.
What i have did wrong?

A: Tensorboard requires that you use linux style paths with forward slashes, e.g.
tensorboard --logdir C:/Users/SIMBU/python_pgm/TensorFlow/graph


text:
Q: how to match a word with a list of tubles i am trying to find a word in a list of tuples. I tried the following code
 keywords_adera = [('athletes', 0.4235), ('scrimmages', 0.3895),('athlete', 0.379),('sport', 0.3714),('soccer', 0.3699)]
b_adera='athletes'
if b_adera in keywords_adera2:
    print('macrious4')

the code does not give any output. Any suggestions are appreciated.

A: You have to iterate over a list keywords_adera
Then you check if your searched word is in current tuple
for t in lst:
    if word in t:
        print('found')

A: The tuple is in list you need to match entier tuple with
Value for if statement to be true
 keywords_adera = [('athletes', 0.4235), ('scrimmages', 0.3895),
 ('athlete', 0.379),('sport', 0.3714),('soccer', 0.3699)]
  b_adera=('athletes',0.4235)
  if b_adera in keywords_adera:
      print('macrious4')

Else you would need to iterate over list or specify which index in list


text:
Q: Clojure - process huge files with low memory I am processing text files 60GB or larger. The files are seperated into a header section of variable length and a data section. I have three functions:

*

*head? a predicate to distinguish header lines from data lines

*process-header process one header line string

*process-data process one data line string

*The processing functions asynchronously access and modify an in-memory database

I advanced on a file reading method from another SO thread, which should build a lazy sequence of lines. The idea was to process some lines with one function, then switch the function once and keep processing with the next function.
(defn lazy-file
  [file-name]
  (letfn [(helper [rdr]
            (lazy-seq
             (if-let [line (.readLine rdr)]
               (cons line (helper rdr))
               (do (.close rdr) nil))))]
    (try
      (helper (clojure.java.io/reader file-name))
      (catch Exception e
        (println "Exception while trying to open file" file-name)))))

I use it with something like
(let [lfile (lazy-file "my-file.txt")]
  (doseq [line lfile :while head?]
    (process-header line))
  (doseq [line (drop-while head? lfile)]
    (process-data line)))

Although that works, it's rather inefficient for a couple of reasons:

*

*Instead of simply calling process-head until I reach the data and then continuing with process-data, I have to filter header lines and process them, then restart parsing the whole file and drop all header lines to process data. This is the exact opposite of what lazy-file intended to do.

*Watching memory consumption shows me, that the program, though seemingly lazy, builds up to use as much RAM as would be required to keep the file in memory.

So what is a more efficient, idiomatic way to work with my database?
One idea might be using a multimethod to process header and data dependant on the value of the head? predicate, but I suppose this would have some serious speed impact, especially as there is only one occurence where the predicate outcome changes from alway true to always false. I didn't benchmark that yet.
Would it be better to use another way to build the line-seq and parse it with iterate? This would still leave me needing to use :while and :drop-while, I guess.
In my research, using NIO file access was mentioned a couple of times, which should improve memory usage. I could not find out yet how to use that in an idiomatic way in clojure.
Maybe I still have a bad grasp of the general idea, how the file should be treated?
As always, any help, ideas or pointers to tuts are greatly appreciated.

A: You should use standard library functions.
line-seq, with-open and doseq will easily do  the job.
Something in the line of:
(with-open [rdr (clojure.java.io/reader file-path)]
  (doseq [line (line-seq rdr)]
    (if (head? line)
      (process-header line)
      (process-data line))))

A: There are several things to consider here:

*

*Memory usage
There are reports that leiningen might add stuff that results in keeping references to the head, although doseq specifically does not hold on to the head of the sequence it's processing, cf. this SO question. Try verifying your claim "use as much RAM as would be required to keep the file in memory" without using lein repl.

*Parsing lines
Instead of using two loops with doseq, you could also use a loop/recur approach. What you expect to be parsing would be a second argument like this (untested):
    (loop [lfile (lazy-file "my-file.txt")
           parse-header true]
       (let [line (first lfile)]
            (if [and parse-header (head? line)]
                (do (process-header line)
                    (recur (rest lfile) true))
                (do (process-data line)
                    (recur (rest lfile) false)))))

There is another option here, which would be to incorporate your processing functions into your file reading function. So, instead of just consing a new line and returning it, you could just as well process it right away -- typically you could hand over the processing function as an argument instead of hard-coding it.
Your current code looks like processing is a side-effect. If so, you could then probably do away with the laziness if you incorporate the processing. You need to process the entire file anyway (or so it seems) and you do so on a per-line basis. The lazy-seq approach basically just aligns a single line read with a single processing call. Your need for laziness arises in the current solution because you separate reading (the entire file, line by line) from processing. If you instead move the processing of a line into the reading, you don't need to do that lazily.


text:
Q: ASP.NET MVC3 - Clear cache from another application (subdomain) I have application on www.domain.com, and admin application on admin.domain.com.
Now, at some point I want to clear output cache on domain.com from admin.domain.com
Is that possible?

A: jsonp did the trick in the end.


text:
Q: Ubuntu Gnome LTS 16.04. Laptop's wifi keeps cutting out and it won't scan for networks Randomly, my wifi goes out and all networks disappear from the list. Refreshing does nothing, it won't scan. I have to go to Connect To Hidden Network in settings and manually type in my SSID and password again. Then it connects and the other networks show up again. If it helps, I checked install 3rd party MP3 and wifi software during installation
price@OlReliableJr:~$ lspci -knn | grep Net -A2
02:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8188CE 802.11b/g/n WiFi Adapter [10ec:8176] (rev 01)
    Subsystem: Realtek Semiconductor Co., Ltd. RTL8188CE 802.11b/g/n WiFi Adapter [10ec:8211]
    Kernel driver in use: rtl8192ce

The installation of that custom driver failed. The output of network diagnostics is here. http://pastebin.com/P5PaXd7h


text:
Q: How to store the content in content block using AMPScript in salesforce marketing cloud? How to store the content(FN,LN,Email) in content block using AMPScript through landing pages?

A: You will need to store the data for first name, last name, and email address in the list attribute or in a data extension.
Then using AMPscript, you can use variables to reference that data using set and @ for the variable name. If the data is in the sendable data extension, reference the data field name using %%field_name%%
If using list attributes you can use %%_firstname%%, %%_lastname%% and %%emailaddr%%
I suggest checking out the AMPscript 101 documentation  and also AMPscript personalization.


text:
Q: Button to the right inside a textbox (is this the best way to do it?) Would my solution (inserting a button and floating it to the right of my textbox) be the best to do this, also would it be cross browser compatible at an HTML 5 standard?
It also seems that my [+] is a little off center from the top.

    <input id="refdocs_input" type="text">

    <input id="refdocs_button" type="button" value="+">

A: I think you're over-complicating things.
Try this.
HTML:

    <input id="refdocs_input" type="text"/><input id="refdocs_button" type="button" value="+"/>

CSS:
#refdocs_wrapper {
    display: inline-block;
    padding: 1px;
    border: 1px solid rgb(128,128,128);

    line-height: 18px;
}
#refdocs_button {
    padding: 0;
    height: 20px;
    width: 20px;
}
#refdocs_input{
    width: 154px;
    padding: 0px;

    border: 0;
}

A: Add this in css:
#refdocs_wrapper {
    position:relative;
 }

Then try to absolute the inner element with respect to outer.

A: You should try this :
#refdocs_wrapper{
...
position:relative;
}
#refdocs_button {
clip:rect(1px 200px 19px 1px);
position: absolute;
right: xx%; /* or left */
top: xx%; /* or bottom */
height: 18px;
width: 18px;
}

An element with absolute position is positioned relative to the closest relative position parent element.

A: Here is the best I got for Chrome, FF and IE.  FF is clearly the worst of them.  Note that I added ::-moz-focus-inner to help with the FF formatting.
http://jsfiddle.net/C7XEY/2/
Here is the CSS:
#refdocs_wrapper {
    border: 1px solid rgb(128,128,128);
    height: 20px;
    width: 179px;
}
#refdocs_button {
    float: right;
    height: 100%;
    width: 19px;
    font-weight: bold;
    text-indent: 0;
    padding: 0;
    vertical-align: middle;
}
#refdocs_input {
    border: 0;
    width: 154px;
    padding:0px 0px 0px 2px;
}
#refdocs_button::-moz-focus-inner {
    padding: 0;
    border: 0
}


text:
Q: kubernetes volume claim pending with specific volume name I'm trying to create a PersistentVolumeClaim giv it a specific volumeName to use.
I use this code:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  namespace: zipkin
  name: pvc-ciro
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: nfs-provisioner
  resources:
    requests:
      storage: 0.1Gi
  volumeName: "demo"

If I remove volumeName the PVC is correctly bound otherways remain in pending status.
Why?

A: The volumeName is a name of the PersistentVolume you want to use.
On GKE PVC can automatically create a PV that will bound to, or you can specify the name of it using volumeName.
pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-ciro
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: standard
  resources:
    requests:
      storage: 0.1Gi
  volumeName: demo

pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: demo
spec:
  capacity:
    storage: 5Gi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Recycle
  storageClassName: standard
  mountOptions:
    - hard
    - nfsvers=4.1
  nfs:
    path: /tmp
    server: 172.17.0.2

And the output will be:
$ kubectl get pv
NAME   CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM              STORAGECLASS   REASON   AGE
demo   5Gi        RWO            Recycle          Bound    default/pvc-ciro   standard                13s
$ kubectl get pvc
NAME       STATUS   VOLUME   CAPACITY   ACCESS MODES   STORAGECLASS   AGE
pvc-ciro   Bound    demo     5Gi        RWO            standard       8s

You can read more details in Kubernetes documentation regarding Persistent Volumes.


text:
Q: ios provision profile error I'm trying to build development version of application with provision profile included (for Push Notifications) and getting fail to install it. I've cleared all certificates and rebuild them all EXACTLY step-by-step as says http://docs.madewithmarmalade.com/native/platformguides/iosguide/iossigning/iossigningassetssetup.html . When I include iphone-provisioning-profile in mkb file I have success build but if I try to install it on the iPhone 5/iPad 3 installation error occurs. If I build application without provisionprofile file - installation process ok. All devices has actual .provisionprofile files uploaded, iOS 6.1.2.
Marmalade Makefile Builder v6.2.1 [336699]
Copyright (C) 2001-2012 Marmalade.
e:\Marmalade\6.2\s3e\makefile_builder\mkb.py --verbose=1 e:/Marmalade/6.2/examples/s3e/s3eIOSNotifications/s3eIOSNotifications.mkb --deploy-only
Building project: e:/Marmalade/6.2/examples/s3e/s3eIOSNotifications/s3eIOSNotifications.mkb
setting root dir: e:\marmalade\6.2\examples\s3e
loading mkf: [e:\marmalade\6.2\examples\s3e] 'ExamplesMain'
loading mkf: [e:\marmalade\6.2\extensions] 's3eIOSNotifications'
loading mkf: [e:\marmalade\6.2\modules] 'iwutil'
package is deprecated
adding package reference: C:\DOCUME~1\Owner\APPLIC~1\Marmalade\packages\6.2.1\libjpeg_6b
loading mkf: [C:\DOCUME~1\Owner\APPLIC~1\Marmalade\packages\6.2.1\libjpeg_6b] 'libjpeg'
adding package reference: C:\DOCUME~1\Owner\APPLIC~1\Marmalade\packages\6.2.1\libpng_1.2.34
loading mkf: [C:\DOCUME~1\Owner\APPLIC~1\Marmalade\packages\6.2.1\libpng_1.2.34] 'libpng'
package is deprecated
adding package reference: C:\DOCUME~1\Owner\APPLIC~1\Marmalade\packages\6.2.1\zlib_1.2.4
loading mkf: [C:\DOCUME~1\Owner\APPLIC~1\Marmalade\packages\6.2.1\zlib_1.2.4] 'zlib'
using build directory 'build_s3eiosnotifications_vc9'
adding PATH: e:\marmalade\6.2\s3e\gcc\bin
using gcc toolchain: arm-none-eabi-gcc []
using RVCT version: 5.2
adding PATH: E:\DS-5\bin
using RVCT from: E:\DS-5\bin
found app.icf in data dir
adding PATH: e:\marmalade\6.2\s3e\bin
Wrote file 'deploy_config.py'.
adding PATH: e:\marmalade\6.2\tools\gcc\mips\android_mips_windows\bin
using gcc_mips toolchain: mipsel-linux-android-gcc []
Wrote file 'linker_script'.
done
Doing: "Package" on Configuration Default to iphone
running s3e_deploy commandline: "e:\marmalade\6.2\s3e\python\python.exe" "E:\Marmalade\6.2\s3e\deploy\main.py" "-n" "--os" "iphone" "--arch" "arm" "e:\Marmalade\6.2\examples\s3e\s3eIOSNotifications\build_s3eiosnotifications_vc9\deploy_temp.py"
CWD=e:\Marmalade\6.2\examples\s3e\s3eIOSNotifications\build_s3eiosnotifications_vc9
Marmalade Deployment Tool v1.3
Copyright (C) 2001-2012 Marmalade
Licensed Platforms=NONE, current platform=iphone
WARNING: temporary folder already exists (e:\Marmalade\6.2\examples\s3e\s3eIOSNotifications\build_s3eiosnotifications_vc9\deployments\default\iphone\release.old)
deploying s3eIOSNotifications [0.0.1] [arm-release] for 'iphone' to folder: 'deployments\default\iphone\release\intermediate_files'
--> copying files ...
Not using generic splashscreens for iOS
--> updating s3e binary: compression=none signing=0 config-embedding=1
 [execute] s3e_mod.exe
--> performing custom deployment steps for: 'iphone'
Linking iOS loader with extension library s3eIOSNotifications
 [execute] ld64.exe
WARNING: No iPhone portrait splashscreen specified.  Using the generic splash screen.
WARNING: No iPad portrait splashscreen specified.  Using the generic splash screen.
WARNING: No iPad landscape splashscreen specified.  Using the generic splash screen
WARNING: Expanding smaller image (e:/marmalade/6.2/examples/resources/splashscreens\splash_640.png) to (768x1024)
 [execute] s3eRelocate
 [execute] mod_apple_loader.pyc
Embedding provisioning profile in app
signing with Developer entitlements: NOT for App Store
provisioning profile does not specify 'aps-environment' - push notifications and email will not work
App ID from info.plist: 38ZJGRK9WD.38ZJGRK9WD.com.findandtry.findandtry2
Provisioning profile app ID matches: 38ZJGRK9WD.com.findandtry.findandtry2
created temp.xcent
 [execute] codesign.exe
creating .app zip: deployments\default\iphone\release\s3eIOSNotifications.app.zip
adding app_dir to zip: deployments\default\iphone\release\intermediate_files\s3eIOSNotifications.app
creating IPA: deployments\default\iphone\release\s3eIOSNotifications.ipa
creating ipa: deployments\default\iphone\release\s3eIOSNotifications.ipa
adding app_dir to zip: deployments\default\iphone\release\intermediate_files\s3eIOSNotifications.app
SUCCESS (WITH WARNINGS): EVALUATION USE ONLY package written to 'e:\Marmalade\6.2\examples\s3e\s3eIOSNotifications\build_s3eiosnotifications_vc9\deployments\default\iphone\release' [took 4.16s]. This package is not licensed for commercial use

The mkb file:
    #!/usr/bin/env mkb
    files
    {
        s3eIOSNotifications.cpp
    }
subprojects
{
    ExamplesMain
    s3eIOSNotifications
}

assets
{
    (data)
}

deployments
{
    iphone-sign-for-distribution=0

    # Note the App/Bundle ID must be set to the same value as an app registered
    # through iTunes Connect or the app will not be recognised by Apple's APNs
    iphone-appid="38ZJGRK9WD.com.findandtry.findandtry2"

    # A provisioning profile, set up to use the same full app/bundle name, must
    # also be embedded or the app will not be able to retreive a token for
    # remote notifications.
    iphone-provisioning-profile="FindandTry.mobileprovision"
}

I'm using Marmalade 6.2.1, tried both RVCT and GCC compilers for ARM, building standart example of s3eIOSNotifications as-is. I explores .ipa file and compare .provisionprofile files inside .ipa and original - there are identical. What should I do?

A: Explaining iOS builds made using marmalade:-
Development build
When making development build, you do not need to add a provisional profile, in the deploy tool or mkb. The device needs to have development provision profile installed in it, or need to be embedded in the ipa (just open the ipa in winrar and put the mobileprovision file, renamed as embedded.mobileprovision). That's just for development build.
Release Build
To make a release build you need to provide specific release provision profile (not the development one) from either deploy tool or mkb file. Just including the profile in mbk will convert the build as release. The most important thing is, you can't install a release build using ipcu or iTunes (Dunno about any other method) even in devices with development profile installed. The release build is just for submission to the app store.
So the point is, just ignore the provision profile section if you are just testing the build in device. Only include the profile, if you're actually going to submit the same build to app store.


text:
Q: Telerik RadTreeListView Event binding I am currently working on a Telerik Silverlight Control, the RadTreeListView.
Is it possible to bind a DoubleClick Event to this control? Please note that I'am using
MVVM pattern and that the RadTreeListView isn't equal to the RadTreeView control.
It would be nice if anyone can share his experience with me.
I tried many ways, but nothing worked..
Last example (look at the command):
<telerik:RadTreeListView x:Name="TreeListControl"
                             AutoGenerateColumns="False"
                             IsReadOnly="True"
                             ItemsSource="{Binding TreeViewData, ValidatesOnDataErrors=True}"
                             IsExpandedBinding="{Binding IsExpanded, Mode=TwoWay}"
                             CanUserFreezeColumns="False"
                             RowIndicatorVisibility="Collapsed"
                             ColumnWidth="*"
                             CanUserSortColumns="False"
                             evt:MouseDoubleClick.Command="{Binding DoubleCommand}"
                             >

Helper Class:
.... public static class MouseDoubleClick
{
    public static DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command",
            typeof(ICommand),
            typeof(MouseDoubleClick),
            new PropertyMetadata(CommandChanged));

    public static DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached("CommandParameter",
            typeof(object),
            typeof(MouseDoubleClick),
            new PropertyMetadata(null)); ....

The compiler gives out the error:
Error   3   The property 'Command' does not exist on the type 'RadTreeListView' in the XML namespace 'clr-namespace:CombinationTreeViewControl'.    C:\Users\B95703\Documents\Entwicklung\Silverlight\SilverlightComponents\CombinationTreeViewControl\View\CombinationTreeViewControl.xaml 32  34  CombinationTreeViewControl

Best regards
Patrik

A: Instead of using PropertyMetaData in your RegisteredAttached() methods, try using UIPropertyMetaData.
Also see my answer here:
https://stackoverflow.com/a/13886760/430897

A: Try using System.Windows.Interactivity Triggers on your TreeListView on the Click event:
<i:Interaction.Triggers><i:EventTrigger EventName="DoubleClick">
                <i:InvokeCommandAction Command="{Binding DataContext.TreeViewDoubleClickCommand, ElementName=LayoutRoot}"
                                       CommandParameter="{Binding SelectedItem,ElementName=MyTreeView}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>

Considering that the DoubleClick event is exposed in the TreeListView control.

A: you can use of RowsIsexpandedChange.when expanding changing, you can use of variable isexpand.
   private ICommand _rowIsExpandedChangedClick;
    public ICommand RowIsExpandedChangedClick
    {

        get
        {
            if (_rowIsExpandedChangedClick == null)
            {
                _rowIsExpandedChangedClick = new MVVM.DelegateCommand<Telerik.Windows.Controls.GridView.RowEventArgs>(RowIsExpandedChangedClickShow);
            }

            return _rowIsExpandedChangedClick;
        }
        set { _rowIsExpandedChangedClick = value; }
    }
    RadTreeListView _currentRadTreeListView;
    private void RowIsExpandedChangedClickShow(Telerik.Windows.Controls.GridView.RowEventArgs e)
    {

        var folder = e.Row.DataContext as YourClass;
       var  row = e.Row as GridViewRow;
       _currentRadTreeListView = e.OriginalSource as RadTreeListView;
        if (row.IsExpanded)
        {
            folder.Isexpanded = row.IsExpanded;
        }

    }

  //----------------------------------------ExpandHierarchyItem for expand specialitems
  private void collapseorexpand(FolderSarfasl _currntfolder)
  {
      if(_currntfolder.Isexpanded==true)
          if(_currentRadTreeListView!=null)
            _currentRadTreeListView.ExpandHierarchyItem(_currntfolder);
      for (int i = 0; i < _currntfolder.SubFolders.Count; i++)
      {
          collapseorexpand(_currntfolder.SubFolders[i]);
      }
  }


text:
Q: Closed form expression for $n_j$ defined by $n_j=\lceil n_{j−1}/b\rceil$ clarification I came across this answer to this question:
Closed form expression for $n_j$ defined by $n_j=\lceil n_{j-1}/b \rceil$
I was hoping someone could clarify the following step:

$q−1 \leqslant \dfrac{(P−1)}{b} < \dfrac{x}{ab} ⩽ \dfrac{P}{b} ⩽ q $,
which says
$\left\lceil\dfrac{x}{ab}\right\rceil =
> \left\lceil\dfrac{1}{b}\left\lceil\dfrac{x}{a}\right\rceil\right\rceil $.

I realize that the inequality is bounded between q-1 and q, so intuitively the ceiling equality makes sense. Testing real examples also shows that the equality is true. However, I'm a bit lost on how this is rigorously shown from the inequality. Any help would be very much appreciated!

A: That's exactly the same thing Daniel Fischer did in the first inequality of the answer you are asking about, just with different numbers.
Consider a real number $\alpha$. Then by definition $\lceil \alpha \rceil$ is the smallest integer greater than or equal to $\alpha$. In other words, $n = \lceil \alpha \rceil$ if and only if $n$ is an integer and
$$
n - 1 < \alpha \leq n.
$$
Now, the inequality you have tells you that
$$
\color{red}{q-1} \color{gray}{\leq \frac{P-1}{b}} \color{red}{\pmb{<} \frac{x}{ab}} \color{gray}{\leq \frac{P}{b}} \color{red}{\leq q}
$$
hence
$$
q = \left\lceil\frac{x}{ab}\right\rceil.
$$
On the other hand, the same inequality also tells you that
$$
\color{green}{q-1} \color{gray}{\leq \frac{P-1}{b}} \color{green}{\pmb{<}} \color{gray}{\frac{x}{ab} \leq} \color{green}{\frac{P}{b} \leq q}
$$
and since by definition $P = \left\lceil\frac{x}{a}\right\rceil$ we conclude that
$$
q = \left\lceil\frac{P}{b}\right\rceil = \left\lceil \frac{1}{b} \left\lceil\frac{x}{a} \right\rceil \right\rceil.
$$


text:
Q: While import product custom options throws error in magento 2 While trying to import custom options for product throws the below error. Please provide me a solution

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  '4953' for key 'PRIMARY', query was: INSERT INTO
  catalog_product_option_type_value
  (option_type_id,sort_order,sku,option_id) VALUES (?, ?, ?, ?),
  (?, ?, ?, ?), (?,


text:
Q: How to JOIN with one distinct column in one and multiple in the other? Here are the two sample tables (Issues and Users):
╔═════════════╦══════════╗
║ reporter_id ║ agent_id ║
╠═════════════╬══════════╣
║ asdf        ║ jfid     ║
║ asde        ║          ║
║ djij        ║ dije     ║
╚═════════════╩══════════╝
╔══════╦════════════╦═══════════╗
║  id  ║ first_name ║ last_name ║
╠══════╬════════════╬═══════════╣
║ asdf ║ Magnus     ║ Nilsson   ║
║ sdfe ║ Thomas     ║ Keller    ║
║ dije ║ Daniel     ║ Humm      ║
╚══════╩════════════╩═══════════╝

Desired result:
╔═════════════╦══════════╦══════════════════╦═════════════════╦═════════════════════╦════════════════════╗
║ reporter_id ║ agent_id ║ agent_first_name ║ agent_last_name ║ reporter_first_name ║ reporter_last_name ║
╠═════════════╬══════════╬══════════════════╬═════════════════╬═════════════════════╬════════════════════╣
║ asdf        ║ idfj     ║ john             ║ lee             ║ david               ║ lee                ║
║ aiej        ║          ║ mike             ║ dee             ║                     ║                    ║
║ isao        ║ idje     ║ sarah            ║ lee             ║ sarah               ║ dee                ║
╚═════════════╩══════════╩══════════════════╩═════════════════╩═════════════════════╩════════════════════╝

What sort of join can handle this?  For context, this would be on Redshift (postgres).  I was thinking this...
select
    ???
from
    issues join users
        on issues.reporter_id = users.id AND issues.agent_id = users.id

I'm unclear on the select clause and I'm only marginally confident my from clause is correct.

A: You need to Join the User table twice. Also you desired result data doesn't match with the table data.
SELECT I.reporter_id,
       I.agent_id,
       U1.first_name AS agent_first_name,
       U1.last_name  AS agent_last_name,
       U2.first_name AS reporter_first_name,
       U2.last_name  AS reporter_last_name
FROM   issues I
       INNER JOIN users U2
               ON U2.id = I.reporter_id
       LEFT JOIN users U1
              ON U1.id = I.agent_id

A: You can join the same table twice. Just use a different alias, like this:
select
    issues.reporter_id
   ,issues.agent_id
   ,a.first_name as agent_first_name
   ,a.last_name as agent_last_name
   ,r.first_name as reporter_first_name
   ,r.last_name as reporter_last_name
from
    issues left join users r
        on issues.reporter_id = r.id
    left join users a
        on issues.agent_id = a.id

Also, as you have null values for agent_id (and potentially for the reporter_id) you need to use left join


text:
Q: Dell Latitude E6530 CPU upgrade? I have a Dell Latitude E6530 laptop that came with an i5-3340M quad-core CPU.  I refer to it as a quad-core, because under Device Manager -> Processors, it lists FOUR separate listings as below:

Intel(R) Core(TM) i5-3340M CPU @ 2.70GHz
    Intel(R) Core(TM) i5-3340M CPU @ 2.70GHz
    Intel(R) Core(TM) i5-3340M CPU @ 2.70GHz
    Intel(R) Core(TM) i5-3340M CPU @ 2.70GHz

.. and under Properties, each of the above for all four instances under "General" states:

This device is working properly

I'm interested in speeding up my laptop and wanted to know if I can do that with a "drop in" upgrade CPU.
Contacting Dell proved no help, nor did their knowledge base have any solutions. All they wanted to do is sell me a $2000 solution for my $350 refurb laptop.
According to my Dell user manual, the processor IS removable.  It isn't clear, though, whether there is actually a faster compatible CPU to replace it with, and what characteristics I need to look at to identify one.

A: First - The i5-3340M is only a dual-core CPU. You're seeing four "processors" in Device Manager because you have hyperthreading enabled. Thus it can run four threads at once but the collective CPU hardware is that of two cores.
Ok, now about upgrading: The CPU on the E6530's motherboard is indeed socketed - confirmed by an eBay search for "E6530 motherboard" which finds a bunch of boards with empty CPU sockets. So a CPU upgrade is at least physically possible.
Now, to maintain compatibility with the chipset, uou need to stay within the same CPU microarchitecture and the same socket type.
Searching on Wikipedia for "i5-3340M" finds the CPU in this list. The microarchitecture is a mobile Ivy Bridge gen 3, socket type G2. (The processors shown with "BGA" designations are for directly soldering to motherboards; you don't want any of those.) The list shows only a couple of possibilities. And there are apparently no quad-core mobile Core i5's. So the best you could do with an i5 would be to increase CPU frequency from 2.7 to 2.9 GHz. Hardly worth the trouble even if the new CPU was free.
However, it's possible that a Core i7 quad would work. Core i7's are notably faster than i5's per core, and mobile quad-core are available. Generalizing from the previous article title, we look for "List of Intel Core i7 microprocessors". We're looking for mobile Ivy Bridge quad core, and the TOC guides us us to  this list.
We find, for example, the i7-3740QM. Same microarch, same G2 socket, four cores (so with HT enabled can run eight threads). Again, anything in that list with the G2 socket should work.
The 3740QM does have a significantly higher TDP than your CPU (45 watts instead of 35). But it has the same built-in graphics (HD4000), and twice the L2 and L3 cache. So it would likely use battery faster and keep the fan running more, if you put all four cores to work. But if you do put all four cores (or even three) to work, you should notice a significant increase in compute throughput. (But not much in the performance of a single-threaded app. Some increase, yes, because of the increased L3 cache.)
(Going to faster quad-core CPUs in that family does not look cost-effective, based at least on their prices at release. e.g. from almost $400 to $570 to increase CPU speed from 2.7 to 2.8 GHz? Nah!)
Now, you will find used or refurbed E6530's with that i7-3740QM - so it'll probably work as a drop-in replacement. There is a faint possibility that it might not. I don't think it's a big risk, first because Dell support lists the same BIOS downloads for these machines regardless of which CPU you have; and second because Dell wants to use the same mobo for as many different CPUs as possible.
Personal experience; I've done CPU upgrades on a couple of Latitude D-series laptops and they went very well. But I can't promise that the E6530-type motherboard is as friendly. I suspect it is, again because it was very economical for Dell to be able to use the same motherboard regardless of CPU.
But the replacement CPU won't be cheap. I would search the support forums at Dell, and other forum sites, to see if you can find someone who reported success before I invested hundreds of dollars in a new CPU.
As for the SSD: Pull your hard drive. If it's a standard 9mm high 2.5 inch HD (as mine was) then virtually any SSD of the same form factor should work. If you get a thin one (7 mm high) be prepared for some difficulty getting it to plug in properly; Dell uses different "side rails" for the two heights. But it can be done.

A: Yes, the CPU can be upgraded
The i7-3740QM and the i7-3720QM are compatible quads. These are quad cores with 8 threads. Yours 3340M is a 2 core/4 threads which is why you see "Intel(R) Core(TM) i5-3340M CPU @ 2.70GHz" four times.
I have sold and upgraded hundreds of these for a technology refurbishing company.
Both upgrades were found here (for your reference - this is my go to place for compatible upgrades):
Compatible CPU for E6530 Laptops

A: To go for sure it's better to search if Dell has produced models with other cpus and use those. For I7 they have a model with I7-3720QM (which IS 45W cpu vs original 35W)
You can see numerous shops selling it with I7 cpu. Also notebookcheck confirms that it can ship with I7-3720QM

https://www.notebookcheck.net/Review-Dell-Latitude-E6530-Notebook.88073.0.html

I have used this approach before and this has worked for me.
Thinking of upgrading E6530 which has i3-3210M cpu, which is about 2 times slower than I7-3720QM


text:
Q: Troubleshooting runtime exceptions when in Design mode When I open a form, I am suddenly getting an error message:

"Error reading form: 'X' "
Cache is not initialised. Must call TCache.Initialise first. Ignore the Error and continue? NOTE: Ignoring the error may cause components to be deleted or property values lost"

The "Cache is not initialised" bit is an exception raised by one of our classes.
My first question is, why is the Delphi IDE running my code without me asking it to "Run Program"? What code does it run? Is there any way to turn this off?
Secondly, is there any way I can trap this error in the debugger, so I can work out where in the call stack this exception occurs? I have tried putting a breakpoint where the exception is thrown, but Delphi ignores it.
And also, once I have worked out where this exception is coming from, is there a way to tell when I am in "design mode" and not run that code, or run different code? Or even better, not run that code at all if in design mode?
[Update: See Francois' answer to how to stop code running in design mode.]

A: You have some component code that you wrote that is executed when the IDE is trying to load the dfm.
You can test in your code if your component is in "design mode" with
  if (csDesigning in ComponentState) then

A: When the IDE loads a DFM, it creates live objects within the Form Designer, which means component run-time code is actually run within the IDE.  As such, component code needs to check the TComponent.ComponentState property for the csDesigning flag if it wants to skip running portions of its code at design-time.


text:
Q: Fast way to fill a python list to target length I want to fill one of my list to the same length with the others, so they can be used in later pandas
df = pd.DataFrame([list1,list2,list3],columns= column_name_list)

for example, my column_name_list is with length 5
but if list1,list2,list3 is only with length 3, eg:
list1= ['a','b','c']

Before parsing it to dataframe, is there any fast way(like single line) to fill the list1 to target length 5?
What I expect is list1 to be
['a','b','c','empty_or_the_string_I_defined_or_from_target_list','empty_or_the_string_I_defined_or_from_target_list']

I want to fill the rest with blank or specific string or even the same element as target column name list
Thanks!

A: One way using itertools.zip_longest:
from itertools import zip_longest

list1 = ["a", "b", "c"]
list2 = ["aa", "bb"]
list3 = ["aaa", "bbb", "ccc", "ddd"]
columns = ['col0', 'col1', 'col2', 'col3', 'col4']

padded = list(zip_longest(columns, list1, list2, list3, fillvalue="Fillme"))
print(padded)

Output:
[('col0', 'a', 'aa', 'aaa'),
 ('col1', 'b', 'bb', 'bbb'),
 ('col2', 'c', 'Fillme', 'ccc'),
 ('col3', 'Fillme', 'Fillme', 'ddd'),
 ('col4', 'Fillme', 'Fillme', 'Fillme')]

You can then use pandas.DataFrame.set_index with T to make a dataframe:
df = pd.DataFrame(padded).set_index(0).T
print(df)

Output:
0 col0 col1    col2    col3    col4
1    a    b       c  Fillme  Fillme
2   aa   bb  Fillme  Fillme  Fillme
3  aaa  bbb     ccc     ddd  Fillme

A: The easiest might be:
  list1 + ['empty_or_the_string_I_defined_or_from_target_list'] * (target_length - len(list1))

This should do the trick.


text:
Q: Store filehandles in array I try to open all *.xlsx files in a specified folder and store the filehandles in an array.
My code looks like this
Dim Files() As Workbook
ReDim Files(Count)

File = Dir(Path & "\*.xlsx")
Count = 0

Do While File <> ""
    Set Files(Count) = Workbooks.Open(Path & File, , True)
    Count = Count + 1
    File = Dir()
Loop

The code seems to work, however, when I run it a second time (hitting the run button again), I get an error number 13.
Debugging the code I tracked the problem to the line
Set Files(Count) = Workbooks.Open(Path & File, , True)

As I am unexperienced with vba I guess I didn't do this the right way...
What would be a preferable way to store filehandles to all files in a specific folder in an array?

A: you're missing a path separator
Set Files(Count) = Workbooks.Open(Path & "\" & File, , True)

A: The code should be:
Dim Files() As Workbook
Dim Count As Integer
ReDim Files(Count)

File = Dir(Path & "\*.xlsx")
Count = 0

Do While File <> ""
    ReDim Preserve Files(Count)
    Set Files(Count) = Workbooks.Open(Path & File, , True)
    Count = Count + 1
    File = Dir()
Loop

You need to redim your array. Preserve keeps the existing data.


text:
Q: Why doesn't my trigger put data into my table? When I execute my trigger, it says it executed commands, but there is still no data in the tAttackPlan where it is supposed to insert data into. Can not figure out why.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF OBJECT_ID ('trAttack', 'tr') IS NOT NULL
    DROP TRIGGER trAttack
GO
CREATE TRIGGER trAttack
   ON tAttackPlan
   AFTER INSERT, UPDATE
AS
BEGIN

    SET NOCOUNT ON;
    DECLARE @AttackRequirementID INT, @MinionID INT, @DomainID INT, @MinimumCount INT, @Count INT, @MinionID_min INT
    SELECT @DomainID = (SELECT @DomainID FROM inserted)
    SELECT @Count = (SELECT SUM(Count) FROM tCensus GROUP BY MinionID)
    SELECT @MinionID_min = tMinion.MinionID
    FROM dbo.tMinion
    INNER JOIN dbo.tCensus ON dbo.tMinion.MinionID = dbo.tCensus.MinionID
    CROSS JOIN dbo.tAttackRequirement
    CROSS JOIN dbo.tAttackPlan
    INNER JOIN dbo.tDomain ON dbo.tAttackPlan.DomainID = dbo.tDomain.DomainID

    INSERT INTO tAttackPlan (DateOfAttack, DomainID)
    VALUES (1050, @DomainID)

    IF @Count < @MinimumCount
        RAISERROR ('There are not enough minions to attack', 16, 10)
END
GO

A: What learning_DBAdmin is saying makes sense...
if this is the only script you are running, it will only create the trigger...
when you insert or update the table tAttackPlan, it will trigger the trAttack trigger.
Now let's analyze the trigger... If an insert or update is done on the tAttackPlan table the trigger will insert into tAttackPlan the attack date and domainID... Is this what you really want? It seems to be recursive to me but not sure of the whole story behind this piece of code. ... What I see is if your trigger is triggered it will insert into the tAttackPlan table which will trigger the trAttack again, and so on and so forth.
Also, note that a trigger has 2 internal tables inserted and deleted, which define the new value of the insert/update (in inserted) and the old value or records to delete (in deleted)...
Please check Microsoft sites to see how triggers work.


text:
Q: Habilitar CORS em api rails Esto usando esta GEM para habilitar o CORS de minha aplicação.
O código que tenho em meu config/application.rb é o seguinte:
config.middleware.insert_before 0, 'Rack::Cors' do
  allow do
    origins 'http://localhost:8080'
    resource '*',
             headers: :any,
             methods: [:get, :post, :delete, :put, :options],
             max_age: 0
  end
end

O problema é que se altero alguma coisa nesta configuração e reinicio o server a configuração não se aplica.
Ex: Se eu remover o :get e reiniciar o server era para não estar liberado o cors para o get mas ele continua funcionando como se estivesse lá. O que poderia ser?

A: Cheguei a instalar uma vez essa gem e também não funcionou comigo. Fazendo umas pesquisas no Google (não me lembro onde encontrei), achei um tutorial sobre como configurar o CORS sem uma gem. Neste caso. bastaria adicionar alguns métodos no application_controller.rb. Seria assim:
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers

protected

def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST,DELETE, GET, PUT, PATCH, OPTIONS'
  headers['Access-Control-Allow-Headers'] = '*'
  headers['Access-Control-Max-Age'] = "1728000"
end

# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.

def cors_preflight_check
  if request.method == :options
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST,DELETE, GET, PUT, PATCH, OPTIONS'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Max-Age'] = '1728000'
    render :text => '', :content_type => 'text/plain'
  end
end

Espero que isso ajude.

A: No meu caso utilizo o Rails 5, eu criei um arquivo chamado cors.rb no config/initializers/cors.rb
porém coloquei assim:
Rails.application.config.middleware.insert_before 0, "Rack::Cors", :debug => true,
:logger => (-> { Rails.logger }) do
  allow do
    origins '*'
    resource '*',
        :headers => :any,
        :methods => [:get, :post, :delete, :put, :patch, :options, :head]
    end
end

que no meu caso é aberta minha api
e no arquivo de rodas, acrescentei do lado do nome do resource assim
resource :nome, :default => {format: :json}

e funcionou pra mim, tive diversos problemas com o CORS


text:
Q: Replace (change) "Chapter 1" to "Chapter ONE" without affecting lof and lot I used the answer given here Replace (change) "Chapter 1" to "Chapter ONE" but it only should be in case without a following list of tables (lot) or figures (lof).
When used as it is, the following lot and lof also replace the chapter number with a word as shown:

What should be changed to prevent this?

A: You don't mention in your question how you produced the string instead of the number. You mustn't redefine \thechapter, or all references pertaining to the first chapter will have the string ONE.
You can patch the \@makechapterhead instead, with the following:
\documentclass{report}

\usepackage{fmtcount} % for textual representation of numbers

% patch \@makechapterhead
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@makechapterhead}
  {\thechapter}
  {\NUMBERstring{chapter}}
  {}{}
\makeatother

\begin{document}

\listoffigures

\chapter{First}

\begin{figure}
A
\caption{A figure}
\end{figure}

\end{document}

If you want to have "CHAPTER ONE" in front of your chapter title in the table of contents, you need to patch also \@chapter.
\documentclass{report}

\usepackage{tocloft}
\renewcommand{\cftchappresnum}{CHAPTER\ }
\setlength{\cftchapnumwidth}{10em}
\usepackage{fmtcount} % for textual representation of numbers

% patch \@makechapterhead and \@chapter
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@makechapterhead}
  {\thechapter}
  {\NUMBERstring{chapter}}
  {}{}
\patchcmd{\@chapter}
  {\protect\numberline{\thechapter}}
  {\protect\numberline{\protect\NUMBERstringnum{\arabic{chapter}}}}
  {}{}
\makeatother

\begin{document}

\tableofcontents

\listoffigures

\chapter{First}

\begin{figure}
A
\caption{A figure}
\end{figure}

\end{document}

Note that you need \cleardoublepage before \listoffigures, if you want it in a new page. For showing the output I did not add it.

A: Here is an example using the titletoc and fmtcount packages:
\documentclass[11pt,a4paper]{book}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage{titletoc,  fmtcount}

\newlength{\len}
\titlecontents{chapter}[1.2em]{\bfseries \bigskip}%
{\contentslabel[Chapter \Numberstringnum{\thecontentslabel}.]{0.6em}\settowidth{\len} {Chapter \Numberstringnum{\thecontentslabel}}\hspace*{\len}}%]
{\hspace*{-1.5em}}%
{\hfill\contentspage}%
[\smallskip]%

\begin{document}

\tableofcontents

\chapter{Down the Rabbit-Hole}

\section{Alice was beginning to get tired}

\section{Drink me.  Eat me. }

\setcounter{chapter}{10}
\chapter{Who Stole the Tarts?}

\section{The Queen's Croquet-Ground}

\section{The Mock-Turtle's Story}

\end{document}

It shouldn't modify any cross-references using the chapter counter. It is multilingual for a small number of language thanks to the \FCloadlang command.


text:
Q: Counting highest number occurrences of character and return in separate data table/frame in R I am looking for a string of code that will count the number of occurrences of a certain variable, sort it in order, and then limit it to the first X results. Example of what I am looking for:
Dataframe:
ID    Group
1000    A
1001    A
100a    A
100g    D
1004    C
100f    B
100z    B
1293    B
2412    B
3040    B
3452    C

Result: Table or Dataframe showing Top 3 results (of 4), in order of highest to low
Group   Count
B         5
A         3
C         2

Thanks in advance!

A: In dplyr, we can count Group values, select top 3 values and arrange them in decreasing order.
library(dplyr)
df %>% count(Group) %>% top_n(3, n) %>% arrange(desc(n))

#  Group     n
#  <fct> <int>
#1 B         5
#2 A         3
#3 C         2

We can also use
df %>% count(Group) %>% arrange(desc(n)) %>% head(3)

Or in base R
stack(head(sort(table(df$Group), decreasing = TRUE), 3))


text:
Q: Discord.py missing permissions error with permissions I try to edit the Roles from a Member trough the member.edit(roles = list_of_roles) command. For the most Users this works just finde, but for some the I get the Error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions altrough the bot HAS the heighest role on the Server AND admin rights. (No the Role that I try to remove/add is NOT highter or at the same Level as the bot role) Is there anything I might missed? because I dont understand why he cant remove the roles from some members (the members dont have admin rights).

A: After many hours I found out, you cant remove the booster role. This is why ít doesn't work how it should.


text:
Q: Set value to [Flags] Enum from list c# I need to set the Enum value by items taken from the list.
I have Enum:
[Flags]
public enum EnumTest
{
    Val1= 1,

    Val2= 2,

    Val3= 4
}

List with values:
var values = new List<EnumTest> {EnumTest.Val1, EnumTest.Val3};

How can I get the following result using a foreach?
var result = EnumTest.Val1 | EnumTest.Val3;

Thanks

A: EnumTest result = 0;

foreach (EnumTest et in values)
{
   result |= et;
}

A: Here's a solution using Linq:
var result = values.Aggregate((x, y) => x |= y);


text:
Q: When building list of solutions with MSBuild how do I copy all outputs to another folder? We've got a large amount of legacy code in a big folder tree of solutions and projects, many of which we are not interested in (but unfortunately can't move at the moment)
We are currently using MSBuild to compile the solutions we are interested in like this:
<ItemGroup>
  <Solutions Include="some_path\solution1.sln"
  <Solutions Include="some_other_path\solution2.sln"
  <Solutions Include="yet_another_path\solution3.sln"
</ItemGroup>

<Target Name="Rebuild">
  <MSBuild Projects=@(Solutions) Targets="Rebuild" />
</Target>

This builds things just fine but what we would like to do is take all the files that end up in the various projects bin\Release folders to a different tree structure that has the same relative folders but a different root.
How can we do this without just looking for a particular file pattern (eg all the dll or exe files) as the file structure we have contains many files that we are not interested in.
So basically is there a way to find all the files our build script is building and move them to another place retaining their relative paths?

A: Have you tried overriding the Output path?
<MSBuild Projects="@(Solutions)"              Properties="OutputPath=$(ParentDir)\Output\%(Solutions.Filename)"/>

This will put the outputs of each solution in a tree from $(ParentDir)\Output.

A: Here are 2 ideas for you:
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="AllTargetsWrapped">

    <!--
        <UsingTask AssemblyFile="$(ProgramFiles)\MSBuild\MSBuild.Community.Tasks.dll" TaskName="Version"/>
        -->
    <Import Project="$(MSBuildExtensionsPath32)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />

    <PropertyGroup>
        <TPath Condition="Exists('$(MSBuildExtensionsPath32)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks')">$(MSBuildExtensionsPath32)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks</TPath>
    </PropertyGroup>
    <Import Project="$(TPath)"/>

    <PropertyGroup>
        <!-- Always declare some kind of "base directory" and then work off of that in the majority of cases  -->
        <WorkingCheckout>.</WorkingCheckout>
    </PropertyGroup>

    <Target Name="AllTargetsWrapped">
        <CallTarget Targets="ShowVariables" />
        <CallTarget Targets="ShowMeTheFiles" />

    </Target>

    <Target Name="ShowVariables">
        <Message Text=" $_WorkingCheckout_ = '$(WorkingCheckout)' " />

        <Message Text=" $_MSBuildExtensionsPath32_ = '$(MSBuildExtensionsPath32)' " />
        <Message Text=" $_MSBuildProjectDirectory_ = '$(MSBuildProjectDirectory)' " />

    </Target>

    <Target Name="ShowMeTheFiles">

        <ItemGroup>
            <AllFiles Include="$(WorkingCheckout)\**\*.*" />
        </ItemGroup>
        <MSBuild.Community.Tasks.RegexMatch Expression="\d+" Input="%(AllFiles.FullPath)">
            <Output TaskParameter="Output" ItemName="MatchedFiles" />
        </MSBuild.Community.Tasks.RegexMatch>

        <Message Text="rootdir + directory + filename + extension: @(MatchedFiles->'%(rootdir)%(directory)%(filename)%(extension)')"/>

       <Copy
            SourceFiles="@(MatchedFiles)"
            DestinationFiles="@(MatchedFiles->'C:\WUTEMP\DestinationFolder\01\%(RecursiveDir)%(Filename)%(Extension)')"
        />

        <MSBuild.ExtensionPack.FileSystem.FindUnder TaskAction="FindFiles" Path="$(WorkingCheckout)\" SearchPattern="F*">
            <Output ItemName="AllFilesStartingWithF" TaskParameter="FoundItems"/>
        </MSBuild.ExtensionPack.FileSystem.FindUnder>

        <Message Text="rootdir + directory + filename + extension: @(AllFilesStartingWithF->'%(rootdir)%(directory)%(filename)%(extension)')"/>

        <Copy
            SourceFiles="@(AllFilesStartingWithF)"
            DestinationFiles="@(AllFilesStartingWithF->'C:\WUTEMP\DestinationFolder\02\%(RecursiveDir)%(Filename)%(Extension)')"
        />

    </Target>

</Project>

But I think the RecursiveDir is getting whacked in the conversion  :<

A: Here is a stubbed custom MSBuild task.
You can alter the "RunMyCustomKeeperLogic" logic to whatever you want.
I stubbed it as "keep every 5th file" as a dumbed down example.
Once you have the files back in the ".msbuild" world, you can copy/move do whatever you want with them.
namespace GranadaCoder.Framework.CrossDomain.MSBuild.Tasks.IO
{
    using System.Collections.Generic;
    using Microsoft.Build.Utilities;

    public abstract class FileBasedTaskBase : Task
    {
        /// <summary>
        /// Converts the delimited source file string to and IList.
        /// </summary>
        /// <param name="sourceFilesString">The source files string.</param>
        /// <returns></returns>
        protected IList<string> ConvertSourceFileStringToList(string sourceFilesString)
        {
            IList<string> returnList = sourceFilesString.Split(';');
            return returnList;
        }

        /// <summary>
        /// Task Entry Point.
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            AbstractExecute();
            return !Log.HasLoggedErrors;
        }

        protected abstract bool AbstractExecute();
    }
}

namespace GranadaCoder.Framework.CrossDomain.MSBuild.Tasks.IO//.CustomFileKeepTask
{
    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Linq;
    using System.IO;
    using System.Security;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public class CustomFileKeepTask : FileBasedTaskBase
    {
        private static readonly string ROOT_DIRECTORY = "myrootdir";
        private static readonly string FULL_PATH = "myfullpath";
        private static readonly string FILE_NAME = "myfilename";
        private static readonly string DIRECTORY = "mydirectory";
        private static readonly string EXTENSION = "myextension";
        private static readonly string KEEPER = "mykeeper";

        /// <summary>
        /// Gets or sets the source files.
        /// </summary>
        /// <value>The source files.</value>
        [Required]
        public string SourceFiles { get; set; }

        /// <summary>
        /// Gets the file versions as a Task Output property.
        /// </summary>
        /// <value>The file versions.</value>
        [Output]
        public ITaskItem[] FilteredFiles
        { get; private set; }

        /// <summary>
        /// Task Entry Point.
        /// </summary>
        /// <returns></returns>
        protected override bool AbstractExecute()
        {
            InternalExecute();
            return !Log.HasLoggedErrors;
        }

        /// <summary>
        /// Internal Execute Wrapper.
        /// </summary>
        private void InternalExecute()
        {
            IList<string> files = null;

            if (String.IsNullOrEmpty(this.SourceFiles))
            {
                Log.LogWarning("No SourceFiles specified");
                return;
            }

            if (!String.IsNullOrEmpty(this.SourceFiles))
            {
                Console.WriteLine(this.SourceFiles);
                files = base.ConvertSourceFileStringToList(this.SourceFiles);
            }

            List<FileInfoWrapper> fiws = new List<FileInfoWrapper>();

            foreach (string f in files)
            {
                FileInfoWrapper fiw = null;
                fiw = this.DetermineExtraInformation(f);
                fiws.Add(fiw);
            }

            fiws = RunMyCustomKeeperLogic(fiws);

            ArrayList itemsAsStringArray = new ArrayList();

            foreach (var fiw in fiws.Where(x => x.IsAKeeper == true))
            {

                IDictionary currentMetaData = new System.Collections.Hashtable();
                currentMetaData.Add(ROOT_DIRECTORY, fiw.RootDirectory);
                currentMetaData.Add(FULL_PATH, fiw.FullPath);
                currentMetaData.Add(FILE_NAME, fiw.FileName);
                currentMetaData.Add(DIRECTORY, fiw.Directory);
                currentMetaData.Add(EXTENSION, fiw.Extension);

                string trueOrFalse = fiw.IsAKeeper.ToString();
                currentMetaData.Add(KEEPER, trueOrFalse);

                itemsAsStringArray.Add(new TaskItem(trueOrFalse, currentMetaData));
            }

            this.FilteredFiles = (ITaskItem[])itemsAsStringArray.ToArray(typeof(ITaskItem));
        }

        private List<FileInfoWrapper> RunMyCustomKeeperLogic(List<FileInfoWrapper> fiws)
        {
            int counter = 0;
            foreach (var fiw in fiws)
            {
                if(counter++ % 5 == 0)
                {
                    fiw.IsAKeeper = true;
                }
            }
            return fiws;
        }

        /// <summary>
        /// Determines the file version.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>File version or 0.0.0.0 if value cannot be determined</returns>
        private FileInfoWrapper DetermineExtraInformation(string fileName)
        {
            FileInfoWrapper fiw = new FileInfoWrapper();
            fiw.Directory = string.Empty;
            fiw.Extension = string.Empty;
            fiw.FileName = string.Empty;
            fiw.FullPath = string.Empty;
            fiw.RootDirectory = string.Empty;
            fiw.IsAKeeper = false;
            try
            {
                if (System.IO.File.Exists(fileName))
                {
                    fiw.Extension = System.IO.Path.GetExtension(fileName);
                    fiw.FileName = System.IO.Path.GetFileNameWithoutExtension(fileName);
                    fiw.FullPath = fileName;// System.IO.Path.GetFileName(fileName);
                    fiw.RootDirectory = System.IO.Path.GetPathRoot(fileName);

                    //Take the full path and remove the root directory to mimic the DotNet default behavior of '%filename'
                    fiw.Directory = System.IO.Path.GetDirectoryName(fileName).Remove(0, fiw.RootDirectory.Length);

                }
            }
            catch (Exception ex)
            {
                if (ex is IOException
                    || ex is UnauthorizedAccessException
                    || ex is PathTooLongException
                    || ex is DirectoryNotFoundException
                    || ex is SecurityException)
                {
                    Log.LogWarning("Error trying to determine file version " + fileName + ". " + ex.Message);
                }
                else
                {
                    Log.LogErrorFromException(ex);
                    throw;
                }
            }
            return fiw;
        }

        /// <summary>
        /// Internal wrapper class to hold file properties of interest.
        /// </summary>
        internal sealed class FileInfoWrapper
        {
            public string Directory { get; set; }
            public string Extension { get; set; }
            public string FileName { get; set; }
            public string FullPath { get; set; }
            public string RootDirectory { get; set; }
            public bool IsAKeeper { get; set; }
        }
    }
}

and here is an example .msbuild (or .proj or .xml) file to call the above.
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="AllTargetsWrapper" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <UsingTask AssemblyFile="GranadaCoder.Framework.CrossDomain.MSBuild.dll" TaskName="CustomFileKeepTask"/>

  <Target Name="AllTargetsWrapper">
    <CallTarget Targets="CustomFileKeepTask1" />
    <CallTarget Targets="CustomFileKeepTask2" />
  </Target>

  <PropertyGroup>
    <WorkingCheckout>c:\Program Files\MSBuild</WorkingCheckout>
  </PropertyGroup>

  <ItemGroup>
    <MyTask1IncludeFiles Include="$(WorkingCheckout)\**\*.*" />
  </ItemGroup>

  <Target Name="CustomFileKeepTask1">
    <CustomFileKeepTask SourceFiles="@(MyTask1IncludeFiles)" >

      <Output TaskParameter="FilteredFiles"  ItemName="MyFilteredFileItemNames"/>

    </CustomFileKeepTask>

    <Message Text=" MyFilteredFileItemNames MetaData  "/>
    <Message Text="  ------------------------------- "/>
    <Message Text="   "/>

    <Message Text="directory: "/>
    <Message Text="@(MyFilteredFileItemNames->'%(mydirectory)')"/>
    <Message Text="   "/>
    <Message Text="   "/>
    <Message Text="extension: "/>
    <Message Text="@(MyFilteredFileItemNames->'%(myextension)')"/>
    <Message Text="   "/>
    <Message Text="   "/>
    <Message Text="filename: "/>
    <Message Text="@(MyFilteredFileItemNames->'%(myfilename)')"/>
    <Message Text="   "/>
    <Message Text="   "/>
    <Message Text="fullpath: "/>
    <Message Text="@(MyFilteredFileItemNames->'%(myfullpath)')"/>
    <Message Text="   "/>
    <Message Text="   "/>
    <Message Text="rootdir: "/>
    <Message Text="@(MyFilteredFileItemNames->'%(myrootdir)')"/>
    <Message Text="   "/>
    <Message Text="   "/>

    <Message Text="FilteredFile: "/>
    <Message Text="@(MyFilteredFileItemNames->'%(mykeeper)')"/>
    <Message Text="   "/>
    <Message Text="   "/>

    <Message Text="   "/>
    <Message Text="   "/>
    <Message Text="rootdir + directory + filename + extension: "/>
    <Message Text="@(MyFilteredFileItemNames->'%(myrootdir)%(mydirectory)%(myfilename)%(myextension)')"/>
    <Message Text="   "/>
    <Message Text="   "/>

    <Message Text="List of files using special characters (carriage return)"/>
    <Message Text="@(MyFilteredFileItemNames->'"%(myfullpath)"' , '%0D%0A')"/>
    <Message Text="   "/>
    <Message Text="   "/>

  </Target>

  <ItemGroup>
    <MyTask2IncludeFiles Include="c:\windows\notepad.exe"  />
  </ItemGroup>

  <Target Name="CustomFileKeepTask2">
    <CustomFileKeepTask SourceFiles="@(MyTask2IncludeFiles)" >
      <Output TaskParameter="FilteredFiles" PropertyName="SingleFileFilteredFile"/>
    </CustomFileKeepTask>

    <Message Text="SingleFileFilteredFile = $(SingleFileFilteredFile)   "/>

  </Target>

</Project>


text:
Q: Is it possible to make Java code as groovy style I'm trying to know whether we can write null check pointer in the same statement in Java, as we do in groovy? I've four places to check null. Can this be more simplified?
if(doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM") != null) {
            if(doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) != null) {
                Node searchResultNode = doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0);
                if(searchResultNode != null) {
                }
           }
    }

as
doc.getDocumentElement()?.getElementsByTagName("SEARCH-RESULT-ITEM")?.item(0)

Is it possible

A: You asked if it is possible to write Groovy-like code in a regular Java project. The simple answer is no.
However, the statement can be simplified by combining the null checks into one condition. In addition, if doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) is not null we don't need to check the local variable.
So we may end up with:
if (doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM") != null
        && doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) != null {
            Node searchResultNode = doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0);
}

Doing this reduces the number of IF statements from 3 to 1, and eliminates a redundant null check.

A: There is no safe dereference in Java.
It's generally bad practice to toss nulls around and Optional class may come to rescue as well ass checkNotNull at the beginning of the method, but nothing as fancy as Groovy one-liners.


text:
Q: Found fs.open with non literal argument at index 0 when using url built from arguments I'm trying to do something like this (typescript)
window.open(`https://somelink/certificate/${regNumber}?registrationNumber=${type}`);

where regNumber and type are very dynamic.
ESLint is giving me an error
Found fs.open with non literal argument at index 0  security/detect-non-literal-fs-filename
I know this is https://owasp.org/www-community/attacks/Path_Traversal path traversal vulnerability, but simply cannot figure out how to go around it. Any ideas? Thanks
Screenshot:

A: In your case, this rule can be safely ignored.
What the rule does is, it makes a list of these object keys, which includes open, and then checks whether any property accessed in the code (or, more specifically, any MemberExpression) matches one of those keys.
So, while it'll generate a warning for fs.writeFile, and fs.open, for example, it'll also generate one for window.open - despite the fact that the client-side window object is completely different from fs.
fs methods allow for broad manipulation of the server's filesystem. Allowing arbitrary access to this is a bad idea.
window.open only allows a client's browser to open a window to another address, which is nearly innocuous and has very little chance of harming anything.
There's still a potential small vulnerability, but the potential vulnerability will exist regardless of your window.open code - if the webserver is set up improperly and allows arbitrary URL accesses to do something improper (which would be pretty unlikely), that means there's a big issue to fix on the server - but it's not an issue that client-side code should try to deal with.
If the project you're working on does not contain any server-side code, feel free to disable the security/detect-non-literal-fs-filename rule for the whole project.


text:
Q: Angularjs filter orderby numbers and alphabets I want to order by 'displayName'. Sometimes displayName has all numbers or alphabets. $filter('orderBy') is working fine for alphabets. But numbers are rendering like this.
1,13,2,23,3,43.

How can I filter for numbers and alphabets?
    vm.temp=[{id:15, displayName:'ff'},
    {id:2, displayName:'f'},
    {id:10, displayName:'cc'},
    {id:3, displayName:'aa'},
    {id:5, displayName:'h'},
    {id:8, displayName:'y'}]
OR
   vm.temp=[{id:15, displayName:'3'},
    {id:2, displayName:'2'},
    {id:3, displayName:'43'},
    {id:5, displayName:'13'},
    {id:8, displayName:'1'},
 {id:9, displayName:'23'}]

    vm.items = $filter('orderBy')(vm.temp, 'displayName');

A: Add the sorter function:
function sorter(a) {
  if(isNaN(parseInt(a.displayName))) {
    return a.displayName;
  }
  else {
    return parseInt(a.displayName);
  }
}

Update the last line of your code with this:
vm.items = $filter('orderBy')(vm.temp, sorter);

Demo: https://plnkr.co/edit/OfNpqSv3Pj9CDD3bMyoQ?p=streamer

A: Why don't you use in on the other side which is HTML.

{{employee}}

And check out this also please, even though it is the string, the sorting is working in both the ways.
DEMO: https://codepen.io/mkarrfan/pen/QqOaPa

A: Use simple javascript and this script by Brian Huisman based on David koelle's
yourarr.sort(function naturalSorter(as, bs){
var a, b, a1, b1, i= 0, n, L,
rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if(as=== bs) return 0;
a= as.displayName.toLowerCase().match(rx);
b= bs.displayName.toLowerCase().match(rx);
L= a.length;
while(i<L){
    if(!b[i]) return 1;
    a1= a[i],
    b1= b[i++];
    if(a1!== b1){
        n= a1-b1;
        if(!isNaN(n)) return n;
        return a1>b1? 1:-1;
    }
}
return b[i]? -1:0;

});
Here is working plunker


text:
Q: Looking for LSTM / GRU Implementation Some years ago I did a lot of work with "normal" neural networks and supervised learning via backpropagation. And I know how to implement a standard neural network.
Now I want to learn the basics of LSTM / GRU networks, but all I can find are abstract formulas or how to use Keras, TensorFlow or other frameworks. I know that these frameworks are well optimized for speed, but that's not what I'm interested in, because I can't see, what happens inside these frameworks. I'm interested in a simple implementation in plain e.g. Java/C#/VB or whatever, without using a RNN framework to understand how these RNNs work. A simple demo app with a supervised learning to see how all the weights inside are been set would be great. I googled the last two weeks for details, but it seems as if I'm unable to choose the right keywords.
Any programming language appreciated, even FORTRAN or COBOL :-)

A: I suggest you have a look at the stanford course CS231n. The lectures and assignments are at http://cs231n.github.io . You can find course videos on YouTube. The course includes a project to use RNN to generate a description of an image.
A deep learning framework has low level APIs and high level APIs. If your target is only learn the implementation of LSTM or GRU, you can use the low level API of deep learning framework to build a LSTM network by yourself. A framework gives you the functionality of tensor operation and auto gradient, which you may have already known how to implement.
Here I take pytorch as example. You can have a look at the source code of the LSTM implementation in pytorch https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/rnn.py . Don't be afraid to read the source code. This implementation has only 100 lines of useful code. Hopefully it will help you get some idea about the LSTM / GRU network.


text:
Q: How can I make words wrap around inside a ? I have this code:

  Welcome back (said by a person welcoming you back)

The words show in the span and then flow outside of the 10rem div area.
Is there a way that I can make the words wrap around and stay inside of the ?

A: we use word wrap when there is a long word in a paragraph or span you can do this for wrapping words
Welcome back (said by a person welcoming you back)

your current span does not consist of any long word and it's working fine


text:
Q: android layout button does not look as expected I need to create 2 buttons in horizontal layout which will contain icon on the top.
Layout:

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_weight="0.5"
        android:layout_height="wrap_content"
        android:src="@drawable/button" />

    <ImageButton
        android:id="@+id/imageButton3"
        android:layout_width="wrap_content"
        android:layout_weight="0.5"
        android:layout_height="wrap_content"
        android:src="@drawable/button" />

</LinearLayout>

Button:

<item>
    <bitmap
        android:gravity="right"
        android:src="@drawable/ic_action_call"/>
</item>
<item>
    <shape android:shape="rectangle" >

        <gradient
            android:startColor="#FFEEC9A8"
            android:endColor="#90FFDAB9"
            android:angle="45"/>

        <padding
            android:left="7dp"
            android:right="7dp"
            android:top="7dp"
            android:bottom="7dp"/>

        <corners android:radius="10dp"/>

        <stroke android:width="2px" android:color="#ff888888"/>

    </shape>
</item>

I expect it will look like on first picutre, however it looks like on second with a gray area around the icon. What is wrong?

After I added android:scaleType="fitXY" the buttons looks like:

A: Add the following attribute to your ImageButton's XML...
android:scaleType="fitXY"

So, you XML will be...
<ImageButton
    android:id="@+id/imageButton2"
    android:layout_width="wrap_content"
    android:layout_weight="0.5"
    android:layout_height="wrap_content"
    android:src="@drawable/button"
    android:scaleType="fitXY" />

<ImageButton
    android:id="@+id/imageButton3"
    android:layout_width="wrap_content"
    android:layout_weight="0.5"
    android:layout_height="wrap_content"
    android:src="@drawable/button"
    android:scaleType="fitXY" />

Update:
Anothr thing I will recommend you to use android:background instead of android:src as follows...
<ImageButton
    android:id="@+id/imageButton2"
    android:layout_width="wrap_content"
    android:layout_weight="0.5"
    android:layout_height="wrap_content"
    android:background="@drawable/button"
    android:scaleType="fitXY" />

Another way:
if you want to using ImageView then you can do as below...
<ImageView
    android:id="@+id/imageButton2"
    android:layout_width="wrap_content"
    android:layout_weight="0.5"
    android:layout_height="wrap_content"
    android:src="@drawable/button" />

<ImageView
    android:id="@+id/imageButton3"
    android:layout_width="wrap_content"
    android:layout_weight="0.5"
    android:layout_height="wrap_content"
    android:src="@drawable/button" />

A: Quiet simple it is.
No need to create layer list and all
Just use below code
<ImageButton android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@android:color/darker_gray"
   android:src="@drawable/ic_launcher"
   android:paddingLeft="20dip"
   android:paddingRight="20dip"/>

If you observe I have used some plain color for background and provided some icon as an image.
So use two different properties like android:background and android:src
And for Round corner background first create a drawable named round_bg.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="@android:color/darker_gray" />
    <corners android:radius="10dip" />
</shape>

Now in our above code do following modification
android:background="@drawable/round_bg"

And you will be done. :)

A: Use this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ImageButton
    android:id="@+id/imageButton2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:background="@null"
    android:src="@drawable/ic_launcher" />

<ImageButton
    android:id="@+id/imageButton3"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:background="@null"
    android:src="@drawable/ic_launcher" />

</LinearLayout>

A: Yes You can use On Click with Image View
This is for reference only
Also One Thing You create Button With Nine patches so that Your Image will streach In some Part and will be responsive
for example

This is Nine patche Image so only the content part will be streach every time. rest will be as it is.


text:
Q: Missing something when converting rows to columns in SQL I am trying to convert rows to columns from a table, I was able to get the result set but for few records I am missing the logic. Below is the table and SQL I am running, if you the result of the query for P123 PROCEDURE_END should be NULL, Instead of NULL I am getting the PROCEDURE_BEGIN value. I am not sure what I am missing here, please help me out with this.
INSERT  INTO #PAT_TEST
VALUES  ( 'P123', 'D457', '2015-11-29 01:48:00.000', 1 )
,       ( 'P123', 'D457', NULL, 0 )
,       ( 'P872', 'D457', '2015-11-30 02:48:00.000', 1 )
,       ( 'P872', 'D457', '2015-11-30 03:48:00.000', 0 );

SELECT  PAT_ID
      , DOC_ID
      , PROCEDURE_BEGIN = MIN(PROC_TIME)
      , PROCEDURE_END = MAX(PROC_TIME)
FROM    ( SELECT    PAT_ID
                  , DOC_ID
                  , PROC_TIME
                  , rn = ( ROW_NUMBER() OVER ( PARTITION BY PAT_ID, DOC_ID ORDER BY PROC_TIME ) - 1 ) / 2
          FROM      #PAT_TEST
        ) a
GROUP BY PAT_ID
      , DOC_ID
      , a.rn
ORDER BY PAT_ID
      , DOC_ID
      , PROCEDURE_BEGIN;

A: Would this work for you:
If null should be treated as the largest value:
SELECT PAT_ID ,DOC_ID, PROCEDURE_BEGIN=MIN(ISNULL(PROC_TIME,'99991231')),
PROCEDURE_END=CASE WHEN MAX(ISNULL(PROC_TIME,'99991231')) ='99991231' THEN NULL ELSE MAX(ISNULL(PROC_TIME,'99991231')) END
FROM( SELECT PAT_ID ,DOC_ID,PROC_TIME
,rn=(ROW_NUMBER() OVER (PARTITION BY PAT_ID,DOC_ID ORDER BY PROC_TIME)-1)/2
FROM #PAT_TEST
) a
GROUP BY PAT_ID ,DOC_ID, rn
ORDER BY PAT_ID,DOC_ID, PROCEDURE_BEGIN

If null should be treated as the Smallest value:
    SELECT PAT_ID ,DOC_ID, PROCEDURE_BEGIN=CASE WHEN MIN(ISNULL(PROC_TIME,0)) = '19000101' THEN NULL ELSE MIN(ISNULL(PROC_TIME,0)) END,
PROCEDURE_END=MAX(PROC_TIME )
FROM( SELECT PAT_ID ,DOC_ID,PROC_TIME
,rn=(ROW_NUMBER() OVER (PARTITION BY PAT_ID,DOC_ID ORDER BY PROC_TIME)-1)/2
FROM #PAT_TEST
) a
GROUP BY PAT_ID ,DOC_ID, rn
ORDER BY PAT_ID,DOC_ID, PROCEDURE_BEGIN


text:
Q: Getting UI virtualization working with ItemsControl in Silverlight I'm trying to create a scrolling list of fairly large textblocks.  I want there to be a vertical scrollbar to show them all, and if they overflow a certain size I want them to display an ellipsis.  I actually have all this working pretty good.
I have the following Silverlight XAML:
<Grid x:Name="LayoutRoot" MaxWidth="500" MinWidth="100"
    MaxHeight="500" MinHeight="100">
    <Grid.DataContext>
        <app:MainPageViewModel/>
    </Grid.DataContext>
    <ScrollViewer>
    <ItemsControl ItemsSource="{Binding TextItems}" Margin="0,20,0,20">
        <ItemsControl.ItemTemplate><DataTemplate>
            <Border MaxHeight="175" Margin="0,0,0,18" CornerRadius="5">
                <TextBlock Margin="2" TextTrimming="WordEllipsis"
                     TextWrapping="Wrap" Text="{Binding}"/>
            </Border>
         </DataTemplate></ItemsControl.ItemTemplate>
    </ItemsControl>
    </ScrollViewer>
</Grid>

My problem is that this layout does not use UI virtualization, such as with a VirtualizingStackPanel.  So it is pretty slow.  What is the best way to get UI virtualization into this layout?  I've tried about a half dozen different ways and nothing has worked out all that well.
I managed to get this working in a ListBox because it seems to support virtualization out of the box.  However, I'd prefer to use ItemsControl as I don't want these things to be selectable, and I don't want the styling that comes along with a ListBox.
This in Silverlight 4.

A: There are a few things you need to do to make this work.

*

*Set the ItemsPanelTemplate for
your ItemsControl to a
VirtualizingStackPanel.

*Incorporate the ScrollViewer inside
a ControlTemplate for your
ItemsControl instead of just
wrapping it around the outside.

*Make sure the ItemsControl has a fixed height so the layout system can work out how many items it needs to fill the viewport. (It looks like you are already doing this by putting the ItemsControl in a Grid - that will allow the layout system to determine the alloted height for the control)

Here's the simplest example I could come up with of this working:
    <ItemsControl ItemsSource="{Binding TextItems}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.Template>
            <ControlTemplate TargetType="ItemsControl">
                <Border>
                    <ScrollViewer>
                        <ItemsPresenter/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </ItemsControl.Template>
    </ItemsControl>


text:
Q: true / false to Y/N Ex I am trying to change the default value sent from a checkbox. I have this code:
{
    xtype: 'checkcolumn',
    header: 'Contacto de Emergencia',
    dataIndex: 'contactoEmergencia',
    listeners: {
        beforecheckchange: function() {
            return false;
        },
    },
    width: 100,
    flex: 1,
    editor: {
        xtype: 'checkbox',
        cls: 'x-grid-checkheader-editor',
        inputValue: 'Y',
        uncheckedValue: 'N'
    }
}

I am also set my model like:
{
    name: 'contactoEmergencia',
    mapping: 'CONTACTO_EMERGENCIA',
    convert: function(v) {
        return v === 'Y';
    },
    serialize: function(v) {
        return v ? 'Y' : 'N';
    }
},

But it's not working. The default value true/false does not change to Y/N.
Anyone knows why is not changing ? what I am doing wrong ?

A: You can try with below code snippet:-
var store = Ext.create('Ext.data.Store', {
    fields: ['name', 'email', 'phone', 'active'],
    data: [{
        name: 'Lisa',
        email: 'lisa@simpsons.com',
        phone: '555-111-1224',
        active: 'Y'
    }, {
        name: 'Bart',
        email: 'bart@simpsons.com',
        phone: '555-222-1234',
        active: 'Y'
    }, {
        name: 'Homer',
        email: 'homer@simpsons.com',
        phone: '555-222-1244',
        active: 'N'
    }, {
        name: 'Marge',
        email: 'marge@simpsons.com',
        phone: '555-222-1254',
        active: 'Y'
    }]
});

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    height: 200,
    width: 400,
    renderTo: Ext.getBody(),
    store: store,
    columns: [{
        text: 'Name',
        dataIndex: 'name'
    }, {
        text: 'Email',
        dataIndex: 'email',
        flex: 1
    }, {
        text: 'Phone',
        dataIndex: 'phone'
    }, {
        editor: {
            xtype: 'checkbox',
            cls: 'x-grid-checkheader-editor',
            inputValue: 1,
            uncheckedValue: 0
        },
        text: 'Active',
        dataIndex: 'active',
        renderer: function (value, metadata, record, rowIndex, colIndex, store) {
            var tempVal = '',
                me = this;
            if (value === 'Y') {
                tempVal = 'checked';
            }
            return "<input name=" + record.get('id') + "_" + record.get('id') + " type='checkbox'" + tempVal + ">";
        }
    }],
    listeners: {
        cellclick: function (grid, td, cellIndex, record, tr, rowIndex, e, eOpts) {
            console.log(e);
            if (e.target.type && e.target.type === 'checkbox') {
                let checkVal = e.target.checked ? 'Y' : 'N';
                record.set('active', checkVal);
                console.log(record);
            }
        }
    }
});

Also you can check fiddle and on console you can check updated record.
Hope it help :)