text:
Q: 'this' is undefined inside an Object in javascript accessing property of object by another property Type= {
        Container: $get('ctl00_Main_rbtnlst_Type'),
        Local: this.Container.getElementsByTagName('input'),
        Foreign:this.Container.getElementsByTagName('input')
    }

when i ran through this code inside firebug console i get error 'this.Container' is undefined even though it is defined. How else can i access the Container property inside the Local and Foreign property. I even tried this.
Type= {
        Container: $get('ctl00_Main_rbtnlst_Type'),
        Local: Container.getElementsByTagName('input'),
        Foreign:Container.getElementsByTagName('input')
    }

A: You can't get this while instantiating. You can do:
Type= {
        Container: $get('ctl00_Main_rbtnlst_Type'),
        Local: function(){return this.Container.getElementsByTagName('input');},
        Foreign: function(){return this.Container.getElementsByTagName('input');}
    }

And later on get Local or Foreign using Type.Local()/Type.Foreign()
or use this reduntant pattern if you need Local/Foreign within the instance:
Type= {
            Container: $get('ctl00_Main_rbtnlst_Type'),
            Local: $get('ctl00_Main_rbtnlst_Type')
                     .getElementsByTagName('input');},
            Foreign: $get('ctl00_Main_rbtnlst_Type')
                      .getElementsByTagName('input');}
        }

Or use this immediately executed function:
var Type = (function(){
   var container = $get('ctl00_Main_rbtnlst_Type'),
       local = container.getElementsByTagName('input'),
       foreign = container.getElementsByTagName('input');
   return {
           Container: container,
           Local: local,
           Foreign: foreign
          }
})();

and to be complete, you can also use a few getters, but that won't work in all browsers (especially not in IE<9)
var Type = {
    Container: $get('ctl00_Main_rbtnlst_Type'),
    get Local() {return this.Container.getElementsByTagName('input');},
    get Foreign() {return this.Container.getElementsByTagName('input');}
}

note: Local and Foreign are the same, is that what you intended?

A: You can do this:
var container = $get('ctl00_Main_rbtnlst_Type');
Type = {
    Container: container,
    Local: container.getElementsByTagName('input'),
    Foreign: container.getElementsByTagName('input')
}

But what you probably want is this:
function Type(containerId){
    var container = $get(containerId);
    return {
        Container: container,
        Local: container.getElementsByTagName('input'),
        Foreign: container.getElementsByTagName('input')
    }
}

var obj = Type('ctl00_Main_rbtnlst_Type');
// can now use obj.Container, obj.Local and obj.Foreign


text:
Q: Spark - Make dataframe with multi column csv origin.csv
no,key1,key2,key3,key4,key5,...
1,A1,B1,C1,D1,E1,..
2,A2,B2,C2,D2,E2,..
3,A3,B3,C3,D3,E3,..

WhatIwant.csv
1,A1,key1
1,B1,key2
1,C1,key3
...
3,A3,key1
3,B3,key2
...

I loaded csv with read method(origin.csv dataframe), but unable to convert it.
val df = spark.read
            .option("header", true)
            .option("charset", "euc-kr")
            .csv(csvFilePath)

Any idea of this?

A: Try this.
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions._

val df = Seq((1,"A1","B1","C1","D1"), (2,"A2","B2","C2","D2"), (3,"A3","B3","C3","D2")).toDF("no", "key1", "key2","key3","key4")
df.show

def myUDF(df: DataFrame, by: Seq[String]): DataFrame = {
  val (columns, types) = df.dtypes.filter{ case (clm, _) => !by.contains(clm)}.unzip
  require(types.distinct.size == 1)
  val keys = explode(array(
    columns.map(clm => struct(lit(clm).alias("key"),col(clm).alias("val"))): _*
  ))
  val byValue = by.map(col(_))
  df.select(byValue :+ keys.alias("_key"): _*).select(byValue ++ Seq($"_key.val", $"_key.key"): _*)

}

val df1 = myUDF(df, Seq("no"))
df1.show

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display a ordered VIM keyboard mapping Is there any away to show a ordered list of all keyboard mappings of my current vim environment, like this:
a: append
b: back one word
c: ...
.
.
.

---- Ctrl mappings ----
<C-a> (I dont know...)
.
.
.
<C-p> Default mode for CrtlP
...

---- Alt mappings ----
...

This will be very useful for me.

A: :map and :verbose map show you a list of the mappings defined in your session, but they are not ordered like that. AFAIK, Vim doesn't provide such a nice formatting: you'll have to write a custom function for that, I'm afraid.
edit
Also, note that a, b and friends are not "mappings" in the sense that CtrlP's <C-p> is a mapping. :map won't show them at all.
So your idea, while interesting, is probably not something that can be done with a one liner. You could pull info from :h index, add the result of :map and try to arrange all of that in an order that makes sense to you but it doesn't seem to be a trivial task. It sounds like a perfect fit for a python/ruby/php script, doesn't it?
endedit

A: If you want a sorted, searchable list of your current mappings in which to look for unused keys, you can do the following:
function! s:ShowMaps()
  let old_reg = getreg("a")          " save the current content of register a
  let old_reg_type = getregtype("a") " save the type of the register as well
try
  redir @a                           " redirect output to register a
  " Get the list of all key mappings silently, satisfy "Press ENTER to continue"
  silent map | call feedkeys("\<CR>")
  redir END                          " end output redirection
  vnew                               " new buffer in vertical window
  put a                              " put content of register
  " Sort on 4th character column which is the key(s)
  %!sort -k1.4,1.4
finally                              " Execute even if exception is raised
  call setreg("a", old_reg, old_reg_type) " restore register a
endtry
endfunction
com! ShowMaps call s:ShowMaps()      " Enable :ShowMaps to call the function

nnoremap \m :ShowMaps<CR>            " Map keys to call the function

This is a robust function to create a vertical split with the sorted output of :maps. I put it in my vimrc.
The last line maps the two keys \m to call the function, change this as you wish.
Note: As @romainl mentions, this will will not include commands like i to insert text

A: You can also user the FZF Plugin which gives you the :Maps command which brings up the same information as :verbose map but in a pop up window that's fuzzy searchable. Its essentially the same as Tom Hales answer but an fzf version. I've mapped it to <leader>F1.


text:
Q: Why doesn't work .toSet() to create a Collection in Java? I want to create a Collection of values from properties for a specific key. The methods works this way:
Collection<String> getValueOfKey(final Collection<Localization> input, final String key) {
        return input.stream().map(l -> {
            return l.getProperties();
        }).map(p -> {
            return p.getProperty(key, "");
        }).collect(Collectors.toList());
    }

