Q: use task method in overriden I would like to know whats the ideal way to call a method that returns a Task inside an override method?
For example:
public Task<string> GetName()
{
    return Task.Run(() => {
      return "Foo";
    });
}

In one of my methods I would just simple do this:
public async Task<string> DoSomething()
{
    var res = await GetName();
    return res + " rocks";
}

But now I am facing a situation where there is a method delcared like this:
public virtual string DoSomething()
{
  //does something...
}

In my inheritance I need to override this method and do some stuff and call a Task method, so my first thought was to do this:
public override async Task<string> DoSomething()
{
    //does something...
    base.DoSomething();

    var res = await GetName();
    return res + " rocks";
}

This clearly isnt possible since I changed the return value from a overriden method from string to Task string...
How should I solve my problem?
(Note: I cannot modify the base class, since its not mine. Its an external libary.)

A: You could do this:
public override string DoSomething()
{
    //does something...
    base.DoSomething();

    return GetName().Result;
}

Warning: this can cause a deadlock
See Don't block on async code


Q: Matlab: calculate differences between datetime arrays in fractional seconds I'm reading in time data with fractional precision (hundredths of seconds):
For every entry in this datetime array, I want to determine the difference with the first entry, in seconds (with fractional precision):
times=datetime(myCellArray,'InputFormat','HH:mm:ss.SS');
eventtimes=between(starttime,times(2:end));

this returns:
eventtimes =

0h 0m 19.72s
0h 1m 46s
0h 6m 45.9s
0h 6m 53.18s

I want to get from here to a regular array simply holding (fractional) seconds:
[19.72
106
405.9
413.18]

What I've tried so far (split, time), always results is a loss of the fractions.

A: Assuming eventtimes is a cell array of strings, you can do this:
eventtimes={'0h 0m 19.72s'
    '0h 1m 46s'
    '0h 6m 45.9s'
    '0h 6m 53.18s'};

for i=1:length(eventtimes)
    %// Read each line of data individually
    M(i,:)=sscanf(eventtimes{i},'%d%*s%d%*s%f%*s').';
end

s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds

which gives
s =
   19.7200
  106.0000
  405.9000
  413.1800

A: With respect to the answer provided by @David, the last line of code:
s=(M(:,1)*24+M(:,2))*60+M(:,3) %// Convert into seconds

should be:
s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds

Since M(:,1) contains hours, to convert them into seconds, they have to be multiplied by 3600 (60 min. * 60 sec.)
The expected resuls as described in the question and the ones provided by @David seem correct only because all input have "0h".
In case any of the input times last more than 1h, the results will be:
0h 0m 19.72s
2h 1m 46s
3h 6m 45.9s
0h 6m 53.18s

s=
   19.72
 7306.00
11205.90
  413.18

Hope this helps.

A: I've found a solution using etime that bypasses the "between" function and its odd calendarDuration type output:
%read in with fractions
times=datetime(myCellArray(:,1),'InputFormat','HH:mm:ss.SS');

%turn into datevectors (uses today's date: works as long as midnight isn't crossed)
timevect=datevec(times);

%separate start time from subsequent times
starttime=timevect(1,:);
othertimes=timevect(2:end,:);

%use etime with repmat of starttime to get differences:
relativetimes=etime(othertimes,repmat(starttime,[size(othertimes,1) 1]));

relativetimes(1:4)

ans =

                 19.72
                   106
                 405.9
                413.18


Q: Classic ASP HTTP Post from another server I am litte confused, i want to protect one page in classic asp from being accessed by Get Method.
Is it possible that someone can post data from another server to my page?
If Yes, how to detect that and allow only post from my server.
Thanks for help.

A: If you are currently using Request("ParameterName") to retrieve parameters then you should change to Request.Form("ParameterName") which will only get the parameter if it was POSTed.
Alternatively you can lookup the method used to access the page from the Request.ServerVariables collection and end the script if it is not POST. Here's an example:
If Request.ServerVariables("REQUEST_METHOD") <> "POST" Then Response.End

I noticed that you also said that you want to accept posts only from your server. The above changes will still allow another webpage to be set up to POST to your page. If you want to ensure that only your web page can post then you will need to add some more protection. Here's one way of doing it.
1) When you render your form create a random numbers and create a session variable named by the random number with a value to check for later.
Randomize
strVarName = Int((999999 - 100000 + 1) * Rnd() + 100000)
Session(strVarName) = "Authorised"

2) In your form add a hidden field with the value of the random number.
<input type="hidden" name="varname" value="<%= strVarName %>" />

3) In the script that processes the posted form get the value of the hidden field.
strVarName = Request.Form("varname")

4) Check that the session variable is set and has a value of True.
If Session(strVarName) <> "Authorised" Then
    'Failed! Either show the user an error message or stop processing
    Response.End
End If

5) Remove the session variable so that the same form cannot be resubmitted.
Session.Items.Remove(strVarName)

You don't need the random number but using it means that the same user can have multiple forms open in different windows/tabs and each one will work.


Q: Segue Popover won't behave properly I'm trying to use Segue to present then dismiss a Popover view a UIBarButtonItem is clicked.
I've created a generic Segue that is not anchored to anything but the view and given it a name
I've Anchored the UIBarButtonItem in the Interface Builder to:
- (IBAction)clickedSettings:(id)sender {

    if(self.popSegue != nil) {
        [self.popSegue.popoverController dismissPopoverAnimated:YES];
    } else {
        //Current says only a button may
        [self performSegueWithIdentifier:@"Settings" sender:sender];
    }
}

But when ever i click the button to display the Segue it gives me an error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIStoryboardPopoverSegue must be presented from a bar button item or a view.'
It doesn't even hit my -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
I've read the following questions on stack:

*

*iOS:How to dismiss Popover

*UIBarButtonItem + popover segue creates multiple popovers
But i still get the same error. For the life of me i can't figure out what is going wrong

A: I take no credit for this since I got every bit of it from going through multiple StackOverflow threads, but I got this working with:
@interface MyViewController ()
- (IBAction) toggleSettingsInPopover: (id) sender;
@property (nonatomic, strong) UIStoryboardPopoverSegue *settingsPopoverSegue;
@end

@implementation MyViewController
@synthesize settingsPopoverSegue = _settingsPopoverSegue;

- (IBAction) toggleSettingsInPopover: (id) sender {
    if( [self.settingsPopoverSegue.popoverController isPopoverVisible] ) {
        [self.settingsPopoverSegue.popoverController dismissPopoverAnimated: YES];
        self.settingsPopoverSegue = nil;
    } else {
        [self performSegueWithIdentifier: @"Settings" sender: sender];
    }
}

- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender {
    if( [segue.identifier isEqualToString: @"Settings"] ) {
        if( [segue isKindOfClass: [UIStoryboardPopoverSegue class]] )
            self.settingsPopoverSegue = (UIStoryboardPopoverSegue *) segue;
        MySettingsViewController *msvc = segue.destinationViewController;
        msvc.delegate = self;
    }
}
@end

In my storyboard I control-dragged from my settings bar button item to MyViewController and connected it to the toggleSettingsInPopover action. Then I control-dragged from MyViewController to the view for the settings to create the segue, set its type to popover, set its identifier to Settings, set its directions to up and left (the toolbar is at the bottom of the screen and the button is at the right end), then dragged from its Anchor to the bar button item I connected to the action.

