text:
Q: Multilabel text classification using BERT and Tensorflow 2 I am trying to build a simple multilabel text classification pipeline using BERT; the goal is to classify the content of social media posts and any post can have more than one label (i.e., a post can be labeled both "Medications" and "Physical and Mental Health"). I am very new to BERT and was trying to follow this example I found: https://towardsdatascience.com/building-a-multi-label-text-classifier-using-bert-and-tensorflow-f188e0ecdc5d
I have some questions on how to set it up for this task.
In my Anaconda system I have previously installed Tensorflow version 2.0. I have ran the command "pip install bert-tensorflow" and then ran the following:
import tensorflow as tf
import tensorflow_hub as hub
import bert
from bert import run_classifier
from bert import optimization
from bert import tokenization
from bert import modeling

And got this error at the step "from bert import run_classifier":
ModuleNotFoundError: No module named 'tensorflow.contrib'

I did some research and found out that Tensorflow 2.0 indeed does not have the contrib module, but earlier versions do. I just wanted some ideas on how to resolve this issue? I do not want to downgrade my Tensorflow version. And, if anyone can please point me to other examples of multilabel text classification and BERT I would greatly appreciate it (so far the ones I've seen are not very easy to follow).
Thank you!

A: You can avoid this error by selecting Tensorflow version 1.x before your code:
%tensorflow_version 1.x

import tensorflow as tf
tf.__version__   # to check the tensorflow version

Output:
TensorFlow 1.x selected.
'1.15.2'

This code line will convert Tensorflow version to 1.15 for your kernel runtime and now you can import the libraries and run your code without error:
import tensorflow as tf
import tensorflow_hub as hub
import bert
from bert import run_classifier
from bert import optimization
from bert import tokenization
from bert import modeling


text:
Q: Can't get Windows to boot after editing partitions When I attempt to boot Windows I get the error 0xc000000e. This happened after I made a partition in Windows and then deleted it in Mac OS.
Here's my current set up. Is it possible to repair it using GDisk? I've added a description of each partition to the list.
    *** Report for internal hard disk ***

    Current GPT partition table:
     #      Start LBA      End LBA  Type
     1             40       409639  EFI System   (FAT)
     2         409640    166400863  Mac OS X HFS+   (Mac OS)
     3      167731200    169062399  Mac OS X HFS+   (Recovery)
     4      169062400    215558143  Basic Data   (New Partition)
     5      215558144    368127999  Basic Data   (Bootcamp)
     6      368128000    369049599  Unknown   (Don't know how this got here)
     7      369049600    490231807  Basic Data   (Files)

    Current MBR partition table:
 # A    Start LBA      End LBA  Type
 1              1       409639  ee  EFI Protective
 2 *       409640    166400863  af  Mac OS X HFS+
 3      169062400    215558143  07  NTFS/HPFS
 4 *    215558144    368127999  07  NTFS/HPFS

MBR contents:
 Boot Code: None

Partition at LBA 40:
 Boot Code: Windows BOOTMGR (Vista)
 File System: FAT32
 Listed in GPT as partition 1, type EFI System (FAT)

Partition at LBA 409640:
 Boot Code: None
 File System: HFS Extended (HFS+)
 Listed in GPT as partition 2, type Mac OS X HFS+
 Listed in MBR as partition 2, type af  Mac OS X HFS+, active

Partition at LBA 167731200:
 Boot Code: None
 File System: HFS Extended (HFS+)
 Listed in GPT as partition 3, type Mac OS X HFS+

Partition at LBA 169062400:
 Boot Code: None (Non-system disk message)
 File System: FAT32
 Listed in GPT as partition 4, type Basic Data
 Listed in MBR as partition 3, type 07  NTFS/HPFS

Partition at LBA 215558144:
 Boot Code: Windows BOOTMGR (Vista)
 File System: NTFS
 Listed in GPT as partition 5, type Basic Data
 Listed in MBR as partition 4, type 07  NTFS/HPFS, active

Partition at LBA 368128000:
 Boot Code: Windows BOOTMGR (Vista)
 File System: NTFS
 Listed in GPT as partition 6, type Unknown

Partition at LBA 369049600:
 Boot Code: Windows BOOTMGR (Vista)
 File System: NTFS
 Listed in GPT as partition 7, type Basic Data

I've tried to recreate the deleted partition (4) and added it to the MBR block. It still doesn't work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is probability function for mutually exclusive events a linear operator? If the definitive classification criteria for a linear operator are given by:

*

*$L(f+g) = L(f) + L(g)$             [for any/every pair of functions, $f$ and $g$]

*$L(tf) = tL(f)$                   [for any scalar, $t$]

What does this imply for the probability of any two mutually exclusive events?
One knows that for two mutually exclusive events, the probability of one is related to the other by the positive difference of unity and

*

*$P(A) + P(B) = 1 \rightarrow     P(A) = 1 - P(B)$  [for two mutually exclusive events, $A$ and $B$]

*$P(A \cup B) = P(A) + P(B)$
Can the probability function over the union of two mutually exclusive events be considered a linear operator then? Or does this just cross completely incompatible areas of maths?

A: A linear operator is defined over a vector space. I do not know of any general notion of "scalar multiplication" in the case of the "probability operator". That is, there is no analogue of the 2nd condition in the definition of a linear operator in this case.

A: Let me add another answer that has direct bearing on what you asked.
I like the fact that you are trying to bridge two areas of mathematics so please don't take my first answer as being critical. That said, what you have tumbled upon are called subadditivity if you interpret $\cup$ as $+$ (The analogy is not perfect but gets the point across). Subadditivity says
$$
f(x+y) \le f(x) + f(y)
$$
See http://en.wikipedia.org/wiki/Subadditivity for more information.

A: I was going to write this as a comment but I feel that it is important enough that it should be in the answer. This does not directly answer your question. For that look at voldemort's answer.
There is a common misunderstanding that mutually exclusive means that the events are complementary. Thus if $A$ and $B$ are mutually exclusive you cannot conclude that $P(B)=1-P(A)$. All it means that $A$ and $B$ both cannot occur. All you can conclude are
$$
P(A \cap B) = 0\\
P(A \cup B) = P(A)+P(B)
$$
In plain English,

*

*Probability of A and B is zero,

*Probability of A or B is probability of A plus probability of B
You cannot conclude anything else


text:
Q: Ошибка в Fragment Ошибка в Fragment не пойму как исправить, объясните пожалуйста почему в Fragment код работает не так как в Activity
public class Fragment_Menu_list_Tasks_Prapor_1 extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_menu_list_task_prapor_1, container, false);
    }

    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState)
    {
        ImageButton back = requireView().findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(view)
                        .navigate(R.id.action_fragment_Menu_list_Tasks_Prapor_1_to_fragment_Menu_list_Tasks_Prapor);
            }
        });

        final ImageButton quick_menu = requireView().findViewById(R.id.quick_menu);

        quick_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                PopupMenu popupMenu = new PopupMenu(Fragment_Menu_list_Tasks_Prapor_1.this, quick_menu);
                popupMenu.getMenuInflater().inflate(R.menu.quick_menu, popupMenu.getMenu());

                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        return false;
                    }
                });
            }
        });
    }
}

Ошибка
error: incompatible types: Fragment_Menu_list_Tasks_Prapor_1 cannot be converted to Context
                PopupMenu popupMenu = new PopupMenu(Fragment_Menu_list_Tasks_Prapor_1.this, quick_menu);

A: Если в активити что-то требует Context, то this передают, потому что активити наследуется от Context. Фрагмент же не наследуется от Context, но его можно получить с помощью метода getContext()
PopupMenu popupMenu = new PopupMenu(getContext(), quick_menu);

Либо контекст можно получить из View, которая приходит в OnClick
PopupMenu popupMenu = new PopupMenu(v.getContext(), quick_menu);


text:
Q: Error in saving Random Forest Classifier model in Pyspark rf = RandomForestClassifier().setFeaturesCol("features").setLabelCol("label")
pipeline = Pipeline(stages=[tokenizer, hashingTF, idf, rf])
model = pipeline.fit(training)
model.save(sc, '<path_to_save>')

I am trying to save the model file by using the above code.But getting an unexpected error -
TypeError: save() takes exactly 2 arguments (3 given)

I don't understand this error. I am passing 2 arguments only but still getting this error.
Do anybody have idea? What I am doing wrong here?

A: I don't know how this is working. But removing 1st field 'sc' works for me.
model.save('<path_to_save>')

I am able to save the model file by this command.


text:
Q: Running api on different servers I am currently running an express server. It is having routes which is computational and memory extensive. I want to shift that api routes to different server so that it does not harm any other apis.
I am currently proxy passing that request using nginx. But I want to do it in express level in order to get more control.
Is there any different approach or any other npm package to achieve this?

A: It seems like you are looking for a solution like http-proxy-middleware. Intregation is super-simple too.


text:
Q: expandable list view gives wrong group position, only works correctly without view holder I can't proceed without using the view holder pattern however because I am running countdowns in every list and Expandablelistview becomes choppy without it. Maybe its a simple fix. Thanks in advance.
@Override
public View getGroupView(int groupPosition, final boolean isExpanded, View convertView, final ViewGroup parent) {

    final ViewHolderItem viewHolder;

    if (convertView == null) {

        LayoutInflater infalInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.item_lobby, null);
        viewHolder = new ViewHolderItem();

        viewHolder.lobbyItemExpandIndicator = (ImageView) convertView.findViewById(R.id.lobbyItemExpandIndicator);
        viewHolder.draftEnding = (TextView) convertView.findViewById(R.id.lobbyDraftEnding);
        viewHolder.gameType = (TextView) convertView.findViewById(R.id.lobbyGameType);
        viewHolder.accepting = (TextView) convertView.findViewById(R.id.lobbyAccepting);
        viewHolder.gamesInDraft = (TextView) convertView.findViewById(R.id.lobbyGamesInDraft);

        //viewHolder.draftEnding.setText(groupPosition + "");

        convertView.setTag(viewHolder);
    } else {

        viewHolder = (ViewHolderItem) convertView.getTag();
    }

    final ContestItem contest =  mContests.get(groupPosition);

    //setCountdown(viewHolder, contest);

    viewHolder.gameType.setText(contest.getGameType());
    viewHolder.accepting.setText(contest.getAccepting());
    viewHolder.gamesInDraft.setText(contest.getNbaGamesAmnt());

    if (isExpanded) {
        viewHolder.lobbyItemExpandIndicator.setImageResource(R.drawable.w_dash);
    } else {
        viewHolder.lobbyItemExpandIndicator.setImageResource(R.drawable.w_down);
    }

    return convertView;
}

static class ViewHolderItem {
    TextView draftEnding;
    TextView gameType;
    TextView accepting;
    TextView gamesInDraft;
    ImageView lobbyItemExpandIndicator;
}