First I wanted to use Collectors.toSet() instead of Collectors.toList() but then I got wrong results (It just gave me the value from en).  Does anybody know why I can't use .toSet()?
Here is my TestCode:
public class RowCreatorTest {
private final Properties fixturePropertieDe = new Properties();
private final Properties fixturePropertieEn = new Properties();
private final Localization de = new Localization(Languages.GERMAN, fixturePropertieDe);
private final Localization en = new Localization(Languages.ENGLISH, fixturePropertieEn);

private final RowCreator sut = new RowCreator();

@Before
public void prepareFixtures() {
    fixturePropertieDe.put("key1", "foo1");
    fixturePropertieDe.put("key3", "foo3");

    fixturePropertieEn.put("key1", "bar1");
    fixturePropertieEn.put("key2", "bar2");
}

@Test
public void getValueOfKey() {
    assertThat(sut.getValueOfKey(Arrays.asList(de, en), "key1"), contains("foo1", "bar1"));
    assertThat(sut.getValueOfKey(Arrays.asList(de, en), "key2"), contains("", "bar2"));
    assertThat(sut.getValueOfKey(Arrays.asList(de, en), "key3"), contains("foo3", ""));
}

Here is a screenshot of what the test said: test screenshot

A: Based on the link to the error you posted (expected iterable containing ["foo1","bar1"] but item 0 was "bar1"), the assertion expected the two values to appear in the specified order (first "foo1", then "bar1"), but Sets don't maintain order, and "bar1" appeared first when iterating over the Set, so the assertion failed.
Hence the problem is in the assertion, not in the use of toSet().
You could force the Set to be iterated according to insertion order if, for example, you use a LinkedHashSet (replace toSet() with toCollection(LinkedHashSet::new)). This would ensure the assertion doesn't fail.


text:
Q: Сертификат для разных доменных адресов к одному серверу У меня есть сервер. Я для него купил домены. Одно имя, но разные доменные зоны - .ru и .online. Оба предоставлены с бонусным SSL сертификатом.
Сервер на Node.js:
const server = https.createServer({
    key: fs.readFileSync('./key.pem'),
    cert: fs.readFileSync('./cert.pem')
});

Если в key.pem и cert.pem у меня сертификат для домена .online. При попытке зайти на сайт через домен .ru браузер ругается, что сертификат не для того домена. Как обработать, какой сертификат клиенту давать?


text:
Q: Python3 Playsound Tkinter code not running in order expected I want to call a function (trigger) that will hide one image, show another image and play a sound. The sound has to play last as it lasts for several seconds locking everything up. When I call the function my alarm sound plays for several seconds then an image is shown showing which sensor has triggered (the original image does not hide not sure what I'm doing wrong there yet so commented out only dealing with one issue at a time).
First I searched my code for other uses of the word "trigger" to see if I was calling another function.
I put the image display line in brackets.
Added a 1 sec delay in between the image displaying and the sound playing.
Tried having my alarm sound in another function that is called by the image display function, so press button calls image display function, image display function calls play sound function.
Every time the sound plays and then when it finished the image shows. Whilst the sound is playing the program is locked up.
Button(root, text='Trigger Security', bg='#F0F8FF', font=('arial', 12, 'normal'), command=trigger).place(x=10, y=95)

def trigger():
    #canvas.create_image(260,-70, anchor=NW, image=bowstbradarm, state='hidden')
    canvas.create_image(260,-70, anchor=NW, image=bowstbradar, state='normal')
    playsound("tng_red_alert1.mp3")

Is it possible to run 2 functions at the same time so my program doesn't lock up?
I'm on ubuntu using IDLE if that helps at all.

A: It is because playsound() is a blocking function by default, so it blocks the tkinter mainloop from updating until the sound file is played completely.
You can execute playsound() in non-blocking mode by passing False as the second argument:
playsound("tng_red_alert1.mp3", False)

Update: As block=False is not supported in Linux, you need to use thread to execute playsound():
import threading
...

threading.Thread(target=playsound, args=("tng_red_alert1.mp3",)).start()


text:
Q: count number of tab characters in linux I want to count the numbers of hard tab characters in my documents in unix shell.
How can I do it?
I tried something like
grep -c \t foo
but it gives counts of t in file foo.

A: Use a perl regex (-P option) to grep tab characters.
So, to count the number of tab characters in a file:
grep -o -P '\t' foo | wc -l

A: You can insert a literal TAB character between the quotes with Ctrl+V+TAB.
In general you can insert any character at all by prefixing it with Ctrl+V; even control characters such as Enter or Ctrl+C that the shell would otherwise interpret.

A: Use tr to discard everything except tabs, and then count:
< input-file tr -dc \\t | wc -c

A: Bash uses a $'...' notation for specifying special characters:
grep -c $'\t' foo

A: You can use awk in a tricky way: use tab as the record separator, then the number of tab characters is the total number of records minus 1:
ntabs=$(awk 'BEGIN {RS="\t"} END {print NR-1}' foo)

A: My first thought was to use sed to strip out all non-tab characters, then use wc to count the number of characters left.
< foo.txt sed 's/[^\t]//g' | wc -c

However, this also counts newlines, which sed won't touch because it is line-based. So, let's use tr to translate all the newlines into spaces, so it is one line for sed.
< foo.txt tr '\n' ' ' | sed 's/[^\t]//g' | wc -c

Depending on your shell and implementation of sed, you may have to use a literal tab instead of \t, however, with Bash and GNU sed, the above works.


text:
Q: Stripe checkout , getting data after payment I have a stripe checkout that redirects the user to the default stripe checkout page on their side and when the payment is complete, it redirects to my website page. The problem is that i need to get some data from the payment and i read the docs and i cant figure out how to recieve that data.
I know that i have to place in the stripe checkout creation code, but i need to have some kind of function to recieve the data that i am passing.

 const stripe = await this.stripePromise;
 const { error } = await stripe.redirectToCheckout({

     mode: 'subscription',

     lineItems: [{ price: this.priceId, quantity: this.quantity }],

     clientReferenceId: this.userEmail,
     billingAddressCollection: this.userAdress,

     successUrl: `page`,
     cancelUrl: `page`,

   });

I am passing the  clientReferenceId and the billingAddressCollection, but how to recieve that on the success page?
Do i need to have some stripe function?

A: Listen to webhook events such as payment_intent.succeeded. Since you are using Checkout, listen to checkout.session.completed event.


text:
Q: How to fix an "overlap" or collision between multiple monitors? When I connect my Samsung SyncMaster SA300 to my laptop running Windows 7 64 bit, I get a weird behavior.
When the lid is closed, everything seems to work:

When the lid is open, there is a weird collision between the monitors. Only one monitor is identified, and it seems to be a "merge" of the two monitors.

I installed the latest drivers from Samsung's site and ran Windows update. What is causing this, and how to fix?
Update - now the screen is dark with a "check signal cable" box. The cable is connected, and nothing I do (reinstalling driver and playing with monitor's internal config didn't seem to fix it).

A: Clicking Windows-P and extending the desktop to the other monitor helped with the 'check signal cable'. I always forget to try this (even though it was right there in the Screen Resolution settings!).

A: Have you tried using your video card software to configure your view? usually ATI and Nvida have their own application that allows you configure your view and resolution etc... try using that instead of the windows version maybe that would correct this problem of yours.


text:
Q: how to read image file as data url using php In javascript, I read the file data by binding the on-change method to the file input and saving the file data into another input using the following code
$("#release_cover_custom").on('change', function (evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

        // Only process image files.
        if (!f.type.match('image.*')) {
            continue;
        }

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                $("#release_cover_custom_data").val(e.target.result);
            };
        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    }

});

why i use the above code?, to store the image data, because i have a form where i provide settings for the email template that would be sent later and there i have to provide the background image to be used inside the email, i need to preview the email with all the settings and along with the background image provided to upload before saving the form or uploading the image, so i read the image data, save it to an input and then open a modal window to preview email and post all the necessary variables there including the image data which is then used in the following way inside the css to apply the background-image like below in my php view file
background-image:url('" . $background_image . "') !important;
Now i want to do the achieve the same thing via php, means if i have the image saved to a path and i want to read the image data and use it in the same way i did using javascript to futher pass it to the css property,
i tried to use base64_encode(file_get_contents('path/to/file'))
but the encoding seems to be different for the image data, as the background image is not shown should i be using some other method to achieve it in php.

A: @quagaar reply (on the question) helped me solve the problem and replaced the following
$background_image=base64_encode(file_get_contents('/path/to/file'));

with
$background_image='data:image/png;base64,'.base64_encode(file_get_contents('/path/to/file'));

and everything works fine as expected.
EDIT:
between i was dealing with images only and if you are working with Images only and you need mime type (e.g. for headers, or like my case), then this is a fast and reliable technique:
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));

It will output true image mime type even if you rename your image file.


text:
Q: Kivy listview text alignment Is it possible to have dynamic text alignment with kivy listview?
I have a list of responses from a web lookup.
I would like to have the text alignment (left or center) of each list item depending on the quality of the response item.
I can't find a way to access 'halign' for each list item.

A: You can use your own item class, I think this is an option on the ListAdapter (maybe named cls). In doing so, you can add whatever logic you like to how the item is displayed.


text:
Q: How can I show the following statements are equivalent? Let $C ⊂ \mathbb{R}^n$
Prove that the following statements are equivalent.
(i) $C$ is an affine set
(ii) For every $x_0 ∈ C$ , the set $C − x_0 := \{ z − x_0: z ∈ C \}$ is a subspace.
(iii) There exists $x_0 ∈ C$ such that the set $ C − x_0$ is a subspace.
For $C$ to be an affine set contains the line through any two points $x_1, x_2$ in the set.
so (i) is defined as:  $x_1\lambda + (1-\lambda)x_2 ∈ C$ for $\lambda ∈ \mathbb{R}$
then for (ii) be a subspace, we must show it contains the 0 space and that its closed under multiplication and addition.
 Since by definition an affine set is closed for affine combinations whenever $x_0,x_1, \lambda ∈\mathbb{R}$ then is this sufficient to show the equivalence of (i) and (ii) ?

A: Hints:
The following lemmas are not quite difficult to prove and can be helpful.
Let $A\subseteq\mathbb R^n$. Then:

*

*$A$ is a subspace $\iff$ $A$ is affine and contains $\mathbf0$.

*$A$ is affine $\Rightarrow$ $\mathbf{u}+A$ is affine for every $\mathbf{u}\in\mathbb R^n$.


text:
Q: How to download data from an SQL-database and annotate an MT4-chart I have recently download the MetaTrader Terminal platform ( MT4 ).
I have my own back testing engine which stores some output in my SQL-server database. The output depends on the model I am testing. However, the output can just be as simple as the time of entry of a trade.
What I would like to know
Is it possible in MQL4 to download data from a SQL-server database and then annotate the chart with a simple "B" for a buy entry or "S" for a sell entry?
So I have run a back test simulation ( i.e. EURUSD from 2010 to 2011 ) and stored the time of the buy and sell entries. I would then like to go to my MetaTrader 4 platform and run a script which would download the time of all the buy and sell entries from my SQL-database and on my EURUSD chart label these XTO-s.

A: Yes, this is possible
MQL4 language, incl the "New"-MQL4 ( aka MQL4.5 ), has syntactical support for importing DLL-based services, that allow re-integration of tools, the closed-syntax of the MQL4 does not allow to gain in a more natural way.
//+------------------------------------------------------------------+  // msMOD(s) 2014  >>> [dev]_test_(python)_.PUB__(mql).SUB_with_KBD_and_SIG___StatefullGrammarFSA
//| Ver 4.00, Build 509                          [dev]__********.mq4 |  // msMOD(s) 2013
//+------------------------------------------------------------------+  //
#property copyright "[dev] msMOD(s) (c) 1987-2014"                      //
// ---------------------------------------------------------------------<#import>.start
#import  "msLIB_services.ex4"
         void  msLIB.aSnapshot.MAKE();
#import
// ---------------------------------------------------------------------<#import>.end
// ZMQ LIBRARY |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
#include <mql4zmq.mqh>                                                  // Include the libzmq.dll abstraction wrapper
// |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

