text:
Q: Mapstruct - Mapping an object's list item with a method in a different mapper I have two mapper classes as below.

@Mapper
public interface CountryLanguageMapper {

    CountryLanguageMapper INSTANCE = Mappers.getMapper(CountryLanguageMapper.class);

    List<CountryLanguageResponse> toResponseList(List<CountryLanguage> source);

    @Mapping(target = "languageId", source = "id.language.id")
    CountryLanguageResponse toResponse(CountryLanguage source);

}

@Mapper
public interface CountryMapper {

    CountryMapper INSTANCE = Mappers.getMapper(CountryMapper.class);

    List<CountryListResponse> toResponseList(List<Country> source);

    @Mapping(target = "languages", source = "countryLanguages") // how should it be?
    CountryResponse toResponse(Country source);

    CountryListResponse toListResponse(Country source);

    @Mapping(target = "languages", source = "countryLanguages")
    CountryCreateResponse toCreateResponse(Country source);

    Country fromCreateRequest(CountryCreateRequest source);

    void updateFromUpdateRequest(CountryUpdateRequest source, @MappingTarget Country target);

}

Can I have the CountryMapper#toResponse method use the CountryLanguageMapper#toResponseList method when mapping the countryLanguages field?
If not possible how do I map "countryLanguages.id.language.id" to "languages.languageId" without writing a custom mapping method in CountryMapper?
Editing the CountryMapper class as follows works for me. But I was wondering if there is a way to use a method in different mapper.
@Mapper
public interface CountryMapper {

    CountryMapper INSTANCE = Mappers.getMapper(CountryMapper.class);

    List<CountryListResponse> toResponseList(List<Country> source);

    @Mapping(target = "languages", source = "countryLanguages", qualifiedByName = "toCountryLanguageResponseList")
    CountryResponse toResponse(Country source);

    CountryListResponse toListResponse(Country source);

    @Mapping(target = "languages", source = "countryLanguages")
    CountryCreateResponse toCreateResponse(Country source);

    @Mapping(target = "id", ignore = true)
    Country fromCreateRequest(CountryCreateRequest source);

    void updateFromUpdateRequest(CountryUpdateRequest source, @MappingTarget Country target);

    @IterableMapping(qualifiedByName = "toCountryLanguageResponse")
    @Named("toCountryLanguageResponseList")
    List<CountryLanguageResponse> toCountryLanguageResponseList(Collection<CountryLanguage> source);

    @Mapping(target = "languageId", source = "id.language.id")
    @Named("toCountryLanguageResponse")
    CountryLanguageResponse toCountryLanguageResponse(CountryLanguage source);

}

Thanks in advance :)

A: this is possible with the uses directive.
for example:
@Mapper(uses=CountryLanguageMapper.class)
public interface CountryMapper {

for more information see here:
https://mapstruct.org/documentation/dev/reference/html/#invoking-other-mappers


text:
Q: How to get notified when listVIew/gridView finish calling getView on their adapter? it's a simple question.
suppose i call notifyDatasetChanged(), and wish to be notified when the adapterView (listView/gridView/...) has finished calling getView() on the adapter, how do i do that?
The problem is that getView can be called multiple times on the same view, have weird order of calls and so you can never know when it has finished calling on all of the (currently shown) items.
would using this solution ( which uses the ViewTreeObserver and OnPreDrawListener) work on this case   ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Too many errors" - Javascript Estou recebendo a mensagem de Too many errors na linha 113 de meu arquivo Javascript porém não encontro nenhum erro nesse arquivo, meu arquivo é o seguinte:
var x = 0;

var data = new Date();
var dia = data.getDate();
var mes = data.getMonth()+1;
var ano = data.getFullYear();
var hora = data.getHours();
var minuto = data.getMinutes();
var segundo = data.getSeconds();

if (dia.toString().length == 1){
    dia = "0"+dia;
}
if (mes.toString().length == 1){
    mes = "0"+mes;
}
if (hora.toString().length == 1){
    hora = "0"+hora;
}
if (minuto.toString().length == 1){
    minuto = "0"+minuto;
}
if (segundo.toString().length == 1){
    segundo = "0"+segundo;
}

var lista01 = [];
var lista02 = [];
var lista03 = [];
var lista04 = [];
var lista05 = [];
var lista06 = [];
var lista07 = [];
var lista08 = [];
var lista09 = [];
var lista10 = [];
var lista11 = [];
var lista12 = [];
var lista13 = [];
var lista14 = [];
var lista15 = [];
var lista16 = [];
var lista17 = [];
var lista18 = [];
var lista19 = [];
var lista20 = [];
var lista21 = [];
var lista22 = [];
var lista23 = [];
var lista24 = [];
var lista25 = [];
var lista26 = [];
var lista27 = [];
var lista28 = [];
var lista29 = [];
var lista30 = [];
var lista31 = [];
var lista32 = [];
var lista33 = [];
var lista34 = [];
var lista35 = [];
var lista36 = [];
var lista37 = [];
var lista38 = [];
var lista39 = [];
var lista40 = [];
var lista41 = [];
var lista42 = [];
var lista43 = [];
var lista44 = [];
var lista45 = [];
var lista46 = [];
var lista47 = [];
var lista48 = [];
var lista49 = [];
var lista50 = [];
var lista51 = [];
var lista52 = [];
var lista53 = [];
var lista54 = [];
var lista55 = [];
var lista56 = [];
var lista57 = [];
var lista58 = [];
var lista59 = [];
var lista60 = [];
var lista61 = [];
var lista62 = [];
var lista63 = [];
var lista64 = [];
var lista65 = [];
var lista66 = [];
var lista67 = [];
var lista68 = [];
var lista69 = [];
var lista70 = [];
var lista71 = [];
var lista72 = [];
var lista73 = [];
var lista74 = [];
var lista75 = [];
var lista76 = [];
var lista77 = [];
var lista78 = [];
var lista79 = [];
var lista80 = [];
var lista81 = [];
var lista82 = [];
var lista83 = [];
var lista84 = [];
var lista85 = [];
var lista86 = [];
var lista87 = [];
var lista88 = [];
var lista89 = [];
var lista90 = [];
var lista91 = [];
var lista92 = [];
var lista93 = [];
var lista94 = [];
var lista95 = [];
var lista96 = [];
var lista97 = [];
var lista98 = [];
var lista99 = [];
var lista100 = [];

var listaFinal = [];

if ($data.linha01a50 == 1){
    lista01.push($data.numeroLote.value);
    lista01.push($data.formInput.numeroSerie01);
    if($data.situacao01 === false && $data.formInput.peso01 !== null){
        lista01.push("Vazio");
    } else {
        lista01.push($data.formInput.laudo01);
    }
    lista01.push($data.requestSuprimento01[0].nomeFornecedor);
    lista01.push($data.requestSuprimento01[0].suprimento);
    lista01.push($data.formInput.defeito01.defeito);
    lista01.push($data.formInput.residuo01);
    lista01.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista01.push(false);
    lista01.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista01);
}
else if ($data.linha01a50 == 2){
    lista01.push($data.numeroLote.value);
    lista01.push($data.formInput.numeroSerie01);
    if($data.situacao01 === false && $data.formInput.peso01 !== null){
        lista01.push("Vazio");
    } else {
        lista01.push($data.formInput.laudo01);
    }
    lista01.push($data.requestSuprimento01[0].nomeFornecedor);
    lista01.push($data.requestSuprimento01[0].suprimento);
    lista01.push($data.formInput.defeito01.defeito);
    lista01.push($data.formInput.residuo01);
    lista01.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista01.push(false);
    lista01.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista01);
    lista02.push($data.numeroLote.value);
    lista02.push($data.formInput.numeroSerie02);
    if($data.situacao02 === false && $data.formInput.peso02 !== null){
        lista02.push("Vazio");
    } else {
        lista02.push($data.formInput.laudo02);
    }
    lista02.push($data.requestSuprimento02[0].nomeFornecedor);
    lista02.push($data.requestSuprimento02[0].suprimento);
    lista02.push($data.formInput.defeito02.defeito);
    lista02.push($data.formInput.residuo02);
    lista02.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista02.push(false);
    lista02.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista02);
}
else if ($data.linha01a50 == 3){
    lista01.push($data.numeroLote.value);
    lista01.push($data.formInput.numeroSerie01);
    if($data.situacao01 === false && $data.formInput.peso01 !== null){
        lista01.push("Vazio");
    } else {
        lista01.push($data.formInput.laudo01);
    }
    lista01.push($data.requestSuprimento01[0].nomeFornecedor);
    lista01.push($data.requestSuprimento01[0].suprimento);
    lista01.push($data.formInput.defeito01.defeito);
    lista01.push($data.formInput.residuo01);
    lista01.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista01.push(false);
    lista01.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista01);
    lista02.push($data.numeroLote.value);
    lista02.push($data.formInput.numeroSerie02);
    if($data.situacao02 === false && $data.formInput.peso02 !== null){
        lista02.push("Vazio");
    } else {
        lista02.push($data.formInput.laudo02);
    }
    lista02.push($data.requestSuprimento02[0].nomeFornecedor);
    lista02.push($data.requestSuprimento02[0].suprimento);
    lista02.push($data.formInput.defeito02.defeito);
    lista02.push($data.formInput.residuo02);
    lista02.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista02.push(false);
    lista02.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista02);
    lista03.push($data.numeroLote.value);
    lista03.push($data.formInput.numeroSerie03);
    if($data.situacao03 === false && $data.formInput.peso03 !== null){
        lista03.push("Vazio");
    } else {
        lista03.push($data.formInput.laudo03);
    }
    lista03.push($data.requestSuprimento03[0].nomeFornecedor);
    lista03.push($data.requestSuprimento03[0].suprimento);
    lista03.push($data.formInput.defeito03.defeito);
    lista03.push($data.formInput.residuo03);
    lista03.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista03.push(false);
    lista03.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista03);
}
else if ($data.linha01a50 == 4){
    lista01.push($data.numeroLote.value);
    lista01.push($data.formInput.numeroSerie01);
    if($data.situacao01 === false && $data.formInput.peso01 !== null){
        lista01.push("Vazio");
    } else {
        lista01.push($data.formInput.laudo01);
    }
    lista01.push($data.requestSuprimento01[0].nomeFornecedor);
    lista01.push($data.requestSuprimento01[0].suprimento);
    lista01.push($data.formInput.defeito01.defeito);
    lista01.push($data.formInput.residuo01);
    lista01.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista01.push(false);
    lista01.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista01);
    lista02.push($data.numeroLote.value);
    lista02.push($data.formInput.numeroSerie02);
    if($data.situacao02 === false && $data.formInput.peso02 !== null){
        lista02.push("Vazio");
    } else {
        lista02.push($data.formInput.laudo02);
    }
    lista02.push($data.requestSuprimento02[0].nomeFornecedor);
    lista02.push($data.requestSuprimento02[0].suprimento);
    lista02.push($data.formInput.defeito02.defeito);
    lista02.push($data.formInput.residuo02);
    lista02.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista02.push(false);
    lista02.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista02);
    lista03.push($data.numeroLote.value);
    lista03.push($data.formInput.numeroSerie03);
    if($data.situacao03 === false && $data.formInput.peso03 !== null){
        lista03.push("Vazio");
    } else {
        lista03.push($data.formInput.laudo03);
    }
    lista03.push($data.requestSuprimento03[0].nomeFornecedor);
    lista03.push($data.requestSuprimento03[0].suprimento);
    lista03.push($data.formInput.defeito03.defeito);
    lista03.push($data.formInput.residuo03);
    lista03.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista03.push(false);
    lista03.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista03);
    lista04.push($data.numeroLote.value);
    lista04.push($data.formInput.numeroSerie04);
    if($data.situacao04 === false && $data.formInput.peso04 !== null){
        lista04.push("Vazio");
    } else {
        lista04.push($data.formInput.laudo04);
    }
    lista04.push($data.requestSuprimento04[0].nomeFornecedor);
    lista04.push($data.requestSuprimento04[0].suprimento);
    lista04.push($data.formInput.defeito04.defeito);
    lista04.push($data.formInput.residuo04);
    lista04.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista04.push(false);
    lista04.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista04);
}
return {
    'listaRetorno':JSON.stringify(listaFinal),
    'loteEncerrado':false
};