A: You should keep your countdowns in group model object instead of keep in views, views are reused each time. so you must keep countdown in your group model and then on get view restore countdown each time.
for example if your displaying data is:
private HashMap<MenuCategoryModel, List<ChildCategoryModel>> mMainMenuExpandableList;

then you must keep your countdowns in MenuCategoryModel or if for each subitem then in ChildCategoryModel and on get views group or child (whatever needed) - restore countdowns.


text:
Q: Detect only RGB blue in image using OpenCV I am trying to detect the 3 circles of blue color on the image below, using C++ and openCV.

I use this code
int main(){
     Mat original=imread("img.jpg");
     Mat hsv;
     cvtColor(original,hsv,CV_BGR2HSV);
     Mat bw;
     inRange(hsv,Scalar(110,50,50),Scalar(130,255,255),bw);//detects blue
}

This code does detect the 3 blue circles BUT also detect other blue points. I am thinking it has to do with the range I specified. Is there a way to detect only those RGB blue circles because I do not think there are any other points which are RGB blue in the image. How can I detect only this color (255,0,0)??

A: If you want to detect the colour represented by (255,0,0) then this is the value you should specify when using the inRange function. Also, if you are interested in the RGB colour, then you don't need to convert your image to hsv.
Note that the relevant page in the OpenCV docs says that the upper and lower bounds in the inRange function are inclusive - you can use the same value for both.
Some minor modifications:
int main()
{
    // Paint a blue square in image
    cv::Mat img = cv::Mat::zeros(100,100,CV_8UC3);
    cv::Scalar blue(255,0,0);

    img(cv::Rect(20,20,50,50)) = blue;
    cv::imshow("Original Image", img);

    // Detect this blue square
    cv::Mat img2;
    cv::inRange(img, blue, blue, img2);
    cv::imshow("Specific Colour", img2);

    cv::imwrite("Input.png",img);
    cv::imwrite("Output.png",img2);
    cv::waitKey(0);

    return 0;
}

Input.png
A blue square drawn in an image

Output.png
The blue square has been detected in this binary image

A: For the image you provided  above, the below thresholds will work fine.
Scalar hsv_l(110,150,150);
Scalar hsv_h(130,255,255);
cvtColor(original,hsv,CV_BGR2HSV);
inRange(hsv,hsv_l,hsv_h,bw)

And you can easily find the HSV value of any pixel using mouse as described here.
Also the HSV color wheel (below) might be helpful to choose any color and get it's HSV value.


text:
Q: How can I print every item in an infinite list with proper IO monad I have this simple definition of the integers, done with an infinite list:
nats = 0: map (+1) nats

And I would like to make a version of that infinite list that print every element.
I did it with Data.Trace (trace)
nats = 0: map (\x -> 1 + trace (show x) x) nats

But it's a bit cheating.
It would be nicer to do it properly with the IO monad.
I tried to do it with an infinite list of type IO [Int] with the following code:
nats' = (fmap f nats') >>= mapM (\x -> do{print x; return x})
  where f l = 0:map (+1) l

The type signatures work, but however when I try to evaluate it with take 10 'nats,
it gets stuck in an infinite recursion without printing anything.
What is wrong with this code, is the type signature right and what would be the right way to approach this problem?
EDIT :
I have a variant of this problem where I want to create an infinite list containing all the inputs of the user.
How can I do that?

A: The IO monad is strict. When we run x <- ioAction, we fully execute ioAction and observe all its side effects before x is bound to a value. Consequently, if ioAction is an infinite loop, it will never return a value to be bound to to x.
In your case, the code has the form
nats' = (fmap f nats') >>=  ...

which is equivalent to
nats' = nats' >>= return . f >>= ...

So, nats' will recurse before executing return . f, causing an infinite loop and preventing any output.
How to make this actually work?
The most idiomatic Haskell way is to separate side effects from actual computation: we define a pure value
nats = 0 : map (+1) nats

and the we print it
nats' = for_ nats print

Note that above there is little point to use for/traverse/mapM (instead of their _ variants), since the list is infinite so it will never return a value, but only perform infinitely many prints.
If you really want to interleave IO and computation, even if that's usually less idiomatic, you can use recursion:
nats' = go 0
  where go l = print l >>= go (l+1)

If you want to try returning a list anyways, even if that will actually never happen, you can use this:
nats' = go 0
  where go l = do
           print l
           ls <- go (l+1)
           return (l:ls)

However, this is unnecessarily complex.


text:
Q: AngularJs DatePicker not showing view I am new to AngularJS and trying to integrate the Angular Material Date Picker with AngularJS but I can't see the calendar(controller/date.controller.js,
 views/calendar.html).Please find the link of plunkr(whole app) and let me know your suggestions.
http://plnkr.co/edit/cHXi8EBfrhcTfwBvJ5nU?p=preview
Below is the controller
 'use strict';
angular.module('plunkr', ['ngMaterial' , 'ngMessages']).controller('mycont', function(){
      this.myDate = new Date();
      this.isOpen = false;

    });

A: You have some issues in your code thats why calendar doesnt show.
First of all, you have two app module one named  plunkr and other named plunker thats cause some injector fail, also in each controller you redefine entire module adding the [] part.
main.controllers.js
angular.module('plunker', []).controller('MainCtrl', function($scope) {....

date.controller.js
angular.module('plunkr', ['ngMaterial' , 'ngMessages']).controller('mycont', function(){....

app.js
angular.module('plunker', []);

here is the fork plknr i took from yours.


text:
Q: Why does my first nextLine() get skipped? Sitting with a school project and I am really confused.
My first nextLine(); in both my for loops gets skipped. I do not seem to understand why, i get this answer might be basic but i really cannot grasp this!
    for (int i = 0; i < antal; i++) {

        System.out.println("Name of the customer?");
        String name = sc.nextLine();
        Kunde.setName(name);

        System.out.println("Adress of the customer?");
        String adresse = sc.nextLine();
        Kunde.setAdress(adresse);

        System.out.println("Mail of the customer?");
        String mail = sc.nextLine();
        Kunde.setMail(mail);

        System.out.println("Phone number of the customer?");
        int tlf = sc.nextInt();
        Kunde.setTlf(tlf);

        System.out.println("Postal code of the customer?");
        int postalcode = sc.nextInt();
        Kunde.setPostalCode(postalcode);

        int x = ran.nextInt(100000);
        Kunde.setOrderNumber(x);

    }

    for (int i = 0; i < antal; i++) {
        System.out.println("Any specific orderdetails revolving order " + Kunde.getName(i)
        + " If not, press enter");
        String details = sc.nextLine();
        order.add(details);

    }

A: Scanner.nextInt method does not consume the last newline character of your input.
That's probably why the second loop's first nextLine is skipped.
Maybe you have a similar cas right before the first for as well?


text:
Q: proper use of trackList? Hello I've been searching around for the best way to crate a "2 dimensional" List. And came across an example given in: Are 2 dimensional Lists possible in c#?
But I'm not getting the sorta output I were hoping for.
Running below code my goal is to proper Console.Writeline( Stuff in the track list ), but all the console is writing is HelloWorld.Track
namespace HelloWorld
    {
        class Track
        {
            public int TrackID { get; set; }
            public string Name { get; set; }
            public string Artist { get; set; }
            public string Album { get; set; }
            public int PlayCount { get; set; }
            public int SkipCount { get; set; }

          //  List<Track> trackList = new List<Track>();

            public void add()
            {
                var trackList = new List<Track>();
                trackList.Add(new Track
                {
                    TrackID = 1234,
                    Name = "I'm Gonna Be (500 Miles)",
                    Artist = "The Proclaimers",
                    Album = "Finest",
                    PlayCount = 10,
                    SkipCount = 1

                });

                Track firstTrack = trackList[0];
                Console.WriteLine(firstTrack);
                Console.ReadKey();
            }
        }
    }

Also what would be the termology name for such a case? Searching for c# track on google just suggest guitar videos.

A: The problem with the Console.WriteLine is that you are passing in the object instance.  What it is doing is calling the ToString method on your object.  Since you have not overridden that method in your Track class, it executes the default implementation which is to output the type name of the object.  You can override the ToString method to return your own custom string.  See https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx on how to do that.  Or you can change how you're calling the Console.WriteLine method to pass in the specific message and object property values that you want to have displayed instead of just passing the object instance.

A:
my goal is to proper Console.Writeline( Stuff in the track list ), but
  all the console is writing is HelloWorld.Track.

That is because you are printing the object and not it's properties. Which can be done using following code:
Console.WriteLine(String.Format("{0}:{1}:{2}:{3}:{4}:{5}", firstTrack.TrackID, firstTrack.Name, firstTrack.Artist, firstTrack.Album, firstTrack.PlayCount, firstTrack.SkipCount));

For extra help, printing all properties from a certain object, try this link:
ObjectDumper Stackoverflow
For more information about how Console.WriteLine() works:
Console.WriteLine (MSDN)


text:
Q: Length of regular local ring Let $A$ be a regular local ring of dimension $n$ with maximal ideal $\mathcal m$.
Then one can consider the $A-$module $A/\mathcal m^i$ for all natural numbers $i$.
My question is simply what length this module has. For $i=0$ it is clearly of length $1$.
But what about $i=2$ and bigger? Can one write down a formula for the length depending just on $n$?
And do you know a reference for this problem?

A: $\newcommand\m{\mathfrak{m}}$
For regular local rings $A$ of dimension $n$ one has the formula:
$$\mathrm{length}(A/\m^{i+1}) = \binom{i+n}{n}.$$
More generally,
let $(A,\m)$ be any Noetherian local ring.
Associated to $A$ is the graded $k = A/\m$-algebra
$$\mathrm{gr}(A) =
\bigoplus_{j=0}^{\infty} \mathrm{gr}^j(A),$$
where $\mathrm{gr}^j(A):=\m^j/\m^{j+1}$. It is a fact that $\mathrm{gr}(A)$
is a local $k$-algebra of dimension equal to $n = \dim(A)$.
The length of $A/\m^{i+1}$ is equal to the sums of the lengths of
$\m^j/\m^{j+1}$ for $j \le i$. Since these latter modules are vector spaces,
this is the same as saying that:
$$\chi_A(i) := \mathrm{length}(A/\m^{i+1}) =
\sum_{j=0}^{i} \dim_k \mathrm{gr}^j(A).$$
The main fact to know is that  $\chi_A(i)$
is a polynomial for sufficiently large $i$. This polynomial is known
as the Hilbert-Samuel polynomial; it has degree $n$ and leading coefficient $1/n!$.
If $A$ is regular, however, then $\dim \m/\m^2 = n$, and so by Nakayama's
lemma, $\mathrm{gr}(A)$ is a quotient of $k[x_1,x_2, \ldots, x_n]$.
Since any non-trivial quotient of this has dimension less than $n$, it follows that
$$\mathrm{gr}(A) \simeq k[x_1,x_2, \ldots, x_n].$$
From this it follows that
the Hilbert-Samuel polnomial is exactly:
$$\binom{i+n}{n},$$
and moreover that $\chi_A(i)$ is given by this formula for all $i \ge 0$.


text:
Q: How can I automatically login to a website using vbscript? On Error Resume Next:
Const PAGE_LOADED = 4

Set objIE = CreateObject("InternetExplorer.Application")
Call objIE.Navigate("http://172.25.25.32:8090/")

objIE.Visible = True

Do Until objIE.ReadyState = PAGE_LOADED : Call WScript.Sleep(100) : Loop

objIE.Document.all.Username.Value = "ashishgi"
objIE.Document.all.Password.Value = "apac2015#"

If Err.Number <> 0 Then
    msgbox "Error: " & err.Description
End If

Call objIE.Document.all.gaia_loginform.submit

Set objIE = Nothing

A: The gaia_loginform is the "form id" of Gmail. Have a look here: http://i.imgur.com/45H7pKP.jpg.
Now I think you should get the form name/id of the site (by viewing the source) so that the script can hit the login button.


text:
Q: Ionic 2 - OneSignal - Obter player_id Eu uso o OneSignal para notificações push em uma aplicação ionic 2.
Para enviar as notificações direcionadas à usuários específicos eu preciso recuperar o player_id do OneSignal.
Alguém tem ideia de como recuperar esse id da plataforma?

A: Encontrei como fazer para recuperar o player_id do plugin OneSignal, e na verdade é bem simples.
No app.component.ts, adicionei o código:
  window["plugins"].OneSignal.getIds(ids => {
    console.log("player_id: " + ids.userId);
  });

Com isso, consigo o PLAYER ID do usuário, possibilitando, por exemplo, o envio de notificações push direcionadas ao usuário em específico.


text:
Q: CSS: Sidebar 100% display height without overlapping navigation bar. (individual nav height) I want to build a specific layout for a settings view. This is how it should look like:

There is a fixed navigation bar on the left side and the content on the right can be scrolled independently. The navigation bar on the left should always fill the complete page except the navigation bar.
I know, I could make the left navigation position:fixed and give it an offset of the top-navigation height, but the height of the navigation changes dynamically.
So is there any dynamic solution?

body,
html {
  padding: 0;
  margin: 0;
}

h1 {
  margin: 0;
}

.lorem {
  background-color: Gainsboro;
  height: 100px;
  margin: 10px;
}

#nav-top {
  height: 100px;
  Background-color: SeaGreen;
}

#nav-sub {
  height: 30px;
  Background-color: YellowGreen;
}

.content {
  position: relative;
}

.left-nav {
  position: fixed;
  background-color: Teal;
  top: 0;
  margin: 0;
  bottom: 0;
  z-index: 2;
}

 Navigation

 Subnavigation

Item

Item

Item

Item

Item

Scrollable Content

This is the link to my JSFiddle:
Thanks for any help!

A: Why not use a table instead?

body, html {
  padding: 0;
  margin: 0;
}

h1{
  margin:0;
}

.lorem{
  background-color: Gainsboro;
  height: 100px;
  margin:10px;
}

#nav-top{
  height:100px;
  Background-color:SeaGreen;
}
#nav-sub{
  height:30px;
  Background-color:YellowGreen;
}