A: You have to anchor the segue to the UIBarButton by Ctrl-Dragging the Anchor Field from the segue Attribute Inspector to the UIBarButton.
If you do it the opposite way, Ctrl-Dragging from the Button to the Window to be shown you won't have a possibility to control the behaviour from the Popoverwindow.
(The important part is also in the last sentence of LavaSlider's Reply)


Q: How to clustering based on the distance in Python pandas? I have two dataframes with two groups of stations information. One for the 15 small stations and another for the 5 main stations.
Small Station Information(15*3):
       SmallStation_ID  longitude  latitude
0           dongsi_aq    116.417    39.929
1          tiantan_aq    116.407    39.886
2         guanyuan_aq    116.339    39.929
3    wanshouxigong_aq    116.352    39.878
4     aotizhongxin_aq    116.397    39.982
5     nongzhanguan_aq    116.461    39.937
6           wanliu_aq    116.287    39.987
7       beibuxinqu_aq    116.174    40.090
8        zhiwuyuan_aq    116.207    40.002
9   fengtaihuayuan_aq    116.279    39.863
10         yungang_aq    116.146    39.824
11         gucheng_aq    116.184    39.914
12        fangshan_aq    116.136    39.742
13          daxing_aq    116.404    39.718
14        yizhuang_aq    116.506    39.795

Main Station Information(5*9):
    MainStation_id   longitude   latitude  temperature  \
0       shunyi_meo  116.615278  40.126667         -1.7
1       hadian_meo  116.290556  39.986944         -1.6
2      yanqing_meo  115.968889  40.449444         -8.8
3        miyun_meo  116.864167  40.377500         -6.6
4      huairou_meo  116.626944  40.357778         -5.2

       pressure  humidity  wind_direction  wind_speed      weather
0        1028.7        15           215.0         1.6  Sunny/clear
1        1026.1        14           231.0         2.5  Sunny/clear
2         970.8        35           305.0         0.8         Haze
3        1023.3        28        999017.0         0.2         Haze
4        1022.8        27            30.0         0.8  Sunny/clear

I want to classify those small stations into the main stations after I calculate the distance: sqrt((x1-x2)^2+(y1-y2)^2)(Here the x and y are longitude and latitude, respectively). Find the closest neighbor. Then merge these two groups of dataframes to get the main stations external weather information. The head of the final dataframe will seems like,
 SmallStation_ID  distance  temperature  pressure  humidity  wind_direction  wind_speed      weather

It is a 15*8 dataframe.
Hope I made this question clear.
Thanks!

A: Alright... I solved this by myself...
I am not familiar with iteration and hope someone gives me an easier understand way in some pandas functions.
Small Station is a dataframe called aqstation.
Main Station is a dataframe called meostation.
l = []
# All I want to do is to merge Main Station weather information into Small Stations...

Calculate the Euclidean distance then classify small stations into main stations.
for i in range(len(aqstation)):

 station = meostation['station_id'][(((aqstation['longitude'][i]-meostation['longitude'])**2+(aqstation['latitude'][i]-meostation['latitude'])**2)**(0.5)).idxmin()]
 l.append(station)

# print(len(l))
aqstation['station_id'] = l

del aqstation['longitude']
del aqstation['latitude']
del meostation['longitude']
del meostation['latitude']

Merge the two dataframes.
aqstation = pd.merge(aqstation, meostation, how='left', on='station_id')
print(aqstation.head(10))

          Station ID       station_id    temperature  \
0          dongsi_aq     chaoyang_meo           -0.7
1         tiantan_aq      beijing_meo           -2.5
2        guanyuan_aq       hadian_meo           -1.6
3   wanshouxigong_aq      fengtai_meo           -1.4
4    aotizhongxin_aq       hadian_meo           -1.6
5    nongzhanguan_aq     chaoyang_meo           -0.7
6          wanliu_aq       hadian_meo           -1.6
7      beibuxinqu_aq    pingchang_meo           -3.0
8       zhiwuyuan_aq  shijingshan_meo           -1.8
9  fengtaihuayuan_aq      fengtai_meo           -1.4

   pressure  humidity  wind_direction  wind_speed      weather
0    1027.9        13           239.0         2.7  Sunny/clear
1    1028.5        16           225.0         2.4         Haze
2    1026.1        14           231.0         2.5  Sunny/clear
3    1025.2        16           210.0         1.4  Sunny/clear
4    1026.1        14           231.0         2.5  Sunny/clear
5    1027.9        13           239.0         2.7  Sunny/clear
6    1026.1        14           231.0         2.5  Sunny/clear
7    1022.5        17           108.0         1.1  Sunny/clear
8    1024.0        12           201.0         2.5  Sunny/clear
9    1025.2        16           210.0         1.4  Sunny/clear

My code is very lengthy. Hope someone can make it simpler.


Q: How to let this media query works the same in different browsers on Samsung Galaxy Note4? I have a HTML code as:
<!DOCTYPE html>
<html lang="en">
<head>
<title>test page</title>
<style>
.hint {width:510px;}
@media only screen and (max-device-width: 720px) {
  .hint {width:280px}
}
@media only screen and (max-device-width: 720px) and (orientation: landscape){
  .hint {width:350px}
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
  <div class="hint">just a test
    <script>alert($(window).width()); alert($('.hint').css('width'));</script>
  </div>
</body>
</html>

It works fine on all iOS devices but behaves weird for some Android devices like Samsung Galaxy Note 4 as I can reproduce the issue.
For the default browser, it works fine. The alert result is 980px and 280px but for some browsers like UC browser, it's 510px.
Is there anything wrong with my media query code?
Thanks for any kind of tips!

A: You should take a look at how "Twitter Bootstrap" outlines their media query structure at http://getbootstrap.com/css/#grid-media-queries
Try comparing those with your own written media query structure, and if you are still stuck, you should check out Chris' written media query set at https://stackoverflow.com/a/21437955/4069464
Hope this helps!
Note: If after you have setup all the proper media query sets, and somehow this is still not working for the UC browser, then you probably have to read out in detail on how UC browser defines their mobile screen size (possibly they might have defined themselves a different set of definition of screen sizes)


Q: Paper '12mm' is not supported by 'DYMO LabelWriter DUO Label I'm working on a small project that requires printing directly to a DYMO printer using their SDK. I've made other projects before using the same method:

*

*Find DYMO

*Get .label file

*Set label variable object(s)

*Print label

However, I receive the following error from the VB.NET program when calling the label.Print() method:
Paper '12mm' is not supported by 'DYMO LabelWriter DUO Label'
I receive the error delayed, so I'm assuming that the Print() method runs in a separate thread. Therefore I'm also assuming that the error occurs in the Print() method. This method is also the only point that the Label and IPrinter objects are provided in a single method according to the list above.
This error does not make sense, as the DYMO software has successfully printed labels using the same .label template. Is there possibly an incompatibility issue with the V8.+ of the SDK/Software and this model? If so, how/where can I determine a compatible version?
Insight on the fixing the error would be greatly appreciated or even any leads on documentation of error handlers with the DYMO SDK (all I've found are old samples of how to use the SDK).


Q: How to find the intersection point between the invisible frame of `\rput` and the line segment of `\ncline`?
Points enclosed by black ovals are the intersection points between the frame boundary of \rput and the line segment of \ncline.
How to find these points?

The screenshot above is copied from PSTricks Tutorial series on page 4.

A: \documentclass{article}
\usepackage{pst-node}\SpecialCoor
\makeatletter
\def\psGetEdgeA#1#2{tx@NodeDict begin 0.0 0.0 neg 0.0 0.0 0 0
  /N@#1 /N@#2 InitNC { NCCoor } if pop pop \tx@UserCoor end}
\def\psGetEdgeB#1#2{tx@NodeDict begin 0.0 0.0 neg 0.0 0.0 0 0
  /N@#1 /N@#2 InitNC { NCCoor } if 4 2 roll pop pop \tx@UserCoor end}
\makeatother

\begin{document}
\Huge
\hspace*{4cm}\rnode{B}{Node B}

\vspace{2cm}
\rnode{A}{Node A}
\ncline{A}{B}
\pscircle*[linecolor=blue,opacity=0.4](!\psGetEdgeA{A}{B}){10pt}
\pscircle*[linecolor=blue,opacity=0.4](!\psGetEdgeB{A}{B}){10pt}

\end{document}


Q: Invalid column name - Python pandas I'm a beginner at coding or machine learning and I'm struggling with my code. I would like to remove random word from a column which also contain sometimes integer or float (it's a column of an email exchange), and next ask BERT to add words that match, to do a data augmentation, but I have a problem in my code.
import pandas as pd
import nltk
from nltk.tokenize import word_tokenize

# lire les données de la colonne Excel en utilisant pandas
df = pd.read_excel("Output_Summarization/OUTPUT_ocr_OPENAIGOOD.xlsx", usecols="Open_AI_Text")

# itérer sur chaque ligne de la colonne
for index, row in df.iterrows():
  # tokeniser le texte de la ligne en mots individuels
  words = word_tokenize(row["Open_AI_Text"])

  # choisir un mot au hasard à enlever
  word_to_remove = random.choice(words)

  # enlever le mot du texte
  new_text = row["Open_AI_Text"].replace(word_to_remove, "")

  # mettre à jour la ligne dans le DataFrame
  df.at[index, "Open_AI_Text"] = new_text

# enregistrer le DataFrame mis à jour dans un nouveau fichier Excel
df.to_excel("Texte_Trou.xlsx", index=False)

I'm 100% it'ss my column name, as I can use it if I write df['Open_AI_Text'].
The problem written is :
ValueError                                Traceback (most recent call last)
<ipython-input-44-e9ccdb1ab0b2> in <module>
      4
      5 # lire les données de la colonne Excel en utilisant pandas
----> 6 df = pd.read_excel("Output_Summarization/OUTPUT_ocr_OPENAIGOOD.xlsx", usecols="Open_AI_Text")
      7
      8 # itérer sur chaque ligne de la colonne

/usr/local/lib64/python3.6/site-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    294                 )
    295                 warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
--> 296             return func(*args, **kwargs)
    297
    298         return wrapper

/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_base.py in read_excel(io, sheet_name, header, names, index_col, usecols, squeeze, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols)
    332         skipfooter=skipfooter,
    333         convert_float=convert_float,
--> 334         mangle_dupe_cols=mangle_dupe_cols,
    335     )
    336

/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_base.py in parse(self, sheet_name, header, names, index_col, usecols, squeeze, converters, true_values, false_values, skiprows, nrows, na_values, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols, **kwds)
    924             convert_float=convert_float,
    925             mangle_dupe_cols=mangle_dupe_cols,
--> 926             **kwds,
    927         )
    928

/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_base.py in parse(self, sheet_name, header, names, index_col, usecols, squeeze, dtype, true_values, false_values, skiprows, nrows, na_values, verbose, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols, **kwds)
    442
    443             data = self.get_sheet_data(sheet, convert_float)
--> 444             usecols = _maybe_convert_usecols(usecols)
    445
    446             if not data:

/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_util.py in _maybe_convert_usecols(usecols)
    146
    147     if isinstance(usecols, str):
--> 148         return _range2cols(usecols)
    149
    150     return usecols

/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_util.py in _range2cols(areas)
    117             cols.extend(range(_excel2num(rng[0]), _excel2num(rng[1]) + 1))
    118         else:
--> 119             cols.append(_excel2num(rng))
    120
    121     return cols

/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_util.py in _excel2num(x)
     82
     83         if cp < ord("A") or cp > ord("Z"):
---> 84             raise ValueError(f"Invalid column name: {x}")
     85
     86         index = index * 26 + cp - ord("A") + 1

ValueError: Invalid column name: Open_AI_Text

I tried to just use df[Open_AI_Text] as df but then this problem appeared :
AttributeError                            Traceback (most recent call last)
<ipython-input-48-17e13b68c999> in <module>
      9
     10 # itérer sur chaque ligne de la colonne
---> 11 for index, row in df.iterrows():
     12   # tokeniser le texte de la ligne en mots individuels
     13   words = word_tokenize(row["Open_AI_Text"])

/usr/local/lib64/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5137             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5138                 return self[name]
-> 5139             return object.__getattribute__(self, name)
   5140
   5141     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'iterrows'

Sorry again, I'm a total beginner in an internship

A: You’re using the wrong kind of value for the usecols attribute. Check the documentation:
usecols: str, list-like, or callable, default None
If None, then parse all columns.
If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
If list of int, then indicates list of column numbers to be parsed (0-indexed).
If list of string, then indicates list of column names to be parsed.
If callable, then evaluate each column name against it and parse the column if the callable returns True.
Returns a subset of the columns according to behavior above.


Q: A non-smooth map with smooth Jacobian? I am looking for an example of a non-smooth Sobolev map $f \in W_{\text{loc}}^{1,d}(\Omega,\mathbb{R}^d)$, where $\Omega$ is an open subset of $\mathbb{R}^d$, such that $\det df \in C^{\infty}$ is everywhere non-zero.
In other words, I am looking for a map which is less regular that its Jacobian.

A: For example, a shear deformation $f:\mathbb{R}^2\to\mathbb{R}^2$
$$
f(x, y) = (x, y + h(x))
$$
where $h$ is a Sobolev function. The Jacobian determinant is identically $1$.


Q: Angular 2 Component Library I am trying to create a component library that I can share with anyone via npm. I am building my component lib with webpack.  When I try to install my component lib into an Angular 2 project's module, the project's module does not recognize the name of my component lib module.
In my App I do this...
 import '@angular/core';

    import {NgModule} from '@angular/core';
    import {BrowserModule} from '@angular/platform-browser';
    //it says it does not recognize the module name, I installed it via npm i bt-module.
    import {BarChartComponent} from "BTModule";

    @NgModule({
        imports: [
            BrowserModule,
            BTModule
        ],
        declarations: [
            AppComponent
        ],
        bootstrap: [AppComponent]
    })
    export class App {
    }

I have the following folder structure for my component lib...
bt-module
|_______src
|       |____barchart
|       |    |____barchart.component.ts
|       |    |____barchart.styles.scss
|       |____bt.module.ts
|       |____index.ts
|_______package.json
|_______tsconfig.json
|_______webpack.config.js

My barchart.component.ts is like this...
import {Component, OnInit, ViewChild, ElementRef, Input} from "@angular/core";

import * as d3 from 'd3'

@Component({
    selector: 'bar-chart',
    styles: [
        require('./barchart.styles').toString()
    ],
    template: '<div #barchart class="chart box"></div>'
})
export class BarChartComponent implements OnInit {

    @Input('data') data: Array<any>;

    @ViewChild('barchart') barchart: ElementRef;

    constructor() {
    }

    ngOnInit() {

        //barchart code here...

    }

}

My bt.module.ts looks like this...
import '@angular/core';

import {NgModule, ModuleWithProviders} from '@angular/core';
import {BarChartComponent} from "./barchart/barchart.component";

@NgModule({
    declarations: [
        BarChartComponent
    ],
    exports: [
        BarChartComponent
    ]
})
export class BTModule {
}

My index.ts looks like this...
export * from './barchart/barchart.component'
export * from './avs.module';

My tsconfig.json looks like this...
{
  "compilerOptions": {
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es6",
      "es2015",
      "dom"
    ],
    "noImplicitAny": false,
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "mapRoot": "",
    "outDir": "./release",
    "skipLibCheck": true,
    "suppressImplicitAnyIndexErrors": true,
    "baseUrl": "",
    "types": [
      "node"
    ],
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules/*",
    "**/*-aot.ts"
  ],
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "debug": true
  }
}