O erro ocorre na linha: var lista87 = [];. Se tiverem alguma ideia de o que pode estar ocorrendo e como resolver.
Versão com um ARRAY:
else if ($data.linha01a50 == 2){
    lista01.push($data.numeroLote.value);
    lista01.push($data.formInput.numeroSerie01);
    if($data.situacao01 === false && $data.formInput.peso01 !== null){
        lista01.push("Vazio");
    } else {
        lista01.push($data.formInput.laudo01);
    }
    lista01.push($data.requestSuprimento01[0].nomeFornecedor);
    lista01.push($data.requestSuprimento01[0].suprimento);
    lista01.push($data.formInput.defeito01.defeito);
    lista01.push($data.formInput.residuo01);
    lista01.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista01.push(false);
    lista01.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista01);
    lista01 = [];
    lista01.push($data.numeroLote.value);
    lista01.push($data.formInput.numeroSerie02);
    if($data.situacao02 === false && $data.formInput.peso02 !== null){
        lista01.push("Vazio");
    } else {
        lista01.push($data.formInput.laudo02);
    }
    lista01.push($data.requestSuprimento02[0].nomeFornecedor);
    lista01.push($data.requestSuprimento02[0].suprimento);
    lista01.push($data.formInput.defeito02.defeito);
    lista01.push($data.formInput.residuo02);
    lista01.push(ano+"-"+mes+"-"+dia+" "+hora+":"+minuto+":"+segundo);
    lista01.push(false);
    lista01.push($data.user.user_name.toUpperCase().replace('.',' '));
    listaFinal.push(lista01);
}


text:
Q: Embedding a table view inside a table view cell In my table view custom cells are used. Each cell need to be expanded and a list of details need to be shown for each cell item. This is dynamic and the number of details could only be known at run time. So is it possible to embed another table view inside each cell? I have not seen any where such an implementation. What will be impact ? Please advise.

A: Instead of using a UITableView in this instance, perhaps you might consider using a UICollectionView - they are built for something like you describe more than a UITableView. Or, switch to a different UITableViewCell (or multiple of them) be telling the UITableViewController to add cells or reloading the section (and reflecting the changes in your model).


text:
Q: App Name not updating in ipa to upload in MDM - iOS I created ios Application "PetFinder" and wanted to create separate environments for my app and so created Schemes Debug, QA, Preprod & Prod
I have different bundle-identifier and provisioning profiles for each environment
When I update my Bundle display name according to scheme, it works perfectly when I run from Xcode (For Eg: For QA scheme, my app name in device shows "PetFinder-QA" as expected
My problem is: When QA scheme is selected, generated ipa and try to update in my MDM, App name still shows as PetFinder. (I verified that this has bundle-identifier pointing to QA "com.xyzcompany.petfinder-qa" which is correct)
Below is how my info.plist is being set up

I've tried setting Bundle display name dynamically using variables. As mentioned, this works when i run from Xcode to my device but not when I ship my ipa to MDM
Added display name from user-defined variables in Build settings
Please refer attached screens
Actual should be when QA scheme selected, it should display my app name as "PetFinder-QA"


text:
Q: Open sqlite db file from a project's subfolder I have this folder structure:
├── gorm.sqlite // this works
├── main.go
├── simulator
│   ├── data
│   │   ├── gorm.sqlite //this does not work
│   │   └── profiles.go
│   ├── driver
│   │   ├── apis.go
│   │   ├── client.go
│   │   ├── routing-events.go
│   │   └── websocket.go
│   └── router.go

In my simulator/router.go:
func SetupConfig() {
    config := &driver.Config{}
    if db, err := gorm.Open(sqlite.Open("gorm.sqlite"), &gorm.Config{}); err != nil {
        panic(err)
    } else {
        config.Db = db
    }
    //etc
}

While sqlite.Open("gorm.sqlite") works and access the file in the project main folder, sqlite.Open("/simulator/data/gorm.sqlite") does not work! it panics unable to open database file: no such file or directory.
How can I access a db file in a sub folder.

A: Try this way
    db, err := gorm.Open(sqlite.Open("./simulator/data/gorm.sqlite"), &gorm.Config{})


text:
Q: For loop function not returning the correct output I'm trying to write a program to see how many times a 3-digit substring shows up in a string. For example, the substring "122" would show up in the string "122122" 2 times. However, whenever I run it, it returns 0, even if the substring does actually show up. Can you tell me what's wrong with my function?
def count_substring(string, sub_string):
    count = 0
    for i in range (len(string)):
        if string[i:i+3] == sub_string:
           count+=1

A: Using @Samwise's comment as a suggestion:
def count_substring(string, sub_string):
    return string.count(sub_string)

Although, since that's a one-liner, if you only need to run this function once, you may not even want to break it off into its own function. So just use string.count(sub_string) where you need it.

A: This can help you:
def count_substring(string, sub_string):
    return string.count(sub_string)


text:
Q: Image slider for Light gallery React I'm using light gallery for the image viewer. The problem here is when i have multiple images all those are stacked in rows with 2 images in a row and i have 10 rows for 20 images. So i'm trying to integrate a custom carousel in the light gallery with which i'll have one row of images and a slider.
Both work individually well but couldn't integrate. Also wanted to know if the light gallery has an slider inbuilt.
//Light gallery code:
<LightGallery speed={100} download={true} plugins={[lgThumbnail]} mode="lg-fade" >
                          {
                            abc.xyz.attachments.map((item: any) => {
                              let fileName = item.split('/').pop();
                              return (

                              )
                            })
                          }
                        </LightGallery>

//Carousel Code:
 <Carousel items={abc.xyz.attachments} />

Any help?


text:
Q: Run an EXE file from MATLAB 64bit (Windows 8.1 64Bits) I want to run an EXE file named "LBRM.EXE" by MATLAB.
I try:
dos('lbrm.exe')

and I get error:

'lbrm.exe' is not recognized as an internal or external command,
  operable program or batch file.

Exactly the same code works fine in 32bit MATLAB.
mesh -setup did not help!

A: Since it appears you're not returning any arguments from the call, you could see if you have better luck with the bang operator:
!lbrm.exe

A: You have to add the EXE in your environmental variables in Windows or to move to the directory of the EXE file.
To move to the directory of the EXE file, use CD('EXE file folder') then you can execute your file by using the system command. system('lbrm.exe')


text:
Q: Match Array Values to URL String I have an array:
$blacklist = array("asdf.com", "fun.com", "url.com");

I have an input string:
$input = "http://asdf.com/asdf/1234/";

I am trying to see if string $input matches any values in $blacklist.
How do I accomplish this?

A: Sounds like a decent use for parse_url():
<?php
    $blacklist = array("asdf.com", "fun.com", "url.com");
    $input = "http://asdf.com/asdf/1234/";

    $url = parse_url($input);

    echo (in_array($url['host'], $blacklist) ? '(FAIL)' : '(PASS)') . $url ['host'];
?>

Output:
(FAIL)asdf.com

A: One way could be (but I didn't measure performance):
$san = preg_replace($blacklist, '', $input);

if($san !== $input) {
    //contained something from the blacklist
}

If the input does not contain any string from the backlist, the string will be returned unchanged.
An other, maybe better suited and definitely more efficient approach could be to extract the host part from the input and create the blacklist as associative array:
$blacklist = array(
      "asdf.com" => true,
      "fun.com" => true,
      "url.com" => true
);

Then testing would be O(1) with:
if($blacklist[$host]) {
    //contained something from the blacklist
}

A: Using foreach is probably the best solution for what you're trying to achieve.
$blacklist = array("/asdf\.com/", "/fun\.com/", "/url\.com/");

foreach($blacklist as $bl) {
  if (preg_match($bl, $input)){return true;}
}

A: in_array is of no use, as it searches for the exact string.
You have to loop through the array, and search for it
foreach($str in $blacklist)
{
   if( stristr($input, $str ) )
    {
         //found
    }
}

A: This code should work:
$blacklist = array("asdf.com", "fun.com", "url.com");
$input = "http://asdf.com/asdf/1234/";
if (in_array(parse_url($input,PHP_URL_HOST),$blacklist))
  {
  // The website is in the blacklist.
  }


text:
Q: setState() function doesn't work and I cannot update my states. How can I solve this problem? I want to update my states for controlling my Models, but it doesn't work when I run this code.
These are my states which are controlling the model's visibility
state = {
    loginWithMail: false,
    registerWithMail:true,
    remember:true,
  }

That's what I tried in function.
    this.setState({
        registerWithMail: false,
        loginWithMail: true,
      })
      console.log(this.state)
  };

And this is my model which is I tried to control
 <Modal isVisible={this.state.registerWithMail}>

A: setState is async, so you would need to put the console.log into the callback provided by setState to log once the state is updated.
    this.setState({
        registerWithMail: false,
        loginWithMail: true,
      }, () => console.log(this.state))
  };

Also I believe react native modal needs this property unless that is a custom component you created <Modal visible={this.state.registerWithMail}>
https://facebook.github.io/react-native/docs/modal.html#visible


text:
Q: .NET Core 1.0.1 VS 2015 Tooling Preview 2 without Visual Studio installed I found many topics regarding this issue but it looks like it none of them can help me. I'm trying to install DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe without Visual Studio installed - basically it's our build machine. When I run executable I get: "This product requires Visual Studio 2015 ..." . I've already tried to use SKIP_VSU_CHECK=1 and it didn't help.
Context:
We have TeamCity server build agents hosted on different machine and we don't want to install Visual Studio there. One of our project is *.xproj project and it cannot be built due to the following error: " error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\DotNet\Microsoft.DotNet.Props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
What I found so far is that I should install Vs2015Tools in order to build it. I have already installed .NET core SDK.


text:
Q: Customising ToC appearance of chapter titles in front and back matter This might be a duplicate, but I am interested in customising the ToC appearance of chapter titles for \chapter commands placed:

*

*in the front and back matter, and

*after the \appendix command in the main matter.

I only wish to change font series (to medium) and shape (to italic) as shown below. (Vertical spacing between front matter chapter titles probably needs to be reduced as well.)