.content{
  width:100%;
}

.left-nav {
  background-color: Teal;
  vertical-align: top;
}

 Navigation

 Subnavigation

Item

Item

Item

Item

Item

Scrollable Content

A: Apply width and height to body, and apply fixed dimensions to the header, sidebar and main content.

body {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  overflow: hidden;
}

header {
  width: 100%;
  min-height: 100px;
  background-color: rgb(103, 194, 33);
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 5%;
}

aside {
  width: 20%;
  max-height: calc(100% - 100px);
  background-color: rgb(159, 159, 159);
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction:  column;
  align-items: center;
}

li {
  padding: 5%;
}

main {
  width: 80%;
  max-height: calc(100% - 100px);
  overflow-x: hidden;
  overflow-y: scroll;
  box-sizing: border-box;
  padding: 2.5%;
}

.container {
  width: 100%;
  height: 25%;
  background-color: rgb(223, 223, 223);
  margin-bottom: 2.5%;
}
Brand

item

item

item

item

Some Content


text:
Q: How can I refresh a child component from a parent component multiple times from the same method? Right now my child component only updates once the GetLeads() method in the parent component is finished. I never see the spinner or Searching text.
Parent Component:
<SearchResultComponent  @ref="ChildComponent"></SearchResultComponent>

Code:
 protected SearchResultComponent ChildComponent;
 public int LeadsFound { get; set; }
 public void GetLeads()
 {
      ChildComponent.Refresh(true, 0);
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }

Child Component:
@code {

    public bool Searching { get; set; } = false;
    public int LeadsFound { get; set; } = 0;
    public void Refresh(bool searching, int leadsFound)
    {
        Searching = searching;
        LeadsFound = leadsFound;
        StateHasChanged();
    }
}

@if (Searching)
{

Searching...

}
else
{

Leads Found: @LeadsFound

}

A:
my child component only updates once

You can make the eventhandler async. That allows you then to call Task.Delay(1) or Task.Yield() and that will effectuate the StateHasChanged().
The call form @onclick="@GetLeads" can remain the same. Note that you don't need the 2nd @ in there.
If your searchService.Search() was async then you wouldn't need Task.Yield()
 public async Task GetLeads()
 {
      ChildComponent.Refresh(true, 0);
      await Task.Yield();  // enable the render thread to run.
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }


text:
Q: Return the greater numbers in a binary search tree in java I have this code where I am trying to print the greater numbers of a binary search tree. For example when I call the greater method greater(5) and my binary search tree has values 1,2,3,4,5,6,7,8,9,10 I want to return the greater values from 5, so the outcome it will be 6,7,8,9,10. But my code has a problem and I don't know where is the problem. The system out should be return. It work with system out.
private int greater(BTNode<Integer> n,int nu)
{   int o=0;
    int leftAns = 0;
    if (n.left != null)
        leftAns = greaterInt(n.left, nu);
    int rightAns = 0;
    if (n.right != null)
        rightAns = greaterInt(n.right, nu);
    int answer = leftAns + rightAns;

    if (n.data.intValue() > nu){
        o+=n.data;
       System.out.println(n.data);
        //System.out.println(answer);
    }

   return o;
}
public int greater(int n)
{ if (root == null)
    return 0;
else
    return greaterInt(root,n);
}

A: You have more values not only one; so just add those values in a list
private void greater(BTNode<Integer> n, int nu, List<Integer> integers) {
    if (n.left != null)
         greaterInt(n.left, nu);
    if (n.right != null)
        greaterInt(n.right, nu);
    if (n.data.intValue() > nu) {
        //System.out.println(n.data);
        //System.out.println(answer);
        integers.add(n.data);
    }
}

public List<Integer> greater(int n) {
    if (root == null)
        return Collections.EMPTY_LIST;
    List<Integer> ar = new ArrayList<>();
    greaterInt(root, n, ar);
    return ar;
}

If you want the sum of elements greater than n as your source looks like:
private int sum(BTNode<Integer> n, int nu) {
    int leftAns = 0;
    int rightAns = 0;

    if (n.left != null)
        leftAns = greaterInt(n.left, nu);
    if (n.right != null)
        rightAns = greaterInt(n.right, nu);
    if (n.data.intValue() > nu) {
        //System.out.println(n.data);
        //System.out.println(answer);
        return leftAns + rightAns + n.data;
    }
    return leftAns + rightAns;

}

public int sum(int n) {
    if (root == null)
        return 0;
    else {
        return sum(root, n);
    }
}

A: T max = null;

if(rootNode.getRightChild() == null){

max = rootNode.getData();

}

else{

maxItem(rootNode.getRightChild());

}

return max;


text:
Q: Creating transition matrix per indexed Time interval I have a dataset on the transition of users between states (9 in total) in a specific time interval. This dataset will be used for a markov chain model. In total there are 96 time intervals, thus: for every user there are 96 observations each of which provides the specified time interval, a start location and an end location. A state that combines two locations simply means that the user is still in transition between the two states.
Below is a fictional dataset. In this example, unlike the actual dataset, start and end location are not necessarily linked, but I believe this will serve just as well as an illustration of the problem.
ID <- rep(1:10, each = 96)
TimeInterval <- rep(1:96, 10)
Locations <- c("Home", "Bakery", "Grocery", "Home-Bakery", "Home-Grocery", "Bakery-Home", "Bakery-Grocery", "Grocery-Home", "Grocery-Bakery")
startLocation <- sample(Locations, 960, replace = TRUE)
endLocation <- sample(Locations, 960, replace = TRUE)
df <- data.frame(ID, TimeInterval, startLocation, endLocation)

I want to calculate a transition matrix for every time interval, where the transition probability is calculated by the probability of transitioning into a state/location given the state/location at the previous time interval. For instance, to calculate the transition probability matrix for TimeInterval 37 the probability of being in a certain state  in TimeInterval 37 given the state in TimeInterval 36 is taken.
This will result in a total of 96 transition matrices. The probability of transitioning from one state (Location) to another given a specific timeframe then depends on probability of all users combined.
However, I do not know how to aggregate the results of the individual transitions. What would be an efficient way to calculate these matrices?
The transition matrix per time interval should be a 9x9 matrix that includes all the states.
Edit:
A (very ugly) dplyr solution that worked for a single transition matrix:
Interval36 <- df %>% filter(TimeInterval== 36)
Interval37 <- df %> filter(TimeInterval == 37)

timeBlock37 <- as.data.frame(cbind(Interval37$journey, Interval36$journey))
mTimeBlock37 <- as.data.frame.matrix(table(timeBlock37))
timeBlock <- prop.table(mTimeBlock37 )
timeBlock

A: I solved it myself, although not in the most elegant way with quite a unstructured for-loop.
matrixList <- list()
states <- Locations
for(i in 1:96){
  i <- ifelse(i < 96,i + 1, 96)
  t1 <- df %>% filter(timeBlock == i)
  j <- ifelse(i < 96,i + 1, 96)
  t2 <- df%>% filter(timeBlock == j)

  timeBlock <- as.data.frame(cbind(t1[,8], t2[,8]))
  mTime <- as.data.frame.matrix(table(timeBlock))
  timeBlock <- prop.table(mTime)
  timeBlock <- as.matrix(timeBlock)

  mat1 <- matrix(0, nrow = 9, ncol = 9)
  colnames(mat1) <- states
  rownames(mat1) <- states

  colsNeeded <- colnames(mat1)[colnames(mat1) %in% colnames(timeBlock)]
  rowsNeeded <- rownames(mat1)[rownames(mat1) %in% rownames(timeBlock)]
  mat1[rowsNeeded, colsNeeded] <- timeBlock[rowsNeeded, colsNeeded]
  matrixList[[i]] <- mat1

}

I created an empty matrix in the for-loop that could be populated with the transition matrix to take into account for the situations where not all states would appear within a certain timeframe.
If someone still has a more elegant/cleaner solution, feel free to contribute for future readers.