This way your code, be it MQL4-Script or MQL4-ExpertAdvisor can communicate with external processes, incl. any reasonably working DBMS.
Beware
There are few important features a code-design and integration architecture should bear in mind. MQL4, since the earliest days, is not a plain sequential-processor, namely the MQL-CustomIndicator is by far distant from this paradigm. The code ( except for the case of MQL4-Script ) acts as an event-driven factory, that is initiated by asynchronous flow of incoming Market Events. User is responsible for all measures to not violate real-time stability of this Alpha&Omega principle-of-MQL4-principles. In other words, a poor design, that may get some I/O-blocking ( due to RDBMS processing et al ), will be most probably a reason for Trading Terminal crash(es), which is the last thing anybody is willing to experience ( be it in live-trading or back-testing phase ), isn't it?
So, a sound non-blocking, heterogenous, parallel multi-processing integration architecture & code-design is to be used for this task.
It works great, if done professionally
Keeping the said in mind allows very smart, fast and (almost) unlimited architectures to work together with Trading Terminal(s). Having multiple cases with near-real-time messaging between MT4/MQL4 code and AI/ML engine via python, fast FIX-Protocol streaming engine for real-time data input from Liquidity Pool provider, using a remote NVIDIA/GPU computation fabric, remote co-integrated IRC/skype/email Signal provisioning channels.
So a can do philosophy is in place. SQL is nothing extra in this sense. Puting labels is trivial in the same sense. Just of your imagination, MQL4 allows to build ( again, using a near-real-time design ) responsive/interactive GUI-layer, that allows, within a few [msec] stability barrier, work with the Trading Terminal in a pure-graphical manner ( long ago before a One-Click-Trading marketing tag came with just a click-To-Buy / click-To-Sell ) working fully interactively with line-controlled / graphical-objects visual trading aids, be it for a fully automated trade-execution ( with an indirect GUI-configuration of the rules-set ), or for an Augmented Trading style.

Yes, can make your MT4 Trading Terminal a sort of "remote-programmable charting display", driven not by FX-Market, but from a Cloud-processor, where your remote Strategy Testing Engine rulez ...


text:
Q: How to call constructor from Template Haskell I have function (let's call it mkSome) which constructs some data type with Template Haskell. It has typical signature Name -> Q [Dec].
Somewhere in its body I'm extracting constructors of another type with
pattern-matching:
case tyCons of
  DataD ctx nm tyVars mbKind cs derivs -> ...

Type of those constructors cs instantiates some class like this:
class MyClass a where
  specialValue :: a

So, I'm iterating over those cs but I want to skip one of them which is
equal to specialValue. Something like this:
[c | c <- cs, c /= specialValue]

Example:
data OtherData = A | B | C
instance MyClass OtherData where
  specialValue = C
$(mkSome ''OtherData) -- mkSome must skip C-constructor!

How to do this in Template Haskell's (with Con type: c is it) ? Sure, I can't simply call constructor to compare created value with a specialValue because it's AST node, not real constructor

A: It depends entirely on how you want to use this expression. You can write e.g.
mkCons :: Name -> Q Exp
mkCons ty = do
  TyConI (DataD ctx nm tyVars mbKind cs derivs) <- reify ty
  let cons = ListE $ map (\(NormalC c _) -> ConE c) cs
  [| [c | c <- $(pure cons), c /= specialValue] |]

which is a splice whose result is the constructors of ty except specialValue.
But if you want to manipulate the resulting list within the splice (e.g. generate some code for all constructors except specialValue) then the situation is much more complicated. You'll need to have a nested splice which manipulates the result of the above splice:
mkSome :: Name -> Q Exp
mkSome ty =
  [| do e1 <- mapM lift $(mkCons ty)
        let mkD (ConE n) = DataD [] (mkName $ "Foo" ++ nameBase n) [] Nothing [] [] -- example function
        pure $ map mkD e1
    |]

Note also the use of lift; the result of $(mkCons ty) has type [OtherData] (in this case) but lift gives you the TH AST corresponding to those constructors.
Also note that the functions above use the Eq, Lift and MyClass instances of the given type. Due to the stage restriction, you have to define these instances in a seperate module than the use of the splice. So the following won't work:
module A where

import TH (mkSome)

data OtherData = A | B | C deriving (Lift, Eq)
instance MyClass OtherData where
  specialValue = C

$( $(mkSome ''OtherData) )

You must use it like so:
-- A.hs
module A where

data OtherData = A | B | C deriving (Lift, Eq)
instance MyClass OtherData where
  specialValue = C

-- B.hs
module B where

import TH (mkSome)
import A

$( $(mkSome ''OtherData) )

The result:
    mkSome ''OtherData
  ======>
    do { e1_adJ0 <- mapM
                      lift [c_adJ2 | c_adJ2 <- [A, B, C], (c_adJ2 /= specialValue)];
         let mkD_adJ1 (ConE n_adJ3)
               = DataD
                   [] (mkName $ ("Foo" ++ (nameBase n_adJ3))) [] Nothing [] [];
         (pure $ (map mkD_adJ1 e1_adJ0)) }

    (do { e1_adJ0 <- mapM
                       lift [c_adJ2 | c_adJ2 <- [A, B, C], (c_adJ2 /= specialValue)];
          let mkD_adJ1 (ConE n_adJ3)
                = DataD
                    [] (mkName $ ("Foo" ++ (nameBase n_adJ3))) [] Nothing [] [];
          (pure $ (map mkD_adJ1 e1_adJ0)) })
  ======>
    data FooA
    data FooB


text:
Q: Number of zero entries in symmetric (0-1)-matrix with full diagonal Let $S$ be an $n\times n$ symmetric matrix whose diagonal consists only of $1$s and whose other entries are either $0$ or $1$ .
If the determinant and rank of $S$ are known, what can be said about the number of zero entries in $S$ ?

A: I'm thinking, not a lot.
Suppose $S$ is $10\times10$ with determinant zero and rank 5. $S$ could have a $6\times6$ matrix of all-ones in the upper left corner, no other ones except the 4 on the diagonal, for 40 ones and 60 zeros.
Or, it could have $2\times2$ squares of ones down the diagonal, zero everywhere else, 20 ones and 80 zeros.
Rank 3, you could have a zero in the upper right corner and one in the lower left, or three blocks of ones on the diagonal, so anywhere from 2 zeros to $100-16-9-9=66$ zeros.
Seems like there's a lot of wiggle room.
EDIT: Similar example with nonzero determinant: if $n$ is even, then the matrix that is all ones except for having zeros down the "other" diagonal has determinant $n-1$. So for example the $4\times4$ has 12 ones, 4 zeros, and determinant 3; the $28\times28$ has 756 ones, 28 zeros, and determinant 27. Now make a $28\times28$ matrix that has three of the $4\times4$ matrices along the diagonal, ones down the rest of the diagonal, zeros everywhere else. It also has determinant 27, but only 52 ones, and 732 zeros.


text:
Q: Symfony/Doctrine inserts null as foreign key in many to one relationship I have two entities, League and Club, and predictably a League can have many Clubs. Just to test things out I'm trying to insert a club called test into the league with an ID of 1 (which does exist in the database, that's not the problem). If I do the following then it works fine:
$club = new Club();
$club->setName("test");
$league = $this->getDoctrine()->getRepository("AppBundle:League")->find(1);
$club->setLeague($league);
$em->persist($club);
$em->persist($league);
$em->flush();

However, if I alter the fourth line to $league->addClub($club); then it inserts a null value as the league_id in the database.
I have the following code for the Club entity:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Club
 *
 * @ORM\Table(name="club")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ClubRepository")
 */
class Club
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="League", inversedBy="clubs")
     * @ORM\JoinColumn(name="league_id", referencedColumnName="id")
     */
    private $league;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Club
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set league
     *
     * @param \AppBundle\Entity\League $league
     *
     * @return Club
     */
    public function setLeague(\AppBundle\Entity\League $league = null)
    {
        $this->league = $league;

        return $this;
    }

    /**
     * Get league
     *
     * @return \AppBundle\Entity\League
     */
    public function getLeague()
    {
        return $this->league;
    }
}

and the following for the League entity:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * League
 *
 * @ORM\Table(name="league")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\LeagueRepository")
 */
class League
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="Club", mappedBy="league")
     */
    private $clubs;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return League
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->clubs = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add club
     *
     * @param \AppBundle\Entity\Club $club
     *
     * @return League
     */
    public function addClub(\AppBundle\Entity\Club $club)
    {
        $this->clubs[] = $club;

        return $this;
    }

    /**
     * Remove club
     *
     * @param \AppBundle\Entity\Club $club
     */
    public function removeClub(\AppBundle\Entity\Club $club)
    {
        $this->clubs->removeElement($club);
    }

    /**
     * Get clubs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getClubs()
    {
        return $this->clubs;
    }
}

I've checked that the database schema is up to data with doctrine:schema:update, and I've tried seemingly every combination of persisting and flushing... persisting the club before the league, persisting the league before the club, persisting just the league, persisting just the club, persisting the league then flushing then persisting the club then flushing again... Nothing has worked.

A: The problem comes from your addClub()method. When you add a club in the league, you have to tell the club in which league it's being added.
Your method should look like this
public function addClub(Club $club)
{
    $this-cubs[] = $club;
    $club->setLeague($this); // <-- there, tell the club in which league it is

    return $this;
}

A:
Doctrine will only check the owning side of an association for changes.
  http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/unitofwork-associations.html

You can cascade changes to the owning side like this
// AppBundle\Entity\League.php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * League
 *
 * @ORM\Table(name="league")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\LeagueRepository")
 */
class League
{