At the moment I'm using the standard document class book and:
\usepackage[nottoc]{tocbibind} % nottoc option for inclusion of LoT/LoF/Bib in ToC
\usepackage{hyperref}

A: One possibility using the titletoc package; the etoolbox package was used to patch \frontmatter, \mainmatter, and \appendix, so as to automatically use the corresponding style:
\documentclass{book}
\usepackage[nottoc]{tocbibind}
\usepackage{titletoc}
\usepackage{etoolbox}

\newcommand\frontformat{%
\titlecontents{chapter}[0em]
  {\itshape}{\contentslabel{0em}}
  {}{\normalfont\titlerule*[1pc]{.}\contentspage}}
\newcommand\mainformat{%
\titlecontents{chapter}[1.4em]
  {\addvspace{10pt}\bfseries}{\contentslabel{1.15em}}
  {}{\normalfont\titlerule*[1pc]{.}\bfseries\contentspage}
}
\newcommand\backformat{%
\titlecontents{chapter}[1.5em]
  {\addvspace{10pt}\itshape}{\contentslabel{1.5em}}
  {\hspace*{-1.5em}}{\normalfont\titlerule*[1pc]{.}\contentspage}}

\titlecontents{section}[3.8em]
  {}{\contentslabel{2.3em}}
  {\hspace*{-2.3em}}{\titlerule*[1pc]{.}\contentspage}

\apptocmd{\frontmatter}{\frontformat}{}{}
\apptocmd{\mainmatter}{\mainformat}{}{}
\apptocmd{\appendix}{\backformat}{}{}

\begin{document}

\frontmatter

\tableofcontents
\chapter{Preface}
\listoftables
\listoffigures

\mainmatter

\chapter{Introduction}
\chapter{Results and Discussion}
\section{Section}
\section{Another Section}
\chapter{Conclusion}

\appendix

\chapter{My Appendix}
\cite{testa}

\backmatter

\begin{thebibliography}{9}
\bibitem{testa} Author A, Title A, 2012
\end{thebibliography}

\end{document}

A: The solution of Gonzalo Medina uses package titletoc that does not work well with hyperref, because it extracts the heading number of the entry in the table of contents (and LOF, LOT) and sets it outside the link.
The following solution patches \l@chapter, \l@section, …, which are responsible for the formatting of the entry in the table of contents to add \TocTitleFormat. Depending on the switch \ifTocMainMatter, \TocTitleFormat does nothing or adds \textit for the title. If \itshape is used instead, also the page number would be in italic.
Similar to Medina's solution \frontmatter and friends are patched to add the setting of the switch \ifTocMainMatter into the .toc file.
Since hyperref is used, likely also bookmarks are generated. The same style can be applied to them via package bookmark.
\documentclass{book}
\usepackage[nottoc]{tocbibind}
\usepackage{etoolbox}
\usepackage{hyperref}
\usepackage{bookmark}
\bookmarksetup{numbered,open}