text:
Q: Fatal error: Uncaught Error: Class - composer Em alguns posts(perguntas), não consegui encontrar uma solução para este erro e gostaria da ajuda de vocês expert no assunto.
É algo simples, só quero que mostre um simples echo "Listar Pagina" de acordo com o composer.json, para ter certeza de que esta tudo ok no trajeto, mas, nada resolve, não encontro o erro... :'(
index.php
require 'vendor/autoload.php';

use Core\ConfigController as Home;

$Url = new Home();
$Url->carregar();

ConfigController.php
<?php
namespace Core;
class ConfigController {
    public function carregar() {
        $listarPg = new \App\adm\Models\AdmsPaginas();
    }
}

AdmsPaginas.php
<?php
class AdmsPaginas {
    public function listarPaginas() {
        echo "Listar Paginas";
    }
}

autoload.php
{
    "name": "w/m",
    "description": "Projeto WM",
    "authors": [
        {
            "name": "WM",
            "email": "wm@gmail.com"
        }
    ],
    "autoload": {
        "psr-4": {
            "Core\\": "core",
            "Sts\\": "app/sts",
            "Adm\\": "app/adm"
        }
    },
    "require": {}
}

autoload_psr4.php
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'Sts\\' => array($baseDir . '/app/sts'),
    'Core\\' => array($baseDir . '/core'),
    'Adm\\' => array($baseDir . '/app/adm'),
);

Pastas
Erro

A: Obrigado, já resolvi, só precisei colocar o caminho no index.php
index.php
<?php

require './core/Config.php';
require './vendor/autoload.php';
require './app/adm/Models/AdmsPaginas.php';

use Core\ConfigController as Home;

$Url = new Home();
$Url->carregar();


text:
Q: How to dynamically call all methods of a struct in Golang? I'm building a library where once methods are added to a struct we want them to be automatically called w/o using some sort of method list.
I want to build on the work here by calling all of the methods dumped that is linked here How to dump methods of structs in Golang?.
package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
    Prop string
}

func (f Foo) Bar(i int) {
    fmt.Println("Called from Foo.Bar()")
}

func (f Foo) Baz(i int) {
    fmt.Println("Called from Foo.Baz()")
}

func (f Foo) Floop(i int) {
    fmt.Println("Called from Foo.Floop()")
}

func main() {
    fooType := reflect.TypeOf(&Foo{})

    fmt.Println("--- Calling methods ---")
    for i := 0; i < fooType.NumMethod(); i++ {
        method := fooType.Method(i)

        method.Func.Call(nil)
    }
}

Also seen here: https://play.golang.org/p/gNUsANjuPV0
This will always panic w/ a message for too few arguments to .Call(). I don't see where this differs structurally from the code here: https://play.golang.org/p/HB8yB91LRme.

A: To call the method from the type, you must pass a reflect.Value instance that provides the Foo object that is the receiver plus a reflect.Value instance that provides the int argument that each function receives:
fooType := reflect.TypeOf(&Foo{})
fooVal := reflect.ValueOf(&Foo{})
fmt.Println("--- Calling methods ---")
for i := 0; i < fooType.NumMethod(); i++ {
    method := fooType.Method(i)
    arg := i + 10
    method.Func.Call([]reflect.Value{fooVal, reflect.ValueOf(arg)})
}

for instance.  Note that if you call the method from the value, the receiver is provided via that value, so we get to drop the first argument:
    arg = i + 20
    reflect.Indirect(fooVal).Method(i).Call([]reflect.Value{reflect.ValueOf(arg)})

complete example on Go playground—but note that we only need to obtain the foo object once, above the loop over its methods: https://play.golang.org/p/HHk_mO2KXc6 so that the last line in the loop is just:
    fooObj.Method(i).Call([]reflect.Value{reflect.ValueOf(arg)})


text:
Q: How can I start the Thieves Guild quests if Brynolf is hiding from me? I have just kind of learned about the Nightingale armor and how cool it is an all. I figured out I have to complete the Thieves Guild quest line.
I went into my quests and do not see a quest on the list of quests I found for the specific quest line. Here is my problem. I have joined the guild, but that was a long time ago. I have no clue weather I succeeded in planting the ring or not. In addition, no matter where I look, I can not find Brynjolf in Riften. Is there any way I can still start these quests?
Also, all of the odd jobs I ask for are auxiliary quests except the "No Stone Unturned" quest and I only need Proudspire Manor to complete that quest. Is that another way to access the main quest line?

A: Brynjolf won't be in Riften proper once you do the initial ring-planting quest (A Chance Arrangement). He moves to the Ratway once you finish the quest (successfully or not; failing to plant the ring does not prevent you from joining the guild).
If you can't find him in Riften's market or the Bee and Barb, and you can't find him in the Ratway, you may have encountered a bug.


text:
Q: VueJS 3 Reactive Form Submitted with Old Input Values In my vue.js 3 application I have the following scenario:
I have a toolbar component and a content component (CustomContent). The CustomContent contains a custom form component (CustomForm).
After a submit button in the toolbar was clicked, an event will be emitted from the toolbar to the CustomContent component
using mitt event bus.
On this event the CustomContent change the content parameter of the prop formData which is passed to the
CustomForm. Furthermore, the boolean prop submit will be set to true, which is also passed to the CustomForm. This submit
prop will be watched inside the CustomForm. If it is true, the form will be submitted.
In a nutshell:
   App
   ├─ Toolbar: emits event 'toolbarAction' to CustomContent via mitt emitter (eventBus)
   └─ CustomContent: on:toolbarAction -> set new content in formData and notify form to submit
      └─ CustomForm (formData & submit props given)
         └─ <form ref="form" />  -> this.$refs.submit() if submit==true

So far everything's look good. The new content is applied to the CustomForm. Everything's looks reactive at first.
But when the form inside CustomForm is submitted, a POST request containing the old content will be send to the server,
although the changes were applied. I can see it in the browser's console. I also can see, that the DOM of the form
was updated correctly:
   <form action="/update/some/resource" method="post">
     <input type="hidden" name="_method" value="PUT">
     <input type="hidden" name="_token" value="some_token">

     <input type="hidden" name="content" value="new content">
   </form>

But for some reason the POST request contains the old initialized form state with 'old content'.
CustomContent.vue
<template>

    <custom-form
      :form-data="formData"
      :submit="submit"
    ></custom-form>

</template>

CustomForm.vue
<template>

    <form
      :action="formData.action"
      method="post"
      ref="form"
    >
      <input type="hidden" name="_method" :value="formData.method" />
      <input type="hidden" name="_token" :value="formData.csrf_token" />
      <input
        v-for="param in formData.parameters"
        type="hidden"
        :name="param.name"
        :value="param.value"
      />
    </form>

    {{ formData.parameters[0].value }}

</template>

Does anyone have any idea what I am doing wrong here? Thanks.


text:
Q: How to use regular expressions in Swift 3? I wanted to follow this tutorial to learn about NSRegularExpression in Swift, but it has not been updated to Swift 3. When I open the playground with the examples they provide, I get several errors being one of them the call:
let regex = NSRegularExpression(pattern: pattern, options: .allZeros, error: nil)

I've seen that now that initializer throws an exception so I changed the call, but that .allZeros does not seem to exist anymore. I don't find any tutorial or example with an equivalent of that in Swift 3, could somebody tell me what option should now replace such .allZeros option?

A: I believe .allZeros was to be used when no other options applied.
So with Swift 3, you can pass an empty list of options or leave out the options parameter since it defaults to no options:
do {
    let regex = try NSRegularExpression(pattern: pattern, options: [])
} catch {
}

or
do {
    let regex = try NSRegularExpression(pattern: pattern)
} catch {
}

Note that in Swift 3 you don't use the error parameter any more. It now throws.

A: You can use []:
let regex = try! NSRegularExpression(pattern: pattern, options: [])

which is also the default value, so you can omit this argument:
let regex = try! NSRegularExpression(pattern: pattern)

The easiest way to find this out is to command+click jump to the methods definition:
public init(pattern: String, options: NSRegularExpression.Options = []) throws


text: Q: Could the equivalence classes in the construction of quotient group be the orbits of some group action? Given a group $G$, $S\le G$, the $G/S$ is the collection of all left cosets, $gS$ for all $g\in G$.  And These cosets partition $G$. Given that the orbits of any group action on $G$ also partition $G$, could there be a group action on $G$ the collection of the orbits is identical to the collection of the left cosets of $S$?


text:
Q: Rails: how to save statistics based on some conditions I'm developing a Rails application and I need to save and show some statistics based on the following conditions:

*

*For the current month, display all entries in the database

*For the last 8 months, display a cumulative of each month

*For the rest, show a cumulative of all values

The thing is that I don't want to save all the data in my database and than apply the condition when showing. Is there a way of keeping my database structured in a way that it also covers the conditions (for example, when the current month changes, apply all the conditions and update the database)?


text:
Q: LASSO Regression with noise I know LASSO regression is useful to exclude redundant features, so can it be useful when you have noisy data?
I explain better with this example: Suppose I generated a data set using an equation (e.g y = x^2 + x + 3). So if I build a matrix containing different functions (x, x^2, x^3, sin(X), ...) and apply a regression to find their coefficients, I would hope to find those terms I used in the generation phase (only x, x^2 are non-zero).
Now, if I add noise to data before applying the regression, I will find new non-zero terms due to the noise (Least Square fit tries to minimize cost function using all predictors) but those terms weren't in my equation!
So my idea is to use LASSO Regression to reduce the number of terms and I should find only those who where in the equation. Does it sound logical?


text:
Q: html2canvas not working in FireFox and IE 11 for Google Material Charts I want to download the Google Material charts image. But the function getImageUri not supported in material charts right now. So i did some google search and found out html2canvas lib for doing this. the below mentioned code working fine in Chrome but not in FireFox and IE.
     html2canvas($(".Tab1"), {
            onrendered: function(canvas) {
                var myImage = canvas.toDataURL("image/png");
                window.open(myImage);
                }
});

The above picture taken from Firefox. In IE only empty browser showing..
Can anyone help me to resolve this issue.

A: The Below Fix Make it working in IE as well (Tested with IE 10)

This seems to be a parsing error, if I add the following lines at the beginning of the 'svg.parseXml' function my code now works.