    // ...

    /**
     * Add club
     *
     * @param \AppBundle\Entity\Club $club
     *
     * @return League
     */
    public function addClub(\AppBundle\Entity\Club $club)
    {
        $this->clubs[] = $club;
        $club->setLeague($this);

        return $this;
    }

    // ...
}


text:
Q: Incorrect value - Looping Servicecalls in Angular I'm trying to get value of this.totalbuilds_overview_jaas which will update after every service call. Below is the code
constructor(private dataservice: CicdDashboardApiService) {   }

  calculating_jaas_builds_count(){
     var counter:number = 0;
    console.log("calculating jaas total builds..")
    this.jaasclients.forEach(element => {
      this.dataservice.getTotalBuildCounts_jaas(element.url,element.token).subscribe((response: TotalBuilds[]) => {
      counter = this.total_getObject_jaas(response['jobs'])
      this.totalbuilds_overview_jaas += counter
     },err => console.log(err))
    })
  }

The problem is - this.totalbuilds_overview_jaas not giving constant value. It keeps varying when I reload the application. How can I make necessary changes to load this.totalbuilds_overview_jaas only after completing the loop.
*this.total_getObject_jaas(response['jobs']) => returns some number

A: The problem is likely that you don't really know when the calls to CicdDashboardApiService will actually be complete at the time of retrieving this.totalbuilds_overview_jaas because calculating_jaas_builds_count() is actually asynchronous.
You need to wait for all the service requests to complete before you can get the total count. One way of doing it is simply with promises:
  async calculating_jaas_builds_count() {
    console.log("calculating jaas total builds..");

    // Execute a data service request for each of the clients
    const promises = this.jaasclients.map(element =>
      this.dataservice
        .getTotalBuildCounts_jaas(element.url, element.token)
        .pipe(take(1))
        .toPromise()
    );

    // Wait for all requests to complete
    const responses = await Promise.all(promises);

    // Process each of the service responses and collect the jobs
    for (const response of responses) {
      this.totalbuilds_overview_jaas += response["jobs"];
    }
  }

You can then await this method and only then you can get the total count:
await calculating_jaas_builds_count();
console.log('total count', this.totalbuilds_overview_jaas)

I'm not 100% sure about the structure of your service response because your typings say the response is an array of TotalBuilds, but on the next line you say response['jobs'], which seems like a mistake in itself. In any case, hope you get the idea.


text:
Q: Excel VBA For Loop Error I'm trying to run a simple For loop which will be expanded to include more functionality later but having trouble as it keeps throwing an error "invalid next control variable reference". The code I am trying to use is listed below.
Sub Tickbox()

Set Location = Sheets("TickBoxSheet").Range("B:B")

i = WorksheetFunction.CountA(Location)

Sheets("TickBoxSheet").Range("B2").Select

For a = 1 To i
    If Selection.Value = "True" Then
        Row = Selection.Row
        'Hide some rows in another sheet via if statements

        ActiveCell.Offset(1, 0).Select
    End If
Next i

End Sub

I don't know if I need more coffee this morning but I can't seem to figure out what the hell is going on. Any help will be greatly appreciated.

A: The incremented variable (in Next) should be the index variable, i.e.:
For a = 1 To i
  '...
Next a

i is so popular as index that you should think twice before using it in other contexts.

A: You have already got your answer from llmo. However there are few other things I would like to stress upon...
Try and avoid .Select. It will slow down your code.
Also It is not necessary that WorksheetFunction.CountA(Location) will give you the last row considering that you want to loop through all the rows which have data. I suggest this
Sub Tickbox()
    Dim i As Long, a As Long, Rw As Long

    With Sheets("TickBoxSheet")
        i = .Range("B" & .Rows.Count).End(xlUp).row

        For a = 2 To i
            If .Range("B" & a).Value = "True" Then
                Rw = a
                'Hide some rows in another sheet via if statements
            End If
        Next a
    End With
End Sub

You can make it more fast using Autofilter as well so that you loop through cells which only have True For example
Sub Tickbox()
    Dim i As Long, a As Long, Rw As Long
    Dim Location As Range, acell As Range

    With Sheets("TickBoxSheet")
        '~~> Remove any filters
        .AutoFilterMode = False

        i = .Range("B" & .Rows.Count).End(xlUp).row

        With .Range("B1:B" & i)
            .AutoFilter Field:=1, Criteria1:="True"
            Set Location = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
            Debug.Print Location.Address
        End With

        '~~> Remove any filters
        .AutoFilterMode = False

        For Each acell In Location
            If acell.Value = "TRUE" Then
                Rw = acell.row
                'Hide some rows in another sheet via if statements
            End If
        Next acell
    End With
End Sub


text:
Q: Number of trits matching count criteria For all trinary numbers with length 36 (including those starting with
0's), how many have exactly equal counts of 1's and 2's, or exactly one
more 1 than 2?
For example:

*

*00 - yes

*01 - yes

*02 - no

*10 - yes

*11 - no

*12 - yes

*20 - no

*21 - yes

*22 - no

So for all trinary numbers of length 2, 5 out of 9 possibilities match.
This presumably gets smaller as the length increases.  For length 3, there
are 13 out of 27.
If we were dealing with binary numbers, there are a number of solutions available here but it isn't clear to me how to generalise these to trinary numbers.

A: The process seems straightforward enough as a combinatorial exercise.  For every N in [1..18], find all the different arrangements of "1" in a 36-place tritstring.  Then multiply that by the number of different arrangements of N "2"s in the positions not taken by a "1", and also for N-1 "2"s.  Find the sum of those 36 numbers.  After all that, add 1 for N=0, that being a tritstring of all "0"s.
The number of different arrangements of N trits in a 36-long tritstring should be
36! / N!(36-N)!

The problem sounds like a brainteaser.  I haven't developed the above further, but I highly suspect the presence of shortcuts.

A: A friend of mine gave me the following answer, and he knows more math than I do.  I have marked this as 'community' because it is not my work.
You would need to know the number of ways for every (most?)
combination, not just equal 1s/2s.  EG you can put together +18 and
-18 to get an equal number of 1s and 2s
18
0/0
0/1
...
0/18
1/0
1/1
...
1/17
...
18/0

Solving directly seems much easier.
0/0
1/0
1/1
2/1
2/2
3/2
3/3
...
18/17
18/18

Do the combinatorics
0/0 = 1 way
1/0 = (36C1) = 36 possibilities
1/1 = (36C1) * (36-1C1) = 1260 possibilities
2/1 = (36C2) * (36-2C1) = 21420
2/2 = (36C2) * (36-2C2) = 353430
3/2 = (36C3) * (36-3C2) = 3769920
3/3 = (36C3) * (36-3C3) = 38955840
4/3
4/4
5/4
5/4

18/17 = (36C18) * (36-18C17) = 163352435400
18/18 = (36C18) * (36-18C18) = 9075135300

Perl script to print out lines for bc, because I'm too lazy to write
code that balances the multiplications and divisions nicely.
sub print_choose
{
    $n = $_[ 0 ];
    $c = $_[ 1 ];

    if( $c == 0 ) { print "1"; return; }

    for( $j = 0; $j < $c; ++$j ) {
        if( $j ) { print "*"; }
        print $n - $j;
    }
    for( $j = 0; $j < $c; ++$j ) {
        print "/", $c - $j;
    }
}

for( $i = 0; $i <= 18; ++$i ) {
    if( $i > 0 ) {
        print_choose( 36, $i );
        print "*";
        print_choose( 36 - $i, $i - 1 );
        print "\n";
    }

    print_choose( 36, $i );
    print "*";
    print_choose( 36 - $i, $i );
    print "\n";
}

foo.pl | bc | perl -ne '$sum += $_; print "$sum\n"'
1
37
1297
22717
376147
4146067
43101907
335270707
2453494507
14315547787
78370635499
355942682251
1512492877051
5477807830651
18506699821051
54336152794651
148388466850351
357393609196351
798626687482351
1592846228397151
2943019447952311
4906907767305271
7584937293695671
10709305074484471
14094036837005671
17218404617794471
19862100432308071
21750454585532071
22964396541176071
23611832250852871
23913968915368711
24027270164562151
24062676804935101
24071007779140501
24072477951059101
24072641303494501
24072650378629801


text:
Q: JNI DETECTED ERROR IN APPLICATION: use of deleted weak global reference JNI file looks like,
#include <jni.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/face.hpp>
#include <opencv2/core/utility.hpp>
#include <vector>
#include <opencv2/highgui.hpp>

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

#include <fstream>
#include <sstream>
#include <map>

#include <android/log.h>

#define LOG_TAG "Opencv3_test"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

using namespace std;
using namespace cv;
using namespace cv::face;

extern "C" {

JNIEXPORT void JNICALL Java_com_opencv_test_FaceRecognizer_train
        (JNIEnv *, jobject, jlongArray, jintArray);

JNIEXPORT void JNICALL Java_com_opencv_test_FaceRecognizer_predict
        (JNIEnv *, jobject, long, jintArray, jdoubleArray);

Ptr<LBPHFaceRecognizer> model;

JNIEXPORT void JNICALL Java_com_opencv_test_FaceRecognizer_train
        (JNIEnv *env, jobject thisObj, jlongArray images1, jintArray labels1) {
    model = LBPHFaceRecognizer::create();

    jsize length = (*env).GetArrayLength(images1);
    jlong *mats = (*env).GetLongArrayElements(images1, 0);
    jint *matLabels = (*env).GetIntArrayElements(labels1, 0);

    if (length > 0) {
        vector<Mat> images;
        vector<int> labels;
        for (int i = 0; i < length; i++) {
            Mat &mGr = *(Mat *) mats[i];
            images.push_back(mGr);
            labels.push_back(matLabels[i]);
            mGr.release();
        }
        model->train(images, labels);
        images.clear();
        labels.clear();
    }
    (*env).ReleaseLongArrayElements(images1, mats, 0);
    (*env).ReleaseIntArrayElements(labels1, matLabels, 0);
}

JNIEXPORT void JNICALL Java_com_opencv_test_FaceRecognizer_predict
        (JNIEnv *env, jobject thisObj, long images1, jintArray label, jdoubleArray confidence) {
    Mat &mGr = *(Mat *) images1;
    jint *labelBody = (*env).GetIntArrayElements(label, 0);
    jdouble *confidenceBody = (*env).GetDoubleArrayElements(confidence, 0);
    int &myLabel = labelBody[0];
    double &myConfidence = confidenceBody[0];
    LOGD("Prediction started in JNI");
    model->predict(mGr, myLabel, myConfidence);
    LOGD("Prediction ended in JNI");
    (*env).ReleaseIntArrayElements(label, labelBody, 0);
    (*env).ReleaseDoubleArrayElements(confidence, confidenceBody, 0);
}
}

FaceRecognizer.java looks like
public class FaceRecognizer {

    private static final String TAG = FaceRecognizer.class.getSimpleName();

    public FaceRecognizer() {
    }

    public void predict(Mat mGrey, int[] label, double[] confidence) {
        predict(mGrey.getNativeObjAddr(), label, confidence);
    }

    public boolean train() {
        File root = new File(activity.getFilesDir().getAbsolutePath() + "/" + TRAIN.name() + "/");

        FilenameFilter pngFilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".jpg");

            }
        };

        File[] imageFiles = root.listFiles(pngFilter);
        long[] mats = new long[imageFiles.length];
        int[] IDs = new int[imageFiles.length];
        int counter = 0;
        for (File file : imageFiles) {
            Log.v(TAG, file.getAbsolutePath());
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            if (bitmap != null) {
                Bitmap bmp32 = bitmap.copy(Bitmap.Config.ARGB_8888, true);
                Mat b = new Mat(bmp32.getWidth(), bmp32.getHeight(), CvType.CV_8UC1);
                Utils.bitmapToMat(bmp32, b);
                Imgproc.cvtColor(b, b, Imgproc.COLOR_RGB2GRAY);
                int id = Integer.parseInt(file.getAbsolutePath().split("_")[1]);
                Log.v(TAG, "id : " + id);
                mats[counter] = b.getNativeObjAddr();
                IDs[counter] = id;
                counter++;
            }
        }
        train(mats, IDs);
        return true;
    }

    public native void train(long[] mats, int[] label);

    public native void predict(long mats, int[] integer, double[] d);
}