Any ideas? What am I missing?  I have read many blogs and tutorials (which are all with older versions of angular) and I can't seem to make it work. This is one of the articles I have tried: http://www.dzurico.com/how-to-create-an-angular-library apperantly there is a difference between AOT and NON-AOT, no luck.

A: Make sure the package.json for your library includes the main field (see https://docs.npmjs.com/files/package.json#main), which should be the transpiled .js file that has your module in it.
I created a component library using https://github.com/flauc/angular2-generator and was able to get it to work.
Also, here's an excellent example of creating a component library using the Angular CLI:  See https://github.com/nsmolenskii/ng-demo-lib and https://github.com/nsmolenskii/ng-demo-app.


Q: Have a few questions about caches and cache hits/misses This is a homework problem, but the homework was already due and we were already given the answers, I just have no idea how they actually came up with these answers.
It relates to caches, and I'm just getting a lot of concepts mixed up.
Here is the question:
For a direct-mapped cache design with a 32-bit address, the following bits of the
address are used to access the cache.

From my understanding, the index bits determine which block in the cache a particular location in memory is mapped to. The lowest log(base2) bits off the address determine the cache block, and here there are 5 index bits, so I know that there will be a total of 2^5 blocks in the cache, or 32.
What is the cache block size (in words)?
According to the answers given to us, the cache block size is 8. According to some notes given to us by our TA, the block size is 2^(# of offset bits), which in this case would be 5. However, that gives me as an answer 32, so I do not know where the 8 is coming from. Furthermore, nowhere in this book is the term "offset bits" defined, so can somebody tell me exactly what this means?

**What I'm thinking here is that since the same memory address is never referenced twice, there should be NO hits, since the cache will never already have the data it is looking for within the cache. However, according to the answers, the hit ratio should be .25, so once again I guess I'm not understanding what is going.
Finally, for the last question it says the answer is as follows:

<000001, 0001, mem[1024]>
<000001, 0011, mem[16]>
<001011, 0000, mem[176]>
<001000, 0010, mem[2176]>
<001110, 0000, mem[224]>
<001010, 0000, mem[160]>
Which contains some memory addresses (176, 2176) that weren't even in the original question, so by this point I completely lost about everything. Can somebody help clear some of these things up for me?**

A: In the example the cache block size is 32 bytes, i.e., byte-addressing is being used; with four-byte words, this is 8 words.
Since an entire block is loaded into cache on a miss and the block size is 32 bytes, to get the index one first divides the address by 32 to find the block number in memory. The block number modulo 32 (5-bit index) is the index. The block number divided by 32 is the tag. The trace would look like this:
   0  miss  <00000, 0000, mem[0..31]>
   4  hit   <00000, 0000, mem[0..31]>
  16  hit   <00000, 0000, mem[0..31]>
 132  miss  <00100, 0000, mem[128..159]>
 232  miss  <00111, 0000, mem[224..255]>
 160  miss  <00101, 0000, mem[160..191]>
1024  miss  <00000, 0001, mem[1024..1055]>
  30  miss  <00000, 0000, mem[0..31]>
 140  hit   <00100, 0000, mem[128..159]>
3100  miss  <00000, 0011, mem[3072..3103]>
 180  hit   <00101, 0000, mem[160..191]>
2180  miss  <00100, 0010, mem[2176..2207]>

As you can see there are four hits out of 12 accesses, so the hit rate should be 33%. (It looks like the provider of the answer thought there were 16 accesses.)
Side comment: Since this is starting from an empty cache, there is only one conflict miss (the mem[30] access) and the remaining seven misses are compulsory (first access) misses. However, if this was the body of a loop, in each iteration after the first there would be four conflict misses at index 00000 (address 0, 1024, 30, 3100), two conflict misses at 00100 (addresses 132, 2180), and six hits (addresses 4, 16, 140 are hits whose cache blocks have been reloaded in each iteration, corresponding to conflict misses; addresses 232, 160, 180 are hits whose cache blocks were loaded in the first iteration and not evicted).
Running through this trace, one can find that at the end the following blocks would be valid (being the last accessed for their index):
<00000, 0011, mem[3072..3103]>
<00100, 0010, mem[2176..2207]>
<00101, 0000, mem[160..191]>
<00111, 0000, mem[224..255]>

Note how this differs from the given answer which is clearly wrong because with 32-byte blocks, no block would start at mem[16] and 1024 divided by 32 gives a block number (in memory) of 32, 32 modulo 32 is 0 (not 1) for the index.
Incidentally, providing the byte range cached in the block is probably more helpful than just providing the starting address of the block.


Q: How to add concatenation to transfer learning?

I'm using transfer learning for semantic segmentation.
model=vgg(weights="imagenet")
new_model=Sequential()
for l,n in model.layers:
     new_model.add(l)
     if(n==18): break

 #Upsampling
m1=model.layers[-1].output
new_model.add(Conv2DTranspose(512,(3,3),strides=(2,2),
padding="same"))
m2=new_model.layers[-1].output
concatenate1=concatenate(m1,m2)

Till this step it works fine. Now how can I add this concatenation to the network.
new_model.layers[-1].output=concatenate1.output
new_model.layers[-1].output=concatenate1
# these are wrong

A: You can directly use the functional version of keras that will be easier for you.
You will simply use all the layers to n = 18 and that output will connect to m1.
Finally, you create the model. The code would be the following:
model = vgg(weights="imagenet")
input_ = model.input
for l, n in model.layers:
    if n == 18:
        last_layer = l
        break

#Upsampling
m1 = last_layer
m2 = Conv2DTranspose(512, (3, 3), strides=(2, 2), padding="same")(m1)
concatenate1 = Concatenate(axis=-1)(m1, m2)

new_model = Model(inputs=input_, outputs=concatenate1)


Q: Bash - Convert comma separated list I'm trying to write a script that works on a list of files.  If I want to work on all files in the same directory then
FILES=*.ext

for i in $FILES; do
  something on "$i"
done

works OK, the problem comes when I want to work on just a selection of files and not everything.  How do I convert a comma separated list of files, which may or may not contain spaces into the same format, so that I can store it in $FILES and use the same code?
Many thanks, in advance
David Shaw

A: The correct thing to do is not use a delimited list of filenames but use an array (and avoid uppercase variable names), this will avoid the problem of filenames containing your separator (e.g. ,) and is the idiomatic approach:
files=( *foo*.ext1 *bar*.ext2 file1 "file 2 with a space" )

for file in "${files[@]}"; do
    [ -e "${file}" ] || continue
    do_something_with "${file}"
done

Unless you have no control over how $files is populated this is what you want, if your script gets fed a comma-separated list and you absolutely cannot avoid it then you can set IFS accordingly as in @BroSlow's answer.
Since globbing does the right thing when expanding filenames with spaces are not a problem (not even in your example).
You might also want to check extended globbing (extglob) to be able to match more specifically.

A: If I am interpreting your question correctly you can just the internal field separator (IFS) in bash to comma and then have word-splitting take care of the rest, e.g.
#!/bin/bash

FILES="file1,file2 with space,file3,file4 with space"

IFS=','
for i in $FILES; do
  echo "File = [$i]"
done

Which would output
File = [file1]
File = [file2 with space]
File = [file3]
File = [file4 with space]

Note, as Adrian Frühwirth pointed out in comments, this will fail if the filenames can contain commas.


Q: How to restore trash mails to original folder in Microsoft Graph API? I have tried this https://graph.microsoft.com/v1.0/me/mailFolders/deleteditems/{messageId}/restore but getting 400 Bad request.

A: As Glen said here there is no method to directly restore trash mails through Graph API. Please raise a feature request for this in the Microsoft Graph Feedback Forum so that the product team could implement it in the future.


Q: AlarmManager canceled when app closed but ok after reboot I've an issue with an Alarm Manager. I wan't to execute my service each hour.
Alarm Manager is launched after reboot and work well, even if the app is not open or open and closed (My PhoneStartReceiver call launchBackgroundService one time, after a completed boot).
My problem is when I launch application after installation, without phone reboot. In this case, AlarmManager is killed when application is force closed or destroyed.
Problem is juste between installation, and next reboot. How to maintain AlarmManager enabled until next reboot ?
        <receiver
        android:name=".helpers.PeriodicalServiceCaller"
        android:process=":remote"/>
<receiver
        android:name=".helpers.PhoneStartReceiver"
        android:process=":remote">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>

Here is my launchBackgroundServiceMethod, called in the both cases.
public static void launchBackgroundService(){
    // Construct an intent that will execute the PeriodicalServiceCalle

    Intent intent = new Intent(getApplicationContext(), PeriodicalServiceCaller.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Create a PendingIntent to be triggered when the alarm goes off
    final PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), PeriodicalServiceCaller.REQUEST_CODE,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);
    // Setup periodic alarm every minute
    long firstMillis = System.currentTimeMillis(); // alarm is set right away
    AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

    // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 1000L, pIntent);

}

PeriodicallServiceCaller code
public class PeriodicalServiceCaller extends BroadcastReceiver {

public static final int REQUEST_CODE = 12345;

// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {

        Log.i("START-SERVICE", "PeriodicalServiceCaller");

        Intent i = new Intent(context, MonitorDataService.class);
        context.startService(i);
}

EDIT
My launchBackgroundService is launch by an Acitivity if it's after install and by PhoneStartReceiver if it's after a reboot

A: You need to register a BroadcastReceiver to detect when your are has been updated.
<receiver android:name=".MyBroadcastReceiver">
   <intent-filter>
     <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
   </intent-filter>
</receiver>

Take a look at
How to know my Android application has been upgraded in order to reset an alarm?

A: Is launchBackgroundService in a service or run from the activity? If it is run from the service please check this answer Background Service getting killed in android
START_STICKY was the thing I missed.


Q: php & mysql syntax errors: possibly string? Having a problem with some code and string handling

Syntax error, unexpected end of file...

Can someone help?
<?php

    require("common.php");

    if(empty($_SESSION['user']))
    {

        header("Location: login.php");

        die("Redirecting to login.php");
    }

    $query = "
        SELECT
            id,
            username,
            email,
            gold
        FROM users
    ";

    try
    {

        $stmt = $db->prepare($query);
        $stmt->execute();
    }
    catch(PDOException $ex)
    {

        die("Failed to run query: " . $ex->getMessage());
    }

    $rows = $stmt->fetchAll();

mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."');

header('Location: quests.php');
die();

?>

A: You forgot to close the quoted string:
mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."'");