// -- Internet Explorer trick, otherwise an error is generated in the 'parseFromString' function when
// -- You use declarations, this is the case for Raphael
xml = xml.replace(/xmlns=\"http:\/\/www.w3.org\/2000\/svg\"/, '');

Ref: https://github.com/gabelerner/canvg/issues/189

A: The below mentioned code working fine in firefox but not in IE
$('.pngexport').click(function () {
            canvg();
            //saves the d3.js as a png
            html2canvas($('.Tab1'), {
            useCORS: true,
                onrendered: function (canvas) {
                    var img = canvas.toDataURL("image/png");
                    //////////////////////////
                    var download = document.createElement('a');
                    download.href = img;
                    download.download = 'Vendor.png';
                    download.click();
                    function fireEvent(obj, evt) {
                        var fireOnThis = obj;
                        if (document.createEvent) {
                            var evObj = document.createEvent('MouseEvents');
                            evObj.initEvent(evt, true, false);
                            fireOnThis.dispatchEvent(evObj);
                        } else if (document.createEventObject) {
                            var evObj = document.createEventObject();
                            fireOnThis.fireEvent('on' + evt, evObj);
                        }
                    }
                    fireEvent(download, 'click');
                }
            });
        });

A: I have faced the similar issue with IE11 while capturing the highchart charts which generates the svg charts. We used the technique of converting all svg images to canvas. Place the newly created canvas at svg. Now capture the dom and print/download it. Once print/download is done remove the canvas from dom again. It was working on chrome, FF and IE. Google bar charts are rendered in the browser using SVG or VML. So this technique will also work with Google Charts.


text:
Q: Importing data from csv into R, column not populated I am new to R programming. I have imported a csv file using the following function
PivotTest <- read.csv(file.choose(), header=T)

The csv file has 7 columns: Meter_Serial_No, Reading_Date, Reading_Description, Reading_value, Entry_Processed, TS_Inserted, TS_LastUpdated.
When uploading, the Meter_Serial_No is filled with zero while there are data in that column in the csv file. When running a function to see what data are in that particular column (PivotTest$Meter_Serial_No), it's returning NULL. Can anyone assist me please.
Furthermore, the csv that I'm importing has more than 127,000 rows. When doing a test with 10 rows of data only, I don't have that problem where the column Meter_Serial_No is replaced with zero.

A: Depends on the class of values which are there in the column   (PivotTest$Meter_Serial_No). I believe there is a problem in type conversion, try the following.
PivotTest <- read.csv("test.csv", header=T,colClasses=c(PivotTest$Meter_Serial_No="character",rep("numeric",6)))


text:
Q: How Do I Clear The Credentials In AWS Configure? I have deleted the AWS credentials in sudo nano ~/.aws/config. But, the credentials are still in aws configure. Is there a way to reset aws configure with clear state?

A: Here is the graphical presentation for mac user

A: For windows users just open aws credentials file and update based on your requirements.
File is located in C:> Users > yourusername  >  .aws - credentials

A: just remove ~/.aws/credentials along with ~/.aws/config
EDIT: Note path references user home directory and specific to each user in system.

A: Do not delete the files if you have multiple profiles created as all will be lost if you delete these files!
unless thats what you want :)
Go to each of the file -
 - ~/.aws/credentials
 - ~/.aws/config

and remove just the part profiles you want to delete. Eg.
~/.aws/credentials
[default]
aws_access_key_id=yourAccessKeyId
aws_secret_access_key=yourSecretAccessKey

[user2]
aws_access_key_id=yourAccessKeyId
aws_secret_access_key=yourSecretAccessKey

and
~/.aws/config
[default]
region=us-west-2
output=json

[profile user2]
region=us-east-1
output=text

Just delete entries corresponding to user2 profile if thats what you want. And you should also give a profile name to profile you configure -
aws configure --profile user2

Else it will just be [default]
More details - http://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html

A: Not sure if this clears the credentials but I was able to simply change the credentials by running aws configure again and entering in new credentials. I was also able to make multiple profiles by running aws configure --newusername and I could run a future command with that user by appending --profile newusername. Good tutorial here: https://www.crybit.com/configure-iam-user-on-your-linux-machine/

A: Maybe just a Windows thing but if you edit the ~.\aws\config and ~.\aws\credentials files like is suggested by Aniket Thakur, you might run into an issue where aws configure complains about a profile you deleted not being available. This seems to be because the AWS_PROFILE environment variable is referencing that profile. Unset that variable and you should be back in business.
Tried to comment under his answer but I don't have enough points (on this account).


text:
Q: XAMPP takes a long time to load data This problem has been pulling my hair out in this week. This is really annoying me because I still cant find the solution. My problem: localhost takes a long time to load. Localhost takes up to 1400 seconds to load data. Maybe this information can help you to know about my problem:
I have view table. My view table query is like this
select DISTINCT `TahunAwal`,
   (SELECT COUNT(*) AS `< 2.50` from `akdhis_kelanjutanstudi`
        LEFT JOIN `akdmst_mahasiswamagister` on `akdhis_kelanjutanstudi`.`MahasiswaID` = `akdmst_mahasiswamagister`.`MahasiswaID`
        LEFT JOIN `akdhis_statusmahasiswa` on `akdhis_kelanjutanstudi`.`MahasiswaID` = `akdhis_statusmahasiswa`.`MahasiswaID`
        LEFT JOIN `akdref_tahunsemester` on `akdhis_statusmahasiswa`.`TahunSemesterID` = `akdref_tahunsemester`.`ID`
        LEFT JOIN `akdref_tahunakademik` on `akdref_tahunsemester`.`TahunAkademikID` = `akdref_tahunakademik`.`ID`
        WHERE `IPK` < 2.50 AND `SemesterMahasiswa` = 8 AND `mhsMagister`.`TahunAwal`=`akdref_tahunakademik`.`TahunAwal`) AS `< 2.50`,

    (SELECT COUNT(*) AS `2.50-2.74` from `akdhis_kelanjutanstudi`
        LEFT JOIN `akdmst_mahasiswamagister` on `akdhis_kelanjutanstudi`.`MahasiswaID` = `akdmst_mahasiswamagister`.`MahasiswaID`
        LEFT JOIN `akdhis_statusmahasiswa` on `akdhis_kelanjutanstudi`.`MahasiswaID` = `akdhis_statusmahasiswa`.`MahasiswaID`
        LEFT JOIN `akdref_tahunsemester` on `akdhis_statusmahasiswa`.`TahunSemesterID` = `akdref_tahunsemester`.`ID`
        LEFT JOIN `akdref_tahunakademik` on `akdref_tahunsemester`.`TahunAkademikID` = `akdref_tahunakademik`.`ID`
        WHERE 2.50 < `IPK` < 2.74 AND `SemesterMahasiswa` = 8 AND `mhsMagister`.`TahunAwal`=`akdref_tahunakademik`.`TahunAwal`) AS `2.50-2.74`
from `akdref_tahunakademik` AS `mhsMagister`
ORDER BY `mhsMagister`.`TahunAwal`

that's a part of my codes
and the result in phpmyadmin is like this
enter image description here
I think localhost takes a long time to load data because of the tables that consists of many data records, but I don't know how to solve that problem. I have tried to change
ServerName Localhost to ServerName 127.0.0.1:80.
I also have edited
my.ini.
I uncommented
bind-address="127.0.0.1"

I edited
config.inc.php
I change
$cfg['Servers'][$i]['host'] = 'localhost' to $cfg['Servers'][$i]['host'] = '127.0.0.1'

but localhost still too slow.
I use XAMPP in windows 7.
is there any way to fix that problem? Please help me to fix that problem. Thank you so much

A: Create a view out of your query and pull the records using the view that you made from it. See if it could make any changes as views seem to be a faster workaround for handling lots of data rather than running a select query for it every time.
Also, you might want to have your SELECT query restricted to just the columns that you need for the formula as it can also affect the loading speed of your query.


text:
Q: component won't receive updates from parent angularjs I'm trying to receive updates from the parent component (async update) however while the original $onInit receives data from the parent, any updates doesn't update the parent (comes back as undefined)
Any way to receive updates?
Child component:
import template from 'html-loader!./child.html'

export const childComponent = {
    template: template,
    require: {
        parentComponent: '^parentComponent'
    },
    controllerAs: 'vm',
    controller: class {

        constructor($scope) {
            this.option = null
            this.items = []
            this.$scope = $scope
        }

        static get $inject() {
            return ['$scope']
        }

        $onInit() {
            this.items = this.parentComponent.items
            // this.items doesn't get updated when this.parentComponent updates
        }
    }
}

UPDATE:

        <parent-component items="vm.fruit">
            <div ng-if="vm.fruit.length < 1">Loading...

            <child-component></child-component>
        </parent-component>

A: Take a look at this demo
The reason, $onInit() was not getting called because, you need you need to add 2 things:
Add transclude: true in parentComponent declaration
and then add ng-transclude in html as below:
<parent-component ng-transclude>

  <child-component></child-component>

</parent-component>


text:
Q: Vector Iterators Incompatible when in class I've got a pretty simple class with a vector as a private variable like so:
#include "Zombie.h"
#include <vector>

class CGame{
public:
CGame();
void DoVectorStuff();
private:
std::vector<Zombie> zombies;
};

In the function DoVectorStuff() im just looping through the vector like so:
for(std::vector<Zombie>::iterator it = zombies.begin(); it != zombies.end(); ++it)
{
   it->Update(delta);
}

Which is causing Visual Studio 2010 to give me a debug assertion when I run it. The same code worked fine when it was in a function by itself, I assume its something to do with me adding it to a class but I can't figure out what.
EDIT: http://i.imgur.com/xl6Z6.png This is the error I'm getting.

A: The assertion you are getting vector iterators imcompatible indicates that you are trying to compare iterators from different vectors.
Typically you can get these by
POSSIBILITY 1
std::vector<int> foo( 100 );
std::vector<int> bar( 100 );

for( std::vector<int>::iterator iter = foo.begin();
    iter != bar.end();
    ++iter )
{
    std::cout << *iter;
}

Notice the above code and you will notice that I am comparing iter that is a iterator from foo vector to bar.end()
POSSIBILITY 2
Another way you can get the same error is by hanging on to invalid iterators.
std::vector<int> foo( 3 );
std::vector<int>::iterator enditer = foo.end();

foo.push_back( 3 );
foo.push_back( 3 );
foo.push_back( 3 );  // can invalidate endIter above

for( std::vector<int>::iterator iter = foo.begin();
    iter != enditer;
    ++iter )
{
    std::cout << *iter;
}

Notice how in the above code I have hanged on to endIter which can be invalidated by adding more elements to foo

A: Wild Guess: Zombie::Update updates, among other things, the zombies vector, invalidating the iterator it. Do zombies die or reproduce during their Update cycle?

A: Try to use
std::vector<Zombie>::iterator

instead of
std::vector::iterator


text:
Q: Core data parent child relationship I have a basic question regarding Core Data.
I have 2 tables one to many.
I have setup the app to add children to the parent, but I cannot understand how I set the relationship so that when I add a new child via a view controller that It adds the child to the correct parent.
I have generated the entity subclasses and have managed to get the app to add a child (but it adds it to index 0), but I cant seem to work a fetchrequest that finds the correct parent.
 - (IBAction)save:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];

 Child *newChild = [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:context];
    [newChild setValue:self.childName.text forKey:@"childName"];
    [newChild setValue:self.born.text forKey:@"born"];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ParentList" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

    ParentList *parent = [fetchedObjects objectAtIndex:0]; //this adds it to the first parentList in list at index 0 not to the correct parent
    NSLog(@"parent: %@ created", league);
    [parent addChildObject: newChild];

        //
        ///////////////////////////////////////////
        //////index path is wrong//////////////////
        ///////////////////////////////////////////

}