But when I am trying predict, app crashes with following logcat error.

JNI DETECTED ERROR IN APPLICATION: use of deleted weak global
  reference 0xffffffff from void
  com.opencv_test_FaceRecognizer.predict(long, int[],
  double[])

A: This happens because native method path is
Java_com_opencv_test_FaceRecognizer_predict
->com.opencv.test.FaceRecognizer#predict but this class path is com.idesign.opencvmaketest.FaceRecognizer


text:
Q: Differences between C++ and Java compilation process I have high level idea on the differences between C++ and Java compilation. But, I want to really understand and dive deep. can you suggest any references or blogs ?

A: Maybe this can bring some light on the subject
Java:

C++:


text:
Q: Creating new layer out of features selected using expression, in QGIS? I have lots of points representing buildings, scattered on top of polygons representing output areas of a city. I'd like to select only those points that have a certain descriptor in their database, and make a new layer with them.
This is done a number of times with a view to then counting how many buildings of each category are in each output area. I think I'm going to use a spatial join for that.

A: You almost described the steps necessary to create the new layer:
Open the attribute table for the point layer and choose the option 'Select features using an expression'. In the new window you can enter an expression like "column_name" = 100 (or choose the wanted column from "Fields and Values") and press Select.
After that right-click on the layer and choose "Save As...". Make sure that you select the "Save only selected features" in the save dialog.
For the calculation of the number of buildings inside the output areas have a look at the "Count points in polygon function" from the vector tools.

A: If you're going to do this often, you could also consider making a model from the Processing Toolbox which would automatically select features based on an expression you provide and save the selected features in one go:


text:
Q: Sql Server FileTable drawbacks I'm looking at using File Tables instead of simply storing the file as binary data in the database, or storing a column in the database that contains a URL to a file share. Our apps use Entity Framework, so that's one minor snag that I see, but one that can pretty easily be worked around. Another is that, from what I can tell, the files must be stored on the same server as the database in a folder path such as "MachineName\InstanceName\FileShare" (Can this be configured so that the folder can exist on another server?).
Are there any additional drawbacks to using FileTables?

A: As for filetable drawbacks, aside from the slightly fiddly setup required to get them going, the only thing I can think of is that if your BLOBs are less than 1Mb in size, the documentation suggests that storing them in the database rather than on the filesystem will give better performance.
With regards to putting the filestream filegroup on a network share, this won't work.  One of the common misconceptions with filestream/filetable is that the fileshare that is created is just a normal windows fileshare like any other.  It is not, the files are stored in a special location on the filesystem called an NTFS data container, they are then presented to the outside world via the NTFS streaming APIs as a fileshare.  The files have to be local to the machine because those NTFS APIs do not work over UNC.
The only way you can really make it work on a different machine is to use an iSCSI drive so that the NTFS APIs will still work, but the files are physically on the other machine.


text:
Q: objective c: Moving view up when keyboard appears if textfield or textview is clicked I'm trying to get my view to move up when a certain textField or textview is selected instead of every textfield i have. The view has 4 textfields and one textview. I want ONLY the 4th textfield and the textview to move up when the keyboard is being activated. (since the keyboard covers the textfield and textview)
I've tried many suggestions given here, however none of them work for me.
I found an example (https://stackoverflow.com/a/21257034/5292561) of how i want it to look like, however when clicking on every textfield the view moves up rather than when i click only the 4th textfield or textview.
NOTE: I want to AVOID using scrollview since i don't like how it's being used. I've read negative things about it.
I'm still trying to learn so please bear with me.
Thanks in advance
Here is the code for the textField and Textview i want to move up when clicking on the textfield and textview:
//dienstPicker input and styling

self.dienstPicker = [[UIPickerView alloc] init];
self.dienstPicker.delegate = self;
self.dienstPicker.dataSource = self;
self.dienstPicker.showsSelectionIndicator = YES;

[self.dienstPicker selectRow:1 inComponent:0 animated:YES];
//UITextField *textfield = [UIResponder currentFirstResponder];
[self.dienstTextField setInputView:_dienstPicker];
UIToolbar *toolBar2=[[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, 320, 44)];
[toolBar2 setTintColor:[UIColor grayColor]];
UIBarButtonItem *doneBtn2=[[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                           style:UIBarButtonItemStylePlain
                                                          target:self
                                                          action:@selector(ShowSelectedOption2)];

UIBarButtonItem *space2= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil
                                                                       action:nil];
[toolBar2 setItems:[NSArray arrayWithObjects:space2, doneBtn2, nil]];
[self.dienstTextField setInputAccessoryView:toolBar2];

self.dienstArray = @[@"test1",@"test2"];

    self.omschrijvingTextView.delegate = self;
    self.omschrijvingTextView.layer.borderWidth = 1.0f;
    self.omschrijvingTextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];

UIToolbar *toolBar4=[[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, 320, 44)];
[toolBar4 setTintColor:[UIColor grayColor]];
UIBarButtonItem *doneBtn4=[[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                           style:UIBarButtonItemStylePlain
                                                          target:self
                                                          action:@selector(ShowDescription)];
UIBarButtonItem *space4= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil
                                                                       action:nil];
[toolBar4 setItems:[NSArray arrayWithObjects:space4, doneBtn4, nil]];
[self.omschrijvingTextView setInputAccessoryView:toolBar4];

CGRect textViewFrame = CGRectMake(0, 0, 320, 44);
UITextView *omschrijvingTextView = [[UITextView alloc] initWithFrame:textViewFrame];
omschrijvingTextView.returnKeyType = UIReturnKeyDone;

pragma mark - UIPickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if ([pickerView isEqual: _dienstPicker]){
        return [self.dienstArray count];
    } else if ([pickerView isEqual: _projectPicker]){
        return [self.projectArray count];
    } else return 0;
}

pragma mark - UIPickerViewDelegate
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if ([pickerView isEqual: _dienstPicker]){
        return self.dienstArray[row];
    } else if ([pickerView isEqual: _projectPicker]){
        return self.projectArray[row];
    } else return 0;
}

-(void)pickerView:(UIPickerView *)pickerView selectRow:(NSInteger)row inComponent:(NSInteger)component {
    if ([pickerView isEqual: _dienstPicker]){
        self.dienstTextField.text = self.dienstArray[row];
    } else if ([pickerView isEqual: _projectPicker]){
        self.projectTextField.text = self.projectArray[row];
    }
}

A: in your Viewcontroller.h
@interface ViewController : UIViewController<UITextFieldDelegate,UITextViewDelegate>
{
 CGFloat animatedDistance;

 }

in ViewController.M
paste the below 4 line in anywhere on the class (outside the method)
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