A: mysqli_query($con,"UPDATE users SET gold = gold + 10 WHERE username= '".$_SESSION['user']['username']."');

You have forgotten to close the quote "
Should be like this:
mysqli_query($con,"UPDATE users SET gold = gold + 10 WHERE username= '".$_SESSION['user']['username']."'");

A: You're missing a closing " on your mysqli_query line:
."');

needs to be
."'");

If your editor doesn't make this very obvious with syntax hilighting, you should use a different editor.

A: Instead of
mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."');

use
mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."'");


Q: Accessing hidden operator from parent namespace in C++ I want to intercept the operator << inside a namespace to add some additional formatting to basic types before printing them out. Can this be done?
namespace Foo {
    std::ostream& operator<<(std::ostream& os, bool b) {
        //Can I call std::operator<< here now. Something like:
        // os std::<< (b ? 10 : -10) << std::endl;
    }
}

Thanks!

A: You can do it using explicit function call syntax. For your case, the call should be os.operator<<(b ? 10 : -10), because the corresponding operator<< is a member function.
However, with your operator<<, you will no longer be able to use expressions such as std::cout << true in namespace Foo, because this will trigger an ambiguity between your Foo::operator<<(std::ostream&, bool) and std::ostream's member function std::ostream::operator<<(bool): both accept an lvalue of type std::ostream as its left operand, and both accept a value of type bool as its right operand, neither is better than the other.


Q: Gerrit- Git push Error (n/a (unpacker error)) while pushing to gerrit I'm android developer so I had setted up Gerrit Code Review and Github for my Team! So After lots of struggle i got my github projects added to gerrit and also got replication work, but i'm not able to push this one repo. All other repos get pushed fine.
I cloned my github repo and then added my ssh link of project of gerrit with git remote add * and then I typed git push gerrit HEAD:refs/for/ics  but i'm getting some unpack error
Here is the whole log:
keyur@keyur-Inspiron-N4010:~/android_device_lge_p350$ git push gerrit HEAD:refs/for/ics
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 526 bytes, done.
Total 5 (delta 3), reused 0 (delta 0)
fatal: Unpack error, check server log
remote: Resolving deltas: 100% (3/3)
error: unpack failed: error Missing unknown c605ed77d4a43b8389c7bb544c3a5834cf0f64cf
To ssh://keyur2maru@review.pecancm.insomnia247.nl:6117/android_device_lge_p350.git
 ! [remote rejected] HEAD -> refs/for/ics (n/a (unpacker error))
error: failed to push some refs to 'ssh://keyur2maru@review.pecancm.insomnia247.nl:6117/android_device_lge_p350.git'
keyur@keyur-Inspiron-N4010:~/android_device_lge_p350$

