text:
Q: Cómo acceder a un objeto creado durante la ejecución, dependiendo del Imput del usuario, en otra clase en C# Cómo se puede acceder a una instancia de una clase creada en otro archivo/clase. He visto algunas formas, pero estoy empezando a programar, y la mayoría no las entiendo. Luego, es un poco diferente, porque no es que en una clase haya hecho un Class class = new Class(); y ya está, es que he creado una función que crea instancias de una clase que depende de una variable:

Estas son las clases:
interface IObj
{
    string A();
}

public class ClassA : IObj
{
    string A()
    {
        return "Hola";
    }
}

public class ClassB : IObj
{
    string A()
    {
        return "Adiós";
    }
}

Y esta la función:
public static class ObjBuilder
{
    public static void DefineChamp(string args)
    {
        Assembly assembly = Assembly.Load("Project1");
        Type t = assembly.GetType($"Project1.{args}");
        IObj obj = (IChamp)Activator.CreateInstance(t);
    }
}

Esta función, de hecho, no la he creado yo, la he sacado de esta otra pregunta mía.

Ahora mi pregunta es, ¿Cómo hago para usar ese objeto? Sé que hay ya respuestas en internet, pero no he encontrado ninguna que yo entienda que se parezca a mi caso, en el que el objeto no se ha creado todavía.

A: Para este caso específico te recomiendo hacer lo siguiente:
public estática class ObjBuilder
{
   public estática IObj DefineChamp(string args)
   {
      Assembly assembly = Assembly.Load("Project1");
      Type t = assembly.GetType($"Project1.{args}");
      return (IChamp)Activator.CreateInstance(t);
   }
}

Construimos un método que devuelve un tipo IObj y dentro de este método creamos el objeto deseado y al final lo devolvemos con la instrucción return.
Para hacer uso de este método hacemos:
var miObjeto = ObjBuilder.DefineChamp("parametro");

Y lo usamos como queramos.
Te recomiendo que te estudies los patrones de diseño Inyección de Dependencias, y Factoria, te van a ayudar mucho.


text:
Q: How to decide Bounce Back EmailMessage on Office365? I'm using Exchange web service to read email from Office365. The C# program works fine. I can get EmailMessage in Inbox, and get their subject and message body, etc. However, I could not figure out the way to check whether the message is a bounce back message or not.
Do I have to parse the message body to see whether there are some special sentence, ie. Mail Delivery Failure? If so, is it possible different email servers bounce back emails with different words? i.e some use 'Mail Delivery Failure', some use 'Mail Delivery Not Succeeded'? (just an example, I do not know whether this is true)
Or, the message object has an attribute that can be used for this purpose?
Thanks
*** Just found that the exchange webservice can not see 'Bounce back' messages in INBOX. I'm using below code, all messages can be 'seen' except Bounce Back ones. Do I miss anything to filter te bounce back messages? They are actually in INBOX, unread, and I can see it from Office365 page.
private static void ProcessEmailMessages(SearchFolder searchFolder, Folder folderHistory, Folder folderBounceBack)
{
    if (searchFolder == null)
    {
        return;
    }

    const Int32 pageSize = 50;
    ItemView itemView = new ItemView(pageSize);

    PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
    itempropertyset.RequestedBodyType = BodyType.Text;
    itemView.PropertySet = itempropertyset;

    PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName);
    folderHistory.Load(propertySet);
    folderBounceBack.Load(propertySet);

    FindItemsResults<Item> findResults = null;
    do
    {
        findResults = searchFolder.FindItems(itemView);
        foreach (Item item in findResults.Items)
        {
            if (item is EmailMessage)
            {
                // load body text
                item.Load(itempropertyset);

                EmailMessage email = item as EmailMessage;
                //email.Move(folder.Id);

                // check email subject to find the bounced emails
                bool subjectContains = Regex.IsMatch(email.Subject, "Mail Delivery Failure", RegexOptions.IgnoreCase);
                bool bodyContains = Regex.IsMatch(email.Subject, "Delivery", RegexOptions.IgnoreCase);
                if (subjectContains || bodyContains)
                {
                    email.Move(folderBounceBack.Id);
                    Console.WriteLine("Move the Bounced email: {0}", email.Subject);

                    ShowMessageInfo(email);
                }
                else
                {
                    email.Move(folderHistory.Id);
                    Console.WriteLine(">>> Keep the email: {0}", email.Subject);
                }
            }
        }

        itemView.Offset += pageSize;
    } while (findResults.MoreAvailable);
}

A: Check the ItemClass attribute. Messages like that should have a class that contains "REPORT" in it.

A: I use EWS in an O365 environment to help process bounce backs and use the following code to just get the NDRs from a users' inbox.
var sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "REPORT.IPM.Note.NDR");
var SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, sf);
var view = new ItemView(1000) {PropertySet = new PropertySet(BasePropertySet.IdOnly)};
var findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

Hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: softlayer billing api to get a past invoice wondering is there a softlayer rest api that i can use to get an invoice for a particular month from the past.
For instance, i want to pull the invoice for the month of April 2016. i looked at Softlayer Billing Invoice service but in vain.
Also i do see a property called createDate on an invoice object but not sure if it can be of any help for the given scenario.

A: It would be possible using Object Filters, in this case it's necessary to use a filter between dates, try the below example for it:
https://$username:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Account/getInvoices?objectFilter={"invoices":{"createDate":{"operation":"betweenDate","options":[{"name":"startDate","value":["04/01/2016 00:00:00"]},{"name":"endDate","value":["04/30/2016 23:59:59"]}]}}}

Method: Get

It will display invoices between 04/01/2016 00:00:00 and 04/30/2016 23:59:59
References:

*

*SoftLayer_Account::getInvoices

Updated

How to get a single invoice for a specific month?
You need to get the information from invoice with "typeCode": "RECURRING", in this case, you can use the following request:
https://$username:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Account/getInvoices?objectFilter={"invoices":{"createDate":{"operation":"betweenDate","options":[{"name":"startDate","value":["06/01/2016 00:00:00"]},{"name":"endDate","value":["06/30/2016 23:59:59"]}]}, "typeCode":{"operation":"RECURRING"}}}

Method: Get


text:
Q: Convergence of $L^2$ functions with conditions on their Fourier transforms Let $\{f_n\}_{n\in\mathbb{N}}$ be a Cauchy sequence of $L^2(\mathbb{T})$ functions, where $\mathbb{T}=[-\pi,\pi)$. Assume that, $\forall n\in\mathbb{N}$ and for $k\geq 0$, the following inequality holds:
$$\sum_{m=-\infty}^{+\infty} (1+m^2)^k |\hat{f_n}(m)|^2 \lt +\infty$$
where $\hat{f_n}$ is the Fourier transform of $f_n$.
I have to show that this sequence converges to a function $f\in L^2(\mathbb{T})$ which satisfies the same inequality.
This question is related to another problem I posted here a few days ago (the link is below), but I couldn't find a solution.
As another user said, probably the best way to approach this problem is to notice that, if $||\cdot||_2$ is the usual norm in $L^2(\mathbb{T})$, the sequence converges to a function $f$ in $L^2(\mathbb{T})$ and then to show that
$$\sum_{m=-\infty}^{+\infty} (1+m^2)^k |\hat{f_n}(m)-\hat{f}(m)|^2 \rightarrow 0$$
as $n \rightarrow+\infty$, but I really don't know how to show it. Any ideas?
Previous question: Real positive index Sobolev spaces are Hilbert spaces

A: The statement is not true for $k\ge 1$. ($k=0$ case is trivial by Parseval's identity.) Note that any trigonometric polynomial $f$ satisfies the condition
$$
\sum_{j\in\mathbb{Z}} (1+|j|^2)^k |\widehat{f}(j)|^2 <\infty.\tag{*}
$$
Let $F(x) = \sum_{n=1}^\infty \frac{\sin nx}{n}=\frac{\pi-x}{2}$, $0<x<2\pi$ and $f_n$ be the Fourier series of $F$. Then each $f_n$ converges to $F$ in $L^2$-norm and satisfies $(*)$. However, since $|\widehat{F}(j)| \ge \frac{c}{|j|}, j\ne 0$ for some $c>0$, $(*)$ cannot hold for $F$ for all $k\ge 1$. This can be a counterexample : $f_n$ is Cauchy in $L^2$ and satisfies $(*)$ but the limit $F$ does not.
EDIT: Define a norm as$$
\|f\|_s^2 = \sum_{j\in\Bbb Z}(1+|j|^2)^{s}|\widehat{f}(j)|^2.
$$ Suppose $f_n$ is Cauchy in $\|\cdot\|_s$, i.e.
$$
\sum_{j\in\Bbb Z}(1+|j|^2)^{s}|\widehat{f_n}(j)-\widehat{f_m}(j)|^2\to 0
$$ as $n,m\to\infty$. Then for each fixed $j$, $\widehat{f_n}(j)$ is a Cauchy sequence in $\Bbb C$ and $\lim_n \widehat{f_n}(j) =: s_j$ exists. Since $\|f_n-f_m\|^2_{L^2(\Bbb T)}\le \|f_n-f_m\|^2_s$, there exists $f\in L^2(\Bbb T)$ such that $f_n\to f$ in $L^2(\Bbb T)$ and $\widehat{f}(j) = s_j$. Now, for a given $\epsilon>0$, we can find $N\in\Bbb N$ such that
$$
\sum_{j\in\Bbb Z}(1+|j|^2)^{s}|\widehat{f_n}(j)-\widehat{f_m}(j)|^2\le \epsilon^2
$$ for all $n,m\ge N$. Observe that for all finite $J\in\Bbb N$,
$$
\sum_{j=-J}^J(1+|j|^2)^{s}|\widehat{f_n}(j)-\widehat{f_m}(j)|^2\le \epsilon^2
$$ for all $n,m\ge N$. Take $m\to\infty$. Then
$$
\sum_{j=-J}^J(1+|j|^2)^{s}|\widehat{f_n}(j)-\widehat{f}(j)|^2\le \epsilon^2.
$$ Take $J\to\infty$. Then
$$
\sum_{j\in\Bbb Z}(1+|j|^2)^{s}|\widehat{f_n}(j)-\widehat{f}(j)|^2\le \epsilon^2
$$ for all $n\ge N$. This proves $$\lim_{n\to\infty}\|f_n -f\|_s^2 =0$$ and $$
\|f\|_s^2<\infty
$$as desired.


text:
Q: Text Fields in android-studio Can someone tell me how to use a Text Field with an onclick listener on a button in android studio and give me the xaml code too.

A: First you need write in xml file what you need, we need button and textview:
<Button
    android:id="@+id/button1"
    android:layout_width="70dp"
    android:layout_height="30dp"
    android:text="textEdit"
    android:layout_marginLeft="5dp"
    android:textColor="#fff"
    android:layout_marginRight="2dp"
    android:background="#333"
    android:onClick="ButtonOneClick"
    android:layout_marginBottom="4dp"
/>

<TextView
    android:id="@+id/txtView"
    android:layout_width="50dp"
    android:layout_height="30dp"
    android:hint="text view"
/>

After xml you need define this in class. Because we define android:onClick="ButtonOneClick" in xml,
we can just call it , and set what you want to do.
TextView tv;

tv =(TextView)findViewById(R.id.txtView);

public void ButtonOneClick(View view) {
    tv.setText("Test");
}

Other method is to declare button to, and set onClickListener.
Button butt;
butt= (Button) findViewById(R.id.button1);
butt.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    tv.setText("Test")
  }
});