NSError *error = nil;
    // Save the object to persistent store
if (![context save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}

[self dismissViewControllerAnimated:YES completion:nil];

}

A: You need to pass the parent's objectID to the second view controller (if I understood your setup correctly).
Fetch the parent (using existingObjectWithID:error: of the NSManagedObjectContext) in the other view context.
Set the child parent as the fetched object.
should look something like:
NSError* error = nil;
NSManagedObjectID* parentID = //the parent object id you selected
Parent* parent = [context existingObjectWithID:parentID error:&error];
if (parent) { //parent exists
    Child *newChild = [NSEntityDescription insertNewObjectForEntityForName:@"Child"
                                                    inManagedObjectContext:context];
    [newChild setValue:self.childName.text forKey:@"childName"];
    [newChild setValue:self.born.text forKey:@"born"];
    [newChild setValue:parent forKey:@"parent"];//Set the parent
} else {
    NSLog(@"ERROR:: error fetching parent: %@",error);
}

Edit:
To get the selected object id (assuming you are using a NSFetchedReaultsController):
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
    //Use object.objectID as the selected object id to pass to the other view controller
    //what ever you need to do with the object
}


text:
Q: Pad a file using awk So I have this working on a server with awk 3.1.7 and when I try using on a server with awk 4.0.2 it does not seem to work. I am just trying to add a filename 14 digits, is the goal. I don't have the perl version on rename just in case it is brought up.
Anyhow this is my code
ls 800001.1.pull | awk -F'.pull' '{ printf "%s %014s.pull%s\n", $0, $1, $2; }' | xargs -n 2 mv

I get this error mv: '800001.1.pull' and '800001.1.pull' are the same file
ls 800001.1.pull | awk -F'.pull' '{ printf "%s %014s.pull%s\n", $0, $1, $2; }' | xargs -n 2 mv
mv: '800001.1.pull' and '800001.1.pull' are the same file

This same things that has been running on the other server for a few years and I don't get an error, I get a file named:
ls 800001.1.pull | awk -F'.pull' '{ printf "%s %014s.pull%s\n", $0, $1, $2; }' | xargs -n 2 mv
000000800001.1.pull

and this is why I said this:
I will take it that the newer awk handles delimiters different?
The expected output is 000000800001.1.pull
The original file needs to be 0 padded to 14.
Thanks!

A: $ echo 800001.1.pull | awk -F'.pull' '{ new=sprintf("%14s%s",$1,FS); gsub(/ /,0,new); print $0, new }'
800001.1.pull 000000800001.1.pull

$ echo 800001.12.345.pull | awk -F'.pull' '{ new=sprintf("%14s%s",$1,FS); gsub(/ /,0,new); print $0, new }'
800001.12.345.pull 0800001.12.345.pull


text:
Q: How to shred XML with TSQL XQUERY I'm struggling to shred the following XML. I'm using Azure SQL database.
Here's my sample data and code attempt.
DROP TABLE IF EXISTS #t ;
CREATE TABLE #t (XMLResult XML) ;
INSERT INTO #t (XMLResult)
VALUES (    '<testsuites>
                  <testsuite id="1" name="Verify" tests="1" errors="0" failures="1" timestamp="2021-12-08" time="0.000" hostname="" package="tSQLt">
                    <properties />
                    <testcase classname="Verify" name="Verify [Feature].[measure] format" time="0.000">
                      <failure message="Format incorrectly set." type="Failure" />
                    </testcase>
                  </testsuite>
                </testsuites>
                ') ;

SELECT  T.* ,
        TS.H.value('name[1]', 'varchar(255)') AS [Test Method] ,
        TS.H.value('tests[1]', 'int') AS [Tests] ,
        TS.H.value('failures[1]', 'int') AS [Failures] ,
        TC.H.value('name[1]', 'VARCHAR(255)') AS [TestCase] ,
        TF.H.value('message[1]', 'VARCHAR(255)') AS [Failure Message]
FROM    #t  T
CROSS APPLY T.XMLResult.nodes('/testsuites/testsuite')          AS TS(H)
CROSS APPLY T.XMLResult.nodes('/testsuites/testsuite/testcase') AS TC(H)
CROSS APPLY T.XMLResult.nodes('/testsuites/testsuite/testcase/failure') AS TF(H)
 ;

Current output

Where am I going wrong?

A: As mentioned in the comments, you have XML attributes, not values, which you are trying to retrieve. So you need to reference them with @
You are also using .nodes wrong: you should refer each one to the previous one. As it is, you are just cross-joining all the node levels together.
SELECT  --T.* ,
        TS.H.value('@name', 'varchar(255)') AS [Test Method] ,
        TS.H.value('@tests', 'int') AS [Tests] ,
        TS.H.value('@failures', 'int') AS [Failures] ,
        TC.H.value('@name', 'VARCHAR(255)') AS [TestCase] ,
        TF.H.value('@message', 'VARCHAR(255)') AS [Failure Message]
FROM    #t  T
CROSS APPLY T.XMLResult.nodes('/testsuites/testsuite')          AS TS(H)
CROSS APPLY TS.H.nodes('testcase') AS TC(H)
CROSS APPLY TC.H.nodes('failure') AS TF(H)
 ;

Note that if you are referring directly to an attribute of the current node (rather than a child node), you do not need the [1] predicate
db<>fiddle


text:
Q: Define additional parameters to pass from View to Controller (using DropDownList) I have used scaffolding templates to create the necessary parts in the Controller and the accompanying Views for my Model class Question pictured here:
public class Question
    {
      [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int QuestionId { get; set; }

      [StringLength(250, ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "MaxCharsQuestionAchieved")]
      public string GeneralQuestion { get; set; }

      [StringLength(1000, ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "MaxCharsExplanationAchieved")]
      public string Explanation { get; set; }

      public bool IsTemplate { get; set; }

      public QuestionState QuestionState { get; set; }
      public DateTime DateSubmitted { get; set; }
      public DateTime? JudgementDate { get; set; }

      public virtual Regular Author { get; set; }

      public virtual List<Politician> AddressedPoliticians { get; set; }
      public virtual List<Topic> Topics { get; set; }

      public virtual Moderator LastEditor { get; set; }

      public virtual List<Attachment> Attachments { get; set; }
      public virtual List<Answer> Answers { get; set; }

      public virtual List<QuestionSubscription> QuestionSubscriptions { get; set; }

      public int FbShares { get; set; }
      public int FbLikes { get; set; }
      public int TwitterShares { get; set; }
      public int SiteVotes { get; set; }
}

I'd like to change the template for the Create View. As you can see Question has a list of AddressedPoliticians. I'd like to present the users with a dropdownlist of all the Politicians in my Database. The value has to be the id of the Politician, the display member should be their FirstName. The View has a model of type Question, of course. How can I construct the dropdownlist and give the selected value to my Create(Question question) ActionResult method, so I can get the Politician out of the database to add it to AddressedPOliticians in Question?
I tried fiddling with ViewBag, but can't seem to get it to work. Hope someone can give me some tips/ suggestions.
EDIT:
I should probably show what I already tried :)
ActionResult methods:
public ActionResult Create()
    {
      ViewBag.PolIds = new SelectList(context.Politicians.ToList(), "UserId", "FirstName");
      return View();
    }

    //
    // POST: /Question/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Question question)
    {
      if (ModelState.IsValid)
      {
        var polId = ((SelectList)ViewBag.PolIds).SelectedValue;
        Politician pol = context.Politicians.Single(p => p.UserId == (int)polId);
        question.AddressedPoliticians.Add(pol);
        question.DateSubmitted = DateTime.Now;
        manager.CreateQuestion(question);
        return RedirectToAction("Index");
      }

      return View(question);
    }

Create.cshtml:
@model PoliticiOnline.DTO.Question

@{
    ViewBag.Title = "Stel een vraag!";
}

Stel een vraag!

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Vraag</legend>

                @Html.LabelFor(model => model.GeneralQuestion, "Algemene Vraag")

                @Html.EditorFor(model => model.GeneralQuestion)
                @Html.ValidationMessageFor(model => model.GeneralQuestion)

            @Html.Label("Politicus")
            @Html.DropDownList("PolIds", "Kies een politicus...")

            @Html.LabelFor(model => model.Explanation, "Extra Uitleg")

            @Html.TextAreaFor(model => model.Explanation)
            @Html.ValidationMessageFor(model => model.Explanation)

            <input type="submit" value="Indienen!" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

A: For a Dropdown: Create the values to select from as a List and a property to store the selected value in (probably an int). Then use:
@Html.DropDownListFor(m => m.SelectedValue, Model.SelectListItems)

For a list of checkboxes, you should add a List or similar, containing the selected Politicians ID's. Then add a list of checkboxes with name='name of List', value='id of politictian' and of course the name as the text of the associated label.
An example from one of my own views:

@foreach (var gender in Model.FilterData.Genders)
{

    <input id="gender@(gender.Id)" type="checkbox" name="Filters.Genders" value="@gender.Id" @(Model.Filters.Genders.Contains(gender.Id) ? "checked" : "") />
    @gender.Name

}

Now, I have a list of genders to select from in my Model.FilterData object, having an Id and a Name each. I also have an object "Filters" in my Model, with a List Genders.
So as you can see each checkbox has the name "Filters.Genders", i.e. pointing to this list.
If you want to be able to select only one, just create a single int property in your model and bind a range of radiobuttons to the same int property. Again an example:

  @foreach (var function in Model.FilterData.Functions)
  {

      @Html.RadioButtonFor(m => m.Filters.FunctionId, function.Id)
      @Html.LabelFor(m => m.Filters.FunctionId, function.Name)

  }

This is easier as you can use the Helper functions. As you can see, each radiobutton points to the same model property (Filters.FunctionId) - so the rendered inputs all have this as their name.
If used in a GET method, you'll see that it repeats the same property multiple times (i.e. Filters.Genders=2&Filters.Genders=4&Filters.Genders=5) which will be parsed into the List in your action.

A: Add a field in your Question model:
[NotMapped]
public decimal PoliticianId { get; set; }

In your view :

            @Html.Label("Politicus")
@Html.DropDownListFor(model => model.PoliticianId, (SelectList)ViewBag.PolIds)

And in your action:
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Question question)
    {
      if (ModelState.IsValid)
      {
         var selectedPolitician = question.PoliticianId; // The selected politician id
      }
    }

EDIT:
Or like mjepson mentioned in his comment, you can do it without adding a field to your Question model like :
In your view :

            @Html.Label("Politicus")
@Html.DropDownList("PoliticianId", (SelectList)ViewBag.PolIds)

And in your action:
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Question question, int PoliticianId) // PoliticianId will now have the selected value of the dropdown
    {
      if (ModelState.IsValid)
      {
         // do your stuff
      }
    }