And it fails :( I'm able to commit on any other repos :( but not able to get this one work :(
My config file :
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = git@github.com:PecanCM/android_device_lge_p350.git
[branch "cm-10.1"]
    remote = origin
    merge = refs/heads/cm-10.1
[remote "gerrit"]
    url = ssh://keyur2maru@review.pecancm.insomnia247.nl:6117/android_device_lge_p350.git
    fetch = +refs/heads/*:refs/remotes/gerrit/*
[branch "ics"]
    remote = origin
    merge = refs/heads/ics

My Github repo : https://github.com/PecanCM/android_device_lge_p350
My Gerrit Server : http://review.pecancm.insomnia247.nl

A: If you have access to the gerrit server, check whether you have granted enough permissions to the git folder of your gerrit.


Q: if I have lists for the values in a dictionary, can I perform a conditional zip on these value lists? I have the following dict that I created :
dct = {'T': [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0]], 'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]], 'J': [[0, 0, 1, 0, 0], [0, 0, 0, 0, 1]], 'K': [0, 0, 0, 0, 1]}

Note that each value is either a single list or multiple lists. I am trying to figure out if I can do a conditional zip on the value lists for each key (or some alternative solution that gives me my desired output). The condition is that I only want the value lists to zip together for a given key if the 1s on consecutive value lists are within a distance of 2 index values from each other.
The final output I want from this input dict should look like this:
zp_dict = {'T': [2, 1, 0, 1, 0], 'B': [[0, 1, 0, 0, 0], [0, 1, 0, 0, 0]], 'J': [0, 0, 1, 0, 1], 'K': [0, 0, 0, 0, 1]}

Notice that the value lists for 'T' and 'J' should be zipped together because the non-zero values are no more than 2 indices apart, but the value lists for 'B' should be kept separate because the non-zero values are 3 indices apart, and the 'K' value list should be left alone.
To illustrate what I'm trying to do, consider the following code that almost does what I want to do, but without the condition:
zp_dict = {}

for k, v in dct.items():

    zp_dict[k] = [sum(x) for x in zip(*v)]

This produces the following new dict, which is wrong for key 'B':
zp_dict = { 'T': [2, 1, 0, 1, 0], 'B': [0, 1, 0, 0, 1], 'J': [0, 0, 1, 0, 1], 'K': [0, 0, 0, 0, 1]}

A: This technically achieves the result you are asking for. However, I am assuming you want everything to be added together if at least 2 of the lists have numbers within 2 indexes of each other. For example [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]] would result in [1, 1, 0, 0, 1] NOT [[1, 1, 0, 0, 0], [0, 0, 0, 0, 1]] despite the last list having its number more than 2 indexes away from any other list.
The code sums the lists together, then finds how far apart the first 2 non-zero number are. If they are <= 2 indexes apart, then the summed list is added to zp_dict, else the list of lists (v) remains unchanged, and added to the zp_dict
The code is on OnlineGDB, if you want to tinker with it
Note: I assumed 'K' in the dct you provided had a typo, in that it was supposed to be a list within a list (like the others) - if not, sum(x) for x in zip(*v) would break. If not, it doesn't take much to fix - just validate the number of lists in v.
dct = {
    'T': [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0]],
    'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]],
    'J': [[0, 0, 1, 0, 0], [0, 0, 0, 0, 1]],
    'K': [[0, 0, 0, 0, 1]]
}

zp_dict = {}

for k, v in dct.items():
    sum_list = [sum(x) for x in zip(*v)]
    first_non_zero = next((i for i, n in enumerate(sum_list) if n), 0)
    second_non_zero = next((i for i, n in enumerate(sum_list[first_non_zero+1:]) if n), 0)
    zp_dict[k] = sum_list if second_non_zero < 2 else v

print(zp_dict)
>>{'T': [2, 1, 0, 1, 0], 'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]], 'J': [0, 0, 1, 0, 1], 'K',: [0, 0, 0, 0, 1]}

EDIT:
You can also add if statements (with functions inline), if that is what you were looking for.
zp_dict[k] = [sum(x) for x in zip(*v) if conditionTest(v)]

If the conditionTest returns True, it would add the lists together. Although if you were fine with adding functions, I would clean it up and just add the for loop into the function:
zp_dict[k] = sumFunction(v)


Q: VBA Code to loop and save as PDF: keep value in first cell, renaming cells beneath I am having trouble writing a loop macro for a Client report. The main column that needs to be changed is column A, essentially a list of Client names. I am trying to have the following be looped:

*

*Starting with the first cell in column A, I would like the loop to keep the name, but rename the cells below it, respetively. I.e. A2 = Bob, A3= Jane, A4 = Tom..I want to keep "Bob" as A2, but rename jane as "Client 2", Tom as "Cient 3"

*Save as PDF to a location, with the PDF having "2022 Report_name" in the PDF name, i.e. "2022 Report_Bob"

*Loop it, so it restarts until everyone in column A has a PDF, but I would like to ensure that the names that already have a a PDF are renamed. I.e. For Jane's file (ideal second PDF), the cell that has "Bob" would be renamed as "Client 1".

Mainly just want to ensure that all the PDFs have only the client's name showing, while the others are renamed to "Client 1, 2"..etc.
Hoping you could assist me.
Thank you in advance! :)
As of now, I only have the save to PDF part:
Sub Report()
    'Defining worksheets

    Dim ClientSheet As Worksheet
    Set ClientSheet = ActiveWorkbook.Sheets("Client")

    Application.ScreenUpdating = False

    'Looping the through each row

    For i = 2 To 43
        'Assigning values

        SName = ClientSheet.Cells(i, 1)

        'Save the PDF file
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                       Filename:="\\! Routine Reports\Client\" & SName,  _
                       Quality:=xlQualityStandard, _
                       IncludeDocProperties:=True, _
                       IgnorePrintAreas:=False, _
                       OpenAfterPublish:=False
    Next i

    Application.ScreenUpdating = True
End Sub


Q: Looking for a certain phrase in pandas column I am trying to look for a certain phrase in pandas column using this code:
workfromhome = df.loc[df['Description'].str.contains("work from home",na=False)]
df['Work From Home'] = workfromhome

here is the description column:
About AgodaAgoda is an online travel booking p...
1       DescriptionWe are looking for an experienced B...
2       Key Responsibilities and Accountabilities To w...
3       About AgodaAgoda is an online travel booking p...
4       Data entry InternshipResponsible for adding ne...
5       Siemens EDA is a global technology powerhouse....
6       Job DescriptionThis is a remote position.Excep...
7       Curenta is changing the shape of long-term hea...
8       Job RequirementsBachelors Degree in Computer S...
9       Where You’ll Work Andela is a network of techn...
10      QualificationsPostgraduate, master’s degree or...
11      متاح طوال ايام العمل يقبل العمل بعد فترة الدوا...
12      About The JobYou’re looking for fulfillment, w...
13      About AgodaAgoda is an online travel booking p...
14      Ready to tackle the challenges of the vehicle ...
15      About AgodaAgoda is an online travel booking p...
16      Siemens EDA is a global technology powerhouse....
17      About AgodaAgoda is an online travel booking p...
18      IGNITION is a 12 months program designed to gi...
19      Management Trainee ProgramRotational program f...
20      Siemens EDA is a global technology powerhouse....
21      Siemens EDA is a global technology powerhouse....
22      Votre Mission Chez CegedimWe are looking for a...
23      About AgodaAgoda is an online travel booking p...
24      Votre Mission Chez CegedimWe are looking for a...
25      RequirementsBachelor's degree in Computer Scie...
26      DescriptionWe are looking for an iOS developer...
27      Designs, develops and executes all testing-rel...
28      About AgodaAgoda is an online travel booking p...
29      Auto req ID: 247864BRJob DescriptionDevelop an...
30      Job DescriptionABOUT THIS JOB A Reporting Offi...
31      About AgodaAgoda is an online travel booking p...
32      Job DescriptionProvide technical mentor ship a...
33      About AgodaAgoda is an online travel booking p...
34      Job briefWe are looking for a Java Developer w...
35      About The JobJob DescriptionTo be responsible ...
36      يكون لدية الخبرة فى ادارة وتطوير الشركات Show ...
37      Job ScopeThe job scope covers the execution of...
38      About GemographyJoin Gemography and work direc...
39      About This JobJob DescriptionA Reporting Offic...
40      Job DescriptionVotre mission chez Cegedim :Ove...
41      Essential Job FunctionsResponsibilitiesContrib...
42      DescriptionWe are looking for a Full Stack Dev...
43      DescriptionWe are looking for a passionate Dat...
44      Auto req ID: 248881BRRoleJob DescriptionThe HR...
45      1 Bachelors or diploma in computer engineering...
46      DescriptionWhat are we looking for?We are look...
47      Requirements• Development experience of 8 year...
48      DescriptionWe are looking for Devops engineers...
49      DescriptionSouq.com, an Amazon.com Company, is...
50      Siemens EDA is a global technology powerhouse....
51      ResponsibilitiesParticipates as a member of a ...
52      About AgodaAgoda is an online travel booking p...
53      About AgodaAgoda is an online travel booking p...
54      The ideal candidate will be responsible for cr...
55      DescriptionOLX is on the hunt for an experienc...
56      Siemens EDA is a global technology powerhouse....
57      We are hiring a Senior Backend Developer who m...
58      Company Name:Elsewedy Electric - ISKRAEMECODep...
59      DescriptionSouq.com, an Amazon.com Company, is...
60      Votre Mission Chez CegedimAs a Tester you will...

now when I was looking for the social insurance using the same exact code! it worked no problem! but now when I look for medical insurance or work from home! it returns this error:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Work From Home'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1070         try:
-> 1071             loc = self.items.get_loc(item)
   1072         except KeyError:

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Work From Home'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-448-4f0e407389ac> in <module>
      1 #df['Social Insurance'] = df.loc[df['Description'].str.contains("social insurance", case=False,na=False)]
      2 workfromhome = df.loc[df['Description'].str.contains("work from home",na=False)]
----> 3 df['Work From Home'] = workfromhome

~\anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   2936         else:
   2937             # set column
-> 2938             self._set_item(key, value)
   2939
   2940     def _setitem_slice(self, key, value):

~\anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   2999         self._ensure_valid_index(value)
   3000         value = self._sanitize_column(key, value)
-> 3001         NDFrame._set_item(self, key, value)
   3002
   3003         # check if we are modifying a copy

~\anaconda3\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
   3622
   3623     def _set_item(self, key, value) -> None:
-> 3624         self._data.set(key, value)
   3625         self._clear_item_cache()
   3626

~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1072         except KeyError:
   1073             # This item wasn't present, just insert at end
-> 1074             self.insert(len(self.items), item, value)
   1075             return
   1076

~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in insert(self, loc, item, value, allow_duplicates)
   1179         new_axis = self.items.insert(loc, item)
   1180
-> 1181         block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
   1182
   1183         for blkno, count in _fast_count_smallints(self._blknos[loc:]):

~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in make_block(values, placement, klass, ndim, dtype)
   3051         values = DatetimeArray._simple_new(values, dtype=dtype)
   3052
-> 3053     return klass(values, ndim=ndim, placement=placement)
   3054
   3055

~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
   2599             values = np.array(values, dtype=object)
   2600
-> 2601         super().__init__(values, ndim=ndim, placement=placement)
   2602
   2603     @property

~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
    122
    123         if self._validate_ndim and self.ndim and len(self.mgr_locs) != len(self.values):
--> 124             raise ValueError(
    125                 f"Wrong number of items passed {len(self.values)}, "
    126                 f"placement implies {len(self.mgr_locs)}"

ValueError: Wrong number of items passed 21, placement implies 1

Help me extract the information please

A: Try define column Description for return Series in variable workfromhome:
workfromhome = df.loc[df['Description'].str.contains("work from home",na=False), 'Description']


Q: HTML5 section tag meanings? I know there are tons of questions about this topic but I can't find an authoritative source for the answer.
This is the official definition and the wiki page, and there there is more documentation, but there they don't explain the correct usage if not in a very simple examples or in different ways.
What I've "understood" so far:

 defines a part(section) of the page, like blogrolls, headlines news, blog entries list, comments list, and everything which can be with a common topic.

 defines a content which has sense estranged from the rest of the page (?) and which has a single topic (blog entry, comment, article, etc).
But, inside an
, we can split parts of it in sections using
, and in this case it has the function of container to mark chapters of a bigger text.

The doubt
If these sentences are correct (or partially correct) that means that
 has two completly different usage cases.
We could have a page written in this way:
<!DOCTYPE html>

        <meta charset=utf-8>
        <title>Fruits</title>

Fruits war blog

What's new about fruits?

Apples are the best
Apples are better than bananas

Apple's cakes
With apples you can prepare a cake

Articles about fruits

Apples vs Bananas

Introduction:

                    Bananas have always leaded the world but...

The question:

                    Who is the best? We don't know so much about apples...

And this is how looks the Outline:
1. Fruits war blog
   1. What's new about fruits?
      1. Apples are the best
      2. Apple's cakes
   2. Articles about fruits
      1. Apples vs Bananas
         1. Introduction:
         2. The question:

So the
 is thought with two completly different and not related semantic meanings?
Is it correct use:

in this neasted way?
I've found that is possible to use in the inversed way:

But I can't find an answer to the way I've written below.
I guess read the discussion where the W3C group has wrote the basis of the
 tag could be useful but I can't find it.
N.B. I'm looking for replies documented with authorative sources

A: http://www.w3.org/wiki/HTML/Elements/section is not the official definition of section. section is defined in the HTML5 specification, which currently is a Candidate Recommendation (which is a snapshot of the Editor’s Draft).
In the CR, section is defined as:

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.

section is a sectioning content element (together with article, aside and nav). Those sectioning elements and the headings (h1-h6) create an outline.
The following three examples are semantically equivalent (same meaning, same outline):

My first day

…

Waking up

…

The big moment!

…

Going to bed

…

My first day

…

Waking up

…

The big moment!

…

Going to bed

…

My first day

…

Waking up

…

The big moment!

…

Going to bed

…

So you can use section whenever (*) you use h1-h6. And you use section when you need a separate entry in the outline but can’t (or don’t want to) use a heading.
Also note that header and footer always belong to its nearest ancestor sectioning content (or sectioning root, like body, if there is no sectioning element) element. In other words: each section/article/aside/nav element can have its own header/footer.
article, aside and nav are, so to say, more specific variants of the section element.

two completly different usage cases

These two use-cases are not that different at all. In the "container" case, you could say that section represents a chapter of the document, while in the "chapter" case section represents a chapter of the article/content (which, ouf course, is part of the document).
In the same way, some headings are used to title web page parts (like "Navigation", "User menu", "Comments", etc.), and some headings are used to title content ("My first day", "My favorite books", etc.).

A: OK so here is what I've gathered from authorative sources.
MDN:
The HTML Section Element () represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading.
Usage notes :
If it makes sense to separately syndicate the content of a  element, use an  element instead.
Do not use the  element as a generic container; this is what  is for, especially when the sectioning is only for styling purposes. A rule of thumb is that a section should logically appear in the outline of a document.
Shay Howe's guide:
A section is more likely to get confused with a div than an article. As a block level element, section is defined to represent a generic document or application section.
The best way to determine when to use a section versus a div is to look at the actual content at hand. If the block of content could exist as a record within a database and isn’t explicitly needed as a CSS styling hook then the section element is most applicable. Sections should be used to break a page up, providing a natural hierarchy, and most commonly will have a proper heading.
dev.opera.com
Basically, the article element is for standalone pieces of content that would make sense outside the context of the current page, and could be syndicated nicely. Such pieces of content include blog posts, a video and it's transcript, a news story, or a single part of a serial story.
The section element, on the other hand is for breaking the content of a page into different functions or subjects areas, or breaking an article or story up into different sections.

A:
 and
 are both sectioning content.  You can nest one sectioning element inside another to slice up the outer element into sections.
HTML Living Standard, 4.4.11:

...
  Sectioning content elements are always considered subsections of their nearest ancestor sectioning root or their nearest ancestor element of sectioning content, whichever is nearest, regardless of what implied sections other headings may have created.
  ...

You can consider a
 as a generic sectioning element.  It's like a
 that defines a section within its closest sectioning parent (or the nearest sectioning root, which may be the ).
An
 is also a section, but it does have some semantics.  Namely, it represents content that is self-contained (that is, it could possibly be its own page and it'd still make sense).

A: Here's the official w3c take on section:
http://www.w3.org/wiki/HTML/Elements/section
Quote: "The [section] element represents a generic section of a document or application."
I guess, in theory if you have an article within an article then your nested selections example might work. But, why would you have an article within an article ? Makes little semantic sense.


Q: Red5 java error on startup When I started red5 I got the following error message;
Exception in thread "main" java.lang.ClassNotFoundException: org.red5.server.Launcher
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:249)
at org.red5.server.Bootstrap.bootStrap(Bootstrap.java:115)
at org.red5.server.Bootstrap.main(Bootstrap.java:48)

Please help I need this to start up again quickly.
Running Ubuntu and red5 1.0.0

A: From http://code.google.com/p/red5/wiki/ServerWontStart

ClassNotFoundException Launcher
When the Launcher cannot be located, it usually means the server jar
  is missing or misnamed. The Red5 server jar must be named like so
  until we fix the bootstrap bug: red5-server-1.0.jar


Q: Should there be at least one assert in a unit test? If so, why? If we take for example gtest, we have the option to use asserts like ASSERT_NE or checks like EXPECT_NE. One of my colleagues pointed out that I should have at least one assert in my test preferably the condition which checks the main objective.
So, far I was used to using ASSERTs in places where the continuation of test is useless, and EXPECTs in places where the test could continue.
What is the correct way of using ASSERTs and EXPECTs?

A: The main difference between EXPECT_* and ASSERT_* macros is that assertions stop the test immediately if it failed, while expectations allow it to continue.
Here's what GoogleTest Primer says about it:

Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

So, to illustrate it:
TEST_F(myTest, test1)
{
    uut.doSomething();
    ASSERT_EQ(uut.field1, expectedvalue1);
    ASSERT_EQ(uut.field2, expectedvalue2);
}

If field1 doesn't match assertion, test fails and you have no idea if field2 is correct or not. This makes debugging much more difficult.
Choice between these options is mostly matter of agreement in your team, but I'd stick to GTest proposition of using EXPECT_* as the backbone of all checks and ASSERT_* only if you test something crucial to continue, without which further part of test doesn't make any sense (for example, if your unit under test was not created correctly).


Q: How to change layer.border.top color? In iOS, how can I change layer.border.top color? If I change self.layer.borderColor, all the side change. But If I only want to change one side, and keep other three sides as is, what should I do?

A: how about adding a new layer?
yourView.clipsToBounds = YES;

CALayer *topBorder = [CALayer layer];
topBorder.borderColor = [UIColor redColor].CGColor;
topBorder.borderWidth = 1;
topBorder.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), 2);
[yourView.layer addSublayer:topBorder];

replace yourView with whatever view is contained in your view controller that you want to add the border to.
Also, this related answer might help you out a bit.


Q: Best Way to Force use of SSL Certificate When a browser connects to my website by entering it's FQDN the connection is encrypted using the site's SSL Certificate.
However it has come to my attention that it is possible to bypass the SSL and initiate an unencrypted connection by entering the load balancer IP Address (in which case you get an error saying it could not be encrypted).
The link below suggests that I could solve this with a redirect.
Apache reverse proxy so that SSL browser requests for IP of server are redirected to FQDN
Is this good practice or should I really be tying the certificate to the IP address in addition to the FQDN?


Q: How would write this? In a list, should it be 'A,' 'B,' 'C,', etc., or 'A', 'B', 'C'?  Should commas go inside or outside?

A: In general, BrEng prefers putting the comma outside of the quotation marks, while AmerEng puts them inside. Because of this, neither is universally accepted as correct.

A: Often in technical publishing, single quotes are reserved for literal references.  Contextual punctuation in this usage is kept outside the single quotes.

‘A’,  ‘B’,  . . .

means the following list:

  A
    B
    . . .

Whereas

‘A,?’,  ‘,,B,,’,  . . .

means this bizarre list:

  A,?
    ,,B,,
     . . .

This allows linguists, grammarians, and computer scientists to unambiguously write about sentences, punctuation, and computer code.
Except: Even in technical writing, just as elsewhere, quotes within quotes alternate between single and double quotes:

‘Well, I'd hardly finished the first verse,’ said the Hatter, ‘when the
  Queen jumped up and bawled out, “He's murdering the time! Off with his
  head!” ’

That's how Lewis Carroll used double quotes within single quotes in Alice's Adventures in Wonderland. The modern preference, however, is to have double quotes outermost:

“Well, I'd hardly finished the first verse,” said the Hatter, “when the
  Queen jumped up and bawled out, ‘He's murdering the time! Off with his
  head!’ ”

This double-quotes-outermost preference is supported by The Chicago Manual of Style in an answer to How should I punctuate around quotes?.


Q: PHP date validation similar to ASP isDate() for user submitted dates, times, or date/time pairs I am converting an ASP application to PHP and am having difficulty transcribing date validation functionality.
In ASP, I have the function isDate(), which allows me to validate a date regardless of its format. So if someone enters any of the following, isDate() returns true:
1/1/2012
January 1, 2012
Jan 12, 2010 1:00 pm
1/1/2012 1:32 pm

The benefit is that I can let the user enter the data and time in whatever format they choose. After that, with minimal effort, I can update a database without doing any post processing (assuming true is returned). E.g.:
UPDATE my_table SET date_field = @date_var WHERE my_id = @id_var
[note: SQL Server 2008]

With PHP, I’m finding that validating a date/time is more complex. I’ve reviewed the assorted questions posted here as well as the documentation and there doesn’t seem to be a straightforward way to validate a date or time or date/time combination easily.
I’m wondering if there are classes available to do the grunt work. Something that will work like isDate() and send me back a true/false based on a user entered date/time/date & time.
Thanks.

A: You can check the return value of strtotime() to see if a date can be parsed:
if(strtotime($date) !== false) {
   // valid date/time
}

This is also how to normalize all the dates, by storing them as the return value of strtotime().

A: Perhaps you could use strtotime()?


Q: Add and commiting a file into SVN using SVN-Kit jar Actually i want to commit source into svn. I need to add and commit new files into svn repository and am using the below code. Code works properly but not able to commit into SVN
    String urls = "http://192.168.0.19/svn/cadgraf/Branch/Jobs";
    final String url = urls+File.separator+l_users.getSelectedValue().toString()+File.separator+"Active";
    System.out.println("svn url------>"+url);
    final String destPath = "/home/dev702/Desktop/Jobs-test/Tempfiles";
    SVNRepository repository = null;
    setupLibrary();
    try {
        //initiate the reporitory from the url
        repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
        //create authentication data
        ISVNAuthenticationManager authManager =
                SVNWCUtil.createDefaultAuthenticationManager("xxxxxx", "xxxxxx");
        repository.setAuthenticationManager(authManager);
        //output some data to verify connection
        System.out.println("Repository Root: " + repository.getRepositoryRoot(true));
        System.out.println("Repository UUID: " + repository.getRepositoryUUID(true));
        //need to identify latest revision
        long latestRevision = repository.getLatestRevision();
        System.out.println("Repository Latest Revision: " + latestRevision);

        //create client manager and set authentication
        SVNClientManager ourClientManager = SVNClientManager.newInstance();
        ourClientManager.setAuthenticationManager(authManager);
        //use SVNUpdateClient to do the export
        SVNCommitClient commitClient = ourClientManager.getCommitClient();
        commitClient.setIgnoreExternals(false);
    commitClient.doCommit(new File[]{new File(destPath)}, false, "Commit message", null, null, false, false, SVNDepth.INFINITY);
        SVNCommitClient client = new SVNCommitClient(authManager, null);
         SVNCommitInfo info;
         info = client.doCommit( new File[]{new File(destPath)}, false, "Commit message", null, null, false, false, SVNDepth.INFINITY);
    } catch (SVNException e) {
        e.printStackTrace();
    } finally {
        System.out.println("Done");
    }

code works fine but its not commiting files into SVN.


Q: Mysql crate conn.query multi-statement SQL query not returning QueryResult I'm using the mysql crate, to perform a multi-statement SQL query (put a record into a table) and return a value with a select statement. However the QueryResult returned is None. Performing this on a mysql terminal the statement works fine.
let mut row_iter = self
    .pool
    .get_conn()
    .unwrap()
    .query(format!(
        r#"
        SET @next_j_id = (SELECT IFNULL(MAX(j_id), 0) + 1 FROM people);
        INSERT INTO people (j_id, name, email)
        VALUES (@next_j_id, "{name}", "{email}");
        SELECT @next_j_id;
        "#,
        username = &name,
        email = &email
    ))
    .unwrap();
let row_option = row_iter.next();
match row_option {
    Some(result_row) => {
        let row = result_row.unwrap();
        let j_id: u64 = row.get("@next_j_id").unwrap();
        Ok(j_id)
    }
    None => {
        debug!("Errored");
        Err(Error)
    }
}

I expect row_option to be Some(j_id), but the actual output is None.


Q: Testing println output with JUnit I am testing a simple helloWorld class.
package Codewars;

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World");
    }

}

And I have a test class as follows (based on the answer ):
import static org.junit.jupiter.api.Assertions.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class helloWorldTest {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final PrintStream originalOut = System.out;

    @BeforeEach
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }

    @AfterEach
    public void restoreStreams() {
        System.setOut(originalOut);
    }

    @Test
    void test() {
        HelloWorld.main(null);
        assertEquals("Hello World\n", outContent.toString());
    }

}

It results in failure with error message as follows:
org.opentest4j.AssertionFailedError: expected: <Hello World
> but was: <Hello World
>
    at org.junit.jupiter.api@5.5.1/org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at org.junit.jupiter.api@5.5.1/org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    ...

It seems like the strings are same and still the error is thrown?
Thank you in advance.

A: Make sure that your line separator is equal to \n on your system.
This is not the case on Windows.
To fix the test, modify it to take system-specific separator into account
assertEquals("Hello World" + System.lineSeparator(), outContent.toString());


Q: Inequality involving real parts of characteristic functions Given $X$ is a continuous random variable taking values in the reals, and $\phi(t)$ is its characteristic fiction, that is, $\phi(t):=\Bbb E(\exp(iXt))$, then prove that
$$\Re (1-\phi(t))\ge \frac14\Re(1-\phi(2t)).$$
Reducing everything, I get what is to be shown is actually
$$\Bbb E|\cos tY|\le \Bbb E|\cos tY|^2+\frac14.$$
I don't know how to get over that $\dfrac14$. Is there any inequality that can yield an additive constant on one side? As far as I know, neither Chebyshev nor Hölder can.

A: It's just a trigonometric inequality, obtained from the double-angle formulae. On the left hand side, we use
$$1 - \cos \varphi = 2\sin^2 \frac{\varphi}{2},$$
and on the right hand side,
\begin{align}
\frac{1-\cos (2\varphi)}{4} &= \frac{\sin^2 \varphi}{2} \\
&= \frac{\bigl(2\sin \frac{\varphi}{2}\cos \frac{\varphi}{2}\bigr)^2}{2} \\
&= 2\sin^2 \frac{\varphi}{2} \cos^2 \frac{\varphi}{2}.
\end{align}
Since $\cos^2 \frac{\varphi}{2} \leqslant 1$, we have a pointwise inequality for the integands, and integrating with respect to a positive measure, in particular a probability measure, preserves the pointwise inequality.


Q: Multiple table Set-based insert with identity column in table1 and foreign key in table2 I am writing an Application that imports configuration data from multiple external systems. To decouple the user-data from imported data y am using an intermediate table. The following tables are simplified for the sake of the argument.

*

*table [connection] (generic connection information referenced by other tables not included)

*table [importConfig] (Connection configuration from one of the external systems)

*table [connectionImportConfig] (intermediate table, linking [connection] and [importConfig]

For each connection in [importConfig] I want to create a row in [connection] with an identity column. Then I want to insert the new IDs from [connection] together with the identifier from [importConfig] in [connectionImportConfig].
Constraint: I don't want to use a cursor. Must be a set-based solution.
The examples I have found on stackoverflow are either not set-based or I found them not applicable for other reasons.

*

*T-SQL Insert into multiple linked tables using a condition and without using a cursor (not valid for multiple rows, using @@IDENTITY)

*How to perform INSERT/UPDATE to Linking (Join) table which has FKs to IDENTITY PKs (not valid for multiple rows. Not telling how to join the identity values with the original data I want to insert)
I have tried a lot and am stuck at the point where I have to insert the new IDs into connectionImportConfig
-- Test tables&data (stripped down version)
CREATE TABLE connection            (ConnectionID int identity(1,1) NOT NULL, comment nvarchar(max) null)
CREATE TABLE connectionImportConfig(connectionID int NOT NULL, ConfigCode nvarchar(50) NOT NULL)
CREATE TABLE importConfig          (ConfigCode nvarchar(50) NOT NULL)
DECLARE @MyConnection table        (ConnectionID int not null);

insert into importConfig values ('a')
insert into importConfig values ('b')
insert into importConfig values ('c')

-- Insert into PK-table creating the IDs
INSERT  INTO connection (comment)
        OUTPUT INSERTED.ConnectionID  INTO @MyConnection
SELECT * from importConfig

-- How do I insert the new IDs together with the ConfigCode? 1 has to be replaced with the ID.
-- JOIN doesn't seem to work because there is no join condition to use
INSERT INTO connectionImportConfig (connectionID, ConfigCode)
SELECT 1, ConfigCode FROM ImportConfig

select * from @MyConnection
select * from connectionImportConfig

-- Cleanup
DROP TABLE importConfig;
DROP TABLE connection;
DROP table connectionImportConfig;

A: Have a look at this.  I am sure you could loosely modify this to your needs. I don't typically like inserting right off the output but it really depends on your data.  Hope this example helps.
IF OBJECT_ID('tempdb..#ImportConfig') IS NOT NULL DROP TABLE #ImportConfig
IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config
IF OBJECT_ID('tempdb..#Connection') IS NOT NULL DROP TABLE #Connection
GO

CREATE TABLE #ImportConfig (ImportConfigID INT PRIMARY KEY IDENTITY(1000,1), ImportConfigMeta VARCHAR(25))
CREATE TABLE #Config (ConfigID INT PRIMARY KEY IDENTITY(2000,1), ImportConfigID INT, ConfigMeta VARCHAR(25))
CREATE TABLE #Connection (ConnectionID INT PRIMARY KEY IDENTITY(3000,1), ConfigID INT, ConnectionString VARCHAR(50))

INSERT INTO #ImportConfig (ImportConfigMeta) VALUES
('IMPORT_ConfigMeta1'),('IMPORT_ConfigMeta2')

;MERGE
INTO    #Config AS T
USING   #ImportConfig AS S
ON      T.ConfigID = S.ImportConfigID
WHEN    NOT MATCHED THEN
        INSERT (ImportConfigID, ConfigMeta) VALUES (
                                                    S.ImportConfigID,
                                                    REPLACE(S.ImportConfigMeta,'IMPORT_','')
                                                    )
OUTPUT  INSERTED.ConfigID, 'CONNECTION_STRING: ' + INSERTED.ConfigMeta INTO #Connection;

SELECT 'IMPORT CONFIG' AS TableName, * FROM #ImportConfig
SELECT 'CONFIG' AS TableName, * FROM #Config
SELECT 'CONNECTION' AS TableName, * FROM #Connection


Q: How to make a line with a laser pointer So I was going through a meandering "thought journey" and was thinking about human's persistence of vision.  This can be demonstrated by rapidly moving a laser pointer back and forth, which tricks the human brain into seeing a solid line.  This works, since the "point" of the laser inst actually a cartesian point, but a circle with measurable width.  Then I was thinking there are actual ways to make a line with the laser pointer.  These are the ones I can think of:

*

*Hold the end of a laser pointer on the edge of a piece of paper (with a slight angle) and the width of the beam will form a line down the paper

*Curve the paper and the width of the beam will form a line, relative to the angle of the beam and the curve of the paper

*Reflect the laser pointer off a straight or curved surface and it will create a line down the paper (Technically, this would work, but seems just an alternate way to do 1 and 2)

*Use a prism to break the laser into its separate wavelengths (I assume this would technically work, but not be visible)

Are there any other ways to make a line with a laser pointer?
-- I hope this isnt off topic here.  But this seemed the most likely place on StackExchange to get the right answer.


Q: Add custom key in fetched JSON I am making simple blog website in React and when I fetch posts I am getting user id, who posted it. with this id I am making another axios where I get user with given id and then I assign author key to my fetched posts JSON like this:

export const getPosts = async () => {
  try {
    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/posts"
    );
    for (const item of data) {
      let user = await getUser(item["userId"]);
      item["author"] = user.username;
    }
    return data;
  } catch (err) {
    toast.error(err.message);
  }
};

export const getUser = async (id) => {
  try {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/users/" + id
    );
    return response.data;
  } catch (err) {
    toast.error(err.message);
  }
};

This method causes 5-10 seconds delay to display posts. I am searching for faster and simpler way to display username to every post.
U also can tell me if there is better way to fetch data and display it.
Thanks!

A: You have done it the exact right way if there is no other endpoint available to fetch multiple post author information at a time.
Well, this is meant to be an answer, but I'd start with a question.
Do you have access to the maintainer or developer handling the Restful API endpoint you are trying to get from?
If yes?
Tell them to simply include the author information on the response for fetching the post(s)
Or simply provide you with an endpoint that allows you to get author information for many posts at a time.
If No
Go over the documentation provided (if any) and see if there is any endpoint that allows you to fetch author information for multiple posts with a single request.
If none of the above option seems to be a way, kindly remember to block the UI When fetching the resources.
You can also fetch for few authors first and display while fetching for more in the background or on request for more by user, that way you would give a better user experience.
Happy hacking and coding


Q: How do I extract a single byte from within a string on iPhone? In Android, I can extract a single byte from within a string using code like the following:
byte[] arrByte = String.getBytes(); .

If I wanted to do this on the iPhone in Objective-C, how could I accomplish the same task?  Additionally, how could I get a byte for a given index in the string?

A: If you take a look at the NSString reference you will get various methods to get the data from a string. An example is
NSData *bytes = [yourString dataUsingEncoding:NSUTF8StringEncoding];

You can also make use of the method UTF8String


Q: Dropdown menu showing total; need it to show the selected items I have a script that shows total price for each option in dropdown menu. Now I need to show the name of selected menu with the total.
You will find the script below that shows the total price. I need it to show the name in the <option>.
Any idea how to modify this to show the name of each dropdown selected?

//<![CDATA[
$(function() {
  $("#type").on("change", function() {
    $("select.calculate option").eq(0).prop('selected', true);
    calc();
  });
  $("select.calculate").on("change", calc);
  $("input[type=checkbox].calculate").on("click", calc);
  function calc() {
    var basePrice = 0;
    newPrice = basePrice;
    $("select.calculate option:selected,input[type=checkbox].calculate:checked").each(function(idx, el) {
      newPrice += parseInt($(el).data('price'), 10);
    });
    newPrice = newPrice.toFixed(2);
    $("#item-price").html(newPrice);
  }
});

<select id="type" name="buyer" class="form-control input-lg form-el">
  <option value="">Service Needed</option>
  <option value="kite">Car Wash & Detailing</option>
    <option value="user">Mechanic visit</option>
  <option value="elect">Electrican visit</option>
  <option value="tyre">Tyre Service</option>
  <option value="bat">Battery Service</option>
</select>

  <select id="type2" name="buyername" class="form-control input-lg form-el calculate">
    <option data-price="0" value="">-- Select --</option>
    <option data-price="100" value="kite1">Car Wash exterior</option>
    <option data-price="150" value="kite1">Car Wash In & Out</option>
    <option data-price="1000" value="kite2">Full Detailing</option>
  </select>

  <select id="type2" name="tyrem" class="form-control input-lg form-el calculate">
    <option data-price="0" value="">-- Select --</option>
    <option data-price="100" value="kite1">Road tyre problem rescue</option>
    <option data-price="50" value="kite1">4 Tyre pressure check and adjust</option>
    <option data-price="100" value="kite2">tyre 1 plug repair</option>
    </select>

  <select id="type2" name="batm" class="form-control input-lg form-el calculate">
    <option data-price="0" value="">-- Select --</option>
    <option data-price="100" value="kite1">Battery rescue / jump start</option>
    <option data-price="150" value="kite2">Battery check , jump start or replace - price depends on battery</option>
  </select>
  0


Q: Utilizando um select com UNION ou outro parametro mysql Estou desenvolvendo fluxo de caixa da minha empresa e estou encontrando uma dificuldade.
Eu tenho duas tabelas diferentes. Uma tabela é a tb_compras(id, fornecedor, nfe, valor, data) e então tenho outra tabela tb_compras_historico_pagamentos(id, id_compra, valor_pago, data).
Eu preciso criar uma conta corrente igual de banco, fluxo de caixa de um determinado FORNECEDOR meu.
Eu vou lançando as compras na tabela tb_compras que no caso é um débito(-) e os pagamentos na tabela tb_compras_historico_pagamentos que no caso são os créditos(+).
Então tb_compras é o débito e tb_compras_historico_pagamentos é o crédito.
Ex:
Data | Descrição        | Crédito | Débito | Total
12/06 Cupom fiscal 02               -100,00 -100,00
13/06 Depósito 233        +80,00            -20,00
15/06 Cupom fiscal 11               -200.00 -220.00
17/06 Depósito 1223       +400,00           +180,00

Não estou conseguindo fazer o select para pegar os resultados das duas tabelas em um único select e ordenar pela data pra poder listar da forma do exemplo acima.
Lembrando que a tabela tb_compras_historico_pagamentos está relacionada com a tabela tb_compras.
Pensei em usar o select abaixo, mas está dando erro no select, não sei se ele é a forma ideal para isso.
Porque no caso eu preciso pegar todos os registros da tabela tb_compras e da tabela tb_compras_historico_pagamentos(que esta ligada com a tb_compras) e listar todos por ordem de data para criar o fluxo de caixa de entrada e pagamentos.
O select que estou tentando é esse, mas sem sucesso:

SELECT valor FROM tb_compras WHERE
  fornecedor = 'ID_FORNECEDOR' UNION ALL SELECT valor FROM
  tb_compras_historico_pagamento WHERE id_compra =
  tb_compras.id

A: Neste caso você precisa fazer um inner join, recuperar os valores da tabela de históricos relativas ao débito.
SELECT A.valor as debito, B.valor as recebido FROM tb_compras A INNER JOIN tb_compras_historico_pagamento B ON A.id_compra = B.id_compra;

A: Para versões de MySQL >= 8.0,
WITH RECURSIVE Q (rowid, data, fornecedor, credito, debito, saldo) AS
(
    SELECT C.id, C.data, C.fornecedor, HCRED.valor_pago as credito, HDEB.valor_pago as debito, COALESCE(HDEB.valor_pago, 0) + COALESCE(HCRED.valor_pago, 0) as saldo
    FROM      tb_compras C
    LEFT JOIN tb_compras_historico_pagamento HCRED
              ON C.id = HCRED.id_compra AND HCRED.valor_pago > 0
    LEFT JOIN tb_compras_historico_pagamento HDEB
              ON C.id = HDEB.id_compra AND HDEB.valor_pago < 0

    UNION

    SELECT C.data, C.fornecedor, HCRED.valor_pago, HDEB.valor_pago, COALESCE(HCRED.valor_pago, 0) + COALESCE(HDEB.valor_pago, 0) + Q.saldo
    FROM tb_compras C
    JOIN Q ON C.id = Q.rowid + 1
    LEFT JOIN tb_compras_historico_pagamento HCRED
              ON C.id = HCRED.id_compra AND HCRED.valor_pago > 0
    LEFT JOIN tb_compras_historico_pagamento HDEB
              ON C.id = HDEB.id_compra AND HDEB.valor_pago < 0
)
SELECT *
FROM Q
ORDER BY 2, 3;


Q: How to add different Quality in a Single video in my website? How can I add different Quality in videos. Do I have to embed it in  or  or any other tag . I mean I want to open a video website. Now I have to post 720p and 1080p. I have to post them separately. But I want them to be posted at once in same video . The people could change the Quality just by choosing like YouTube. Or Is there anyway I can post 2 separate button. 1. 720p 2. 1080p . By Clicking no. 1 a video will be open in the same page. Then clicking no.2 the other Quality video will open in same place as 720p video and forcing the 720p to be hidden

A: There's no way to downscale video on YouTube manually. YouTube does this automatically, just upload the highest quality you can, and the appropriate lower qualities will be "created" in the quality settings.


Q: Will scaling down RDS instance preserve data? I have Amazon Aurora for MySQL t3.db.medium instances. I would like to scale down to t3.db.small.
If I modify the instance settings in AWS console, will my DB data be preserved? So can I scale down without service interruption? I think I should be able to do this, but I just wanna make sure. There is prod instance involved.
I have the same question about Elastic Cache (AWS redis). Can I scale that down without service interruption?

A: According to Docs, there is table(DB instance class) which tells which settings can be changed, you can change your instance class for your aurora, as a note An outage occurs during this change.

For redis

according to docs, you can scale down node type of your redis cluster (version 3.2 or newer). During scale down ElastiCache dynamically resizes your cluster while remaining online and serving requests.
In both the cases your data will be preserved.


Q: Python: last item position So I have a huge string and I process it element by element. I want to know how much is left so I try to take the current position word minus the last position word to see how many are left. I tried something like this:
with codecs.open("C:\\dna_chain.txt",'r', "utf-8") as file:
    for line in file:
        temp_buffer = line.split()
        for i,word in enumerate(temp_buffer):
            print(enumerate(temp_buffer[i]))
            print(enumerate(temp_buffer[-1]))

I get positions in memory and they are the same.

A: enumerate() returns a generator object; you only printed the representation of the object, then discard it again. The second line then reused the same memory location for a now object.
You can just refer directly to the temp_buffer object without enumerate() here:
for i, word in enumerate(temp_buffer):
    print(temp_buffer[i])
    print(temp_buffer[-1])

but temp_buffer[i] is the same thing as word in that loop. temp_buffer[-1] is the last word in your list.
If you wanted to know how many more words there are to process, use len(temp_buffer) - i, the length of the temp_buffer list, subtracting the current position.

A: You should count the number of items beforehand:
words = len(temp_buffer)

in your code this would look like
import codecs

with codecs.open("C:\\dna_chain.txt",'r', "utf-8") as file:
    for line in file:
        temp_buffer = line.split()
        words = len(temp_buffer)
        for i,word in enumerate(temp_buffer):
            print(i, word, words-i-1)

this will print the index i, the word word and the number of remaining items in this row words-i-1.


Q: Comparing two text files is not working in Powershell I am trying to compare the contents of two text files and have only the differences be outputted to the console.
The first text file is based on the file names in a folder.
$AsyFolder = Get-ChildItem -Path .\asy-data -Name
I then remove the prefix of the file name that is set up by the user and is the same for every file and is separated from the relevant info with a dash.
$AsyFolder| ForEach-Object{$_.Split("-").Replace("$Prefix", "")} | Where-Object {$_}|Set-Content -Path .\templog.txt
The output looks like $Asyfolder Output
bpm.art
gbr.pdf
asy.pdf
fab.pdf
as1.art
odb.tgz
ccam.cad
read_me_asy.txt

There is another file that is the reference and contains the suffixes of files that should be there.
It looks like this Reference File
tpm.art
bpm.art
gbr.pdf
asy.pdf
fab.pdf
as1.art
as2.art
odb.tgz
xyp.txt
ccam.cad

And its contents are received with $AsyTemplate = Get-Content -Path C:\Users\asy_files.txt
The logic is as follows
$AsyTemplate |
    ForEach-Object{
        If(Select-String -Path .\templog.txt -Pattern $_  -NotMatch -Quiet){
           Write-Host "$($_)"
        }

    }

I have tried various ways of setting up the templog.txt with -InputObject: using Get-Content, Get-Content -Raw, a variable, writing an array manually. I have also tried removing -NotMatch and using -eq $False for the output of select string.
Everytime though the output is just the contents of asy_files.txt (Reference File). It doesn't seem to care what is in templog.txt ($AsyFolder Output).
I have tried using compare-object/where-object method as well and it just says that both files are completely different.

A: Thank you @Lee_Dailey for your help in figuring out how to properly ask a question...
It ended up being additional whitespace (3 tabs) after the characters in the reference file asy_files.txt.
It was an artifact from where I copied from, and powershell was seeing "as2.art" and "as2.art               " I am not 100% as to why that matters, but I found that sorting for any whitespace with /S that appears after a word character /W and removing it made the comparison logic work. The Compare-Object|Where-Object worked as well after removing the whitespace.


Q: How do I configure logback to use xz compression for my logs automatically? How do I configure logback to use xz compression for my logs automatically?
Is xz even supported or only gz and zip?

A: No, logback doesn't support xz. You can see it in source for RollingPolicyBase.java and source for Comressor.java


Q: how to generate a UI for a ListView Adapter for FaceBook like Feed how to creat a Arraylist adapter which will change the view based on a flag in the LISTVIEW, Flag can be IMAGE , IMAGETEXT, VIDEO , VIDEOTEXT, TEXT
e.g like in facebook post , 1.   if a friend posts a text, list row will only contain a text with his Name
2. if a friend posts a Image , list row will only contain a image with his Name
3. if a friend poasts a Video , list row will only contain a Video with his Name , and only Video onClick() ,
 Playing  that Video in a external Player

*

*Flag = text. view to be attached is text.xml

*Flag = Video, View to be attached is video.xml

*Flag = Image ,View to be attached is image.xml
ANY HELP ON THIS.
Thanks in Advance...

A: override  getItemViewType(int position) and getViewTypeCount() method in your adapter and
inflate you view according to it from getView(). In you case write methods like
 @Override
public int getItemViewType(int position) {
        if(list.get(position).flag == text)
            return 0;
         else if(list.get(position).flag == image)
            return 1;
         else
            return 2;
}

@Override
public int getViewTypeCount() {
    return 3;
}

A: I am not pretty much sure but it's my concept that firstly create a layout for row that can hold every thing that you want show(image, video, text etc ). And make this layout such a way if one thing is not present then it automatically wrapped(means if video is not present then video space will not be there).
Now make json of every list row and pass it to Adapter of list. Then override getView() method of the
adapter and parse json there and display according to your layout.

A: i implemented similar Custom Adapter for ListView which is used in this link , also used ViewHolders
check this link
http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/


Q: Getting an Array from Return statement, deduce a string from that I have a 'Case' conditional code snippet wherein I am returning two objects.
The psuedocode is -
case name
when 'a'
object1 = - SQL Logic -
when 'b'
object1 = - SQL Logic -
when 'c'
object2 = - SQL Logic -
when 'd'
object2 = - SQL Logic -
end
return object1, object2

As evident, I am returning two objects. However, in my Controller I need one object at a time. The object are returned in form of Array like ['value', 'nil']. One of them is always nil.
In my controller I am passing one of these objects as -
Model.find_by_sql ["select * from #{object}"]  #either object1 or object2

Is there any way that I can break off this array and return the object that is required at that place as String?
Thanks.

A: While you can use compact to eliminate the nil values from your array, I'm not sure why you need this in the first place.
Doing
case name
  when 'a'
    return "SQL statement"
  when 'b'
    return "SQL statement"
  when 'c'
    return "SQL statement"
  when 'd'
    return "SQL statement"
end

is way more intuitive.

A: return [object1, object2].compact
you can use compact method to remove nil value of array.

A: You could write:
return (['a', 'b'].include?(name) && - SQL Logic 1 -) ||
         (['c', 'd'].include?(name) && - SQL Logic 2 -)

If it's the last line of a method, you don't need return.
Let's see what's happening.
If ['a', 'b'].include?(name) #=> true, - SQL Logic 1 -, which is truthy, will be returned.
If ['a', 'b'].include?(name) #=> false, the first && clause is false (- SQL Logic 1 - is not executed), so we consider the other || clause. ['c', 'd'].include?(name) must be true, so we return - SQL Logic 2 -.