in delegate methods are
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
  if(textField.tag==3) //textFieldFirst.tag =0,textFieldSecond.tag=1,textFieldThree.tag=2,textFieldFour.tag=3
  {
    CGRect textFieldRect =
    [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect =
    [self.view.window convertRect:self.view.bounds fromView:self.view];

    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator =
midline - viewRect.origin.y
- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =
(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
* viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
    {
       heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
       heightFraction = 1.0;
    }

    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];
 }
}

- (void)textFieldDidEndEditing:(UITextField *)textField

{
   if(textField.tag==3)
   {
     CGRect viewFrame = self.view.frame;
     viewFrame.origin.y += animatedDistance;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];
   }

 }

-(void)textViewDidBeginEditing:(UITextField *)textView
{
  CGRect textViewRect =
  [self.view.window convertRect:textView.bounds fromView:textView];
  CGRect viewRect =
  [self.view.window convertRect:self.view.bounds fromView:self.view];
  CGFloat midline = textViewRect.origin.y + 0.5 * textViewRect.size.height;
  CGFloat numerator =
midline - viewRect.origin.y
- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
  CGFloat denominator =
(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
* viewRect.size.height;
  CGFloat heightFraction = numerator / denominator;
  if (heightFraction < 0.0)
  {
    heightFraction = 0.0;
  }
  else if (heightFraction > 1.0)
  {
    heightFraction = 1.0;
  }
  animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
  CGRect viewFrame = self.view.frame;
  viewFrame.origin.y -= animatedDistance;
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationBeginsFromCurrentState:YES];
  [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
  [self.view setFrame:viewFrame];
  [UIView commitAnimations];
}

- (void)textViewDidEndEditing:(UITextField *)textView
{
  CGRect viewFrame = self.view.frame;
  viewFrame.origin.y += animatedDistance;
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationBeginsFromCurrentState:YES];
  [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
  [self.view setFrame:viewFrame];
  [UIView commitAnimations];
}

A: If you have implemented your textfields in scroll view and move them up like apple suggets when managing content with keyboard. You can assign tag to the text fields and execute the scroll movement when specific textfield is clicked by checking the tag of the text field. Hope this helps

A: There are many approaches to achieve that. One simple approach can be assign tags to each textField and than in delegate method
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
   Int *tagId = textView.tag;
if (tagId == "TAG OF YOUR TEXTFIELD") {
    // Move View up
    return YES;
 }
  return NO;
}
//Also Move your view down in textViewShouldEndEditing method.

A: *

*If you are using storyboard, put all your textfields in a ScrollView and use this code on your ViewController.m

*Don't forget to set the textfields delegates to the ViewController (via storyboard or via code on ViewDidLoad