text:
Q: how to call startActivityForResult from back button android? How to  call startActivityForResult() method in back button,
and please give me sample on how to result will back to calling activity?
If not possible is there any way to like this?
Regards,
Rajendar

A: You can override the back keys function but just don't do it.
You will deliver a very user unfriendly experience to your users since normally any Android user expects the back key to do one thing and that would be to get him back in the Activity stack. Now when you start an Activity from that key and the user presses it then he will not get the expected behavior which is a very bad idea.
However thats how you would override the KEYCODE_BACK event.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode==KeyEvent.KEYCODE_BACK) {
        // do something here
    }

    return(super.onKeyDown(keyCode, event));
}

Implement that method inside your Activity.


text:
Q: Time travel novel or series involving a professor at the Citadel who identifies the point of deviation There were two apparent timelines -  the 1st was thought to be unchangeable until the plot happened; a key person in identifying the point of deviation between the two timelines was a professor at the Citadel military college in South Carolina, in the present day, who retained his memories from the previous timeline and who becomes interested in his student (a pilot hero, who I think became a cyborg, but do not take my word for it).
The professor was like a second generation German immigrant - this became important to the resolution of the POD.

A: Possibly The Gordian Protocol by David Weber.
I never actually finished this book (I read just over half of it a few years ago) but some of your elements seem to match my memories of it. It follows Doctor Benjamin Schröder, Chairman of the Castle Rock University history department, who teams up with Commander Abramowski, a highly decorated Navy fighter pilot, after he has what he initially believes to be a psychotic break, where he's flooded with memories of our timeline, where the Holocaust happened.


text:
Q: JSON request 400 response: "The request sent by the client was syntactically incorrect" We have such object:
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@Document(collection = Order.COLLECTION_NAME)
public class Order implements Serializable {
public static final String COLLECTION_NAME = "orders";

@Id
private Long id;
private Long orgId;
private Long userId;
private Date creationDate = new Date();
private Integer statusCode = Status.NEW.code();
private Integer typeCode;
private Integer paymentCode;
private Date date;
private String phoneNumber;
private List<UserAddressList> userAddressList;
private BigDecimal cash;
private Integer persons;
private String comments;
private List products;

@Indexed(unique = true)
private String token = UUID.randomUUID().toString();

private Boolean deleted = Boolean.FALSE;

In this object we have two Lists which contains 2 another objects:
private List userAddressList;
private List products;

public class UserAddressList implements Serializable {

private String street;
private String house;
private String building;
private Long flat;
private Long entrance;
private Long floor;
private String intercom;

public class ProductPack implements Serializable {
private Long productId;
private Integer quantity;

public ProductPack() {
}

public ProductPack(Long productId, Integer quantity) {
    this.productId = productId;
    this.quantity = quantity;
}

We have such api method for adding new order:
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody ResponseDto addOrder(
     @RequestHeader(value = "Authorization") String authorization,
     @RequestBody final Order order) {

When we send this JSON to the server:
{"statusCode": 0,
 "typeCode": 1,
 "paymentCode": 4,
 "date": 2430919020590,
 "phoneNumber": "+79216450091",
 "userAddressList":
 [{
 "street": "Test",
 "house": "House",
 "building": "A",
 "entrance": 1,
 "floor": 8,
 "intercom": "intercom",
 "flat": 12
 }]
 ,
 "persons": 1,
 "products":
 [{
 "productId": 97,
 "quantity": 5
 }
 ]}

it returns "The request sent by the client was syntactically incorrect"
when we send this JSON:
{"statusCode": 0,
"typeCode": 1,
"paymentCode": 4,
"date": 2430919020590,
"phoneNumber": "+79216450091",
"persons": 1,
"products": [
{
"productId": 97,
"quantity": 5
}
]}

server accepts it but userAddressList is null
Can you please help to figure out the problem?

A: Check conformity between your fields in the JSON-request and in the code. It is possible that field you have declared is not that field that servers maps. For example UserAddressList could be address.


text:
Q: Approval process won't trigger record-triggered flow I want to follow up on my previous question. Because of some version issues with process builder, we wanted to move some apex action invocation to record-triggered flow with scheduled path. The condition to trigger this flow is Status = waiting for approval. Then we have an approval process which in its initial submission action have field update wf which sets Status = waiting for approval and the re-evaluation is set to true, but the flow is not triggered.
Is this some feature or bug?

A: This has been fixed as of Spring '22


text:
Q: PHPEXCEL export excel in kohana shows machine code how can i clear? I have tried this code as like
require_once dirname(__FILE__) . '/../../vendor/PHPExcel/Classes/PHPExcel.php';

    $objPHPExcel = new PHPExcel();
    $objPHPExcel->setActiveSheetIndex()->setCellValue('A1', 'Hello world!');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

    $this->response->body( $objWriter->save('php://output'));
    $this->response->send_file(TRUE, '01simple.xls');
    exit;

and error getting like as following image

A: Could you please try this...
require_once dirname(__FILE__) . '/../../vendor/PHPExcel/Classes/PHPExcel.php';
$phpExcel = new PHPExcel();
$phpExcel->getActiveSheet()->setTitle("Title of my excel");
$phpExcel->setActiveSheetIndex(0);
$phpExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$filename = "file_name";
ob_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
ob_end_clean();
$objWriter->save('php://output');

A: Use this method its working for me. Set your content in one variable and assign. here I have mentioned example
            require_once APPPATH.'libraries/reader/PHPExcel.php';
            $objPHPExcel = new PHPExcel();
            $reportHtml = '

                  Customer Name
                  Email
                  Mobile
                  Invoice Id
                  Invoice Date
                  Due Date
                  Balance Amount
                  Total Amount

';
            // Put the html into a temporary file
            $tmpfile = time().'.html';
            file_put_contents($tmpfile, $reportHtml);
            // Read the contents of the file into PHPExcel Reader class
            $reader = new PHPExcel_Reader_HTML;
            $content = $reader->load($tmpfile);
            // Pass to writer and output as needed
            header("Cache-Control: private", false);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename=test_1'.time().'.xlsx');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
            $objWriter->save('php://output');
            unlink($tmpfile);


text:
Q: How do I recursively iterate over an object that has unknown hierarchies with Angular JS? So take this example:
http://jsfiddle.net/7U5Pt/
Here I've got an object that describes a (very basic) menu. Each item can have multiple children with potentially unlimited levels of hierarchy.
The ng-repeat directives I'm using to turn it into

 elements work fine for the first two levels, but not for the third or any subsequent level of the hierarchy.
What's the best way to recursively iterate over this object, dealing with unlimited levels of children?
Any help much appreciated!
Here's the code incase the fiddle goes away:
HTML:

NAME: {{ item.name }}

SUB NAME: {{ item.name }}

JS:
var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', function ($scope) {
  $scope.mytree = {
  "items": [{
    "name": "one",
    "children": {
      "items": [
        {
          "name": "one sub a",
          "children": {
            "items": [{
              "name": "one sub level two a"
            },
            {
              "name": "one sub level two b"
            }]
          }
        },
        {
          "name": "one sub b"
        }
      ]
    }
  },
  {
    "name": "two"
  },
  {
    "name": "three"
  },
  {
    "name": "four",
    "children": {
      "items": [{
        "name": "four sub a"
      },
      {
        "name": "four sub b"
      }]
    }
  },
  {
    "name": "five"
  }]
};
});

A: So it turns out that the best way to do this, for anyone interested, is with the angular-recursion helper here:
https://github.com/marklagendijk/angular-recursion
This allows you to call the ng-repeat function recursively. So in your view, something like:
<tree family="mytree"></tree>

and then define a directive for  that calls itself like so:
.directive('tree', function(RecursionHelper) {
  return {
    restrict: "E",
    scope: {family: '='},
    template:
      '{{ family.name }}'+
      '
' +
      '
' +
      '<tree family="child"></tree>' +
      '
' +
      '
',
    compile: function(element) {
      return RecursionHelper.compile(element);
   }
 };
});

Apparently the recursion helper is necessary to stop some sort of infinite loop thing, as discussed here. Thanks to @arturgrzesiak for the link!


text:
Q: How to find the length of each element stored in an array separated by comma and to check the first digit of it How to find the length of each element stored in an array separated by comma and to check the first digit of it...Here is the code:
Sub validation()

    Dim acc_validation As String
    Dim acc_no As Variant, i As Integer
    Dim flag1

    flag1 = False

    acc_validation = Range("I7").Value

    acc_no = Split(acc_validation, ",")