A: in tampil.xml
 <Button
     android:id="@+id/button1"
     android:text="PENCET"
    android:onClick="onPencet" />

and in u're class, use public void nameonClick(view v){ statement }
public class Tampil {

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

}

public void onPencet(View v){
**U're statement }
}


text:
Q: How to label bars in barplots without a "y" variable in aesthetic mappings - ggplot2? I am finding it incredibly difficult to add labels to bar plots using ggplot2. I am working with the titanic dataset, and am having to create additional data frames just for the sake of adding labels - and this whole thing is arduous and driving me crazy.
This is what the basic code and chart looks like:
titanic %>% ggplot(aes(x=Sex, fill=Survived))+
  geom_bar() +
  scale_fill_discrete(name=NULL,labels=c("Dead", "Survived")) +
  labs(y="Number of Passengers", title="Titanic Survival Rates by Sex")

As you can see, there are no labels on the bars. Because there is no "y" variable in the aesthetic mappings, the geom_text(aes(label= xxx)) layer does not work. Also, without a "y" variable, geom_bar(stat="identity") doesn't work. This is what I did to get around the problem:
# Create a data frame from a two-way table including Survived and Sex

>table(titanic$Survived,titanic$Sex)
   female male
  0     81  468
  1    233  109

rates_by_sex<-data.frame(Sex=c("Female","Male"), Dead=c(81,468), Survived=c(233,109))

# Convert data frame to long format

>rates_by_sex_long <- melt(rates_by_sex, id="Sex")

    Sex     variable   value
1   Female  Dead       81
2   Male    Dead       468
3   Female  Survived   233
4   Male    Survived   109

ggplot2 can now make use of geom_text() and aes(label=value)
rates_by_sex_long %>% ggplot(aes(x=Sex, y=value, fill=variable)) +
  geom_bar(stat="identity") +
  geom_text(aes(label=value), position = position_stack(vjust=0.5),colour = "white", size = 5) +
  scale_fill_discrete(name=NULL) +
  labs(y="Number of Passengers",title="Titanic Survival Rates by Sex")

Now this gives me the following chart with labels:

Here is another one I did using the same arduous method just to show the percentages:
# Manually create a data frame with the rate of survival.

table(titanic$Survived) # Gives raw counts of each category
100*round(prop.table(table(titanic$Survived)),4) # Survival rate in percentages

titanic_survival_rate<-data.frame(Survived=c("Yes","No"),Number=c(342,549), Percent=c(38.38,61.62))

titanic_survival_rate %>% ggplot(aes(x=Survived, y=Number)) +
  geom_bar(stat="identity",fill="steelblue", colour = "black") +
  geom_text(aes(label=paste0(Percent,"%")),nudge_y=25,colour = "black", size = 4) +
  labs(y="Number of Passengers",title="Titanic Survival Rate")

Doing it this way is highly inefficient. There are so many charts to be made, and constructing data frames for each of them separately is going to be impractical and impossible. I don't even know what I will do when faceting.
Question: How can I get the labels (counts and percentages) for barplots with a categorical variable? I know it can be done with some additional coding (i.e., adding something to geom_text()) but I can't quite figure it out.
Please feel free to use this reproduceable code:
df<-data.frame(survived=c(1,1,0,0,0,1,0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0),sex=c("M","F","M","M","M","F","F","F","M","M","M","F","F","F","M","F","M","F","F","M","M","M","M","M","M","M","M"))

df$survived<-as.factor(df$survived)

df %>% ggplot(aes(x=sex, fill=survived))+geom_bar()+geom_text(aes(label=???))

A: You can prepare the data along with labels before plotting.
library(dplyr)
library(ggplot2)

df %>%
  count(sex, survived) %>%
  ggplot(aes(sex, n, fill = survived)) +
  geom_col() +
  geom_text(aes(label = n),
            position = position_stack(vjust=0.5),colour = "white", size = 5)


text:
Q: Oracle PL/SQL regex for sanitize input from textArea I have basic editor which allow the user to enter notes. I am using the https://quilljs.com/ API for the editor. The content of the editor will be saved in a database, but before that persisting the data, I want to sanitize the HTML content, to remove all possible JavaScript events in Oracle PL/SQL. I am not able to get a regular expression to sanitize the HTML content before saving.
Example:
This is www.test.com

ffffff

Review at www.1159PM.com

fffffff
'
Expected Result:
This is www.test.com

ffffff

Review at www.1159PM.com

fffffff
'
All Js events removed. Other scripts and styles should be removed as well. Please help me with the Oracle RegEx to solve this problem.