\makeatletter
\newcommand*{\PatchTocEntry}[1]{%
  \expandafter\@PatchTocEntry\csname l@#1\expandafter\endcsname
  \csname org@l@#1\endcsname{org@l@#1}%
}
\newcommand*{\@PatchTocEntry}[3]{%
  \@ifdefinable{#3}{%
    \let#2#1%
    \renewcommand*{#1}[1]{%
      #2{\TocTitleFormat{##1}}%
    }%
  }%
}
\@for\@tmp:=chapter,section,subsection,subsubsection,paragraph,subparagraph\do{
  \PatchTocEntry{\@tmp}%
}
\newif\ifTocMainMatter
\let\ifTocMainMatter\if@mainmatter
\newcommand*{\SetTocMainMatter}[1]{%
  \addtocontents{toc}{%
    \expandafter\protect\csname TocMainMatter#1\endcsname
  }%
  \begingroup
  \edef\x{\endgroup
    \noexpand\bookmarksetup{%
      italic=\csname if#1\endcsname false\else true\fi
    }%
  }\x
}
\apptocmd{\frontmatter}{\SetTocMainMatter{false}}{}{}
\apptocmd{\mainmatter}{\SetTocMainMatter{true}}{}{}
\apptocmd{\appendix}{\SetTocMainMatter{false}}{}{}
\apptocmd{\backmatter}{\SetTocMainMatter{false}}{}{}
\newcommand*{\TocTitleFormat}[1]{%
  \ifTocMainMatter
    #1%
  \else
    \textit{#1}%
  \fi
}
\makeatother

\begin{document}

\frontmatter

\tableofcontents
\chapter{Preface}
\listoftables
\listoffigures

\mainmatter

\chapter{Introduction}
\chapter{Results and Discussion}
\section{Section}
\section{Another Section}
\chapter{Conclusion}

\appendix

\chapter{My Appendix}
\section{Section in Appendix}
\cite{testa}

\backmatter

\begin{thebibliography}{9}
\bibitem{testa} Author A, Title A, 2012
\end{thebibliography}

\end{document}


text:
Q: how to save input text as a list in Django admin I am trying to work with the Django admin. In particular, I am interested in having a CharField so that I receive the input text from the user, process it inside the model and save it as an array to the database.
So, having a database column origins_asns in PostgreSQL defined as an array of integers
origin_asns   BIGINT[] DEFAULT '{}',

The corresponding model should look something like this
    class DynCdn(models.Model):
...
        origin_asns = models.CharField(
            verbose_name="Origin ASNs",
            help_text="Hint: use a space ' ' character to enter multiple ASNs.",
            max_length=64,
        )
        interfaces = ChoiceArrayField(
            base_field=models.CharField(
                max_length=64,
                choices=DYNCDN_INTERFACES,
            ),
            default=list,
        )
...

        def save(self, *args, **kwargs):
...
            if self.origin_asns is not None:
                self.origin_asns = [
                    int(_) for _ in self.origin_asns.split() if _.isdigit()
                ]
            return super(DynCdn, self).save(*args, **kwargs)
...

The above fails with the following error message:
Jun 08 10:21:33 __ registry[61043]: django.db.utils.DataError: malformed array literal: "[101, 202, 303]"
Jun 08 10:21:33 __ registry[61043]: LINE 1: ...2f5c910bfd4f'::uuid, 'JSHGSAVS', '101, 202, 303', '[101, 202...
Jun 08 10:21:33 __ registry[61043]:                                                              ^
Jun 08 10:21:33 __ registry[61043]: DETAIL:  Missing "]" after array dimensions.

It seems that the list is being casted to a string. Would you be so kind how to solve it?
Having ChoiceArrayField defined like this:
class ChoiceArrayField(ArrayField):
    def formfield(self, **kwargs):
        defaults = {
            "form_class": forms.MultipleChoiceField,
            "choices": self.base_field.choices,
        }
        defaults.update(kwargs)
        return super(ArrayField, self).formfield(**defaults)

wouldn't do the trick as the choices cannot be suggested beforehand.
Installing 3rd party packages is not preferred.


text:
Q: show the scroll bar when the content overflows I'm trying to apply an animation that looks this way:
The page loads and after one second there is a box shows up slowly from the bottom of the page, I achieved that with adding a class called height (that you see in my code below).
The problem is that box will have some content that will be input by the user so its height will be increased to be able to display all the content that the user input, but this is not what happens when the content passes the provided height (the height coming from the height class) the overflow content will be hidden.
I don't want that behaviour I want the scrolling bar to show up.
here is an executable snipet: https://codepen.io/Amoocris/pen/vPWOpX

setTimeout(

  function() {
    document.querySelector(".plansBackground").classList.add("height");
  }, 1000

);
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: Roboto;
  font-weight: bold;
}

.backIMg {
  background-color: rgb(155, 230, 170);
  height: 100vh;
  width: 100vw;
}

.plansBackground {
  background-color: rgba(255, 255, 255, .5);
  width: 100vw;
  height: 0;
  position: fixed;
  bottom: 0;
  left: 0;
  transition: 1s;
  color: black;
}

.height {
  height: 25vw;
}

<link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

          Monday

A: Yeah, overflow:visible will act like overflow:hidden on absolutely positioned elements that are at the very bottom of the viewport/page. The simple solution is to give overflow-y:auto to .height.

A: Just add ti CSS
.plansBackground {
     overflow-y: auto;
}

Example


text:
Q: reshape to wide format, while varying only a single column at a time (for sensitivity analysis) There are already many Q&A's relating to reshaping data, but I did not find one that deals with this specific case.
I want to take a long format table that provides low, average and high values for an arbitrary number of parameters, with values varying over an arbitrary number of groups.  Here is a simple example table with just two parameters (f1, f2) and two groups (A, B).
library(data.table)
input = fread("
grp variable value level
A   f1       0.1   low
A   f1       0.2   average
A   f1       0.3   high
A   f2       0.5   low
A   f2       0.6   average
A   f2       0.7   high
B   f1       1.0   low
B   f1       2.0   average
B   f1       3.0   high
B   f2       -10   low
B   f2       -5    average
B   f2       0     high
")

To conduct sensitivity analyses, I would like to convert this to a table in which each parameter is varied from low to high, while fixing all other parameters at their average value (for each group).
The expected output for the simple example would look like this:
expected = fread("
grp  variable    level  f1   f2
A    f1          low   0.1  0.6
A    f1          high  0.3  0.6
A    f2          low   0.2  0.5
A    f2          high  0.2  0.7
B    f1          low   1.0  -5
B    f1          high  3.0  -5
B    f2          low   2.0  -10
B    f2          high  2.0  0
")

I can find the varying factors for each sensitivity, using dcast:
dcast(input, grp + variable + level ~ variable)[level != 'average']
#    grp sensitivity level  f1    f2
# 1:   A          f1  high 0.3    NA
# 2:   A          f1   low 0.1    NA
# 3:   A          f2  high  NA   0.7
# 4:   A          f2   low  NA   0.5
# 5:   B          f1  high 3.0    NA
# 6:   B          f1   low 1.0    NA
# 7:   B          f2  high  NA   0.0
# 8:   B          f2   low  NA -10.0

But, I did not find a neat way to also fill in the average values for the other factors that works for any number of groups and factors.  I'm really interested in base or data.table solutions, but other packages also welcome as they could help others.

Here's a slightly larger input table with 3 parameters and 3 groups, to test solutions on:
structure(list(grp = c("A", "A", "A", "A", "A", "A", "A", "A",
"A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C", "C",
"C", "C", "C", "C", "C", "C"), variable = c("f1", "f1", "f1",
"f2", "f2", "f2", "f3", "f3", "f3", "f1", "f1", "f1", "f2", "f2",
"f2", "f3", "f3", "f3", "f1", "f1", "f1", "f2", "f2", "f2", "f3",
"f3", "f3"), value = c(0.1, 0.2, 0.3, 0.5, 0.6, 0.7, 4, 5, 6,
1, 2, 3, -10, -5, 0, 11, 12, 13, 100, 200, 300, 3, 6, 9, 21,
22, 23), level = c("low", "average", "high", "low", "average",
"high", "low", "average", "high", "low", "average", "high", "low",
"average", "high", "low", "average", "high", "low", "average",
"high", "low", "average", "high", "low", "average", "high")), row.names = c(NA,
-27L), class = c("data.table", "data.frame"))

In case it helps, we can also generate larger input tables to test using the following.  My current use case has nearly 10,000 groups and ~25 parameters.
Ngrp = 5
Nf = 7
grp = 1:Ngrp
f = paste0("f", 1:Nf)
input = expand.grid(grp = grp, variable=f, level = c("low", "average", "high"))
setDT(input)
setkey(input, grp, variable, level)
input[level == 'low',     value := rnorm(.N, grp,    grp/10), by=.(grp,variable)]
input[level == 'average', value := rnorm(.N, grp*5,  grp/2), by=.(grp,variable)]
input[level == 'high',    value := rnorm(.N, grp*10, grp), by=.(grp,variable)]

A: I suggest a two step strategy.  I was actually trying to do it in one syntax (i.e. without creating intermediate df1 but wasn't able to figure out how to use arguments when one lambda function is passed within another one in purrr style of writing functions).  Nevertheless, since your final values are cross matching you indeed have to follow a longer route.  This is only based on assumption that your sensitivity levels start from character f.
step-1 create intermediate df1
library(tidyverse)

merge(df %>%
        select(v1 = variable) %>%
        unique(),
      df %>%
        select(v2 = variable) %>%
        unique(),
      all.x = T) %>%
  full_join(df , by = c('v1' = 'variable')) %>%
  filter(level != 'average') %>%
  pivot_wider(id_cols = c(grp, v1, level),
              names_from = v2,
              values_from = value) -> df1

final step
library(glue)

df %>% filter(level == 'average') %>%
  mutate(variable = paste0('av_', variable)) %>%
  pivot_wider(id_cols = grp, names_from = variable, values_from = value) %>%
  right_join(df1, by = "grp") %>%
  mutate(across(starts_with("f"), ~ifelse(v1 != cur_column(),
                                          get(glue('av_{cur_column()}')),
                                          .)
                )
         ) %>%
  select(grp, variable = v1, level, starts_with("f"))

# A tibble: 18 x 6
   grp   variable level    f1    f2    f3
   <chr> <chr>    <chr> <dbl> <dbl> <dbl>
 1 A     f1       low     0.1   0.6     5
 2 A     f1       high    0.3   0.6     5
 3 A     f2       low     0.2   0.5     5
 4 A     f2       high    0.2   0.7     5
 5 A     f3       low     0.2   0.6     4
 6 A     f3       high    0.2   0.6     6
 7 B     f1       low     1    -5      12
 8 B     f1       high    3    -5      12
 9 B     f2       low     2   -10      12
10 B     f2       high    2     0      12
11 B     f3       low     2    -5      11
12 B     f3       high    2    -5      13
13 C     f1       low   100     6      22
14 C     f1       high  300     6      22
15 C     f2       low   200     3      22
16 C     f2       high  200     9      22
17 C     f3       low   200     6      21
18 C     f3       high  200     6      23

The two steps are actually for better understanding.  Two steps can be combined within one single pipe
df %>% filter(level == 'average') %>%
  mutate(variable = paste0('av_', variable)) %>%
  pivot_wider(id_cols = grp, names_from = variable, values_from = value) %>%
  right_join(merge(df %>%
                     select(v1 = variable) %>%
                     unique(),
                   df %>%
                     select(v2 = variable) %>%
                     unique(),
                   all.x = T) %>%
               full_join(df , by = c('v1' = 'variable')) %>%
               filter(level != 'average') %>%
               pivot_wider(id_cols = c(grp, v1, level),
                           names_from = v2,
                           values_from = value), by = "grp") %>%
  mutate(across(starts_with("f"), ~ifelse(v1 != cur_column(),
                                          get(glue('av_{cur_column()}')),
                                          .)
                )
         ) %>%
  select(grp, variable = v1, level, starts_with("f"))

A: Using data.table we could also do:
f <- function(x, y)nafill(x, "const", na.omit(x[y=="average"]))

dcast(input, grp + variable + level ~ variable)[,
      rapply(.SD, f, "numeric", how="replace", y=level), by=grp][level !="average"]

   grp variable level  f1    f2
1:   A       f1  high 0.3   0.6
2:   A       f1   low 0.1   0.6
3:   A       f2  high 0.2   0.7
4:   A       f2   low 0.2   0.5
5:   B       f1  high 3.0  -5.0
6:   B       f1   low 1.0  -5.0
7:   B       f2  high 2.0   0.0
8:   B       f2   low 2.0 -10.0

A: I found a data.table method using a row-wise loop:
out = dcast(input, grp + variable + level ~ variable)[level != 'average']
fs = input[, unique(variable)] # vector of unique parmeter names
f = function(g,v) input[grp==g & variable != v & level=="average", as.list(value)]
for (i in seq_len(nrow(out))) {
  set(out, i, setdiff(fs, out[i,variable]), out[i, f(grp, variable)])
}


text:
Q: Stretch child element to fill parent element's height while also and vice versa (HTML) Please note I will not accept any answers that prevent bootstrap from being usable
The scenario is as follows:
I have a parent element (div) with two child elements (also divs) nested inside. I would like the children to be able to fill the height of the parent regardless of the content that is in side the children. On top if this, if the parent element is not tall enough to contain the child content, I would like the parent element to stretch to the necessary height to display the content within the children.
A non-working example is located here: https://jsfiddle.net/uqh76pku/2/

text content goes here

text content goes here

Many of the answers I have found (listed below) provide information which simply does not work. I have tried the following list of answers.
How to stretch div height to fill parent div - CSS
CSS - Expand child DIV height to parent's height
Stretch Child DIV to Height of Parent (Without hardcoding height)


text:
Q: How to log in to MACM API When trying to use the IBM Bluemix MACM BasicAuth login per REST as in here:
http://www-01.ibm.com/support/knowledgecenter/SSYK7J_8.5.0/macm/macm_bas_auth_login_api.html
you may get the following error code:
Error 404: EJCBD0006E: The resolution of a URI failed. Refer to the SystemOut.log for more detailed information.

What is the cause?

A: If you have a "Error 404: EJCBD0006E: The resolution of a URI failed."  you can check if the userid has at least USER role on this page:
Administration > Manage Pages > search on unique name contains "hidden" > click Key icon next to Web Content Management page > click on USER role > add user or user's group if not currently assigned.


text:
Q: Using variables for CSS id in a loop with Jade Pug I would like to build a loop of collapsable divs in jade / pug.
I am using jade npm package version 1.11.0
For example here is my first iteration which is working:
button.btn.btn-primary(type='button', data-toggle='collapse', data-target='#response0', aria-expanded='false', aria-controls='collapseExample')
  | Show Response
#response0.collapse
  .well
    pre=response

Unfortunately when I try this one
button.btn.btn-primary(type='button', data-toggle='collapse', data-target='#response0', aria-expanded='false', aria-controls='collapseExample')
  | Show Response
div(id= 'response0').collapse
  .well
    pre=session_detail.response

Or this
button.btn.btn-primary(type='button', data-toggle='collapse', data-target='#response0', aria-expanded='false', aria-controls='collapseExample')
  | Show Response
.collapse(id= 'response0')
#response0.collapse
  .well
    pre=session_detail.response

The html output looks great but the collapse button doesnt work.
What I would like to build is something like this that works:
-var i = 0
-session_details.forEach(function(session) {
  .row
    .col-md-5
      pre=session_detail.response
      -var dataTarget='#response'+i
      -var dataTargetResponse='response'+i
      button.btn.btn-primary(type='button', data-toggle='collapse', data-target=#{dataTarget}, aria-expanded='false', aria-controls='collapseExample')
        | Show Response
      div(id= dataTargetResponse).collapse
        .well
          pre=session_
  -i++

Do you have any ideas of what could I do?
Thanks for your help

A: You need to create an array when using a for loop in pug. Or you can use while, something like this;
- var i = 0;
.row
  .col-md-5
    while i < 4
      .collapse(id='response' + i)
      i++

More information over at the pugjs iteration page

A: You can use each loop of Pug to loop over an array and deal with each item in that array.
If you need to generate content in such a loop with different id's in each loop, you can use the index of the array in the loop, like in the following example:
- var sessions = [1, 2, 3, 4, 5];
each session,index in sessions
  button.btn.btn-primary(type='button', data-toggle='collapse', data-target= "#response"+index, aria-expanded='false', aria-controls='collapseExample')
    | Show Response
  .collapse(id= "response"+index)
    .well
      pre=response


text:
Q: Markov inequality limit Let $f: \mathbf{R}^d \rightarrow [0,\infty]$ be a Lebesgue integrable function. Prove $$\lim_{\alpha \rightarrow \infty} \alpha m(\{x:f(x)>\alpha\})=0.$$ Hint: For $\epsilon>0$ take $g$ simple such that $0 \leq g \leq f$ and $\int(f-g)dx<\epsilon$. Then note that $g<\alpha/2$ if $\alpha$ is large and for such $\alpha$ compare $\{f>\alpha\}$ with $\{f-g>\alpha/2\}$.
So this was a problem from a midterm and I get the argument that follows from the hint but no matter how many manipulations of Markov's Inequality I do, I can't prove the hint so I'm pretty sure that I'm missing some kind of intuition here.

A: We have $\{f\gt \alpha\}\subset \{f-g\gt \alpha/2\}\cup\{ g\gt \alpha/2\}$. It can be seen looking at the inverse inclusion for complements. Since $g$ takes a finite numbers of values, it is bounded. So take $\alpha\geqslant 2\sup g$ in order to get for such $\alpha$, the inclusion $\{f\gt\alpha\}\subset \{f-g\gt \alpha/2\}$. Now we can use classical Markov's inequality.


text:
Q: Office 2007 - how to change default load/save directory? With most applications I use (for example: Textpad, Paint.NET), if I have an document open and then go to open another, the file selector will naturally default to the directory where the already open document resides.
Word 2007 and Excel 2007 don't do this. I can't seem to find anything obvious in their options to achieve this. Is there anyway of getting them to do this?

A: Changing the default save folder is done separately for each Office component.
The article Change your default Save As folder in Office explains how to do that. To resume :

Word 2007, click the Office button, choose Word Options at the
  bottom of the window, click Save in
  the left pane, select Browse to the
  right of Default file location, browse
  to the folder of your choice, and
  click OK twice.
Excel 2007, click the Office button, choose Excel Options at the
  bottom of the window, and select Save
  in the left pane. Paste the folder path into the text
  box to the right of Default file
  location, and click OK.
PowerPoint 2007, click the Office button, choose PowerPoint Options at
  the bottom of the window, select Save
  in the left pane, paste the folder
  path in the text field to the right of
  Default file location, and click OK.

If your problem is making "Save As" use the same folder as where the file was opened in, then for Excel you need to use regedit. Go to the registry key
HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Options
and add a dword value named AlwaysSaveToCurrentPath and set it to 0
I do not know of such a solution for Word.

A: As far as I know, MS Office programs always load/save programs in a specified location. To change this location (e.g. for Excel), just follow the steps below:

*

*Click the Office Button.

*Click the Excel Options button.

*In the left pane, select Save.

*In the Default file location textbox, input the path to the desired directory that will be the new default location, and click OK.


text:
Q: Django Time Date Models What is the best field type/field option for a model that should only contain the date and month.
class Reminder(models.Model):
    person = models.OneToOneField(Person)
    reminder_one = models.???
    reminder_two = models.???

As I want to input a date that will act as a reminder each year I want to ensure no year is entered.
Thanks,

A: There are only two standard Django date fields-
DateField
DateTimeField
I suggest you use datefield and use the default querysets to sort by month and day:
QuerySets - Month
Otherwise, you would need to store the month and day as a string, and that gets messy and is just unnecessary.


text:
Q: C# Concurrency - Preferred approach to long running tasks When there needs to be an I/O listener running throughout an applications lifetime, what concurrency model is preferred with C# 5.0 running on the 4.5 framework?
I've settled on the idea that a producer-consumer pattern would be best for handling what I receive, but what infrastructure should support it?
Would a simple Thread thread = new Thread(ThreadStart(method)) be advised? or perhaps a Task or Async/Await model would be preferred?
It is a bit of a quick fire question, but as I'm early in the design, I'd prefer to make sure the foundation is strong. My gut reaction coming from other languages is that a simple thread running in the background is best, but the plethora of parallel frameworks in C# has thrown me off course.
If of any relevance, the poll time in my application would be handled by the I/O read timeout.
Update:
The I/O I refer to is an FTDI device, where bytes may be pushed by the device to the PC at any moment, depending on the state of the on-board controller. As a result, I always need to be ready to pickup the data and process it. The API I'm using is based on the D2XX DLL provided by the FTDI vendor.

A: If I interpret your "I/O listener" correctly, then you should just always have a continuous asynchronous read operation going. No thread is necessary.

A:
The I/O I refer to is an FTDI device, where bytes may be pushed by the
  device to the PC at any moment, depending on the state of the on-board
  controller. As a result, I always need to be ready to pickup the data
  and process it. The API I'm using is based on the D2XX DLL provided by
  the FTDI vendor.

A quick search discovers this document. A brief look at it suggests you'd need to open your device device for overlapped I/O, to implement an efficient listener. Here's a relevant sample code from the document (C++):
FT_HANDLE ftHandle; // setup by FT_W32_CreateFile for overlapped i/o
char Buf[256];
DWORD dwToRead = 256;
DWORD dwRead;
OVERLAPPED osRead = { 0 };
osRead.hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);

if (!FT_W32_ReadFile(ftHandle, Buf, dwToRead, &dwRead, &osRead))
{
    if (FT_W32_GetLastError(ftHandle) == ERROR_IO_PENDING)
    {
        // write is delayed so do some other stuff until ...
        if (!FT_W32_GetOverlappedResult(ftHandle, &osRead, &dwRead, FALSE))
        {
            // error
        }
        else
        {
            if (dwToRead == dwRead)
            {
                // FT_W32_ReadFile OK
            }
            else
            {
                // FT_W32_ReadFile timeout
            }
        }
    }
}
else
{
    // FT_W32_ReadFile OK
}

The key point here is this comment: "// write is delayed so do some other stuff until ... " [BTW, I believe it's a typo, there should be read instead of write there].
How to handle this delay? To make your listener asynchronous, you'd have to wait for the kernel event object asynchronously. I just answered a related question on how to do it efficiently. In your case, it might look like this (a sketch in C#):
async Task<Data> ReadFtdiAsync()
{
    // ...

    var completedMre = new ManualResetEvent(false);
    osRead.hEvent = completedMre.SafeWaitHandle.DangerousGetHandle();

    if (!FT_W32_ReadFile(ftHandle, Buf, dwToRead, ref dwRead, ref osRead))
    {
        if (FT_W32_GetLastError(ftHandle) == ERROR_IO_PENDING)
        {
            // asynchronous completion
            // read is delayed, so await

            var tcs = new TaskCompletionSource<bool>();

            ThreadPool.RegisterWaitForSingleObject(
                completedMre,
                (s, t) => tcs.SetResult(true),
                null, Timeout.Infinite, true)

            // resume asynchronously when the event is signalled
            await tcs.Task;

            if (!FT_W32_GetOverlappedResult(ftHandle, ref osRead, ref dwRead, FALSE))
            {
                // error
                throw new InvalidOperationException("I/O error");
            }
            else
            {
                if (dwToRead == dwRead)
                {
                    // FT_W32_ReadFile OK

                    // retrieve and return the data
                    return data;
                }
                else
                {
                    // FT_W32_ReadFile timeout
                    throw new TimeoutException();
                }
            }
        }
    }
    else
    {
        // synchronous completion

        // retrieve and return the data
        // or handle an error
        return data;
    }
}

This code may and should be improved with proper timeout and cancellation logic. Then you can simply call ReadFtdiAsync in a loop:
while (true)
{
    cancellationToken.ThrowIfCancellationRequested();
    var data = await ReadFtdiAsync(cancellationToken);

    // the execution will resume here likely on a different thread
    ProcessData(data);
}

A: For I/O is always better to use I/O completion ports that in .net are wrapped in methods like
Stream.BeginRead
Stream.BeginWrite

or for .net 4.5
Stream.ReadAsync
Stream.WriteAsync

is a very bad idea to put a thread or a task to wait for a synchronous I/O operation


text:
Q: Precession of perihelion of Mercury? I have a few questions about precession of Mercury and GR corrections. Feel free to any that you can:

*

*GR is used to correct precession caused by Sun on Mercury by time dilation and length contraction. Why isn't same treatment done to gravitational tugs of other planets on Mercury? Their value of 532 arcsec per century is taken as it is and correction is only done to Sun-Mercury couple.

*Why does gravitational tug of other planets on Mercury valid in GR? Metric around Mercury is heavily influenced by Sun and contribution by any other planet should be negligible. Unlike in Newtonian gravity where gravity propagates without a metric.
I have a few more minor doubts but i think they will be cleared if these are cleared first.

A: *

*The GR precession angle correction for the Sun-Mercury pair is proportional to $G M_{\odot} / L$, where $M_{\odot}$ is the mass of the Sun while $L$ is the angular momentum of Mercury relative to the Sun, and it is quite small, less than an arcminute in a century.
If you were to compute it inserting any Solar System mass other than that of the Sun, you would get a much smaller correction: for example, Jupiter is quite massive but $M_{\text{jup} }/ M_{\odot} \approx 10^{-3}$, and the angular momentum contribution $1/L_{\text{jup}}$ would also be smaller than $1/L_{\odot}$ since the distance is larger. You can do the computation if you like: you will find that the corrections due to the other bodies are at least a few orders of magnitude below the main (Sun-Mercury) one.

*GR reduces to Newtonian gravity in the weak-field limit, which is a good approximation for the Solar System, so any Newtonian results you find in this context will be very close to the GR results.
The pull of the other planets on Mercury is "negligible" in GR pretty much as it is in regular Newtonian mechanics: you can neglect it if you want a rough idea of the motion, while if you want to make precise predictions you need to account for it.
What this means is that, when working in the framework of GR, you can achieve different levels of precision by neglecting certain terms which are small in certain contexts.
The roughest approximation to GR is Newtonian mechanics, you can then refine the estimate by considering relativistic effects ever more precisely.
The problem is, the more precisely you want to consider the relativistic effects the harder it becomes in terms of calculations. For the proper, no-approximation route, in all but the simplest cases we need computers to crunch the numbers.
On the other hand, Newtonian gravity is much more tractable, we know how to deal with it.
So, for each interaction between two bodies we ask ourselves: how deep do we need to go? There are certain rules of thumb to tell us what needs to be considered and what does not. It turns out, for the Mercury-other planet pairs the Newtonian approximation works well, and the GR corrections would be undetectable, while for the Mercury-Sun pair the first relativistic order is small but detectable.
$GM/L$ for the two bodies." />
Here is a plot of the order magnitude of the GR correction to the motion of Mercury from the Sun and from Jupiter: you can see that the correction from Jupiter is typically three orders of magnitude smaller than the one from the Sun.
A full-GR calculation for the motion of Mercury would be unnecessarily complicated: the reasonable thing to do in this context is to figure out the margins of error on the measurements of the positions, then estimate how much any corrections will affect the result of the calculation, and neglect anything which is much smaller than the errorbars.
Even the calculation of the correction to the orbit of Mercury is an approximation: the crucial thing is, the expansion parameter (in this case it is $G M_{\odot} / L \approx 0.00016$) is small, so the next term in the expansion is unmeasurable.
As we get more precise measurement devices, we will need to account for more terms.


text:
Q: XCode why is it in red yet still buildable? I downloaded the VLC iOS app which uses libMobileVLCkit. I uses the build script included in the download which download MobileVLCKit source code and builds it, plus a few tweaking (XCode group and files pane points to the wrong folder). And I was able to build just fine.
I noticed that MobileVLCKit includes a few simple sample code, and when I run it it is fine. However, libMobileVLCKit.a which appear in the group and file pane on the left is red, even though it builds fine into the phone.
When I do remove libMobileVLCKit.a from the left pane, build fails.
Why is that the case? What does it really mean to be red?
EDIT:
screenshot


text:
Q: Redirect Image to homepage I want to redirect an image path to my website homepage:
https://www.domainname.com/wp-content/uploads/2017/03/infographic.png

to
www/domainname.com.

I was trying to do it with the code below
# WPhtc: Begin Custom htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !/wp-admin/ [NC]
RewriteRule ^wp-content/uploads/2017/03/.+?\.(jpe?g|png|gif|svg)$ /home [R=301,L]
</IfModule>
# WPhtc: End Custom htaccess

But it's not working.

A: I think this is the simplified rule set what you are looking for:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https?://[^/]+/wp-admin/ [NC]
RewriteRule ^/?wp-content/uploads/\d+/\d+/ / [R=301,L]

It will redirect all requests to something inside those upload folders to the base URL of your site.

Obviously if you only want to redirect from that specific folder this also is possible:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https?://[^/]+/wp-admin/ [NC]
RewriteRule ^/?wp-content/uploads/2017/03/ / [R=301,L]

And you certainly can also limit that logic to certain file name extensions only:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https?://[^/]+/wp-admin/ [NC]
RewriteRule ^/?wp-content/uploads/2017/03/[^/]+\.(jpe?g|png|gif|svg)$ / [R=301,L,NC]


text:
Q: write to database when ios app in background state When iPhone app is in background state or when app is minimized, I want to monitor the duration of time the app is in background and on every regular interval like every 24hrs need to get updates from web server and write the modifications in my local database.
This monitor cycle will repeat as long as app is in background. Is this kind of task is possible in iPhone applications ? Could any body help me how can I perform these tasks when app is in background state ?
beginBackgroundTaskWithExpirationHandler: is the API to make the app in background for long tasks but how long will this support.

A: Background tasks are killed after 10 minutes time, so to answer your question: No, it's not without faking some kind of long term event handling through a significant location's update, and even then, you have no control over when exactly the events are sent.  On the other hand, using APNS to alert the user to a change has the possibility of being ignored, but comes with regularity.


text:
Q: chrome extension - randomly reloading thus loosing all state variables Helllo all
I'm strugling to figure out why my background.js script is randomly reloaded in browser if I reload, open, close tabs.
The problem is that background script holds some state variables and these get lost if script/extension is reloaded.
What I tried so far:

*

*Opening developer console for script worker, does not produce this problem.

*I tried to use local storage to store state variables, but not luck. When script is reloaded local storage value is gone.

*I do not reload extension nor change background scripts in any way while testing

[EDIT]
https://www.dropchop.com/test.zip OR https://www.dropbox.com/s/xtisv8c8pgxnu7z/test.zip?dl=0
Here is test extension. Install it unpacked. Open service worker developer console. Copy paste time from console. Close dev console. Open,close,refresh 10 or more tabs, pages. Reopen service worker developer console. Check time. In my case it's not the same, so that means it was reloaded.
Using Chrome on Linux: Version 97.0.4692.71 (Official Build) (64-bit)
Don't have any other ideas and can't find any help online about it, so I'll appreciate it here
Regards
Armando

A: With the help of wOxxOm I've managed to figure this one out.

*

*service workers in manifest v3 are not stateful so they get destroyed and recreated and that's how state variables get lost

*Store state variables in local storage but beware because, when you get something from local storage you get an object in result. Like object with your key in it
{ "yourKey" : {... your data ....}}


text:
Q: Why after create elements with jquery they'r not visible in Chrome I am creating elements with jQuery in a simple way.
So it should work after document ready, and it works fine with IE, but not with Chrome, Firefox or Safari.
They are created, but are not visible!
In chrome for example, when I include an alert after document ready, after click ok, elements become visible, or when I open "inspect elemnt" elements become visible too.
Any one knows what is the problem?
var radio_span = $('')
 .addClass('jqTransformRadioWrapper')
 .attr('id', spanRadio_id) (...etc)

A: var radio_span = $('')
 .addClass('jqTransformRadioWrapper')
 .attr('id', spanRadio_id) (...etc)

What this does is put your element in the radio_span variable, to see the element you will have to somehow insert it into the document with append, prepend, html or any other method that does this, like so:
radio_span.appendTo('body');

http://jsfiddle.net/adeneo/zKWxp/4/
I see now that your writing that elements become visible when opening inspect element or adding an alert, wich sound very strange, and you will probably have to do what Felix is saying, add more code!

A: Shouldn't it be this:
var radio_span = $('#spanid');
 radio_span.addClass('jqTransformRadioWrapper');

A: try to wrap your code in:
$(function() { ... });

If this doesn't work then try to wrap it into:
$(window).load(function () { ...  });


text:
Q: What is the history of the IndianEnglish usage of "doubt" to mean "question"? I've observed a significant number of questions on SO & SE, presumably written by folks use Indian English, in which the word "doubt" is used where "question" should have been used.  The sentences usually look like "I have a doubt about [interesting topic].."
My question, then, is: how or why did Indian English shift the meaning of "doubt" from its usage in British English?  I'm looking for any historical development of this usage.
Edit required by SE - the latest comments on literal vs. idiomatic translations are more what I'm after. How did the word "doubt' take on this non-BritEng usage in India?

A: The root of this usage can perhaps be traced to one Indian word: Shankaa. The word Shankaa does represent doubt with the sense as in British English. However, it does get used to convey one more sense: a state of 'confusion', i.e., partial understanding enough to make one capable of seeking a clarification. Often this state doesn't get referred to as a state of having a question in mind, since the question itself may not be very clear and precise, and it may also be an invalid one. Secondly, questioning also sounds like being a bit aggressive, conveying a feeling of posing as a challenger. Posing doubts sounds more polite and correct. So, the teachers ask questions and the students have doubts for clarification! Thus, Doubt when used to represent a question becomes more friendlier than Question.


text:
Q: Is there any problem in this task? (molecular formula of a gas inside a cylinder) I got this task:
A cylinder of volume V₁ = 2 L filled with gas of mass m = 7.48 g at T = 10 °C and under pressure P₁ = 2 bar

*

*Calculate the amount of gas substance in the cylinder.

*Infer the molecular formula of a gas? The following gas formulas are given: CH₄, N₂, CO₂, H₂

*What is the number of molecules of this gas inside the cylinder?

I tried to answer 2nd question, but I couldn't because we know:
M(C) =12 g.mol-1, M(O)=16 g.mol-1, M(H)=1 g.mol-1, M(N)=14 g.mol-1
Then: M(CH₄)=18 g.mol-1, M(N₂)=28 g.mol-1, M(CO₂)=44 g.mol-1, M(H₂)=2 g.mol-1
and when you calculate it using:$n = \frac{m}{M}$ you can't find any of the previous results.
Look at my answer:
$P.V=R.T.n$ $$n = \frac{P. V} {R. T} = \frac{2.10⁵. 2} {8,31. 283}=170$$
$$170 = \frac{7,48}{M}$$ $$M = \frac{7,48}{170}=0.044$$


text:
Q: How to decide which file or folder to map with host? I'm new to docker and pulled plesk panel docker image from this link. I succesfully built and ran this container using following command and created some data in it.
docker run -d -p 80:80 -p 443:443 -p 8880:8880 -p 8443:8443 -p 8447:8447 plesk/plesk

Whenever I restart container from image, I lost my data on plesk panel. Fair enough, because I'm creating a fresh container whenever I started container from scratch. I know that I need to create volumes and save data in it and mount container everytime from these volumes, it's ok. But here is my question, which file inside container will I map with host? How to decide it? Is it enough to create a volume with /data directory in every container? How to find container saves data in which of its directories?
Thanks in advance.


text:
Q: How to create a bounded queue for shell tasks? I have 1000 gzipped files which I want to sort.
Doing this sequentially, the procedure looks pretty straightforward:
find . -name *.gz -exec zcat {} | sort > {}.txt \;

Not sure that the code above works (please correct me if I did a mistake somewhere), but I hope you understand the idea.
Anyway, I'd like to parallelize ungzip/sort jobs in order to make the whole thing faster. Also, I don't want to see all 1000 processes running simultaneously. It would be great to have some bounded job queue (like BlockingQueue in Java or BlockingCollection in .NET) with configurable capacity. In this case, only, say, 10 processes will run in parallel.
Is it possible to do this in shell?

A: Use GNU Parallel:
find . -name *.gz | parallel --files 'zcat {} | sort' | parallel -X -j1 sort -m {} ';' rm {} > sorted

You can install GNU Parallel simply by:
wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel

Watch the intro videos to learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1 and walk through the tutorial (man parallel_tutorial). You command line with love you for it.

A: I'd pick make(1) for this task -- it isn't shell, but the make(1) jobserver is nearly exactly what you wanted, and this task is well-suited to make(1)'s abilities. Note that the line starting gzip -cd is indented with a tab character. This is vital. (make(1) can also feel a little old at times.)
$ cat Makefile
TXT := $(wildcard *.gz)

all: $(TXT:.gz=.txt)

%.txt:%.gz
    gzip -cd $< | sort > $@
$ cp /usr/share/man/man2/*.gz .
$ ls -l
total 1992
-rw-r--r-- 1 sarnold sarnold  4447 2011-12-06 00:22 aa_change_hat.2.gz
-rw-r--r-- 1 sarnold sarnold  3977 2011-12-06 00:22 aa_change_profile.2.gz
-rw-r--r-- 1 sarnold sarnold  5082 2011-12-06 00:22 accept.2.gz
...
$ time make -j 10
gzip -cd aa_change_hat.2.gz | sort > aa_change_hat.2.txt
gzip -cd aa_change_profile.2.gz | sort > aa_change_profile.2.txt
gzip -cd accept.2.gz | sort > accept.2.txt
gzip -cd accept4.2.gz | sort > accept4.2.txt
gzip -cd access.2.gz | sort > access.2.txt
...
gzip -cd write.2.gz | sort > write.2.txt
gzip -cd writev.2.gz | sort > writev.2.txt

real    0m0.259s
user    0m0.190s
sys 0m0.020s
$ rm w*txt
$ make
gzip -cd wait.2.gz | sort > wait.2.txt
gzip -cd wait3.2.gz | sort > wait3.2.txt
gzip -cd wait4.2.gz | sort > wait4.2.txt
gzip -cd waitid.2.gz | sort > waitid.2.txt
gzip -cd waitpid.2.gz | sort > waitpid.2.txt
gzip -cd write.2.gz | sort > write.2.txt
gzip -cd writev.2.gz | sort > writev.2.txt
$

Notice with the rm w*txt command that make(1) intelligently only does the minimum amount of work necessary to get anything done.

A: A quick trip to Google reveals this interesting approach: http://pebblesinthesand.wordpress.com/2008/05/22/a-srcipt-for-running-processes-in-parallel-in-bash/
for ARG in  $*; do
    command $ARG &
    NPROC=$(($NPROC+1))
    if [ "$NPROC" -ge 4 ]; then
        wait
        NPROC=0
    fi
done

A: Sorting the uncompressed contents of many compressed files and storing the result in an uncompressed file:
find . -type f -name '*.gz'
    -exec sh -c 'for n; do zcat "$n" | sort -o "$n.txt"; done' sh {} +

This will execute the for loop
for n; do
    zcat "$n" | sort -o "$n.txt"
done

with as many files as possible at once.  A for loop that does not have in X will iterate over "$@" by default.
The sh -c shell will be called by find with as many file paths as possible (due to the + instead of \; at the end), and these paths will be available to the sh -c shell in $@.

In your original command,
find . -name *.gz -exec zcat {} | sort > {}.txt \;

you have some issues:

*

**.gz is unquoted, which means that the shell will perform filename globbing on it with the filenames in the current directory.

*-exec can only grok a simple command, not a pipeline.

*You don't restrict to regular files, which theoretically means you could pick up a directory whose name is something.gz.

A: With GNU xargs, you can do:
xargs -P4 -n 10 -r0a <(find . -name '*.gz' -type f -print0) sh -c '
  for file do
    zcat < "$file" | sort > "$file.txt"
  done' sh {} +

That would call up to 4 sh in parallel, each processing up to 10 files one after the other in a loop.


text:
Q: How did the magicians obtain the buttons that they possessed at the climax of "The Magician's Land" The Magicians trilogy features magical buttons that was used to travel between Earth/Fillory and the Neitherlands (presumably inspired by the similar magic rings featured in the Magician's Nephew).  Towards the end of the novel the text indicates that the magicians possess at least three such buttons.  But based on the earlier books I cannot see how they can have any of them.
Spoilers for all three books below.
In the first book we learn that the Jane brought five buttons back from Fillory.  One of her sisters hid them, but she found them again, and took one of the buttons for her personal use.  She still has it at the end of "The Magicians".
Penny obtains one of the buttons from the magic grey market.  He forms a party with himself, Quentin, Eliot and others to go to Fillory for the first time.  At the end of the book (as mentioned in the answer to How did Quentin and the 3 others return to Fillory between The Magicians and The Magician King) he goes off by himself leaving the button with the rest of the party.
In the second book Josh takes the initial button (since the others want to remain in Fillory) and goes exploring with it.  Later he sells it for $250M to a dragon.
Although Quentin switches between worlds five times in the second book, he never does so by means of a button.  In fact his (and Julia's) search for a button is one of the plot drivers for this book.  As far as I can tell once Josh has sold his button none of the main characters have one any more.
At the start of book three we have Eliot, Janet, Josh and Poppy in Fillory, and Quentin (with Plum) on Earth.  I would not expect anyone to have any buttons at this point, and indeed they go unmentioned until towards the end of this book.
But as the end approaches there seem to be at least three of them around.

*

*Eliot returns by himself to Earth.  It does not say how he travelled, but it would appear that he used a button.  When Eliot and Plum try to travel to the Neitherlands they end up unexpectedly inside one of the buildings.

(page 356) "This isn't right," Eliot said.  "This isn't the Neitherlands I don't think.  We've been hijacked.  Button-jacked."

The inference is that they were traveling by button.

*Quentin and Alice travel to the Neitherlands separately soon after.  On arriving the narrator says

(page 357) Sure enough, up popped Quentin and Alice, her spluttering and blowing, ... then swam breaststroke over to the steps, at which point it became apparent that she was completely naked.  What, did they roll over onto the button halfway through?

Again the inference is that they travelled by button.  It must have been a different button to the one used by Eliot and Plum.

*Simultaneously Fillory is going to pieces.  Although Julia sends Janet, Josh and Poppy to the Neitherlands, it is apparent that they had a button.  Earlier Josh said:

(page 328) "When it gets too bad," he said, "we'll come back for you.  With the button".

Since Eliot has already left at this point, Josh cannot have been talking about either of the buttons that Eliot presumably had with him.  So there must be a third button.

But I do not see how they can have any buttons.

*

*It is hard to believe that the dragon would ever give up the one it bought.

*I could believe that Jane would give up hers.  But when Eliot and Janet meet Jane earlier in the third book it is apparent that they have never met before.  The narration says nothing about her giving her button to them.

*The other three buttons presumably vanished into hands of magic collectors on Earth.  Since the dragon was willing to pay $250M they must not change hands often or at all.  But in any case the narrative is clear that Quentin does not have a button and there seems to be no way that Eliot/Janet/Josh/Poppy could ever have got to Earth to look for one.

So how did they get the buttons?  Did I miss some text?  Or do we just have to assume that Eliot and co. found some cache of buttons in Fillory that the author did not bother to narrate.
(This question is about the books not the TV series)


text:
Q: Getting Error "Cannot start more than one local run" in Unit Tests in Visual Studio I am executing a Test to Automatically start my Windows Application. To lauch the Windows Application; the Code used is Application.Run(Client.MainForm.GetInstance())";. The Debug point comes out of this piece of Code only after i close the Windows Application.
I cannot run any other tests until then. If i try to do so; Visual Studio throws me an error "Cannot start more than one local run". IS there a way out of this problem?

A: Unit-testing is not primarily meant to start / stop GUI's, but more to test blocks of code outside a GUI. However, if you intend to do so, you can add Client.MainForm.GetInstance().Close(); to the end of your test.
Additional info: you cannot start other unit tests while one test is still running. As your GUI test will not be completed until you terminate the GUI (e.g. your test is still running while your GUI is open), other tests cannot start.


text:
Q: excel macro to search a website and extract results I have a value in Sheet 1, A1.  It is either a business name, or its associated business number (as the site searches by number or name). Once I have entered the business name (or number) of the business I need the details on, I want to be able to click a "search" button and have the results of  the search displayed in a table with 2 columns (say sheet 1, A5:B9) with the labels in left column of table and the results in the right.
the site i need to search is http://www.abr.business.gov.au/
eg. If i search for the business number 31701562618 these are the results i get (and how i need displayed in excel:
      Column A                       Column B
5   Entity name:                  AMBROSE, BENJAMIN STEPHEN
6   ABN status:                   Active from 05 Apr 2000
7   Entity type:                  Individual/Sole Trader
8   Goods & Services Tax (GST):   Registered from 01 Jul 2000
9   Main business location:       QLD 4310

A: After some more tinkering i managed to get this to work. This just searches the site for the value in A1, grabs the results data and puts it into cell  starting at A5. NO formatting however that is easy enough to include after the 'End With' bit.
Sub URL_Get_ABN_Query()
strSearch = Range("a1")
With ActiveSheet.QueryTables.Add(Connection:="URL;http://www.abr.business.gov.au/SearchByABN.aspx?SearchText=" & strSearch & "&safe=active", _
Destination:=Range("a5"))

.BackgroundQuery = True
.TablesOnlyFromHTML = True
.Refresh BackgroundQuery:=False
.SaveData = True
End With
End Sub


text:
Q: HTTPS not working; binding set, certificate installed I've installed the certificate and set up the HTTPS bindings. However, when I load the site on HTTPS it does not load.
I've looked at all the settings but everything seems correct.
I've restarted the server numerous times. The certificate is stored on the local computer under Personal > Certificates. I have the private key for the certificate. The port (443) is open.
If I try https://localhost on the server, the site loads, but with a domain error (i.e., it's localhost and not example.net). But https://example.net doesn't load.
I really don't know why the HTTPS URL isn't loading.

A: If you are getting "Server Not Found", that means that the client could not find the responsible server to serve your request. In your case, that's a HTTPS-based application. You also said that HTTP works but HTTPS fails.
Verify the following:
Go to Control Panel\System and Security\Windows Firewall\Allowed Programs
Verify that you have "Secure World Wide Web Service (HTTPS)" and "Domain, Home/Work, and Public" both checked.
You also said that when you try https://example.net from the server itself, it fails. Try browsing the application from the server itself and run netstat -ano and check whether there is any activity happening on port 443.

A: You need to ensure that example.net actually points to the server's IP. You can do this either with an nslookup or just plain old ping the machine. This is your most likely cause.

A: I had the same problem and the cause was that the firewall was blocking port 443, the same as a couple of other people in the comments of the other solutions.  I don't know how all firewall software works, but in Windows Azure, you have to explicitly add an Inbound Traffic rule to allow traffic on port 443.

A: I was facing the same problem and this problem occurred because of my router's port forwarding configuration. I configured my public IPs port forwarding on port 80, not 443. Thats why I can't access my site remotely using HTTPS protocol. I solved this problem by configuring my public IP port forwarding on port 443. Then it starts working. But first, make sure to check that port 443 is open and it is allowed on your firewall.


text:
Q: Error: Lexical or preprocessor issue when trying to import external framework When i try to import external framework (named Mappy), i git an error in the build and run phase:
Lexical or preprocessor issue
'MappyKit/MappyKit.h' file not found.

The obvious thinking say that the MappyKit.h file is missing. However, it does exist in the framework folder.
So, please, what kind of issue is that? i am struggling with that for days.

A: Usually it means just like the error says " 'MappyKit/MappyKit.h' file not found. " So import that file into your folders. Also make sure you are importing it correctly.
#import <something>
vs
#import "something"

Though I have had issues were it was working one build and then getting this error the next. Which i managed to clean my build and it fixed it.
To see if you actually connected the external frameworks, you can hover over #import <something> and hold down command->left click if that opens up your imported file, then you imported correctly!


text:
Q: web element position problem Make each of the two element take half of the width of their parent.
Here is my example:
http://jsfiddle.net/zUqqN/
I just want the div#mapContent_coverage do not show by default,and then the div#mapContent_emap will take all the width of the "mapDiv",
when user click the img in the right,the div#mapContent_coverage should show,and then "mapContent_emap" and "mapContent_coverage" will show at the same time,and I want both of them take half of the width.
I have tried use the  float and absolute to the div,but it does not work,any idea?
BTW,I do not want the scrollbar show in the browser,for exmaple:
Now matter how do I resize the browser ,there is not scroll bar . How to make this?

UPDATE:
The default page layout:

WHen I click the img in the right,the page should change to :

A: to hide the scroll from the browser add this CSS:
html, body {
  overflow: hidden;
}

(I'll reply to the rest after clearing some doubts, check my comment)

A: To display both set each width to 50%. To display only one set the width to 100% and hide the other.


text:
Q: alternate value even or odd week number from startdate I'm trying to assemble a table that shows the amount of hours an employee has to work in each week of the year.
There are 2 tables for this:
First table:
EMPLOYEEID  REGIMENO    DATEACTIVE
700944      04          2012-01-01 00:00:00.000

another table
REGIMENO    Week1   Week2
01          40      40
02          32      32
03          32      32
04          40      32

I want to achieve something like:
EMPLOYEEID WEEKNUMBER HOURS
700944     1          40
700944     2          32
700944     3          40
700944     4          32
....

So i'm kinda stuck how to first of all join every week to it, and second of all keep in mind that not every scheme starts on the same date for each employee...
Any ideas?
Thx in advance


text:
Q: Create COM object from .NET COM method Here is a code sample
    [Guid("159463FB-A87A-4BBB-BCA1-064CD84495FB")]
    public interface ISettingsFactory
    {
        ISettings GetSettings(string userName);
    }

    [Guid("FD11B979-0ED1-41fb-8EB0-1234512345D0")]
    public interface ISettings
    {
        string PrivateKey {get;}
    }

    [Guid("782937826-705F-4be2-1234-A748332D6D1")]
    [ClassInterface(ClassInterfaceType.None)]
    public class SettingsFactory : ISettingsFactory
    {
        public ISettings GetSettings(string userName)
        {
            return new Settings(userName);
        }
    }

     [Guid("8BDC1F18-48FD-4a49-8DF3-D81C6321657B")]
     [ClassInterface(ClassInterfaceType.None)]
     public class Settings : ISettings
     {
         private readonly PrivateData privateData;

         public Settings(string userName)
         {
             privateData= PrivateData.Load(userName);
         }

         public string PrivateKey
         {
            get { return privateData.Key; }
         }
     }

The problem is when creating SettingsFactory COM class from VB6 code and calling method GetSettings(userName)
settings = factory.GetSettings(userName);
key = settings.PrivateKey //<--- Exception occurs saying "Read write from protected memory is not allowed" or something like this.

The problem disappears when in GetSettings method I save Settings instance in field of SettingsFactory, so that GC doesn't collect it. Does anyone know why is this happening? I mean why GC collects objects that are exposed to COM? Isn't RCW increases the ref number on the Settings object after GetSettings get called?

A: I think the problems is that privateData.Key is not being marshalled correctly. I can't see the definition for the type of Key but my guess is it is a ptr to some kind of data and tha this data isn't being marshalled correctly. If thats the case you probably need to use one of the Marhal.PtrToXXX fumctions.
A great place to start if you want to learn more about using COM objects from .net are the MSDN articles on Runtime Callable Wrappers


text:
Q: How Can I get multiple Sub queries from "From Clause" using JSQLparser ? I want to get all the Sub-queries in a from clause but When I have used
 FromItem fromItems = plainSelect.getFromItem();

It just retrieves the first sub query in the from clause and when I used
 Expression exp = plainSelect.getJoins().get(i);

It retrieve the tables in the from statement not the Sub queries.

A: So here is a little code snipped. You have to know, that the first table/subselect is stored within the fromItem from your PlainSelect and the followings within the joins. You have to process both. Thats due to the parsing architecture JSqlParser uses.
Within JSqlParser you have two types of traversing the returned object hierarchy: 1. visitor pattern, 2. direct object hierarchy access. I implemented both within this little example.
EDIT: To find hierarchical all subqueries JSqlParser identifies, I included Type 3, which is kind of a hack, since I somehow missused the deparser.
public class SimpleSqlParser10 {
    public static void main(String args[]) throws JSQLParserException {
        String sql = "SELECT * FROM myTable, (select * from myTable2) as data1, (select b from myTable3) as data2";
        Select select = (Select)CCJSqlParserUtil.parse(sql);
        System.out.println(select.toString());

        System.out.println("Type 1: Visitor processing");
        select.getSelectBody().accept(new SelectVisitorAdapter(){
            @Override
            public void visit(PlainSelect plainSelect) {
                plainSelect.getFromItem().accept(fromVisitor);
                if (plainSelect.getJoins()!=null)
                   plainSelect.getJoins().forEach(join -> join.getRightItem().accept(fromVisitor));
            }
        });

        System.out.println("Type 2: simple method calls");
        processFromItem(((PlainSelect)select.getSelectBody()).getFromItem());
        if (((PlainSelect)select.getSelectBody()).getJoins()!=null)
            ((PlainSelect)select.getSelectBody()).getJoins().forEach(join -> processFromItem(join.getRightItem()));

        System.out.println("Type 3: hierarchically process all subselects");
        select.getSelectBody().accept(new SelectDeParser() {
            @Override
            public void visit(SubSelect subSelect) {
                System.out.println("  found subselect=" + subSelect.toString());
                super.visit(subSelect);             }
        });
    }

    private final static FromItemVisitorAdapter fromVisitor = new FromItemVisitorAdapter() {
        @Override
        public void visit(SubSelect subSelect) {
            System.out.println("subselect=" + subSelect);
        }

        @Override
        public void visit(Table table) {
            System.out.println("table=" + table);
        }
    } ;

    private static void processFromItem(FromItem fromItem) {
        System.out.println("fromItem=" + fromItem);
    }
}

This one outputs
SELECT * FROM myTable, (SELECT * FROM myTable2) AS data1, (SELECT b FROM myTable3) AS data2
Type 1: Visitor processing
table=myTable
subselect=(SELECT * FROM myTable2) AS data1
subselect=(SELECT b FROM myTable3) AS data2
Type 2: simple method calls
fromItem=myTable
fromItem=(SELECT * FROM myTable2) AS data1
fromItem=(SELECT b FROM myTable3) AS data2
Type 3: hierarchically process all subselects
  found subselect=(SELECT * FROM myTable2) AS data1
  found subselect=(SELECT b FROM myTable3) AS data2


text:
Q: accessing doc.id in .onWrite firebase cloud function I'm triggering a cloud function with onWrite. Within the onWrite function, I want to do something with the ref ID of the document that was written. How can I grab this? My current code looks something like this, but I don't know how to fill eventID.
exports.syncEvents = functions.firestore
    .document('events/{eventID}')
    .onWrite((change, context) => {

admin.firestore().collection('users').doc(host).collection('events').doc(eventID).set({
            active: true
          })
        });

A: change.after is a DocumentSnapshot of the document that changed, after it was written.  DocumentSnapshot has a property called id that contains the id of the document.  So change.after.id is the document id.

A: The context object contains the params of the query.
In your example, the context object will look like this:
{
 ...
 params: {
   eventID: "whatever-eventId-is"
 }
 ...
}

So you just call get it from the context:
const eventId = context.params.eventId;

Here is more about context:
https://firebase.google.com/docs/reference/functions/cloud_functions.eventcontext


text:
Q: EXE file package repair I downloaded a large EXE file, but when I try to install it, during the installation process an error message said that some components are corrupted or missing, although the software is compatible with my OS.
Now I don't want to download the software again, because I have a slow connection (128 kbit/s ADSL). Is there any way to repair the EXE file without redownloading it again?

A: No. : (
But you can try downloading it from a different place, or via a different method - there are several, like FTP/HTTP/Torrent .

A: Definitely no. If the checksum doesn't match, then the smallest bit error in any file makes it unreadable. That's why there are checksums.
Certain compression utilities can add cyclic error checks in order to compensate for this, so that's why it's a better idea to compress or split a large file first before downloading. In some cases you can then even try to repair broken files, or at least detect it's broken.
For the next time, just use the checksum or look for another way to download the file, it all depends on what it actually is.

A: As mentioned, there is no (practical) way to "repair" an installation program, especially if the file is the right size.

If it is incomplete (and usually this is the case), something that you can try is to cut the file back by some (it depends on how big the file is, say for example the last 5%), then use a program like WGET to re-download the file, continuing from that point on instead of from the beginning.
However this is in no way guaranteed to work since the corruption could easily have happened earlier in the file (often the file has a chunk missing from somewhere in the middle), and you could end up having to re-download the whole thing anyway.

If the file is of a decently significant size, a better option could be to look around for a TORRENT file that includes the file. Then you can load it into a BitTorrent client and point it at your file, then re-check. It will then indicate any parts of the file that are correct and allow you to re-download only the parts that are bad from a P2P network.
You can also try doing the same thing with the donkey network with eMule: search for the file, import your existing one, re-check, then resume the corrupt chunks.
Again, it depends on the file in question, specifically how big it is and how popular/available it is. If you want, you can say what file it is to get specific help/instructions.

Finally, yet another option is to try opening the file using an archiver (specifically 7-Zip). Then you can examine the contents (assuming that it is an executable archive) and perhaps extract (most of) the contents manually. Of course, if the file is corrupt, then you probably won't be able to get all the files anyway.

A: You'll have to download it again, but if you use a download manager like FlashGet (or wget if you feel like learning its myriad of options) then you can resume it in the event your download fails or gets cut off.


text:
Q: Is this generics example from Bruce Eckel's "Thinking in Java" wrong? I am reading the generics chapter in "Thinking in java". The program is there below.
public class GenericWriting {
    static <T> void writeExact(List<T> list, T item) {
        list.add(item);
    }
    static List<Apple> apples = new ArrayList<Apple>();
    static List<Fruit> fruit = new ArrayList<Fruit>();
    static void f1() {
        writeExact(apples, new Apple());
        // writeExact(fruit, new Apple()); // Error:------------------line 1
        // Incompatible types: found Fruit, required Apple
    }
    static <T> void writeWithWildcard(List<? super T> list, T item) {
        list.add(item);
    }
    static void f2() {
        writeWithWildcard(apples, new Apple());
        writeWithWildcard(fruit, new Apple());
    }
    public static void main(String[] args) { f1(); f2(); }
}

Below it says "The writeExact( ) method uses an exact parameter type (no wildcards). In f1( ) you can see that this works fine—as long as you only put an Apple into a List<Apple>. However, writeExact( ) does not allow you to put an Apple into a List<Fruit>, even though you know that should be possible."
But when I uncomment the line 1 and execute it, it is working fine. Can anyone please help me where I went wrong?

A:
However, writeExact( ) does not allow you to put an Apple into a List<Fruit>, even though you know that should be possible.

This is incorrect. writeExact can put an Apple in to a List<Fruit>. <T> is inferred to be Fruit and Apple (presumably) is a subtype of Fruit.
The book contains an error. I can confirm that this will compile as of Java 5, when generics were introduced.

A: I think the author instead of the line
static List<Fruit> fruit = new ArrayList<Fruit>();
wanted to write
static List<? extends Fruit> fruit = new ArrayList<Fruit>();


text:
Q: Sync folder of VMWare host and guest I am running Win 7 for everyday use, but for development I power up VMWare Workstation 9 with Ubuntu 12.04 LTS installed. What is the easiest way to keep my sourcecode developed in the guest system in sync with the host? (e.g. for the case of guest system failure - I always consider these as disposable.)
Approaches I could think of:

*

*Some kind of "folder sharing" as known from windows-only networks

*Using some VM feature to mount a host folder into the guest

*having an SVN server on the host (Tortoise) reachable from withhin the guest

*Using some Unix feature to upload files via Net to the host

What is the most common / best practise way? One goal it to keep the host system clean and with a minimum of additional software, while I don´t mind what to install on the guest. I would prefer some VMware approach, I exists.
Thanks!

A: The simplest VMware approach would be to utilize shared folders. You can reference this link for more information regarding shared folders and this link details how to mount shared folders on Linux guests


text:
Q: How to remove local git history after a commit? I would like to switch from Dropbox to the open source Sparkleshare. It uses git for the syncing and versioning. If say I had a 1GB file I deleted in my folder, it stays within the history of the local .git folder. But I would like to have this kind of heavy data on the server and not the client.
How can I commit my repository and delete the local one with git?
Many thanks!

A: Solution removing the history

*

*git fetch --depth=1 to prune the old commits. This makes the old commits and their objects unreachable.

*git reflog expire --expire-unreachable=now --all. To expire all old commits and their objects

*git gc --aggressive --prune=all to remove the old objects

Specific solution just to remove the large file in the local history

*

*GitHub offer's Git Large File Storage, which stores large files always on the server and fetches them only on checkouts. Very easy to setup and use - in case your repository is on GitHub, bitbucket, or gitlab.

*git-annex - allows storing big files anywhere

Discussion: How do Git LFS and git-annex differ?

A: Based on koppor's answer, I created this single line bash command to clear the local git history from all repositories which are in the same base folder:
for d in */; do echo $d && cd "$d" && git fetch --depth=1 && git reflog expire --expire-unreachable=now --all && git gc --aggressive --prune=all; cd ..; done

Note: you can replace */ by any specific folder criteria if you wish, such as *mobile*/ .
Windows cmd version (untested):
FOR /D %d IN (*) DO (echo $d && cd "$d" && git fetch --depth=1 && git reflog expire --expire-unreachable=now --all && git gc --aggressive --prune=all & cd ..)

This has saved me a few gigabytes !


text:
Q: Firebase Messaging: Activity from onMessageReceived doesn't open Firebase Notification works perfect. I get the notifications, but I have a problem. I want to open a specific activity after clicking on the notification. If the app is open, it works perfect. But if the app is closed, the MainActivity opens. I don't know why. Can somebody help me. What must I change? Thanks!
Here's the code of onMessageReceived:
public class MessageService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Intent intent=new Intent(this,activity2.class); //To this activity it should also go when the app isn't open

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle("App");
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.drawable.icon);
    notificationBuilder.setContentIntent(pendingIntent);
    NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());

}
}

EDIT
WelcomeActivity (launcher activity):
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    if (getIntent().hasExtra("type")) {
        Intent intent=new Intent(this, activity2.class);
        intent.putExtra("type",getIntent().getStringExtra("type"));
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    } else {
        startActivity(new Intent(this, MainActivity.class));
    }
}

A:
Notification messages delivered when your app is in the background:
  In this case, the notification is delivered to the device's system tray. A user tap on a notification opens the app launcher by default.

From https://firebase.google.com/docs/cloud-messaging/android/receive
One approach is to add the 'click_action' flag which will tell the system which activity to open when the user clicks on the notification. See https://stackoverflow.com/a/37656244/3482621
Also see https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

A: when the application is closed or is in background the data from the notification arrives at your launcher activity in the intent. You can put a check in oncreate() that if your intent has data then open desired activity otherwise simple opens launcher activity or main activity whatever be your launcher activity.