-(void)textFieldDidBeginEditing:(UITextField *)textFieldView {
if (textFieldView == self.myTextField)
    {
        CGPoint scrollPoint = CGPointMake(0.0, self.myTextField.frame.origin.y - self.myTextField.frame.size.height/2);
        [myScrollView setContentOffset:scrollPoint animated:YES];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (textField == self.myTextField)
    {
         CGPoint scrollPoint;
         [_email resignFirstResponder];
         scrollPoint = CGPointZero;
         [myScrollView setContentOffset:scrollPoint animated:YES];
    }
    return YES;
}


text:
Q: Как заблокировать вызовы JS из Console? Насмотревшись на Facebok, решил блокировать вызов JS функций из консоли:

На данный момент я вывожу заглушку об использовании консоли и переопределил:
 console = new Object();

Тем самым заблокировал использования любых log-ов.
Вопрос состоит в следующем:
Можно ли как то отслеживать ввод команд в консоль, либо заблокировать совсем?

A: Ранее это было возможно только в обозревателях сети, основанных на Chrome. Но сейчас разработчики Chrome эту возможность отключили.
Об этом сообщил инженер по безопасности в Facebook (на английском). В своём ответе он вкратце описал как он это делал.
Также один из пользователей сообщил там о том как это было ранее сделано на Facebook (на английском). Подробное описание.
Тем не менее существует возможность просто напугать пользователя, выводя цветные записи в console.  К примеру так:
console.log('%cОстановитесь!\nВыполнив действия в console ваша учётная запись окажется в чёрном списке!', 'color:#f00;font:bold 26px "Courier New";background-color:#000;padding:16px;padding:50px 500px');


text:
Q: Warning when combining textgreek and hyperref package I am trying to include Greek letters into a section title. The MWE below produces the output desired, but also the warning

Glyph not defined in PD1 encoding,(hyperref) removing `\textalpha'

and the same for \textgamma but interestingly not for \textbeta. Obviously hyperref is causing the problem, however it is required.

\usepackage{textgreek}
\usepackage{hyperref}

\begin{document}
\section{\textalpha\textbeta\textgamma}
\end{document}

A: Use the unicode option:
\documentclass{article}
\usepackage{textgreek}
\usepackage[unicode]{hyperref}

\begin{document}
\section{\textalpha\textbeta\textgamma}
\end{document}


text:
Q: Entity Framework sets foreign key to null during saving I have workflow like this:
using dataContext
{
  load entity
  int? previousFr = entity.FrSomething
  entity.FrSomething = null
  entity.FrSomething = previousFr
  save entity
}

during save entity.FrSomething becomes null and null value is saved to database
this is call stack between dataContext.SaveChanges() and FrSomething property setter

UPD: It's Entity framework 4, self-tracking template. I have entity Product and combobox with product Categories. I load Product for edit and list of Categories to fill combo. Product initially has some category specified, and corresponding navigation property is set during EF fixup. Then I select none-category in combobox (FrCategory = null), then select previous one which product had initially. If after selecting none category I select other then initial one, issue is not reproduced. if I change category with Product.Category property instead of Product.FrCategory, issue is not reproduced as well.
Any help will be greatly appreciated.
Thank you.


text:
Q: How does Wireshark identify a TCP packet's protocol as HTTP? Port number equals to 80 is obviously not a sufficient condition. Is it a necessary condition that Wireshark has found a request message or response message in application layer payload?

A: I'm not sure this is a full answer, but here is what I know regarding Wireshark's identification of HTTP packets (all items below are dissected as HTTP):

*

*TCP port 80

*TCP or UDP ports 8080, 8008, 591

*TCP traffic (on all ports) that has line end (CRLF) and the line begins or ends with the string "HTTP/1.1"

*SSDP (Simple Service Discovery Protocol) in TCP or UDP port 1900

*DAAP (Apple's Digital Audio Access Protocol) in TCP port 3689

*IPP (Internet Printing Protocol) in TCP port 631


text:
Q: Possible to change UISlider's button size in iOS5? Time for another iOS question.
Just wondering if it is possible programmatically to change the radius of the slider's control button. I want to make the control bigger or smaller to represent the brush size that it is selecting.
Thanks!

A: From the docs:
Assigns a thumb image to the specified control states:
- (void)setThumbImage:(UIImage *)image forState:(UIControlState)state


text:
Q: add background color to a div when radio button is checked using css I have a radio button and I need to add a style to its parent div when the radio button is checked. This I need to do only with css. In the below html, if the radio is checked, i need to apply a color to the div "options"
HTML

        <input type="radio" name="payMethod" id="payMethod1" value="aaa" >

I tried the below approaches but its not coming correctly
.options input[type="radio"]:checked span{
background-color:black;
}

.options input[type="radio"]:checked div.options{
background-color:black;
}

could somebody please help me on this

A: Sorry, can't do that yet. You can only go down the tree, not up it. You will either need to make the elements you want to style siblings or descendents of the radio button. Ancestor selectors do not yet exist:
http://css-tricks.com/parent-selectors-in-css/

A: <input type="radio" name="payMethod" id="payMethod1" value="aaa" />

css
input[type='radio']:checked + div.options {
  background-color:green;
}
input[type='radio']:checked + div.options span {
  background-color:red;
}

A: That would require using parent selectors from CSS4 http://www.w3.org/TR/selectors4/ Unfortunately CSS4 is not yet available. So for today it is not possible to do that using pure css.

A: Javascript is your answer. Provided Vanilla and jQuery examples.
var payMethod = document.querySelector('#payMethod1');

payMethod.onchange = function() {
    alert('clicked')
    // Get span and div
    if(this.checked) {
        var elements = document.querySelectorAll('.option_radio, .options');

        // Loop elements & add class
        for(var i = 0; i < elements.length; i++) {
            if (elements[i].classList)
              elements[i].classList.add("checked");
            else
              elements[i].className += ' checked';
        }
    }
};

//jQuery implementation
$('#payMethod1').change(function() {
   if($(this).is(':checked')) {
       $('.option_radio, .options').addClass('checked');
   }
});


text:
Q: Is the doc wrong about interpreting \xhh This is from the main TCL doc:
\xhh   The hexadecimal digits hh give an eight-bit hexadecimal value for the
Unicode character that will be inserted. Any number of hexadecimal digits may be
present; however, **all but the last two are ignored** (the result is always a
one-byte quantity).

My doubt is this part, all but the last two are ignored. Here is my experiment:
>set a "\x22"
"
>set a "\x2230"
"30

So you can see that it is the first 2 hexadecimal digits are taken and the rest are just treated as plain char.
Do I miss something?
[EDIT] Looks like I am right, here is from parser.c of tcl8.6:
 860     case 'x':
 861         count += TclParseHex(p+1, (numBytes > 3) ? 2 : numBytes-2, &result);

So only the first immediate 2 digits are taken. Weird, how come nobody finds this doc error.

A: This is a place where the behaviour changed from Tcl 8.5 (and before) to 8.6. It was a bug fix because the old behaviour was so damn weird that nobody ever expected it. (Or the Spanish Inquisition, but I digress…)
In 8.6, the documentation says:

\xhh
  The hexadecimal digits hh (one or two of them) give an eight-bit hexadecimal value for the Unicode character that will be inserted. The upper bits of the Unicode character will be 0.

In 8.5, the documentation says:

\xhh
  The hexadecimal digits hh give an eight-bit hexadecimal value for the Unicode character that will be inserted. Any number of hexadecimal digits may be present; however, all but the last two are ignored (the result is always a one-byte quantity). The upper bits of the Unicode character will be 0.

The difference is plain, and 8.5 and 8.6 behave differently here. The change was due to TIP #388 "Extending Unicode literals past the BMP" (part of a general programme of fixes, some of which had to be postponed to after 8.6 due to the impact on the ABI) which was voted on in September 2011; project lead was Jan Nijtmans.
I remember voting for that TIP, and that fix was something I was very glad was in there.
Sorry it wasn't flagged as a Potential Incompatibility. Missed that one (probably because the old behaviour was so badly broken that nobody really believed that we hadn't fixed it long before…)


text:
Q: Should I use "the" in this sentence? Would you say:
I have a good knowledge of Japanese language and culture
or
I have a good knowledge of the Japanese language and culture
Which one sounds better to you?

A: Both sound okay, but I would go with the sentence not using "the."
Be as concise as can be without losing understanding!
Hope this helps!


text:
Q: Stretch block to fill minipage vertically in beamer I have the following environment that is supposed to divide the beamer page in four equal parts:
\newcommand{\FourQuads}[4]{
\begin{minipage}[t][.5\textheight][t]{\textwidth}
    \begin{minipage}[t]{.47\textwidth}
        \begin{block}{Second}
            #1
        \end{block}
    \end{minipage}
    \begin{minipage}[t]{.47\textwidth}
        \begin{block}{Second}
            #2
        \end{block}
    \end{minipage}
\end{minipage}
\begin{minipage}[t][.5\textheight][t]{\textwidth}
    \begin{minipage}[t]{.47\textwidth}
        \begin{block}{Third}
            #3
        \end{block}
    \end{minipage}
    \begin{minipage}[t]{.47\textwidth}
        \begin{block}{Fourth}
            #4
        \end{block}
    \end{minipage}
\end{minipage}
}

each of the four areas will present the text in a block environment: in particular, one may use it so:
\documentclass[t]{beamer}
\usecolortheme{rose}

\begin{document}
\begin{frame}{A very important slide}
\FourQuads%
{first item\\
another first item}
{second item}
{third item}
{fourth item\\
another fourth item}
\end{frame}
\end{document}

which generates the following:

As you can see, according to the different lengths of the text in each area, the blocks stretch along: this means that whenever the lengths differ, the boxes might mismatch. I am looking for a way to somehow vertically stretch or fill the block environments, whether or not there is text in there (should there be no text, the block may just vertically fill the remaining space in the minipage environment).
It will most likely be some sort of combination of \vfill or \setlength, but I do not know where to exactly place those parameters to achieve the result. Of course, there might also be a better solution than using minipage four times (I have tried columns but it does not really give anything better).

A: Place the minipages inside the blocks to get a fixed height:
\documentclass[t]{beamer}
\usecolortheme{rose}

\newcommand{\FourQuads}[4]{
    \begin{columns}[onlytextwidth]
        \begin{column}{.45\textwidth}
            \begin{block}{First}
                \begin{minipage}[t][.25\textheight][t]{\textwidth}
                    #1
                \end{minipage}
            \end{block}
        \end{column}
        \begin{column}{.45\textwidth}
            \begin{block}{Second}
                \begin{minipage}[t][.25\textheight][t]{\textwidth}
                    #2
                \end{minipage}
            \end{block}
        \end{column}
    \end{columns}
    \begin{columns}[onlytextwidth]
        \begin{column}{.45\textwidth}
            \begin{block}{Third}
                \begin{minipage}[t][.25\textheight][t]{\textwidth}
                    #3
                \end{minipage}
            \end{block}
        \end{column}
        \begin{column}{.45\textwidth}
            \begin{block}{Fourth}
                \begin{minipage}[t][.25\textheight][t]{\textwidth}
                    #4
                \end{minipage}
            \end{block}
        \end{column}
    \end{columns}
}

\begin{document}
\begin{frame}{A very important slide}
\FourQuads%
{first item\\
another first item}
{second item}
{third item}
{fourth item\\
another fourth item}
\end{frame}
\end{document}

A: Another solution is a tcbraster from tcolorbox.
\documentclass[t]{beamer}
\usecolortheme{rose}
\usepackage[most]{tcolorbox}

\newcommand{\FourQuads}[4]{
\begin{tcbraster}[raster columns=2, raster rows=2, raster height=.8\textheight,
    enhanced, size=small, sharp corners, boxrule=0pt,
    colbacktitle=structure.fg!20!bg,
    coltitle=structure.fg,
    colback=structure.fg!10!bg]
    \begin{tcolorbox}[title=First]#1\end{tcolorbox}
    \begin{tcolorbox}[title=Second]#2\end{tcolorbox}
    \begin{tcolorbox}[title=Third]#3\end{tcolorbox}
    \begin{tcolorbox}[title=Fourth]#4\end{tcolorbox}
\end{tcbraster}
}

\begin{document}
\begin{frame}{A very important slide}
\FourQuads%
{first item\\
another first item}
{second item}
{third item}
{fourth item\\
another fourth item}

\end{frame}
\end{document}


text:
Q: Overriding and customizing "django.contrib.auth.views.login" I'm trying to add a "keep me logged in" check box to Django's default login view.
Here is what I'm doing:
urls.py
url(r'^login/$',
    myuser_login,
    {'template_name': 'app_registration/login.html', 'authentication_form': MyAuthenticationForm},
    name='auth_login',
),

views.py
from django.contrib.auth.views import login

def myuser_login(request, *args, **kwargs):
    if request.method == 'POST':
        if not request.POST.get('remember', None):
            request.session.set_expiry(0)

    login(request, *args, **kwargs)

So basically, I'm trying to add additional information to my own view and just simply call Django's default login function. When I do this, I get this error:
ValueError at /accounts/login/
The view app_registration.views.myuser_login didn't return an HttpResponse object.

I checked the Django source code, and the default contrib.auth.views.login function obviously returns an HttpResponse.
What should I do :(((?
Thanks!!

A: All django views must return HttpResponse. Your view isn't returning anything.
You should return like this
def myuser_login(request, *args, **kwargs):
    if request.method == 'POST':
        if not request.POST.get('remember', None):
            request.session.set_expiry(0)

    return login(request, *args, **kwargs)


text:
Q: Using typescript baseurl and paths breaks React-Router I am trying to set baseUrls and paths in the tsconfig, however whenever I change the baseURL I recieve the following error

./node_modules/react-router/es/StaticRouter.js
120:40-54 'history' does not contain an export named 'createLocation'.

I have tried setting the node_path in env config and moving the path and baseurl to a seperate typescript file as was suggested in a github thread, however this did not work.
So here is what I have as of now in the Tsconfig
{
  "compilerOptions": {
    "baseUrl": "src",
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "paths": {
      "sagas/*": ["sagas/*"],
      "src/*": ["./*"],
      "*": [ "node_modules/@types/*", "*"]
    }
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "build",
    "lib",
    "tests",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "__mocks__",
    "__test__",
    "src/setupTests.ts"
  ]
}

Please note changing baseUrl back to '.' fixes the issue but the custom paths will no longer work
Typescript version is 3.3.1

A: Alright a bit of a dolt here.
Had a History.ts file in the "src" directory. So changing the baseUrl to src was resulting in that location being checked first even in the third party libraries. So needless to say that history object did not contain those definitions
Some folder/file reorganization fixed the issue


text:
Q: Display accented characters in an SVG object in an html page Accented characters (acute e etc) do not display in my svg object within an html page. The page is declared:
<!DOCTYPE html>
<html lang="en">
<head runat="server">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> ..

and the SVG file:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"

What's my big mistake?

A: does this show up right for you?

<svg>
  <text y="15">äöüëèéê</text>
</svg>

A: The answer is that if your linked svg file includes accented characters then in asp.net you should use an object:
<object type='image/svg+xml' data='<%#Container.DataItem("FieldName")%>'></object>

rather than the otherwise recommended image:
<asp:Image runat="server" ImageUrl='<%#Eval("FieldName")%>'/>


text:
Q: Using Authorize annotation on a controller method is displaying "Access denied" despite the user having the correct role I have a controller method that is only allowed to be used by users with the canModify role. I have made sure that the user has this role, and that the user is displayed as being a member of this role group. But when I try to edit a post on this account, it displays the "Access Denied" page.
I am not sure where to go from here. I have printed out the roles belonging to the currently logged in user, and it displays "canModify". I have printed out the list of users who possess the role "canModify", and the user I am logged in as is printed out.
GET Edit method in the Controller:
[Authorize(Roles = "canModify")]
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var post = await _context.Post.FindAsync(id);
        if (post == null)
        {
            return NotFound();
        }
        return View(post);
    }

Where the role is set:
private async Task Admin(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
    {
        await rm.CreateAsync(new IdentityRole("canModify"));
        ApplicationUser admin = new ApplicationUser
        {
            UserName = "admin@test.com"
        };
        if (context.Users.Where(u => u.UserName == admin.UserName).Count() == 0)
        {
            userManager.CreateAsync(admin, "Password123!").Wait();
            userManager.AddToRoleAsync(admin, "canModify").Wait();
        }
    }

This is my Configure method in Startup.cs:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();

var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
DbInitializer dbi = new DbInitializer(roleManager);
dbi.Initialize(context, userManager);

It should be the case now that the admin can edit the posts in the system, but it says access denied.


text:
Q: How do JSF/PrimeFaces tags get resolved to default CSS styles? I am still learning JSF and I am confused why, for example, the default style for <p:panel> is declared as .ui-panel in the CSS stylesheet.  I could establish a pattern if the panel was from the ui namespace (facelets) but it is in the p (PrimeFaces) namespace so ui-panel doesn't really make sense.  How does JSF (or in this case, PrimeFaces) map tags to default styles in CSS, i.e. what is the naming convention?

A: Primefaces components are powered by jquery-ui. So the naming convention is based on the naming convention of jquery ui components. Specifically, the class names play an important role in the themeing concept of primefaces that's again based on the themeroller approach of the jquery ui. The classes are split to structural and themeable. The .ui-panel is a themeable class name, classified as a widget container class, and the conventions says

.ui-widget: Class to be applied on outer container of all widgets.
  Applies font family and font size to widget. Also applies same family
  and 1em font size to child form elements specifically, to combat
  inheritance issues in Windows browsers.

as the widget is a panel, hence the .ui-panel. The main focus of the convention is to provide the ability to apply themes that will preserve the visual consistency of the component throughout the application


text:
Q: Three UpdatePanel objects in a ASP.Net page ok? I have a web page and I want to have three UpdatePanel objects working, based on events coming from several different buttons in different sections of the page.  Is this possible?  The buttons/links are not inside the panels.  I don't want to nest panels, either.  Is there any other object in the Ajax Control Toolkit to do this?

A: You can define AsyncPostbackTriggers for each UpdatePanel.  One word of caution, the last UpdatePanel postback wins.  You can not have multiple async postbacks at the same time.


text:
Q: Correct way to upload and save image in Laravel with vue.js and Element-ui I'm making a recipe book and I want the recipes to have the choice to upload images, I'm using Element-UI in this project and they have an upload component. However, I'm not super sure how to use it correctly. I'm basing this on some code I found but it's not really working the $request I receive in the controller always has the image: null. I'm using $intertia.post but I could change to $http.post if needed.
This is what I'm trying
<el-upload
    class="avatar-uploader"
    action="/api/vendors/fake-upload"
    accept="image/*"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">

        <el-button v-if="form.image" class="img-button mt-1" type="warning">
            Change Picture
        </el-button>

</el-upload>

Relevant data() in my vue


text:
Q: SharePoint Contact Card List View formatting is not displaying content I am trying to format a list view into a contact card format by tailoring the samples available on github. I have managed to get the contact cards displaying as gray boxes but cannot get the item details to display within the box.
Tried many different things. Changed column names, only included json for one column to get that right. Tried as divs and spans. No spaces in column names. Spaces in column names. % where there is a space in a column name. the best I have gotten is object Object or the last child as an "a" elmtype showing as a hyperlink but no other fields. Also cannot have the column heading display in the card above the entries also.
{
    "$schema":"https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
    "hideSelection":true,
    "hideListHeader":true,
    "rowFormatter":{
        "elmType":"div",
        "style":{
            "float":"left",
            "display":"flex",
            "flex-wrap":"wrap",
            "flex-direction":"column",
            "align-items":"stretch",
            "justify-content":"space-around",
            "min-width":"600px",
            "min-height":"486px",
            "border-radius":"8px",
            "margin-right":"10px",
            "margin-bottom":"10px",
            "box-shadow":"2px 2px 4px darkgrey"
        },
        "attributes":{
            "class":"ms-bgColor-neutralLighterAlt ms-bgColor-neutralLight--hover ms-fontColor-themePrimary--hover"
        },
        "children":[
            {
                "elmType":"div",
                "txtContent":"[$FirstName]",
                "style":{
                    "color":"black",
                    "font-style":"normal",
                    "font-size":"10px",
                    "display":"block",
                    "width":"250px",
                    "height":"50px",
                    "border-radius":"50%",
                    "word-wrap":"initial",
                    "white-space":"nowrap",
                    "flex-grow":"1",
                    "flex-direction":"column",
                    "flex-wrap":"wrap"
                }
            }
        ]
    }
}

The above example is just one of my column headings in my original list view. The FirstNames' of the entries are not appearing in the boxes

A: {
"$schema":"https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
"hideSelection":true,
"hideListHeader":true,
"rowFormatter":{
    "elmType":"div",
    "style":{
        "float":"left",
        "flex-wrap":"wrap",
        "flex-direction":"row",
        "width":"600px",
        "height":"900px",
        "border-radius":"8px",
        "margin-right":"10px",
        "margin-bottom":"10px",
        "box-shadow":"2px 2px 4px darkgrey"
    },
    "attributes":{
        "class":"ms-bgColor-neutralLighterAlt ms-bgColor-neutralLight--hover ms-fontColor-themePrimary--hover"
    },
    "children":[
        {
            "elmType":"div",
            "__comment:":"DIV 1",
            "style":{
                "flex-grow":"1",
                "display":"flex",
                "flex-direction":"column",
                "flex-wrap":"nowrap"
            },
            "children":[
                {
                    "elmType":"div",
                    "txtContent":"=[$FullName]",
                    "style":{
                        "display":"block",
                        "font-size":"16px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Job Title",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$JobTitle]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-color":"red",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Career Interests",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px",
                        "margin-top":"10px",
                        "margin-bottom":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$CareerInterests]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Beginner",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$SkillLevelBeginner]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Intermediate",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$SkillLevelIntermediate]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Advanced",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$SkillLevelAdvanced]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Previous Roles",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$PreviousRoles]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Qualifications",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Primary Qualifications",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"20px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$PrimaryQualifications]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$PrimaryDisciplineMajor]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"Additional Qualifications",
                    "style":{
                        "display":"block",
                        "font-size":"14px",
                        "font-weight":"bold",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType":"div",
                    "txtContent":"=[$AdditionalQualifications]",
                    "style":{
                        "display":"block",
                        "font-size":"12px",
                        "font-weight":"normal",
                        "padding-top":"10px",
                        "margin-left":"10px",
                        "margin-right":"10px"
                    }
                },
                {
                    "elmType": "a",
                        "style": {
                        "border": "none",
                        "padding-top": "15px",
                        "background-color": "transparent",
                        "color": "#0078d7",
                        "margin-left":"10px",
                        "margin-bottom": "20px",
                        "text-align": "left",
                        "cursor": "pointer",
                        "display": "=if([$LinkedIn]=='','none','')"
                    },
                    "attributes": {
                        "target": "_blank",
                        "iconName": "LinkedInLogo",
                        "href": "[$LinkedIn]"
                    }
                },
                {
                    "elmType": "a",
                        "style": {
                        "border": "none",
                        "display":"float",
                        "padding-top": "15px",
                        "background-color": "transparent",
                        "color": "#0078d7",
                        "margin-left":"10px",
                        "margin-bottom": "20px",
                        "text-align": "left",
                        "cursor": "pointer"
                    },
                    "attributes": {
                        "target": "_blank",
                        "iconName": "CreateMailRule",
                        "href": "[$FullName.email]",
                        "title": "Email"
                    }
                }
            ]
        }
    ]
}

}


text:
Q: Reading text files from subfolders and folders and creating a dataframe in pandas for each file text as one observation I have the following architecture of the text files in the folders and subfolders.
I want to read them all and create a df. I am using this code, but it dont work well for me as the text is not what I checked and the files are not equivalent to my counting.

l = [pd.read_csv(filename,header=None, encoding='iso-8859-1') for filename in glob.glob("2018_01_01/*.txt")]
main_df = pd.concat(l, axis=1)
main_df = main_df.T
for i in range(2):
    l = [pd.read_csv(filename, header=None, encoding='iso-8859-1',quoting=csv.QUOTE_NONE) for filename in glob.glob(str(foldernames[i+1])+ '/' + '*.txt')]
    df = pd.concat(l, axis=1)
    df = df.T
    main_df = pd.merge(main_df, df)

file

A: Assuming those directories contain txt files in which information have the same structure on all of them:
import os
import pandas as pd

df = pd.DataFrame(columns=['observation'])

path = '/path/to/directory/of/directories/'

for directory in os.listdir(path):
    if os.path.isdir(directory):
        for filename in os.listdir(directory):
            with open(os.path.join(directory, filename)) as f:
                observation = f.read()
                current_df = pd.DataFrame({'observation': [observation]})
                df = df.append(current_df, ignore_index=True)

Once all your files have been iterated, df should be the DataFrame containing all the information in your different txt files.

A: You can do that using a for loop. But before that, you need to give a sequenced name to all the files like 'fil_0' within 'fol_0', 'fil_1' within 'fol_1', 'fil_2' within 'fol_2' and so on. That would facilitate the use of a for loop:
dataframes = []
import pandas as pd
for var in range(1000):
    name  = "fol_" + str(var) + "/fil_" + str(var) + ".txt"
    dataframes.append(pd.read_csv(name)) # if you need to use all the files at once
    #otherwise
    df = pd.read_csv(name) # you can use file one by one

It will automatically create dataframes for each file.