A: If your HTML is restricted to valid XHTML (i.e. it has a single root element and each of the opened tags is closed) then you can use:
INSERT INTO table_name (value) VALUES (
  XMLQuery(
    'copy $i := $p1
    modify (delete nodes ($i//@onclick, $i//@ondblclick, $i//@onmouseover, $i//@onkeypress))
    return $i'
    PASSING XMLTYPE('
This is www.test.com

ffffff

Review at www.1159PM.com

fffffff
')
      AS "p1"
    RETURNING CONTENT
  ).getClobVal()
)

Which, for the table:
CREATE TABLE table_name (value CLOB);

Then the inserted value is:

VALUE

This is www.test.com

ffffff

Review at www.1159PM.com

fffffff

db<>fiddle here


text:
Q: Npm install falied in github action I tried to create a github action that build my electron app with vue and vue-cli-plugin-electron-builder,but I can't install Dependencies by npm
my folder tree like this:
|   .gitignore
|   babel.config.js
|   LICENSE
|   package-lock.json
|   package.json
|   README.md
|   vue.config.js
|   yarn.lock
|
+---public
|       favicon.ico
|       index.html
|       test.jpg
|
\---src
    |   App.vue
    |   background.js
    |   main.js
    |   preload.js
    |
    +---assets
    |       ...
    |
    \---components
            ...

when I run the CI,I found a error that
  npm ci
  shell: C:\Program Files\PowerShell\7\pwsh.EXE -command ". '{0}'"
npm ERR! The `npm ci` command can only install with an existing package-lock.json or
npm ERR! npm-shrinkwrap.json with lockfileVersion >= 1. Run an install with npm@5 or
npm ERR! later to generate a package-lock.json file, then try again.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\npm\cache\_logs\2021-08-01T04_59_20_385Z-debug.log
Error: Process completed with exit code 1.

this is my blank.yml:
# This is a basic workflow to help you get started with Actions

name: CI

# Controls when the workflow will run
on:
  # Triggers the workflow on push or pull request events but only for the main branch
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    name: Build
    runs-on: windows-latest
    steps:
    - name: Install Node.js, NPM and Yarn
      uses: actions/setup-node@v1
      with:
          node-version: 16
    - name: Install Dependencies
      run: |
            npm ci
    - name: Electron Build
      run: |
            npm run electron:build --windows nsis --x64 --ia32

I tried search on bing with the key word "npm install failed in github action" but I found nothing helpful.
also,I tried using 'npm install' instead the 'npm ci', but it showed the same error message that it can't find the package.json
the 'npm install' 's error message like this:
Run npm install
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path D:\a\example\example/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'D:\a\example\example\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\npm\cache\_logs\2021-08-01T05_12_56_060Z-debug.log
Error: Process completed with exit code 1.

How can I solve it?
English is not my native language; please excuse typing errors.

A: You are not checking out your code and directly running NPM CI.
Below piece of code should do the job for you
name: CI
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    name: Build
    runs-on: windows-latest
    steps:
    - name: Checkout Code
      uses: actions/checkout@v2
    - name: Install Node.js, NPM and Yarn
      uses: actions/setup-node@v1
      with:
          node-version: 16
    - name: Install Dependencies
      run: |
            npm ci
    - name: Electron Build
      run: |
            npm run electron:build --windows nsis --x64 --ia32


text:
Q: Active users and views in azure workbooks Can someone briefly explain the differences between active users and page views in an azure workbook? I would like to get the stats of active users of a particular azure event, but the counts shown are not realistic for the provided scenario.

As per the attached image, there is only one active user, which has to be at least 3-4 and can go up to 15-16. The value displayed in Views is unrealistic though.
Your valuable inputs are highly appreciated. Thank you

A: if you edit the template/workbook and look at the queries you can see exactly what is going on there:
let start = startofday(ago({Metric}));
union customEvents, pageViews
| where timestamp >= start
| where name in ({Activities}) or '*' in ({Activities}) or ('%' in ({Activities}) and itemType == 'pageView') or ('#' in ({Activities}) and itemType == 'customEvent')
{OtherFilters}
| summarize Users = dcount(user_Id), Sessions = dcount(session_Id), Views = count()
| evaluate narrow()
| project Title = case(Column == 'Users', 'Active Users', Column == 'Sessions', 'Unique Sessions', 'Views'), Metric = Value, SubTitle = '━━'

views in this case, is a count of items in the tables; Views = count(),
Users is dcount(user_Id) and Sessions = dcount(session_Id)
seeing just 1 user/session implies that there's nothing automatically generating "distinct" ids for those values, so the user_Id, session_Id fields are completely empty across all rows (the one unique id being undefined in both columns)
how user and session id values get populated is very specific to what application insights sdks you are using, and how you've configured them.


text:
Q: Как реализовать постепенное растворение фона? Я сделал программу наподобие хаотичного движения газов, и мне нужно чтобы при запуске они растворялись (увеличивали свою прозрачность). У меня все вышло, только после их растворения они снова становятся непрозрачными и процесс повторяется. Попробовал ограничить условием в цикле перебора шариков(alpha[i]<=0) { break}, но выходит что при запуске все уже растворилось и анимации нету. Что не так?
package com.example.android19anim1;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.CountDownTimer;
import android.view.View;

public class MyDraw extends View {
    static int n = 15;
    static boolean started;
    int[] x = new int[n];
    int[] y = new int[n];
    int[] vx = new int[n];
    int[] vy = new int[n];
    int[] color1 = new int[n];
    int[] color2 = new int[n];
    int[] color3 = new int[n];
    static int[] alpha=new int [n];

    int random(int min, int max) {
        return (int) (min + Math.random() * (max + 1));
    }

    void fillArrayRandom(int[] a, int min, int max) {
        for (int i = 0; i < a.length; i++) {
            a[i] = random(min, max);
        }
    }

    void makeBalls() {
        fillArrayRandom(x, 0, this.getWidth());
        fillArrayRandom(y, 0, this.getHeight());
        fillArrayRandom(vx, -10, 50);
        fillArrayRandom(vy, -10, 50);
        fillArrayRandom(color1, 0, 255);
        fillArrayRandom(color2, 0, 255);
        fillArrayRandom(color3, 0, 255);
    }

    void moveBalls() {
        for (int i = 0; i < n; i++) {
            if ((x[i] < 0) || (x[i] > this.getWidth())) {
                vx[i] = -vx[i];
            }
            if ((y[i] < 0) || (y[i] > this.getHeight())) {
                vy[i] = -vy[i];
            }
            x[i] += vx[i];
            y[i] += vy[i];
            alpha[i]-=1;
            if(alpha[i]<=0) {
                break;
            }
            }
        }

    public MyDraw(Context context) {
        super(context);
        MyTimer timer = new MyTimer();
        timer.start();
    }

    protected void onDraw(Canvas canvas) {
        if (!started) {
            makeBalls();
            started = true;
        }
        Paint paint = new Paint();
        for (int i = 0; i < n; i++) {
            canvas.drawCircle(x[i], y[i], 20, paint);
            paint.setColor(Color.argb(alpha[i],color1[i], color2[i], color3[i]));
        }

    }

    void nextFrame() {
        moveBalls();
        invalidate();
    }

    // public static Scanner scan = new Scanner(System.in);
    //
    // public static void main(String[] args) {
    // System.out.println("Введите колличество шариков");
    // n = scan.nextInt();
    // }

    class MyTimer extends CountDownTimer {

        MyTimer() {
            super(1000000, 100);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            nextFrame();

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

        }

    }

}

A: Добавьте callback, который сделает view невидимым по окончанию анимации или вообще удалит view из viewGroup.
callback:
yourView.setAnimationListener(new AnimationListener()...


text:
Q: wget exclude list of filenames I need to fetch data from an ftp server with wget.  I need it to fetch all files from one directory except for a list of filenames.  So, for example:
fetchDir="ftp://user:pass@host/path/to/FileName*.csv.gz"
excludeList="FileName314.csv.gz, FileName271.csv.gz, FileName161.csv.gz"

wget ${fetchDir} --reject ${excludeList} -nc

This however gives me an error that looks like this:
...
Rejecting 'FileName000.csv.gz'.
Rejecting 'FileName001.csv.gz'.
No matches on pattern 'FileName*.csv.gz'.
--2015-12-08 14:27:28--  http://filename314.csv.gz/
Resolving filename314.csv.gz (filename314.csv.gz)... failed: Name or service not known.
wget: unable to resolve host address 'filename314.csv.gz'

How do I change my code such that it accepts my rejects?

A: The --reject option requires a comma-separated list. However, your excludeList variable includes spaces as well as commas. When interpreting a command, the shell carries out word splitting after the shell variables have been expanded.
This results in only the first filename pattern being treated as an argument for the --reject option; the remaining list members will be parsed as extra URLs. The variable assignment should be changed to:
excludeList="FileName314.csv.gz,FileName271.csv.gz,FileName161.csv.gz"

Note: the double quotes aren't actually required since there are no special characters in the string.


text:
Q: How to get slice of 3D data with affine transform in MayaVI I am visualizing scalar field which is defined on a regular but non-orthogonal and not aligned with 'x' 'y' 'z' coordinates grid. Volume visualization works perfectly by putting data to regular grid and applying affine transform like this
self.volume_data_plot =  self.scene.mlab.pipeline.volume(self.data_src3d)
aff_m = ...  # set affine matrix
m=tvtk.Matrix4x4()
m.from_array(aff_m)
# apply scaling matrix to volume data
self.volume_data_plot.actors[0].poke_matrix(m)
self.volume_data_plot.update_pipeline()

However, when I am trying to do 2D cut plane of the same data, I am lost. I've tried image_plane_widget and scalar_cut_plane with no success: they have no actor to apply affine transform to. Or, at least, I can not find how to get them. Mayavi help system is not helpful too: only trivial stuff is documented. Could anyone help?


text:
Q: RegExp para URL Buen día!
Tengo una expresión regular para obtener solo la parte que me interesa de una URL.
Tengo 2 tipos de URL
https://www.miurl.com.co/path/path/page/login?execution=s3p1
https://www.miurl.com.co/path/path/page/login
Por ahora, he logrado con esta regexp  ".*\/(.*\/.+)"
obtener: page/login?execution=s3p1
El tema es que necesito obtener solo esta parte : page/login. Una sola Regexp para ambos ejemplos. He probado alguna otra con la que obtengo lo que quiero, pero al probar con la URL sin "?execution=s3p1" no funciona al no encontrar ninguna interrogación.
Muchas gracias de antemano por toda la ayuda que puedan proporcionarme

A: Específicamente con regex:
Yo lo haría usando algo como:
/\/(\w+)\/(\w+)(\?{1}.*)?$/

Eso significa:
\/        un slash
(\w+)     un texto (grupo de captura)
\/        otro slash
(\w+)     otro texto (grupo de captura)
(\?{1}.*)? query string "?blabla" (grupo de captura,opcional)
$         fin de la cadena

El hecho de que haya un fin explícito de la cadena indica que no te va a tomar los conjuntos texto+slash+texto que hayan en medio, sino sólo los dos últimos.
Como la url puede tener query string o no tenerlo, todo el posible query string también es un grupo de captura. Esto significa:

*

*Sin query string, no existe el último grupo de captura, pero como está seguido de un ? el tercer elemento capturado está vacío.

*Con query string, tiene que ser de la forma ?xxxxxx.

Una estructura como esta te permitiría parsear una url que tenga (aunque no es válida) dos query string de la forma
 https://www.miurl.com/aaa/bbb?param=1/ccc/bbb/?param=2

Porque la primera ocurrencia del patrón slash-texto-slash-texto-signo de interrogación-todo lo demás ya satisface el criterio y una segunda ocurrencia no cambia el resultado (ni tampoco hay búsquedas recursivas)

var expreg = /\/(\w+)\/(\w+)(\?{1}.*)?$/,
  url_con_qs = 'https://www.miurl.com.co/path/path/page1/login?execution=sp1',
  url_sin_qs = 'https://www.miurl.com.co/path/path2/page2/login',
  exec1 = expreg.exec(url_con_qs),
  exec2 = expreg.exec(url_sin_qs);

if (exec1) {
  console.log('url con qs',
    exec1.slice(1, 3).join('/'));
}

if (exec2) {
  console.log('url sin qs',
    exec2.slice(1, 3).join('/'));
}

Una iteración más elaborada podría ser soportar URLS que terminen con slash (opcional) o que soporten slash+query string. Probablemente no te interesa.
/\/(\w+)\/(\w+)(\/?|\/?\?{1}.*)$/

Una manera más corta:
Dado un string de la forma
 https://www.miurl.com.co/path/path2/page2/login?lalala

O bien sin query string:
 https://www.miurl.com.co/path/path2/page2/login

Podrías explotar por ?, quedarte con la primera parte, explotarla por /, tomar los dos últimos valores, y unirlos con /

var url_con_qs = 'https://www.miurl.com.co/path/path/page1/login?execution=sp1',
  url_sin_qs = 'https://www.miurl.com.co/path/path2/page2/login',
  ruta1 = url_con_qs.split('?')[0].split('/').slice(-2).join('/'),
  ruta2 = url_sin_qs.split('?')[0].split('/').slice(-2).join('/');

  console.log('url con qs', ruta1);
  console.log('url sin qs', ruta2);


text:
Q: Is there a Tkinter widget equivalent to .NET's ListView control? In .NET, there is the ListView control, which displays a multicolumn list of items with clickable column headings one can use to sort the list in ascending or descending order by column. I need a scrollable Tkinter widget with exactly that behavior, but there doesn't appear to be anything in the standard Tkinter module with even similar functionality. This seems like a strange oversight. Is there a module out there with a widget like this? A cross-platform solution would be most desirable, but it's most important that the widget function well on Windows (XP and 7).

A: If you're using a modern version of tkinter you can use the ttk.Treeview widget.


text:
Q: JAVA Programming CheckBoxes to MySQL I have four JCheckboxes.
I can select all four options, or three, or two or at least one.
How do I get the values stored in one single column of the MySQL database?
See my code below:
String al = "";
        if(foreign.isSelected()){
            al = foreign.getText();
        }else if(travel.isSelected()){
             al2 = travel.getText();
        }else if(dang.isSelected()){
            al = dang.getText();
        }else if(med.isSelected()){
            al = med.getText();
        }

    try{
        String sql = "INSERT INTO employee (EmployeeID, FirstName, LastName, FlightInCharge, Allowances, Position, Salary) VALUES (?,?,?,?,?,?,?)";
        PreparedStatement stt = con.prepareStatement(sql);

        stt.setInt(1, id1);
        stt.setString(2, fn);
        stt.setString(3, ln);
        stt.setString(4, fg);
        stt.setString(5, al + al2);
        stt.setString(6, po);
        stt.setDouble(7, sa);

        stt.execute();

A: I don't understand why you declared al2 variable. Your code seems good and I don't understand what your exact problem is but consider these changes:
String al = "";
if(foreign.isSelected()){
   al = al + foreign.getText();
}
if(travel.isSelected()){
   al = al + travel.getText();
}
if(dang.isSelected()){
   al = al + dang.getText();
}
if(med.isSelected()){
   al = al + med.getText();
}
...
stt.setString(5, al);

remember when you load data from database you must decode this column and set value for your four fields, and to be able to do that, you can use delimiter in al variable or you can choose unique values for these fields so that you can determine to which field a value corresponds.
If they are check boxes then they have only true or false value so you must use delimiter like f;f;f;t which means the firs three ('foreign' , 'travel' and 'dang') are false and 'med' is true, or you can set column value to 'med:t' which means only 'med' is true and others are false. (You have to update code for inserting 'delimiters')
Notice that storing values of each field in a separate column enables you to query your database more elegantly and probably faster for queries like finding all rows with 'foreign = true' condition.


text:
Q: How to populate H2 in-memory DB from a file (populate.sql)? I want to add H2 in-memory db to my Spring MVC application. For ORM I'm using Hibernate. Here is my configs:
[hibernate.cfg.xml]
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:~/myDB</property>
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password">qwerty</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="de.alf.h2.entity.Student"/>
    </session-factory>
</hibernate-configuration>

[data.xml]
<bean:beans xmlns:bean="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:tx="http://www.springframework.org/schema/tx"
            xmlns:ctx="http://www.springframework.org/schema/context"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <ctx:component-scan base-package="de.alf.h2.repository"/>
    <bean:bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <bean:property name="sessionFactory" ref="sessionFactory"/>
    </bean:bean>
    <bean:bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <bean:property name="configLocation" value="classpath:/hibernate/hibernate.cfg.xml"/>
    </bean:bean>
    <bean:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <bean:property name="sessionFactory" ref="sessionFactory"/>
    </bean:bean>
</bean:beans>

[web.xml]
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/data.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

I need to create db from a file (resource/db/data.sql).
CREATE TABLE student {
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR (250)
}

How to do this in my code?

A: If hbm2ddl.auto is set to create, Hibernate will generate DDL from mapped classes during the SessionFactory creation. You can also add a file named import.sql to your classpath to import some data.
If you are using M2 for testing purpose and you want to do it by yourself, you can also use the H2 Execute SQL on Connection feature :
jdbc:h2:~/myDB;INIT=runscript from '~/resource/db/data.sql'

** Note that the path to data.sql might be differents.

A: you can use JDBC namespace xmlns:jdbc="http://www.springframework.org/schema/jdbc" then you can add embedded database as
<jdbc:embedded-database id="dataSource">
    <jdbc:script location="classpath:db/schema.sql"/>
    <jdbc:script location="classpath:db/test-data.sql"/>
</jdbc:embedded-database>

then use this data source in JDBCTemplate or in JPA with hibernate


text:
Q: How to retrieve HTML content from server using $http in AngularJS I have a requirement like I need to fetch HTML body content using $http service in AngularJS.
When I am trying to get that I am getting entire HTML as a response, but I need only the body part of that content.

A: You could find body inside the returned html.
But the best is definitely to update whatever service you call with $http so that it returns you only what you need (body).
angular.element(response).find('body')


text:
Q: System hangs on using mclapply I am running this code from Linux Terminal on a Ubuntu 14.04 PC with core i7 Processor and 4 GB RAM:
library(parallel)
workerFunc <- function(n) { return(n^2) }
a <- function(){
  CurrentTime <- Sys.time()
  res <- lapply(values, workerFunc)
  TimeTaken <- Sys.time() - CurrentTime
  print(TimeTaken)
}
b <- function(){
  CurrentTime <- Sys.time()
  numWorkers <- detectCores()
  res <- mclapply(values, workerFunc, mc.cores = numWorkers-2)
  TimeTaken <- Sys.time() - CurrentTime
  print(TimeTaken)
}
c <- function(n){
  values <<- 1:n
  print("Evaluating a : ")
  a()
  print("Evaluating b : ")
  b()
}

Running c() with n=9999999 as argument, the code runs for a() but on reaching b(), the system hangs. For smaller values of n as n=9999, n=999, both a() and b() works fine. What can be the possible solution?


text:
Q: Activity's finish() doesn't work and second onCreate is called I have a Main Activity that calls Activity_View_Turn
intent = new Intent(getApplicationContext(), Activity_View_Turn.class);
startActivityForResult(intent, RC_VIEW_TURN);
A dialogFragment is displayed from Activity_view_Turn.
fragdialog_view_summary newFragment = new fragdialog_view_summary().newInstance();
newFragment.show(getSupportFragmentManager(), "dialog");
In the dialogFragment there is an interface implemented by the Activity_View_Turn which executes this
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
In about 1 of 10 times, the onCreate of Activity_view_Turn will execute (a second time) after the onPause() is triggered by finish().  The onPause() only has the super.onPause()
If I try and finish() again the onActivityResult() in the Main Activity will then get executed twice.  The first Result however, doesn't get pushed to the onActivityResult() until after the second finish();


text:
Q: First Class Functions In Ruby I am working my way through this article on functional programming (https://codewords.recurse.com/issues/one/an-introduction-to-functional-programming) and trying to do the exercises in Ruby.
One exercise defines two functions, zero and one. Zero takes a string parameter and returns string index 1 - end if the first character is 0, One does the same thing but only if the first character is one.
Here are the ruby implementations:
def zero(s)
  if s[0] == "0"
    return s[1..(s.length)]
  end
end

def one(s)
  if s[0] == "1"
    return s[1..(s.length)]
  end
end

The problem asks you to write a method called rule_sequence that, given a string and an array of functions, returns the result such that the functions are invoked one at a time -- the first function is invoked in the whole string, the second function invoked on the return value of that string, etc. If, at any point, the one of the functions returns nil, return nil.
The Python implementation is:
def rule_sequence(s, rules):
    if s == None or not rules:
        return s
    else:
        return rule_sequence(rules[0](s), rules[1:])

However, since it doesn't seem like Ruby has support for higher order functions, the most elegant solution I could come up with was the following:
def rule_sequence(string, rules)
  if rules.length == 0 or string.nil?
    return string
  else
    return rule_sequence(rules[0].call(string), rules[1..rules.length])
  end
end

puts rule_sequence('0101', [lambda { |s| zero(s) }, lambda { |s| one(s) }, lambda { |s| zero(s) } ])

Can anyone come up with something more terse than passing or calling lambdas?

A: I'll take this exercise as an opportunity to show how Ruby supports higher order functions.
Let's go one step back and rewrite the zero - one functions.
You can notice they have quite a lot in common.
Let's try to exploit that by writing a lambda that can generate both
tail_on_prefix = lambda {|prefix|
  lambda {|str| str[1..-1] if str[0] == prefix}
}

We can now easily define zero and one
zero = tail_on_prefix.("0")
one = tail_on_prefix.("1")

To rule_sequence now!
rule_sequence = lambda {|str, rules|
  if (str.nil? or rules.empty?)
    str
  else
    rule_sequence.(rules[0].(str), rules[1..-1])
  end
}

now calling rule_sequence looks a bit better, doesn't it
rule_sequence.("100101", [one, zero, zero]) # => "101"

A: You can do this
puts rule_sequence('0101', [method(:zero), method(:one), method(:zero)])

Just BTW, s[1..(s.length)] can be written as s[1..-1], and rules[0].call(string) can be written as rules[0].(string).


text:
Q: Upgrading from Angular 5 to Angular 6 I am looking to upgrade from Angular 5 to Angular 6 on a particular web application.  We are unable to angular 8 at this time due to a dependency issue we've not been able to isolate (probably something deprecated and removed between 5 and 8).
The issue I have is the instruction sets I've seen to upgrade from angular 5 to angular 6 were written when angular 6 was the latest version, so they have things like
npm install @angular/cli@latest -g

which if I did right now would try to upgrade to 8.0.2 (being the latest).
I guess I could try to upgrade with
npm install @angular/cli@6.2.9 -g

or similar, but that brings me into a nightmare of figuring out the versions for the whole suite of upgrades, which is going be a mighty PITA (especially since the guide here has 29 different packages that are installed using @latest (not counting however many I will have to research that we use that are not part of that upgrade set).
Is there any resource that does this legwork for me already?  I'm guessing there's probably not, but you never know.
Our upgrade plan is to upgrade to 6 (to take advantage of some webpack changes and some tools that were written for 6+ to improve our build speed), and then rework everything on the deprecation list before an upgrade to 8.   However, we're to the point where we cannot hold off on the 6 upgrade until after we get the deprecation issues fixed.

A: Although the migration process did not badly effect your project .It depends upon the complexity of web application.
Here is a useful link that can help you in migration https://update.angular.io/#7.0:8.0
https://medium.com/@filipjerga/angular-5-to-angular-6-migration-guide-7ba4d2544411


text:
Q: Kudu post-deployment commands not running I'm trying to run some scripts after my site is deployed to azure (via kudu)
I have the following directory structure
-solution
  - .deployment
  - deploy.cmd
    - deployment
       - postdeployactions
         - test.bat

.deployment looks like this:
[config]
POST_DEPLOYMENT_ACTION_DIR  = deployment\postdeployactions\
command = deploy.cmd

deploy.cmd is unmodified from the one generated by azure site deploymentscript --aspWAP pathToYourWebProjectFile.csproj -s pathToYourSolutionFile.sln (http://blog.amitapple.com/post/38418009331/azurewebsitecustomdeploymentpart2/#.VPYd_PmUeTI)
However test.bat is not getting called.
I have tried setting both POST_DEPLOYMENT_ACTION_DIR and SCM_POST_DEPLOYMENT_ACTIONS_PATH (see https://github.com/projectkudu/kudu/issues/1154)

A: Some "Site Extensions" reconfigure this behaviour inside Azure.
For example, if you use Composer Site Extension in a PHP Web Site,
default kudu deployment script is replaced by other script injected by Composer Site Extension.
Maybe this could be your case.
Look at your COMMAND environment variable.

A: I do exactly the same thing but instead of POST_DEPLOYMENT_ACTION_DIR I use SCM_POST_DEPLOYMENT_ACTIONS_PATH, could that be the issue?
[config]
SCM_POST_DEPLOYMENT_ACTIONS_PATH = deployment\postdeployactions\


text:
Q: How to pass a variable to a curl command in a bash script? I am using the bash code below to store the result of a curl command in a text file.
cat /c/customer_files/Bain/artifacts1.txt
sample=$(curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer <my_token>' '<api_>' | jq -r '.items[] | .id')
echo "$sample" >> /c/my_files/artifacts1.txt

This generates a text file with content below:
606b69cff140fe0d98e78d2a
60a40910c403d464225343b5
607f1e14d514043adcf4a0f6
60c36c380093aa519b816554

Now, I want to iterate through this file line by line. I am using the code below to do that.
while read -r line; do
#reading each line
echo "Line No. $n : $line";
n=$((n+1))

This is producing correct result as expected.
Line No. 1 : 606b69cff140fe0d98e78d2a
Line No. 2 : 60a40910c403d464225343b5
Line No. 3 : 607f1e14d514043adcf4a0f6
Line No. 4 : 60c36c380093aa519b816554

I want to pass variable $line to CURL command via json body below.
input_json="{"executable": "<some ID>", "keepTargetResources": true,"keepTargetRunProfiles": true,"advanced": {"artifactId": "$line","artifactType": "ACTION"}}"

However, this produces a result below:
,artifactType: ACTION}}d6a50bb75bbe81, keepTargetResources: true,keepTargetRunProfiles:
true,advanced: {artifactId: 606b69cff140fe0d98e78d2a
,artifactType: ACTION}}d6a50bb75bbe81, keepTargetResources: true,keepTargetRunProfiles:
true,advanced: {artifactId: 60a40910c403d464225343b5
,artifactType: ACTION}}d6a50bb75bbe81, keepTargetResources: true,keepTargetRunProfiles:
true,advanced: {artifactId: 607f1e14d514043adcf4a0f6
{executable: 60ca3bf02ed6a50bb75bbe81, keepTargetResources: true,keepTargetRunProfiles:
true,advanced: {artifactId: 60c36c380093aa519b816554,artifactType: ACTION}}

It creates an output in the desired format only for the last record:
{executable: 60ca3bf02ed6a50bb75bbe81, keepTargetResources:
true,keepTargetRunProfiles:true,advanced: {artifactId:
60c36c380093aa519b816554,artifactType: ACTION}}

For 1st 3 records, it looks like it is overwriting content at the start of the line.
What am I doing wrong? Please advice.
Thanks in Advance.

A: JSON needs to have its variables and values surrounded with ". Use \ to prevent the shell to interpret the ".
The extra carriage return is a mystery...
Maybe an extra clean up of line could make it
Prefer printf to echo and use "${line}" for more safety.
Give this a try:
artifact_id="$(printf "%s" "${line}" | sed 's/^\(.*[^[:blank:]]\)[[:blank:]]*$/\1/g')"
input_json="{\"executable\": \"<some ID>\", \"keepTargetResources\": true,\"keepTargetRunProfiles\": true,\"advanced\": {\"artifactId\": \"${artifact_id}\",\"artifactType\": \"ACTION\"}}"


text:
Q: How to copy or select content between brackets or opening to closing html with Atom (Including the tags themselves)? In Atom you can use [ctrl + m] to goto the matching bracket or closing html tag.
How can you select the content from the beginning of / including the opening bracket / html to the end of/including closing bracket or closing tag?

A: To select all the text inside the current brackets or opening to closing html with Atom

*

*For Mac OS X [ctrl-cmd-m]

*For Windows [ctrl-alt-m]

A: Emmet has keybindings that expand/reduce selections to a tag which they call "balance outward/inward":

*

*Balance (outward): ctrl-shift-E

*Balance (inward): ctrl-shift-0
Emmet for Atom docs: https://atom.io/packages/emmet

A: My impression is that the key sequence to select text in between brackets has probably changed from version to version.  In Atom 1.58.0 for Windows (the one I am using) the key sequence to select text is ctrl-alt, .  Yes, that's right control alt comma.
In any event, whatever version you have, you should be able to find the key sequence in the Settings for the package shown in Atom.  Go to Packages > Installed Packages.  Enter "bracket-matcher" in the search field.  When the bracket-matcher package comes up click on the Settings button.  In the Settings there is a section called Keybindings.  There you will find the key sequence that works for your Atom installation.


text:
Q: Rails 6 - create has_many through record Why does the CompaniesController not create a record CompanyUser with current_user.companies.build(company_params)?
How can I create CompanyUser record at the time of creation of the Company record?
Models:
User
class User < ApplicationRecord
  has_many :company_users, dependent: :destroy
  has_many :companies, through: :company_users
end

Company
class Company < ApplicationRecord
  include Userstampable::Stampable

  has_many :company_users, dependent: :destroy
  has_many :users, through: :company_users

  accepts_nested_attributes_for :company_users, reject_if: :all_blank

  validates :name, presence: true, length: { maximum: 100 }
  validates :description, length: { maximum: 1000 }
end

CompanyUser
class CompanyUser < ApplicationRecord
  include Userstampable::Stampable

  belongs_to :company
  belongs_to :user

  validates :company_id, presence: true
  validates :user_id, presence: true
end

CompaniesController
class CompaniesController < ApplicationController
  def create
    @company = current_user.companies.build(company_params)

    respond_to do |format|
      if @company.save
        format.html { redirect_to @company, notice: 'Company was successfully created.' }
        format.json { render :show, status: :created, location: @company }
      else
        format.html { render :new }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end

  private

    # Never trust parameters from the scary internet, only allow the white list through.
    def company_params
      params.require(:company).permit(:name, :description)
    end
end

Migrate
class CreateCompanyUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :company_users do |t|
      t.integer :role, default: 0
      t.belongs_to :company, null: false, foreign_key: true
      t.belongs_to :user, null: false, foreign_key: true

      t.timestamps null: false, include_deleted_at: true
      t.userstamps index: true, include_deleter_id: true

      t.index [:company_id, :user_id], unique: true
    end
  end
end

A: You need to set the :inverse_of option on the belongs_to associations in CompanyUser model and remove the presence validations on :company_id and :user_id in ComapanyUser to make this work. The ComapanyUser model should look like this:
class CompanyUser < ApplicationRecord
  include Userstampable::Stampable

  belongs_to :company, inverse_of: :company_users
  belongs_to :user, inverse_of: :company_users
end

Check the description of the :through option in ActiveRecord association docs. It mentions that you need :inverse_of to create join model records.

If you are going to modify the association (rather than just read from
it), then it is a good idea to set the :inverse_of option on the
source association on the join model. This allows associated records
to be built which will automatically create the appropriate join model
records when they are saved. (See the 'Association Join Models'
section above.)


text:
Q: Setting the amount of dots in text-overflow: ellipsis; is there any option to set the specific number of dots in text-overflow: ellipsis. I would like to set the number to 2 instead of 3. I have tried to set it by adding pseudo-element :after, but it adds dots even if the text fits to div.
Actual behaviour:

Expected behaviour:

my css clases:
 .truncate-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}
.truncate-name::after {
    content: "..";
}

A: You're most likely out of luck @Bartosz, unless you only want to target Firefox users ;) Please see this answer on SO: https://stackoverflow.com/a/10349526/3681304
EDIT: There are no selectors for "overflown". As such there are no selectors for computed styles in CSS in general.


text:
Q: MS Excel conditional formatting by date formula does not work I need to apply conditional formatting on cells containing dates (expiration dates of certificates). I want expired certificates in red, expiring withing a week orange, expiring within a month (30 days) in yellow and others unmarked (talking about background colour). But when I put formula
=A2-today()<0 all cells get filled red, regardless the date. When I change the number to 7 and select orange colour, they all cells get filled orange, again regardless of the date. If everything worked fine, the A2 cell should be orange right now. What do I do wrong? How shall I write the formula?

A: You can use the following functions:
DATEDIF
TODAY

This gives the number of days between today and the date in A2:
=DATEDIF(A2, TODAY(), "d")
So, you can use:
=DATEDIF($A2, TODAY(), "D") > 0 [select red color for this formatting]
=AND(DATEDIF(TODAY(), $A2, "D") >= 0, DATEDIF(TODAY(), $A2, "D") < 7) [select orange color for this formatting]
=AND(DATEDIF(TODAY(), $A2, "D") >= 7, DATEDIF(TODAY(), $A2, "D") < 30) [select yellow color for this formatting]
You can go to this link and search for the section called "Highlighting delays":
https://www.microsoft.com/en-us/microsoft-365/blog/2013/04/04/using-conditional-formatting-to-highlight-dates-in-excel/

A: Check that your rules are in the right order.  They're applied in the order shown.
Also check that you're not using an absolute reference (e.g., no dollar signs).  Try highlighting the range before you type in your formula.  If you format the first cell and fill down, it's more problematic.
Here, they're out of order, so they all end up yellow.

Here, the order is corrected.

A: I test on my environment, please try following is helpful.
Red --- Expired certificates, the formula could be =AND(A2-TODAY()<0,A2<>"")
Orange --- Expiring withing a week, the formula could be =AND(A2-TODAY()>=0,A2-TODAY()<7)
Yellow --- Expiring within a month (30 days), the formula could be =AND(A2-TODAY()>=7,A2-TODAY()<30)


text:
Q: How to draw path like canvas in Android using OpenGL ES 2? I have tried Canvas in Android, and I can make sketch or path by moving my finger on the screen.
Now, I want to do the same thing using OpenGL 2.
I'm new to OpenGL programming but I have tried several method to draw a Line using GLES20.glDrawArray(...) and a Line Shape class
but still, this just make a straight line not like a free-form path i wanted just like when I use canvas.
and also, if i try to draw per line segment each time ACTION_MOVE, concurrent modification exception often happens since i store each Line segment in an ArrayList.
is there any helping API by OpenGL to achieve this?
if there's or there isn't, how can i make this?
Thanks!

A: If you want to draw a consistent line along a path, then you're in fact trying to draw many short lines which are all connected to each other.
I think the most intuitive way of doing this, is adding each point on the path into an array of points, and then, maintaining a float buffer, where each 3 items describe a single point on the path (x,y,z). Then, for every point which is added to this vertex buffer, you should add two integers into an index buffer. If you're new to index buffers, the way it works (when you're working with lines), is it tells OpenGL which two vertexes are connected. For instance:
Say you have 3 points. Inside the Vertex buffer, you would have 9 floats - 3 points * 3 coordinates for each point. We would like the 1st point to be connected to the 2nd, and the 2nd point to be connected to the 3rd. We can do this by using an Index Buffer. In the index buffer, we will place 2 integers for every vertex connection. For connecting the 1st point to the 2nd, we will player 0 & 1 into the buffer. This says that the 1st 3 coordinates in the vertex buffer are connected to the 2nd 3 coordinates in the vertex buffer. Then, we will place 1 & 2 in the index buffer. This says that the 2nd 3 coordinates in the vertex buffer are connected to the 3rd 3 coordinates in the vertex buffer - and so on.
Vertex Buffer:
{
  0, 0, 0, // Index 0
  1, 1, 1, // Index 1
  2, 3, 4  // Index 2
}

Index Buffer:
{
  0, 1, // Connect Index 0 to Index 1
  1, 2  // Connect Index 1 to Index 2
}

You will need to call glDrawElements rather than glDrawArrays, but the idea is the same - you only need to maintain an additional buffer for the indexes, and make sure to always update both buffers each time you add a new point.
As for the concurrent modification exception - you need to be a bit careful here. If you add a point to the array while you're iterating over the array (for example, with a "for each" style loop), then this will happen. A good solution is to surround any interaction with the point array with a synchronize block, and use the array itself as a mutex:
Adding:
synchronized(myPointArray)
{
  myPointArray.add(newPoint);
}

Iterating:
synchronized(myPointArray)
{
  for (PointF point : myPointArray)
  {
    // do stuff with the point
  }
}

This should get you started.


text:
Q: How to optimize the apply call on groupby I have a dataframe on which I want to apply below logic to get first row of group having analysis of the individual group.
def mark_wakeup_source(df):
    min_id = df['Astart'].idxmin()
    df.loc[min_id, ["Reason", "Count", "CSwitch", "Used"]] = [df.loc[min_id, "type"],
                                                             len(df.index),
                                                             len(df[df['type'] == "Process"]),
                                                             df["Aduration"].sum()]
    return df

Here is how I am calling the apply function and combining it.
df_t1 = df_t[df_t['type'] != 'Unknown'].copy()
df_t1['Reason'] = "None"
grouped = df_t1.groupby(["CPU", "index"])
df_t1 = grouped.apply(mark_wakeup_source)
df_t = df_t1.append(df_t[df_t['type'] == 'Unknown'])

There are 29K+ unique group in my current data and it is taking about ~140 sec to process. I have data which is much larger than this one, I need to optimize it, and running out of clue how to do it.
My data looks like this, before grouping it:
    CPU   State     Start      Stop pre_state next_state  index    Astart  \
0     4  Active  0.015417  0.056283        C1         C1      1  0.015429
1     4  Active  0.015417  0.056283        C1         C1      1  0.015437
18    5  Active  0.015492  0.015499        C1         C1      2  0.015495
14    4  Active  0.015417  0.056283        C1         C1      1  0.019524
20    1  Active  0.019921  0.020071        C3         C3      1  0.019938

   Astop          Name     type  Count  CSwitch  Used  Reason  Aduration
0   0.015437        System  Process      0        0     0     None   0.000008
1   0.032188       wpr.exe  Process      0        0     0     None   0.016751
18  0.015498        System  Process      0        0     0     None   0.000003
14  0.019727  ntoskrnl.exe      DPC      0        0     0     None   0.000203
20  0.020064        System  Process      0        0     0     None   0.000126

I have reduced the number of groups as much as possible.
Tried Numba but that didn't help at all.
Based on many other answers I tried below code, by returning 0 instead of df, which is taking ~180s:
def mark_wakeup_source(df, df_parent):
    df_len = len(df.index)
    min_id = df['Astart'].idxmin()
    df_parent.loc[min_id, ["Reason", "Count", "CSwitch", "Used"]] =
                                                                 [df.loc[min_id, "type"],
                                                                 df_len,
                                                                 len(df[df['type'] == "Process"]),
                                                                 df["Aduration"].sum()]
    return 0

Running out of clues, so looking for some suggestions to do it in optimum way.

A: Start with a dictionary of aggregation functions.
f = {
       'Astart' : [('Reason', 'idxmin')],
       'type' : [
                  ('Count', 'size'),
                  ('CSwitch', lambda x: x.eq('Process').sum())
        ],
       'Aduration' : [('Used', 'sum')]
}

Next, query + groupby and pass f to agg.
v = df.query("type != 'Unknown'").groupby(['CPU', 'index']).agg(f)
v.columns = v.columns.droplevel(0)

v['Reason'] = df.loc[v['Reason'].values, 'type'].values

v

           Reason  Count  CSwitch      Used
CPU index
1   1          20      1        1  0.000126
4   1           0      3        2  0.016962
5   2          18      1        1  0.000003

Note that using agg here to aggregate data is a lot faster, because it vectorizes your operations (which is faster than a loop-like apply solution).

A: To optimize the code, based on @COLDSPEED's suggestion I used:
df_min = grouped.agg({'Aduration': 'sum', 'type': 'count', 'Astart': 'min'}).reset_index()
df_min.rename(columns={'Aduration': "Used", 'type': 'Count', 'Astart': 'min'}, inplace=True)
df_with_proc = df_t1[df_t1['type'] == "Process"].groupby(["CPU", "index"]).agg({'type': 'count'}).reset_index()
df_with_proc.rename(columns={'type': 'CSwitch'}, inplace=True)
df_t1 = pd.merge(df_with_proc, df_t1, how="right", on=['CPU', 'index'])
df_t1 = pd.merge(df_min, df_t1, how="right", on=['CPU', 'index'])

This can compute in 0.2 sec on same dataframe.


text:
Q: Metaclass and syntax in Python I try to make something like that :
class oObject(object):
    def __init__(self, x = 0, y = 0, z = 0):
        self.x = x
        self.y = y
        self.z = z

def asString (self, value):
    return str(value)

vector = oObject(5,5,5)

# So i can do
asString(vector.x)

# But I want this kind of syntax
vector.x.asString()

It's just an example, i don't really want to convert integrer into a string. It's more about class into a class.

A: You could either write a custom method for your oObject class that returns the string of the given key, or maybe you could write a custom Variant class and wrap your values:
class oObject(object):
    def __init__(self, x = 0, y = 0, z = 0):
        self.x = Variant(x)
        self.y = Variant(y)
        self.z = Variant(z)

class Variant(object):
    def __init__(self, obj):
        self._obj = obj

    def __repr__(self):
        return '<%s: %s>' % (self.__class__.__name__, self.asString())

    def __str__(self):
        return self.asString()

    def asString(self):
        return str(self._obj)

    def value(self):
        return self._obj

Check out this reference as to how PyQt4 does it, with the QVariant class, which is actually from Qt. Normally python wouldn't need this type, but it was necessary for C++ to represent the multiple types.

A: You cannot shouldn't do this kind of things in Python.
What you can however do is implementing the standard __str__ method in the class and that is the code that will be used when converting an instance to a string using str(instance).
Technically you can play a lot of tricks in python, trying to bend the syntax to whatever you are used to, but this is a bad idea because a lot of efforts have been put on making Python more readable and you are basically destroying that work.
In Python conversion to string is done by str(x), not by calling a method named asString. Using __str__ you can already customize what str is going to return, why adding a method? If you need a way to do a custom string conversion then just define a function dispatching on the object type instead of trying to inject new methods on existing classes:
converters = dict()

def add_converter(klass, f):
    converters[klass] = f

def default_converter(x):
    return "<%s: %s>" % (x.__class__.__name__, str(x))

def mystr(x):
    return converters.get(x.__class__, default_converter)(x)

With this approach there is no "magic" (i.e. surprising) behavior and you are not wrapping things (another approach that may surprise who reads the code).
In the above example I'm not handling converter inheritance, but you can do that by using a more sophisticated lookup if you need and if you really want that (not sure it makes sense to inherit a conversion to string function, it would silently lose information).
Also if you don't understand what a metaclass is for just leave that concept alone, most probably you don't really need it. Metaclasses are a powerful but somewhat complex tool that is not needed really that often...
I think this article is a good general explanation of what metaclasses are and what you can do with them. Note that some gory details are missing and you should use official documentation to dig them.

A: To have exactly what you are asking for is tricky in Python -
that is because, when you do
"instance.x.method" - Python first retrieves the attribute "x" from "instance", and them
it would try to find "method" as an attribute in the "x" object itself (without any reference to the "instance" which originally had a reference to "x" that could be possibly retrieved from inside the "method" - but for frame introspection).
I said that it "could be done" - and be made to work for most types of x, but could eventually fail, or have collatteral effects, deppending on the type of the attribute "x":
If you write a  __setattr__ method for your  class that for each attribute set on the instance, it actually creates a dynamic sub-class of that attribute - which would enable the desired methods on the new object. The draw back, is that not all types of objects can be sub-classed, and not all sub-classed objects will behave exactly like their parents. (If "x" is a function, for example). But it would work for most cases:
class Base(object):
    def __setattr__(self, name, attr):
        type_ = type(attr)
        new_dict = {}
        for meth_name in dir(self.__class__):
            function = getattr(self.__class__, meth_name)
            # Assume any methods on the class have the desired behavior and would
            # accept the attribute as it's second parameter (the first being self).

            # This could be made more robust by making a simple method-decorator
            # which would mark the methods that one wishes to be appliable
            # to attributes, instead of picking all non "_" starting methods like here:

            if not callable(function) or meth_name in new_dict or meth_name.startswith("_"):
                continue
            def pinner(f):
                def auto_meth(se, *args, **kw):
                    return f(se._container, se, *args, **kw)
                return auto_meth
            new_dict[meth_name] = pinner(function)
        # This could be improved in order to have a class-based cache of derived types
        # so that each attribute setting would only create a new_type for
        # each different type that is being set
        new_type = type(type_.__name__, (type_,), new_dict)
        try:
            attr.__class__ = new_type
        except TypeError:
            # here is the main problem withthis approach:
            # if the type being stored can't have it's `__class__`dynamically
            # changed, we have to build a new instance of it.
            # And if the constructor can't take just the base type
            # as its building parameter, it won't work. Worse if having another instance
            # does have side-effects in the code, we are subject to those.

            attr = new_type(attr)
        attr._container = self
        super(Base, self).__setattr__(name, attr)

class oObject(Base):
    def __init__(self, x = 0, y = 0, z = 0):
        self.x = x
        self.y = y
        self.z = z

    def asString(self, attr):
        return str(attr)

And after loading these in an interactive section:
>>> v = oObject(1,2,3)
>>> v.x.asString()
'1'
>>> v.w = [1,2,3]
>>> v.w.append(3)
>>> v.w.asString()
'[1, 2, 3, 4]'
>>>

As you can see, this can be done with normal class inheritance  no need for metaclasses.
Another, more reliable approach for any Parameter type would be to use another separator for the attribute name, and the method - them you could writhe a much simpler __getattribute__ method on a base class, that would dynamically check for the request method and call it for the attribute. This approach requires no dynamic sub-classing, and is about 2 orders of magnitude simpler. The price is that you'd write something like vector.x__asString  instead of the dot separator. This is actually the approach taken in the tried and tested SQLALchemy ORM for Python.
# Second approach:

class Base(object):
    separator = "__"
    def __getattr__(self, attr_name):
        if self.__class__.separator in attr_name:
            attr_name, method_name = attr_name.split(self.__class__.separator, 1)
            method = getattr(self, method_name)
            return method(getattr(self, attr_name))
        raise AttributeError

And now:
>>> class oObject(Base):
...     def __init__(self, x = 0, y = 0, z = 0):
...         self.x = x
...         self.y = y
...         self.z = z
...
...     def asString(self, attr):
...         return str(attr)
...
>>>
>>>
>>> v = oObject(1,2,3)
>>> v.x__asString
'1'

(Some more code is required if you want more parameters to be passed to the called method, but I think this is enough to get the idea).


text:
Q: Add custom META tags to pages in Hybris I need to add custom meta tags to a Hybris site, yet I can't find anything in HMC (the site is based on version 6.5) or Backoffice. Is there any way to do it on live site without changes to the code or are code changes necessary for this?

A:
Is there any way to do it on live site without changes to the code or
  are code changes necessary for this?

As per my knowledge, there is no way to add custom meta-type without changing the code. You can only add meta keywords and meta description through back-office.
For <meta http-equiv="abcd" content="1234"/>, you can add it to master.tag
 and for <meta name="my-custom-tag" content="my-custom-value"/> you can again hardcode in master.tag or get it populated from some item type by changing server side code.
Refer createMetaElement method of AbstractPageController, UiExperienceMetadataViewHandler and this answer


text:
Q: VBA - Ignore part of strBody if cell is blank? I have a VBA script made in Excel 2010 that sends me an email 30 minutes before a task reaches its due date. The body of the message "strBody" fetches the value of three cells to make the message unique. It fetches the Name of the Task, the Notes of the Task and the Due Date of the task.
What I am wondering is if there is a way for a part of this message to be left out if one of the referenced cell is blank.
In this template below:
"This email is to notify you that your task : " & Cells(FormulaCell.Row, "A").Value & " with the following note: " & Cells(FormulaCell.Row, "B").Value & " is nearing its Due Date: " & Cells(FormulaCell.Row, "E").Value & "." & vbNewLine & "A wise decision would be to complete this task before it expires!" & _
vbNewLine & vbNewLine & "Truly yours," & vbNewLine & "Task Manager"

I would like the following section to be removed if Cells(FormulaCell.Row,"B") is blank.
" with the following note: " & Cells(FormulaCell.Row, "B").Value & "

This is mainly a cleanup process as having an empty area in a message is far from pretty, and I am using this as a business tool with multiple people in CC.
Currently, a message with a blank Note area looks like:
Hello,
This email is to notify you that your task : Give Denise a Promotion, with the following note:   is nearing its due date: 02/09/2016.
A wise decision would be to complete the task before it expires!

Many thanks!

A: You can do it with only one If statement with conditional concatenation
    msg = "This email is to notify you that your task : " & Cells(FormulaCell.Row, "A").Value

    If Cells(FormulaCell.Row, "B").Value <> "" Then
        msg = msg & " with the following note: " & Cells(FormulaCell.Row, "B").Value
    end if

    msg = msg & Cells(FormulaCell.Row, "A").Value & " is nearing its Due Date: " & Cells(FormulaCell.Row, "E").Value & "." & vbNewLine & "A wise decision would be to complete this task before it expires!" & vbNewLine & vbNewLine & "Truly yours," & vbNewLine & "Task Manager"

A: I would have an if statement to see if it is empty and then just skip over it. So instead of one line of code with all the &, break it up into different sentences. Check to see if there are any values in the strings, then append them into one string for sending.
It will add more code but will look better.
So for instance if you have a part B then your message would append to the sending sting = A+B+C
But if you dont have a value for B then your if statement will then skip the b section and append only a and c to your sending string.
Something like that would work for your purposes I think.

A: Add in an IF ELSE statement.
If Cells(FormulaCell.Row, "B").Value = "" Then
    msg = "This email is to notify you that your task : " & Cells(FormulaCell.Row, "A").Value & " is nearing its Due Date: " & Cells(FormulaCell.Row, "E").Value & "." & vbNewLine & "A wise decision would be to complete this task before it expires!" & _
vbNewLine & vbNewLine & "Truly yours," & vbNewLine & "Task Manager"
Else
    msg = "This email is to notify you that your task : " & Cells(FormulaCell.Row, "A").Value & " with the following note: " & Cells(FormulaCell.Row, "B").Value & " is nearing its Due Date: " & Cells(FormulaCell.Row, "E").Value & "." & vbNewLine & "A wise decision would be to complete this task before it expires!" & _
vbNewLine & vbNewLine & "Truly yours," & vbNewLine & "Task Manager"
End If

Add in ElseIf in there if other fields other than note might be blank too.


text:
Q: How can I iterate through a websites search results and gather meta-data? I have an assignment that requires me to iterate through a website's search results, which are links to journals, to gather each journal's link and other meta-data (authors, date, etc...) and output them to a .txt file using at least Java and Apache HTTPClient, but no web crawlers.  Here is the website: https://www.cochranelibrary.com/cdsr/reviews/topics .  I am to choose any of the categories shown and gather the aforementioned data for each of the journal links in that category.
Below is a bit of code I found online to gather the HTTP entity and response body via Apache HTTPClient.  The program I am facing is when using a simple URL like google.com, it works fine and displays the page's source code for me to later parse.  However, the page I need to use is full of JavaScript wizardry and is not cooperating. Each search result page ends with the "/search" end-point.  Through my browser's web developer tools, I managed to find a direct link to
the current result page I am viewing:
https://www.cochranelibrary.com/en/search?p_p_id=scolarissearchresultsportlet_WAR_scolarissearchresults&p_p_lifecycle=0&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_scolarissearchresultsportlet_WAR_scolarissearchresults_displayText=Allergy+%26+intolerance&_scolarissearchresultsportlet_WAR_scolarissearchresults_searchText=Allergy+%26+intolerance&_scolarissearchresultsportlet_WAR_scolarissearchresults_searchType=basic&_scolarissearchresultsportlet_WAR_scolarissearchresults_facetQueryField=topic_id&_scolarissearchresultsportlet_WAR_scolarissearchresults_searchBy=13&_scolarissearchresultsportlet_WAR_scolarissearchresults_facetDisplayName=Allergy+%26+intolerance&_scolarissearchresultsportlet_WAR_scolarissearchresults_facetQueryTerm=z1506030924307755598196034641807&_scolarissearchresultsportlet_WAR_scolarissearchresults_facetCategory=Topics
However, when attemping to use this it returns a 419 error, which is apparently some unauthorized access/token issue.  So at this point, that is my main problem, I just cannot "import" a categories' search results to even attempt iterating through to gather the required data.
public static void main(String[] args) throws IOException
{
  String url = "http://www.google.com";
  CloseableHttpClient httpclient = HttpClients.createDefault();

  try
  {
    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("User-Agent",USER_AGENT);

    System.out.println("Executing request " + httpget.getRequestLine());

    ResponseHandler<String> responseHandler = new ResponseHandler<String>()
    {
      public String handleResponse(final HttpResponse response) throws IOException
      {
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300)
        {
          HttpEntity entity = response.getEntity();
          return entity != null ? EntityUtils.toString(entity) : null;
        }
        else
        { throw new ClientProtocolException("Unexpected response status: " + status); }
      }
    };

    String responseBody = httpclient.execute(httpget, responseHandler);
    System.out.println("----------------------------------------");
    System.out.println(responseBody);

  }
  finally
  { httpclient.close(); }
}

UPDATE
So I consolidated the code quite a bit after looking at the Apache HTTPClient docs, just to make it easier to work and test with:
public class App
{
    public static void main(String[] args) throws URISyntaxException
    {
      // Builds the URI
      URI uri = new URIBuilder()
          .setScheme("https")
          .setHost("www.cochranelibrary.com")
          .setPath("/")
          .build();

      // Uses Fluent API to execute GET request with uri
      try
      { System.out.println(Request.Get(uri).execute().returnContent().asString()); }
      catch (IOException e)
      { e.printStackTrace(); }
    }
}

However, this particular domain continues to give me issues.  Just attempting to GET from www.cochranelibrary.com returns a 419 error.  I thought maybe it was something with the HTTPS protocol, but testing on https://www.httpvshttps.com returns perfectly fine.  I'm lost as to why this particular domain is being stubborn.


text:
Q: why script code removed after $wp_embed->run_shortcode() in wordpress global $wp_embed;
print_r($wp_embed->run_shortcode('[embed]https://twitter.com/minnna_sokuho/status/907222559006920704[/embed]'));

this is my code.
I expected result as below,

New post (斉藤由貴(51)とかいう不倫しても可愛いから許されるおばさんwwww) has been published on 博士の速報2 - https://blahblah/HEigtcb8Dz pic.twitter.com/zR6hEJfitQ
— みんなの速報 (@minnna_sokuho) September 11, 2017
<

but,   there was no  .
I guess that some filter or hooks chages the result, but I've not found what it is.
How can I fix it ?

A: that was side effect of other plugin(Autouptimizer)


text:
Q: Issue with disappearing of pop up element after clicking button so I'm working on a school project. The goal is to calculate the surface of a triangle in javascript and display the results in html. I created a form to enter the values of the variables g and h.
Now I want to replace the header text with getelementbyid but somehow it pops up and disappears directly when I click the button. try it yourself and let me know what I'm doing wrong.

function berechnen() {
  var g = document.getElementById("grundfläche").value;
  var h = document.getElementById("höhe").value;

  var fläche = g*h/2;
  var ergebnis =  "Das Ergebnis für die Flächenberechnung eines Dreickecks mit der Grundfläche " + g + " und der Höhe " + h + " beträgt " + fläche;
  document.getElementById('heading').innerText = ergebnis;

}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fläche eines Dreiecks</title>
  <link rel="stylesheet" type="text/css" href="style.css">

Die Fläche eines Rechtecks berechnen

    <form>
      <input type="text" name="grundfläche" id="grundfläche" maxlength="10" placeholder="Gib die Grundseite des Dreiecks ein">
      <input type="text" name="höhe" id="höhe" maxlength="10" placeholder="Gib die Höhe des Dreiecks ein">

      <button type="submit" onclick="berechnen()">Berechnen</button>
    </form>

A: So, you have the onclick on a submit button, which submits the form.
You see the change from your javascript, but then your form is posted to the server, refreshing the page, and the change is gone.
So add return false to the javascript method:
function berechnen() {
//...existing code
    return false;
}

and it should behave as you expect (i.e. without submitting the form)
Alternatively change the type=submit to button
Berechnen

A: Try to change your button type to

submit

if you don't have any intention to submit and modify any data on the server side:
<button type="button" onclick="berechnen()">Berechnen</button>


text:
Q: Sync applications between several countries' stores I have a problem with managing purchases from different stores. As you know, Apple doesnt' provide the one global store for purchases made in different countries and some applications are published only in only local country store. Given that, I now have purchases in two countries and realized it's hard to keep track of applications, remove unnecessary and not used and so on.
I decided to clean up my account and hide not used anymore applications. But it's a completely mess: something is downloaded on my mac, something on iphone, something on ipad, it all syncs in ununderstandable ways.
My question is: how do you handle this situation with different stores? I'm thinking about re-purchasing all applications in my current country's  store, but I got used too much to packaging managers and can't imagine doing it manually.

A: I just got my new phone and wanted to sync to the backup of my old phone. The problem was with the apps. I deleted the foreign country's apps that were automatically put on the phone by the service provider (that I was never going to use anyway) and this solved my problem.

A: The simple way to clean things up is to delete all apps you no longer want from iTunes and then carefully examine things the next time you sync.
By deleting the apps you wish to no longer maintain, you can avoid updates and installs.
As to the purchase history, hiding purchases and avoiding re-downloading is the only mechanism that Apple provides today to manage multiple country purchases against the same one Apple ID.

A: I use to have the same problem, cause I had an account from my own home country, the country where I currently live and the US Store. What I did was delete all the applications from my iPod, iPhone and iPad. On my Mac I authorised the iTunes with all the three accounts, and then I applications that I wanted on each I synced, it asked me for a password if I hadn't used this id on the device and that was it. I still use it and I am not being asked for a password everytime.
P.S: I basically use the US store for most of the purchases, occasionally I use the regional stores if the app is not available in the US store.
P.P.S: I download and updates the app from iTunes and not the device directly.


text:
Q: Making a Mathematica version of Wordle interactive Just as a diversion, I'd like to create an interactive Mathematica version of Wordle. As a sketch I have the following:
wordlist =
Import["https://gist.githubusercontent.com/cfreshman/a03ef2cba789d8cf00c08f767e0fad7b/raw/a9e55d7e0c08100ce62133a1fa0d9c4f0f542f2c/wordle-answers-alphabetical.txt", "List"];
word = Characters[RandomSample[wordlist, 1][[1]]];
wordle[string_] := Module[{guess, thread},
guess = Characters[string]; thread = Thread[{word, guess}];
Row[Table[
 If[Length[DeleteDuplicates[thread[[t]]]] == 1,
  Text[Style[DeleteDuplicates[thread[[t]]][[1]], Large, White,
    Background -> Darker[Green]]],
  If[MemberQ[word, guess[[t]]],
   Text[Style[guess[[t]], Black, Large, Background -> Yellow]],
   If[MemberQ[word, guess[[t]]] == False,
    Text[Style[guess[[t]], White, Large, Background -> Gray]],
    Text[Style[guess[[t]], White, Large,
      Background -> Black]]]]], {t, 5}]
]];

(*wordle["stead"]*)

How can I make this sketch interactive?

A: Feel free to take a look at this on the Wolfram community that I did for fun:
a facsimile of Wordle
Moderators: update… I did not see that a link to this was added as a comment above. I am leaving this one as well, but feel free to change it to a comment or to delete it as you see fit. Thanks!

A: This is a very minimal interactive wireframe to get you started.
DynamicModule[{words = {}, word = ""},
 Column[{
   Dynamic@Column@words,
   Row[{
     InputField[Dynamic[word], String],
     Button["Submit", AppendTo[words, wordle[word]]; word = ""]
     }]}]]


text:
Q: Why is my code using 4th Runge-Kutta isn't giving me the expected values? I'm having a little trouble trying to understand what's wrong with me code, any help would be extremely helpful.
I wanted to solve this simple equation

However, the values my code gives doesn't match with my book ones or wolfram ones as y goes up as x grows.
import matplotlib.pyplot as plt
from numpy import exp
from scipy.integrate import ode

# initial values
y0, t0 = [1.0], 0.0

def f(t, y):
    f = [3.0*y[0] - 4.0/exp(t)]
    return f

# initialize the 4th order Runge-Kutta solver
r = ode(f).set_integrator('dopri5')
r.set_initial_value(y0, t0)

t1 = 10
dt = 0.1
x, y = [], []
while r.successful() and r.t < t1:
    x.append(r.t+dt); y.append(r.integrate(r.t+dt))
    print(r.t+dt, r.integrate(r.t+dt))

A: Your equation in general has the solution
y(x) = (y0-1)*exp(3*x) + exp(-x)

Due to the choice of initial conditions, the exact solution does not contain the growing component of the first term. However, small perturbations due to discretization and floating point errors will generate a non-zero coefficient in the growing term. Now at the end of the integration interval this random coefficient is multiplied by exp(3*10)=1.107e+13 which will magnify small discretization errors of size 1e-7 to contributions in the result of size 1e+6 as observed when running the original code.
You can force the integrator to be more precise in its internal steps without reducing the output step size dt by setting error thresholds like in
r = ode(f).set_integrator('dopri5', atol=1e-16, rtol=1e-20)

However, you can not avoid the deterioration of the result completely as the floating point errors of size 1e-16 get magnified to global error contributions of size 1e-3.
Also, you should notice that each call of r.integrate(r.t+dt) will advance the integrator by dt so that the stored array and the printed values are in lock-step. If you want to just print the current state of the integrator use
    print(r.t,r.y,yexact(r.t,y0))

where the last is to compare to the exact solution which is, as already said,
def yexact(x,y0):
    return [ (y0[0]-1)*exp(3*x)+exp(-x) ]


text:
Q: Django - return all associated rows for distinct results set with postgres backend I have data in the following form:
collection_name | type       | manufacturer | description | image_url
---------------------------------------------------------------------------
beach           | bed        | company a    | nice bed    | 1.jpg
beach           | king bed   | company a    | nice bed    | 1.jpg
beach           | nightstand | company a    | nice ns     | 1.jpg
grass           | chest      | company a    | nice chest  | 2.jpg
apple           | chest      | company a    | nice chest  | 3.jpg
fiver           | chest      | company b    | good chest  | 4.jpg

What I need to do, is select all images and only return each image once (distinct), but then return non-distinct row for each image.
My goal is to ensure I display each image only once in my template, but show all records associated with each image.
In the example above, 1.jpg is one image that would show both beds and the nightstand in one image. I would like to show such an image and list associated products with it.
I have seen similar questions, although asking at the SQL/db level and not asking for a pure django solution.
The query I have been using in my view has been something like:
products = product.objects.filter(collection_name=name)

and then iterating over products, retrieving image_url like so:
{% for instance in products %}
{{ instance.image_url }}
{{ endfor }}

I've tried various attempts to limit repeating images in my template, but none have really worked, and attempts to do so in my view have not been successful.
What is the correct way to approach this?
Edit: A relevant excerpt from my models to match the sample data above:
class Product(models.Model):
    collection_name = models.TextField(null='true',blank='true')
    type = models.TextField(null='true',blank='true')
    manufacturer = models.TextField(null='true',blank='true')
    description = models.TextField(null='true',blank='true')
    image_url = models.TextField(null='true',blank='true')

Edit: My idea of views and logic to attempt to solve this, after reading the docs and looking at other questions (no answers):
Pass the product_id of any product in a collection to the view. Then obtain the collection_name field of a record based on the id field:
collectionname = product.objects.filter(id=id).values('collection_name').distinct()

Then, when we have the collection_name field, return all products for a given collection_name:
products = product.objects.filter(collection_name__in=collectionname)

Then, finally, return a list of image_url results for a given collection name, removing duplicates:
images = product.objects.filter(collection_name__in=collectionname).values('image_url').distinct()

I think this should work, in theory...
Edit:
Currently attempting the following based on Juancarlos' answer below:
products = product.objects.filter(collection_name=name)
collectionname = product.objects.filter(id=id).values('collection_name').distinct()
images = product.objects.filter(collection_name__in=collectionname).values("image_url").distinct()
results = []
for img in images:
    pbis = product.objects.filter(collection_name__in=collectionname, image_url=img['image_url'])
    obj = {"image": img['image_url'], "items":[{"type":pbi.type} for pbi in pbis]}
    results.append(obj)

A: You need tell to django what field you want distinct, you can use values to do that:
in your case your answer can seen like this:
products = product.objects.filter(collection_name=name).values("image_url").distinct()

A: mabe this logic can help you, i am not sure but you can do something like this:
images = product.objects.filter(collection_name=name).values("image_url").distinct()
results = []
for img in images:
    pbis = product.objects.filter(collection_name=name, image_url=img['image_url'])###this get all record tha contains this image
    obj = {"image": img['image_url'], "items":[{"attr":pbi.attr, ...} for pbi in pbis]}
    results.append(obj)
    ###this iterate all record by images and you can store items attribute from all recors that contains that image


text:
Q: How to get substring based on special characters in android? Actually this is a very simple question, I tried a lot but I am unable to get the exact solution. I have a string like:
String mystring = "one<1234567>,two<98765432>,three<878897656>";

Here I want the data which is inside "<" and ">". Can anyone help me with this?

A: I would use regex
String str = "one<1234567>,two<98765432>,three<878897656>";
Matcher m = Pattern.compile("<(.+?)>").matcher(str);
while(m.find()) {
    String v = m.group(1);
}

A: Try
String mystring = "one<1234567>,two<98765432>,three<878897656>";
    String[] result = mystring.split(",");
    for (String s : result) {
        s = s.substring(s.indexOf("<")+1);
        s = s.substring(0, s.indexOf(">"));
        System.out.println(s);
    }

Print result :
1234567
98765432
878897656

A: You can use a regex like <(.*?)> :
String mystring = "one<1234567>,two<98765432>,three<878897656>";
Pattern pattern = Pattern.compile("<(.*?)>");
Matcher matcher = pattern.matcher(mystring);
while (matcher.find())
{
    System.out.println(matcher.group(1));
}

A: Try this
String mystring = "one<1234567>,two<98765432>,three<878897656>";
String[] a = myString.split(",");
for(int i = 0; i < a.length; i++){
String substr=a[i].subString(a[i].indexOf("<"),a[i].indexOf(">"));
System.out.println(substr);
}

A: Try if your inner bracket value always numeric and outside alphabetical i.e. <, >
String[] strings=mystring.replaceAll("[a-z<>]", "").split(",");

         for(String string:stringsArray)
         {
          System.out.println(string);
         }

A: i found an new solution from StringTokenizer class
you can use it as,
 StringTokenizer tokens = new StringTokenizer(KEY_SUBFOLDERNAME, ".");
            String first_string = tokens.nextToken();
            File_Ext = tokens.nextToken();
            System.out.println("First_string : "+first_string);
            System.out.println("File_Ext : "+File_Ext);


text:
Q: What will be the logic of the answer? I have this reasoning question (image)

So, what I did is I found the number of dots in this, which came out to be:
2  5    11
7  13  19
5   ?   17
And I can't really find what's the pattern in this.
What I could see is :
5+6=11
13+6=19
x+6=17 so, x = 11
But what will be with 2,7 and 5 then?
Please explain me :)


text:
Q: how to save cookies from puppeteer and use the cookies to make request in python?
const puppeteer = require('puppeteer-extra')
// add stealth plugin and use defaults (all evasion techniques)
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
puppeteer.use(StealthPlugin())

puppeteer.launch({ headless: true,ignoreHTTPSErrors:true, args: [ '--no-sandbox', '--proxy-server=51.158.111.242:8811' ] }).then(async browser => {

console.log('Running tests..')

const page = await browser.newPage()

await page.goto('https://google.com/')

const cookies = await page.cookies();

console.log(cookies);

await fs.writeFile('./cookies.json', JSON.stringify(cookies, null, 2));

await page.screenshot({ path: 'testresult.png', fullPage: true })

await browser.close()

})

after saving the cookies into the file, it saves multiple cookies dictionary in file
[
  {
    "name": "_gat",
    "value": "1",
    "domain": "www.google.com",
    "path": "/",
    "expires": 1582024891,
    "size": 5,
    "httpOnly": false,
    "secure": false,
    "session": false
  },
  {
    "name": "_gid",
    "value": "GA1.2.1936512649.1582024831",
    "domain": "www.google.com",
    "path": "/",
    "expires": 1582111231,
    "size": 31,
    "httpOnly": false,
    "secure": false,
    "session": false
  },
  {
    "name": "_ga",
    "value": "GA1.2.1830413277.1582024831",
    "domain": "www.google.com",
    "path": "/",
    "expires": 1645096831,
    "size": 30,
    "httpOnly": false,
    "secure": false,
    "session": false
  },
  {
    "name": "__cfduid",
    "value": "d9ccc472957afbae818db60dff47cc5e01582024830",
    "domain": "www.google.com",
    "path": "/",
    "expires": 1584616830.613503,
    "size": 51,
    "httpOnly": true,
    "secure": true,
    "session": false,
    "sameSite": "Lax"
  }
]
I am not able to decide which one should use for making a request in the python-requests module?


text:
Q: See implementation of interface on VS I use to develop with eclipse and am missing some things on VisualStudio 2013
As you can see in the gif below, I can use a ctrl + t shortcut to see which classess are imlpementing my interface IFoo  so I can see the details (in this case Microwave51 class)..How can I do the same trick on VS-2013,
This question here is pretty good but only since 2015

Edit:
If I do Right click on the interface declaration and click "Go To Implementation" I get only this:

A: If you have ReSharper...
Right click on the interface declaration and click "Go To Implementation."
If you don't...
Right click on the interface and "Find All References." Gotta look through the results manually.


text:
Q: adding new support library redlines the current library My gradle file
  compileSdkVersion 25
  buildToolsVersion "25.0.3"

  minSdkVersion 17
  targetSdkVersion 25

    dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
    })
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.4.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}

adding 'compile com.android.support:cardview-v7:25.4.0 causes the compile 'com.android.support:appcompat-v7:25.3.1' to be redlined
  `` in my code and i want to use the CardView feature in my app and using only the compile 'com.android.support:appcompat-v7:25.3.1' didnt do the work
what can i do to avoid using libraries that conflicts each other in my code and does it mean ?
The error message i received when i play my mouse on the red line
All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.4.0, 25.3.1. Examples include com.android.support:cardview-v7:25.4.0 and com.android.support:animated-vector-drawable:25.3.1 less... (Ctrl+F1)
There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.)

A: That's because you are trying to add CardView version which is greater than your appcompat version. So in order to fix this you need to use the same version
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'


text:
Q: Error when uploading a file to the in-flow sequence on WSO2 API Manager I am trying to upload a new file to the in flow sequence in WSO2 API manager publisher.
Every time I try and add the file, I get a message when I try to save my changes.

Error while performing registry transaction operation

How can I resolve this?