    For i = 0 To UBound(acc_no)
        If (Len(acc_no(i) <> 16)) Then
            If (flag1 = False) Then
                MsgBox "Please enter the correct account number"
                flag1 = True
            End If
        End If
    Next i

End Sub

A: To get the length and the first digit of your element you try this:
For i = 0 To UBound(acc_no)
    MsgBox "Length: " & Len(acc_no(i)) & " First digit: " & Left(acc_no(i), 1)
    If (Len(acc_no(i) <> 16)) Then
        If (flag1 = False) Then
            MsgBox "Please enter the correct account number"
            flag1 = True
        End If
    End If
Next i

Hope this helps!


text:
Q: Updating a table from another table in SQL Server 2008 I have a temp table variable with a bunch of columns:
 Declare @GearTemp table
    (
        ItemNumber varchar(20),
        VendorNumber varchar(6),
        ItemStatus varchar(20),
        Style varchar(20),
        ItemName varchar(100),
        ItemDescription varchar(1000),
        Color varchar(50),
        [Size] varchar(50),
        ItemCost decimal(9,4),
        IsQuickShipFl bit,
        IsEmbroiderable bit,
        IsBackOrderable bit,
        LoadDate smalldatetime
    )

It gets filled with data from another table via an insert statement, and I want to take that data and update my Products table.  If possible, I would like to do something like this:
Update Products blah blah blah  all columns where itemnumbers match up
SELECT * FROM @GearTemp FT
WHERE EXISTS (SELECT P.ItemNumber FROM Products P WHERE FT.ItemNumber = P.ItemNumber)

Is that possible to do? If it's not, please point me in the right direction.

A: If I understand you correctly, you can use something like this:
UPDATE p SET X = gt.X, Y = gt.Y -- etc... (not sure whether your column names match up)
FROM Products p
    INNER JOIN @GearTemp gt ON p.ItemNumber = gt.ItemNumber

Note that this will only work if, as you stated in the comments above, there is only ever one entry in @GearTemp for each ItemNumber.

A: Since you are working on SQL Server 2008 you can use the MERGE statement:
-- Target Table

DECLARE @tgt TABLE (OrdID INT, ItemID INT, Qty INT, Price MONEY);
INSERT INTO @tgt (OrdID, ItemID, Qty, Price)
    SELECT 1, 100, 10, 10.00 UNION ALL
    SELECT 1, 101, 10, 12.00

OrdID       ItemID      Qty         Price
----------- ----------- ----------- ---------------------
1           100         10          10.00
1           101         10          12.00

-- Source Table
DECLARE @src TABLE (OrdID INT, ItemID INT, Qty INT, Price MONEY);
INSERT INTO @src (OrdID, ItemID, Qty, Price)
    SELECT 1, 100, 12, 10.00 UNION ALL
    SELECT 1, 102, 10, 12.00 UNION ALL
    SELECT 1, 103, 5, 7.00

OrdID       ItemID      Qty         Price
----------- ----------- ----------- ---------------------
1           100         12          13.00
1           102         10          12.00
1           103         5           7.00

MERGE @tgt AS t
USING @src AS s
ON t.OrdID = s.OrdID AND t.ItemID = s.ItemID
WHEN MATCHED THEN
  UPDATE SET
    t.Qty = s.Qty,
    t.Price = s.Price;

Content of the target table after the MERGE operation:
OrdID       ItemID      Qty         Price
----------- ----------- ----------- ---------------------
1           100         12          13.00


text:
Q: Is this function uniformly convex? I am using the following definition of uniformly convex:

A continuous functional $G:Y \to R$ is uniformly convex on a ball $$B(0,\delta):=\{y\in Y : \|y\| < \delta\}$$ if there exists a continuous functional $\phi_\delta : Y \to R_{+}$ such that $\phi_\delta(y) = 0$ iff $y$ is zero element of $Y$ and
$$ G\left(\frac{y_1+y_2}{2}\right) + \phi_\delta(y_2-y_1) \leq \frac{1}{2} (G(y_1) + G(y_2)) \quad \forall y_1,y_2 \in B(0,\delta).$$

I want to know in which region the following functional is uniformly convex with respect to $u$
$$G(x,u(x)) = \frac{1}{2}\int | -I_L(x) + I_R(x) + \gamma (x,u(x)) u(x)|^2 dx $$
where $\gamma(x,u(x))$ is the average integral between [0,1] of
$$\partial_x I_R(x+s u(x)) ds$$
I defined the sets
$$S^+ = \{ x\in \Omega : \gamma(x,u(x)) \geq \alpha \text{ and } I_R(x) > I_L (x)$$
$$S^- = \{ x\in \Omega : \gamma(x,u(x)) \geq -\alpha \text{ and } I_L(x) > I_R (x).$$
With the definition of these two sets I can ensure that in $S = S^+ \cup S^-$ I have the following lower bound for $G$:
$$\int |-I_L + I_R + \alpha u|^2 \leq G[u]$$
Since I found a quadratic lower bound and there is therefore a quadratic gap between this lower bound and my functional $G[u]$ I should be able to prove that $G$ is uniformly convex but I cannot manage. Any answer would be helpful.
Thanks in advance.


text:
Q: Check links against the Web of Trust database Background:
In another of my questions, Ether brought up the idea to check links in an answer against the WOT database. Web of Trust is a community driven project, with the goal to make browsing safer by utilizing a simple reputation and comment system. It has an API-Interface which can be used for requests.
Goals:
Check links for a bad or low reputation when writing or sending an answer/question. This would increase the safety for unexperienced users and also the reliability of external sources.
Upsides:
The clear benefit is that no harmful link could slip-in (intended or unintended), and unexperienced users are...ahm...safer. Another upside is that most spammers would be caught, because those sites already have a low reputation, though, it wouldn't stop them from posting I guess, but at least slow them down or make them stick out immediately.
Downsides:
You'd need an off-site check against a third-party database, which needs some bandwidth and time...and of course time to implement and some maintenance. May sound like nothing big, but I understand that this can be a real deal-breaker.
Possible Usages:
If somebody posts possible malicious links, they could get warned about it but still decide to post it anyway (after all, the WOT database could be wrong, but I've only seen this in one case by now and that was a flamewar which sorted itself out). In that case, an automatic flag for moderator attention and review could be issued.

A: I can't see this being added to the StackExchange engine.
But the idea is nice... how about writing a GreaseMonkey script that scans the pages for links in posts and checks them. Then it would highlight the "problem" ones in red or something.

A: WOT is a scam. In fact, even Googlebot knows it! Search mywot and Google will suggest "mywot scam" as the top related search.
So absolutely no support here. I am aware this is an old post, but it just showed up as a related question to the one I'm about to post.


text:
Q: undefined reference to `printk' I want to use printk function in my userspace code, but I don't want to write kernel module. Is it any possibility to do that?
I tried use linux/kernel.h header and linux/module.h but it doesn't work
printk("<1>some text");

A: Simple Answer is No,
You can't use printk in userspace code by any means.
printk is designed for kernel programmers.
If your intention is to write to syslog -> dmesg, then use syslog() ;
It comes in handy!!
Syslog ManPage
Try This:
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>

int main(void) {

 openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
 syslog(LOG_EMERG, "Hello from my code ");
 closelog();

 return 0;
}

To Configure syslog for file redirection:
http://www.softpanorama.org/Logs/syslog.shtml
http://linux.die.net/man/5/syslog.conf

A: Using of kernel headers in userspace makes behavior or program unpredictable.
One of reasons is the memory where kernel is located is not accessible from userspace directly.
Here you can find some information about these cases:

*

*lwn.net/Articles/113349/

*kernelnewbies.org/KernelHeaders


text:
Q: Comparing value from RFID reader to string I'm trying a very simple thing - grabbing a value from an RFID reader, comparing it to a value and having it do one thing if it's the value and something else if it's not.
Here's my code:
"""
Continuously read.
"""

import serial
ser = serial.Serial('/dev/tty.usbserial-AH02MAUE', 9600) # here you have to write your port. If you dont know how to find it just write ls -l /dev/tty.* in your terminal (i'm using mac)

def rfidResponse(responseID):
    print responseID
    if responseID == "750047FB76BF":
        print "This one"
    else:
        print "other one"

while True:
    try:
        response = ser.readline()
        # print response
        stringResponse = str(response)
        print stringResponse
        rfidResponse(stringResponse)
    except KeyboardInterrupt:
        break

ser.close()

But no matter what card I put to the RFID reader it always does the else - here's an example of my output (with the correct card placed over the reader):
7100253299FF

7100253299FF

other one

750047FB76BF

750047FB76BF

other one


text:
Q: Inflate 2.xml files with TextViews to show correctly in Recyclerview My goal is to show url links (normal and mirror links) in TextViews which are part of two different .xml files which are being inflated and then shown below each other in a RecyclerView.
The two .xml files are identical, except for the TextView IDs (text and mir), below 1 example:
mirror_text_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:clickable="true">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/mir"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:maxLines="1"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:text=""
            android:textColor="?attr/colorPrimary"
            android:textSize="16dp" />

    </RelativeLayout>

</RelativeLayout>

Below code of the DownloadAdapter works so far but the mirror links are always shown in the TextView (id: text) part of the .xml (download_text_item), they should show in the tv (id: mir) part of mirror_text_item.xml which is located below the download_text_item.xml.
DownloadAdapter:
public class DownloadAdapter extends RecyclerView.Adapter<DownloadAdapter.ViewHolder> {

    String[] items;
    Fragment fragment;

    public DownloadAdapter(Fragment fragment, String[] items) {
        this.fragment = fragment;
        this.items = items;
    }

    class MirrorViewHolder extends ViewHolder {
        private TextView textView;
        private View itemView;

        public MirrorViewHolder(View itemView) {
            super(itemView);

            textView = (TextView) itemView.findViewById(R.id.mir);
            this.itemView = itemView;
        }
    }

    class DownloadViewHolder extends ViewHolder {
        private TextView textView;
        private View itemView;

        public DownloadViewHolder(View itemView) {
            super(itemView);

            textView = (TextView) itemView.findViewById(R.id.text);
            this.itemView = itemView;
        }
    }

    @Override
    public DownloadAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View a, v = null;

        if (Utils.downloadVis == 0) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.download_text_item, parent, false);
            return new DownloadViewHolder(v);
        }
        else {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mirror_text_item, parent, false);
            return new MirrorViewHolder(v);
        }
    }

    public String getSelection(int position) {
        return items[position];
    }

    @Override
    public int getItemViewType(int position) {
        return 1;
    }

    @Override
    public void onBindViewHolder(DownloadAdapter.ViewHolder viewholder, final int position) {
        final String item = Utils.unescapeJavaString(Html.fromHtml(getSelection(position)).toString());

        if(viewholder instanceof DownloadViewHolder){
            DownloadViewHolder holder = (DownloadViewHolder) viewholder;
            holder.textView.setText(item);

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Utils.openUri(fragment, item);
                }
            });
        } else {
            MirrorViewHolder holder = (MirrorViewHolder) viewholder;
            holder.textView.setText("Just a test!");

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Utils.openUri(fragment, item);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return items.length;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView text, mir;
        private View itemView;

        public ViewHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.text);
            mir = (TextView) itemView.findViewById(R.id.mir);
            this.itemView = itemView;
        }
    }
}


text:
Q: MapKit not getting the right location when ipHone updated to ios 16.3.1 I am doing a restaurant autocomplete using mapkit, and this was working perfectly before I updated my iphone 14 to 16.3.1 (real device).
Before, it used to show my real location on the mapkit, not it shows me in the middle of new York, because that's the default location I set in case of an error.
The location is allowed on my app.
This is my viewdidLoad
locationManager.delegate = self

locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
locationManager.startUpdatingLocation()

mapView.showsUserLocation = true

let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable

let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Search for restaurants"
navigationItem.titleView = resultSearchController?.searchBar

resultSearchController?.hidesNavigationBarDuringPresentation = false
definesPresentationContext = true

locationSearchTable.mapView = mapView

locationSearchTable.handleMapSearchDelegate = self

When I print the location, it does show me coordinates in new york.
It also gives me this error:
"Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)""
This error used to occur when I didn't allow location services, but this time I did allow them but it still throws this error.

A: The answer was to change the default location from NY to none.


text:
Q: Notation for the coefficient of the $i$th term of formal power series. What notation is standard for the coefficient of $X^i$ in a formal power series $P$? I was thinking of $X^i \bullet P$, by analogy with the dot product.

A: One notation used is $[X^i]P$.  According to Knuth, arXiv:9402216v1, this was introduced by I. P. Goulden and D. M. Jackson in their book Combinatorial Enumeration (Wiley, 1983) on p. 1.


text:
Q: How to match a number and a string in another line with regex in python? I am a newbie in regular expressions. I have a text with a lot of lines like that:
first line
2
It is more
a lot of other lines

How can I match the second line and a part of the third line with regex?
I want to match "2 It is".
Any ideas?
I tried
re.compile(r'2&\n It is')

A: I think that (\d\nIt is) is the pattern that you need.
see https://regex101.com/r/NizJRT/1
When we run the following script
import re

myText = 'first line\n2\nIt is more\na lot of other lines'
found = re.search(r'(\d\nIt is)',myText)
for f in found.groups():
  print(f)

the output is
2
It is