text:
Q: change image path every x-times How can I repeat the code below, so the image path changes after every two seconds for example
OleDbCommand cmd = new OleDbCommand("SELECT TOP 1 userdaten.image FROM userdaten ORDER BY Rnd(ID)", con);

        con.Open();
        OleDbDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows)
        {
            while (dr.Read()) { PictureTrainLabel.Text = "~/Image/" + dr["image"].ToString(); }

            PictureTrain.ImageUrl = PictureTrainLabel.Text;

        }
        con.Close();

A: You need to put that code within a timer, that way you can run it every two seconds. I'm not sure how you plan on changing the path, because I'm not sure what you mean, but the logic for that can be done within the OnTimedEvent.
    private static System.Timers.Timer aTimer;

    private static void SetTimer()
    {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        OleDbCommand cmd = new OleDbCommand("SELECT TOP 1 userdaten.image FROM userdaten ORDER BY Rnd(ID)", con);

        con.Open();
        OleDbDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows)
        {
            while (dr.Read()) { PictureTrainLabel.Text = "~/Image/" + dr["image"].ToString(); }

            PictureTrain.ImageUrl = PictureTrainLabel.Text;

        }
        con.Close();
    }


text:
Q: Using the p-Frobenius on tower fields $\newcommand\F{\mathbb F}$
Example $\F_{p^2}\cong \F_p[x]/(X^2-2)$ for $p\equiv \pm 3\bmod 8$
For any $A\in\F_{p^2}$ we get the $\F_p$ representation as $A=a+bx$ for $a,b\in\F_p$. Computing the p-Frobenius reveals $A^p=(a+bx)^p=a^p+b^p+x^p$, thanks to the freshmen's dream working modulo $p$. The next step is to know the "Fermats little theorem", that says $a^p\equiv a \bmod p$. Therefore, we have $A^p = a+bx^p$. Now we take a closer look onto $x^p$:
$x^p= (x^2)^{\frac{p-1}{2}}x = 2^{\frac{p-1}{2}}x \equiv -x \bmod p$, since 2 is a none-quadratic resudue in our considered case $p\equiv \pm 3\bmod 8$.
All in all the p-Frobenius increases the computation time to be a simple conjugation: $A^p=(a+bx)^p=a-bx$
Question
I derived this technic for the tower field $\mathbb F_{p^{16}}\cong \F_p[x]/(x^{16}-2)$ but I'm not sure if I did any mistakes. Since I am not allowed to publish this, I need to ask something in general about this.
How would you compute the Frobenius? Is there any "state of the art" design? Which tricks would you use to get to the aim?
My Attempt
I started by building up a tower, like in sage:
p=103
R = GF(p)
_.<U> = PolynomialRing(R)
R2.<U> = R.extension(U^2 - 2, 'U')
_.<V> = PolynomialRing(R2)
R4.<V> = R2.extension(V^2 - U, 'V')
_.<W> = PolynomialRing(R4)
R8.<W> = R4.extension(W^2-V, 'W')
_.<X> = PolynomialRing(R8)
R16.<X> = R8.extension(X^2-W, 'X')

But this does not hold for any prime congruent to $\pm 3\bmod 8$. There we have to check on equivalence classes module 32. The class of my interest is $p\equiv 13\bmod 32$.
Question rising from attemption
Sage cannot help me, verify the Frobenius for my prime, since the prim-test fails. I could consider any other prime from the same equivalence class, but how could I be sure that this won information holds?
I check via bruteforce for any prime (first 3 found primes from the same equivalence class) modulo 64, and it turned out, that all information from mod 32 is repeated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML5 multiple images in loop i have an html5 page which loads an single image. but my requirement is to show multiple images one after other in loop. Please provide your suggestions..

A: Try the following code:

Store the images in the appropriate folder and adjust the count of the image where num is calculated. Currently it is set up for 9 images.
Adjust the time at the end of the setInterval function. Currently the images change every 2000 milliseconds.


text:
Q: Как убрать видимость блока в анимации? Нужно, чтобы исчезал блок, но когда я делаю это через opacity, не могу ничего нажать, так как блок по сути все еще находится там, но прозрачный.

.over-all {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: white;
animation-name: over-all2;
animation-fill-mode: forwards;
animation-delay: 0.8s;
animation-duration: 0.8s;
display: flex;
justify-content: center;
align-items: center;

@keyframes over-all2 {
0% {
    opacity: 1;
    padding-top: 0;
}
100% {
    opacity: 0;
    padding-top: 0;
}

A: Пожалуйста!
@keyframes over-all2 {
    0% {
        opacity: 1;
        padding-top: 0
    }

    100% {
        opacity: 0;
        visibility: hidden
    }
}

A: Добавляйте изменение по высоте, чтобы элемент не находился поверх остальных после анимации. Очень важно, чтобы начальное и конечное значения высоты были численными, иначе анимация не сработает (можно оставить height: auto, а манипулировать значениями max-height)

header, footer {
  width: 100%;
  height: 50vh;
  border: 1px solid #000;
  background: yellow
}

header {
  background: blue;
  border-bottom: 0;
}

.over-all {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: white;
  animation-name: over-all2;
  animation-fill-mode: forwards;
  animation-delay: 0.8s;
  animation-duration: 0.8s;
  display: flex;
  justify-content: center;
  align-items: center;
  background: red;
}

@keyframes over-all2 {
0% {
    opacity: 1;
    padding-top: 0;
    height: 100vh;
}
100% {
    opacity: 0;
    padding-top: 0;
    height: 0;
}

Если вам неподходит анимация изменения высоты, можете манипулировать значениями z-index.

header, footer {
  width: 100%;
  height: 50vh;
  border: 1px solid #000;
  background: yellow
}

header {
  background: blue;
  border-bottom: 0;
}

.over-all {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: white;
  animation-name: over-all2;
  animation-fill-mode: forwards;
  animation-delay: 0.8s;
  animation-duration: 0.8s;
  display: flex;
  justify-content: center;
  align-items: center;
  background: red;
}

@keyframes over-all2 {
0% {
    opacity: 1;
    padding-top: 0;
    z-index: 1;
}
100% {
    opacity: 0;
    padding-top: 0;
    z-index: -1;
}


text:
Q: Set Windows 10 Taskbar settings via Group Policy Is it possible to enable/disable specific settings the Windows 10 Taskbar menu? Preferably via GPO. We are running Windows 10 Pro.

A: You can utilize a built-in Group Policy to Lock the Taskbar by enabling the following:
User Configuration > Administrative Templates > Start Menu and Taskbar . Lock the Taskbar

For the others, you may need to utilize registry updates.  To use small/large taskbar buttons, you can modify the following:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced
TaskbarSmallIcons DWORD
0 = Large taskbar buttons
1 = Small taskbar buttons

(Source)
To hide or show badges on taskbar buttons, modify the following:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced
TaskbarBadges DWORD
0 = Hide badges
1 = Show badges

(Source)
To show the Command Prompt or PowerShell on the  + X menu, modify the following:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced
DontUsePowerShellOnWinX DWORD
0 = Show "Windows PowerShell"
1= Show "Command Prompt"

(Source)
That being said, if these machines are on a domain you can use Group Policy Preferences to implement those registry updates.

A: For local GP, check User Configuration\Administrative Templates\Start Menu and Taskbar


text:
Q: probability - defective disks 70% of disk drives made from Company X function properly. If we have a collection of $5$ disk drives, what is the probability that:

*

*At least $1$ disk drive doesn't function?

*At least $1$ disk drive is functioning?

This is what I came up with for the first question:
$\small \operatorname{C}(5,1)\!\cdot\!0.3^1\!\cdot\!0.7^4 + \operatorname{C}(5,2)\!\cdot\!0.3^2\!\cdot\!0.7^3 + \operatorname{C}(5,3)\!\cdot\!0.3^3\!\cdot\!0.7^2 + \operatorname{C}(5,4)\!\cdot\!0.3^4\!\cdot\!0.7^1 + \operatorname{C}(5,5)\!\cdot\!0.3^5\!\cdot\!0.7^0$
This is what I came up with for the 2nd question:
$\small \operatorname{C}(5,1)\!\cdot\!0.7^1\!\cdot\!0.3^4 + \operatorname{C}(5,2)\!\cdot\!0.7^2\!\cdot\!0.3^3 + \operatorname{C}(5,3)\!\cdot\!0.7^3\!\cdot\!0.3^2 + \operatorname{C}(5,4)\!\cdot\!0.7^4\!\cdot\!0.3^1 + \operatorname{C}(5,5)\!\cdot\!0.7^5\!\cdot\!0.3^0$

A: *

*1-probability all disks function

*1 - probability all disks malfunction.
It's often easier to find the probability of the compliment of the event. Now use the Binomial distribution...


text:
Q: Flutter: How to Bottom Center a Button in a ListView? I need to bottom center a button that is contained within a ListView. By bottom, I mean at the bottom of the screen, or if the screen content is longer than the height of the screen, at the end of the content.
I can do this using a Column with a Spacer widget because the height is defined, however my screen has text input on it. If I use a Column instead of a ListView, the screen overflows when I'm typing.
How can I either

*

*Bottom center a button, or

*Use a Column but prevent the screen from resizing or overflowing when typing; I'd like it to ether be scrollable, or simply have the keyboard cover the screen content while typing.

Basic code example:
return Scaffold(
      body: Center(
        child: Container(
          width: workingWidth,
          child: Center(
            child: ListView(children: <Widget>[
              ScreenHeader("Tell Us a Little About Yourself"),
              TextFormField(
                maxLines: 16,
                controller: bioController,
                autocorrect: true,
                textCapitalization: TextCapitalization.sentences,
                maxLength: 500,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(paddingH5),
                  focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: colorPrimary)),
                  border: UnderlineInputBorder(
                      borderSide: BorderSide(color: colorMuted)),
                  hintText: "Enter your bio here...",
                  hintStyle: textMuted,
                ),
              ),
              Spacer(), //This doesn't work because I am using a ListView instead of a Column
              RoundedButton(
                  buttonText: 'Continue',
                  buttonStyle: buttonPrimary,
                  onPressed: () {}
            ),
            ],)
          ),
        ),
      ),
    );

A: To use a Column without yellow/black stripes error when opening the keyboard, you need to wrap it into a SingleChildScrollView, but Spacer will not work in that case if you do not declare the height of its RenderFlex parent.
You can use MediaQuery.of(context).size.height to get the screen size on its context and set to your Container.
At the end you can achieve the desired layout with this:
return Scaffold(
              body: SingleChildScrollView(
                child: Container(
                  width: workingWidth,
                  height: MediaQuery.of(context).size.height,
                  child: Column(
                    children: <Widget>[
                      ScreenHeader("Tell Us a Little About Yourself"),
                      TextFormField(
                        maxLines: 16,
                        controller: bioController,
                        autocorrect: true,
                        textCapitalization: TextCapitalization.sentences,
                        maxLength: 500,
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(paddingH5),
                          focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color: colorPrimary)),
                          border: UnderlineInputBorder(
                              borderSide: BorderSide(color: colorMuted)),
                          hintText: "Enter your bio here...",
                          hintStyle: textMuted,
                        ),
                      ),
                      Spacer(),
                      RoundedButton(
                          buttonText: 'Continue',
                          buttonStyle: buttonPrimary,
                          onPressed: () {}
                      ),
                    ],
                  ),
                ),
              ),
            );


text:
Q: Find and Replace Multiple Lines in Excel I have a document that has a product length | product name | and product price
I have used this code I found online to replace the product price:
Sub Multi_FindReplaceALL_pvc_replace_new()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array("2 ft", "PVC", "390")
rplcList = Array("2 ft", "PVC", "290")

'Loop through each item in Array lists
 For x = LBound(fndList) To UBound(fndList)
'Loop through each worksheet in ActiveWorkbook
  For Each sht In ActiveWorkbook.Worksheets
    sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
      LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
      SearchFormat:=False, ReplaceFormat:=False
  Next sht

  Next x

End Sub

The issue I am having is this VB script is replacing the product name Acrylic's pricing as well.
Any help would be greatly appreciated.  I can also supply any additional information if needed.
Image Link of Doc: http://prntscr.com/h1votx

A: Do you only have 1 sheet? This code will work with the sheet in the print screen, however it is hard coded to the current columns that the values fall into. It can be relaxed a bit if you need it to work for different values or different columns.
Sub Multi_FindReplaceALL_pvc_replace_new()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim sht As Worksheet
Dim i As Integer

Dim lastRow As Integer

'get the last row in the sheet
With ActiveSheet
  lastRow = .Cells(.Rows.Count, "I").End(xlUp).Row
End With

'Loop through each row in the sheet
 For i = 1 To lastRow
'Loop through each worksheet in ActiveWorkbook
    If Cells(i, 9).Value = "2 ft" And Cells(i, 11).Value = "PVC" Then
        Cells(i, 20).Value = "290"
    End If
  Next i

End Sub

Basically your code before was just running through the entire sheet and changing all the values if they were in that array. This function goes row by row and specifically compares the columns that contain your values


text:
Q: Windows: Detect in Registry when a user is logged in but disconnected When I log in into an windows device, I can sometimes see 2 users sessions (I can see it by clicking Task Manager -> Users). One of the users has status Disconnected and the other active
Is there a way for me to see weather the user is disconnected or not in the registry?
Thank you

A: I don't know if there is a registry value you can check and if you find one it must be considered an unintended side effect you should not rely on.
The WTS API is the correct way to handle this.
Call WTSRegisterSessionNotification to receive notifications and/or WTSEnumerateSessionsW to find the current sessions and their states.


text:
Q: How can I view all ng-init content? I am doing the progress bar for each object equipment.
Here is my AngularJS code:
$scope.progressBarEquipements=function(idEquipement) {

     $http.get(url+"/RestResponseCheckLists?idEq="+idEquipement)
     .success(function(data) {
             $scope.Pourcentage = data;
      }).error(function(err, data) {
            console.log("error : " +data);
    });
};

This function returns $scope.progressBarEquipements=function(idEquipement):
console.log("data "+Pourcentage);
/**
* [{'NB_Resp':2,'NB_checks':154}]  //For the first object And the others not
*/

Here is my HTML code:

{{eq.nomEq}}

                  {{((p.NB_Resp/p.NB_checks) * 100) | number:0}}%

So I have four items of equipment are displayed in the html page.

The $scope.Percentage displays the progress bar calculation for the
  first object only.

How to display for each object its calculation in the progress bar?
thank you in advance

A: Although, I don't like the way you are using ng-init, the following should work :
$scope.progressBarEquipements=function(eq) {

     $http.get(url+"/RestResponseCheckLists?idEq="+ eq.idEquipement)
     .success(function(data) {
         eq.Pourcentage = data;
      }).error(function(err, data) {
            console.log("error : " +data);
    });
};

{{eq.nomEq}}

                  {{((p.NB_Resp/p.NB_checks) * 100) | number:0}}%

The idea was to send your function "progressBarEquipements" the full equipment object. In that way, you are able to update it when the server responds.
I don't like the approach of using ng-init because
 - the behaviour of your view is kinda hidden between your controller, and your template.
 - If I had to do it, my API would give the viewmodel containing every information I need to display.


text:
Q: Minimize the code for on click listener I am new to android and I am bored of implementing View.OnClickListener in my every activity. I need a method which could easily do it for me.

A: You can use view injection, this way you can simply write the method and declare it as the onClick of some view on your layout.
See - Dagger, or RoboJuice.

A: You could use ButterKnife
Then use
@OnClick(R.id.submit)
public void submit(View view) {
  // TODO submit data to server...
}

A: You can do this by creating abstract class and extend it to all your activities. Usually know as Base Class.
Here is the code:
public abstract class BaseActivity extends Activity implements View.OnClickListener{

    public void attachClickListener(int... views){
        for(int i = 0; i<views.length;i++){
            findViewById(views[i]).setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {}

}

Keep both methods in your base class and override it from your activity class extended by the base class.
attachClickListener method will loop through all the IDs you will send as argument in your activity class.
Here is the code for your activity class:
@Override
attachClickListener(R.id.yourViewFromXml1, R.id.viewFromXml2, R.id.viewFromXml3 );

you can add infinite IDs.
@Override
OnClick(View v){
    switch(v.getId())
    case R.id.yourViewFromXml1 : // do your stuff;
                                break;
    case R.id.ViewFromXml2 : // do your stuff;
                                break;
}


text:
Q: IllegalStateException on parsing JSON I am trying parse a JSON file in my android application.
I use Retrofit and Gson.
I get this JSON from this website:
http://api.nbp.pl/api/exchangerates/tables/a/?format=json
This is my JSON:
[{
"table": "A",
"no": "023/A/NBP/2019",
"effectiveDate": "2019-02-01",
"rates": [{
    "currency": "bat (Tajlandia)",
    "code": "THB",
    "mid": 0.1190
}, {
    "currency": "dolar amerykański",
    "code": "USD",
    "mid": 3.7243
}, {
    "currency": "dolar australijski",
    "code": "AUD",
    "mid": 2.7027
}, {
    "currency": "dolar Hongkongu",
    "code": "HKD",
    "mid": 0.4745
}, {
    "currency": "dolar kanadyjski",
    "code": "CAD",
    "mid": 2.8334
}, {
    "currency": "dolar nowozelandzki",
    "code": "NZD",
    "mid": 2.5775
}, {
    "currency": "dolar singapurski",
    "code": "SGD",
    "mid": 2.7611
}, {
    "currency": "euro",
    "code": "EUR",
    "mid": 4.2706
}, {
    "currency": "forint (Węgry)",
    "code": "HUF",
    "mid": 0.013462
}, {
    "currency": "frank szwajcarski",
    "code": "CHF",
    "mid": 3.7509
}, {
    "currency": "funt szterling",
    "code": "GBP",
    "mid": 4.8588
}, {
    "currency": "hrywna (Ukraina)",
    "code": "UAH",
    "mid": 0.1352
}, {
    "currency": "jen (Japonia)",
    "code": "JPY",
    "mid": 0.034195
}, {
    "currency": "korona czeska",
    "code": "CZK",
    "mid": 0.1658
}, {
    "currency": "korona duńska",
    "code": "DKK",
    "mid": 0.5720
}, {
    "currency": "korona islandzka",
    "code": "ISK",
    "mid": 0.031036
}, {
    "currency": "korona norweska",
    "code": "NOK",
    "mid": 0.4416
}, {
    "currency": "korona szwedzka",
    "code": "SEK",
    "mid": 0.4114
}, {
    "currency": "kuna (Chorwacja)",
    "code": "HRK",
    "mid": 0.5756
}, {
    "currency": "lej rumuński",
    "code": "RON",
    "mid": 0.8999
}, {
    "currency": "lew (Bułgaria)",
    "code": "BGN",
    "mid": 2.1836
}, {
    "currency": "lira turecka",
    "code": "TRY",
    "mid": 0.7170
}, {
    "currency": "nowy izraelski szekel",
    "code": "ILS",
    "mid": 1.0257
}, {
    "currency": "peso chilijskie",
    "code": "CLP",
    "mid": 0.005679
}, {
    "currency": "peso filipińskie",
    "code": "PHP",
    "mid": 0.0714
}, {
    "currency": "peso meksykańskie",
    "code": "MXN",
    "mid": 0.1951
}, {
    "currency": "rand (Republika Południowej Afryki)",
    "code": "ZAR",
    "mid": 0.2809
}, {
    "currency": "real (Brazylia)",
    "code": "BRL",
    "mid": 1.0216
}, {
    "currency": "ringgit (Malezja)",
    "code": "MYR",
    "mid": 0.9092
}, {
    "currency": "rubel rosyjski",
    "code": "RUB",
    "mid": 0.0568
}, {
    "currency": "rupia indonezyjska",
    "code": "IDR",
    "mid": 0.00026716
}, {
    "currency": "rupia indyjska",
    "code": "INR",
    "mid": 0.052227
}, {
    "currency": "won południowokoreański",
    "code": "KRW",
    "mid": 0.003336
}, {
    "currency": "yuan renminbi (Chiny)",
    "code": "CNY",
    "mid": 0.5526
}, {
    "currency": "SDR (MFW)",
    "code": "XDR",
    "mid": 5.2070
}]
}]

This is my error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

My class:
class MainModel {

@SerializedName("table")
@Expose
var table: String? = null
@SerializedName("no")
@Expose
var no: String? = null
@SerializedName("effectiveDate")
@Expose
var effectiveDate: String? = null
@SerializedName("rates")
@Expose
var rates: List<Rate>? = null

}

class Rate {

@SerializedName("currency")
@Expose
var currency: String? = null
@SerializedName("code")
@Expose
var code: String? = null
@SerializedName("mid")
@Expose
var mid: Double? = null

}

I did it like on this page: http://www.jsonschema2pojo.org
Why did I get this exception?


text:
Q: for loop with a single semicolon throws the error "Uncaught SyntaxError: Unexpected token ')" The following for loop works fine

for (let count = 0;; count++) {
  console.log(count);
  if (count >= 3)
    break
}

It throws an error when there's only one semicolon ; instead of two

for (let count = 0; count++) {
  console.log(count)
  if (count >= 3)
    break
}

Uncaught SyntaxError: Unexpected token ')

A: It's just how the for loops syntax works. The semicolons in the for loop separate three different expressions from each other - the "variable initializing" statement, the "stop condition" expression, and the "post-iteration" expression (I'm just making up names here, but they fit their purpose).
So, in this line of code:
for (let count = 0;; count++)

By putting two semicolons there, you're basically saying that there is no middle expression, i.e. there is no stop condition for this for-loop. You can omit any section you like. for (;;) is a valid loop too, and does the exact same thing as while (true). The important thing is, those two semicolons are always required in the loop.
If, for example, you wrote this line of code:
for (let count = 0; count++)

You're only supplying two of the three required expressions. Which two are you supplying? Is count++ the stop condition? Or is it the after-each-iteration action? Instead of the compiler guessing at your intentions, it just throws a syntax error and requires you to use two semicolons to make it clear that your intentions were for it to be interpreted as for (let count = 0;; count++), not for (let count = 0; count++;).
Learn more about this c-style for loop on MDN here.


text:
Q: Getting values from enum class where enum member names are known at run time in Python I am trying to get enum values from Enum class by getting enum member name runtime . I am trying in the following way:
from enum import Enum

    class EnumList(Enum):

        foo = 1
        bar = 2

enumMemberName=input("Enter enum member name")
enumValue=repr(EnumList.enumMemberName)          // **AttributeError: enumMemberName**
enumValue=repr(EnumList.foo)                     // **working fine**

please provide me with the alternate solution of above problem.

A: I think this is what you want:
edit: revised answer after OP feedback.
from enum import Enum

class EnumList(Enum):

    foo = 1
    bar = 2

enumMemberName=input("Enter enum member name")

enumMember = EnumList.foo
enumMemberTwo = EnumList[enumMemberName]

enumValue = EnumList[enumMemberName].value
enumValueStr = repr(EnumList[enumMemberName].value)

Quoting from the documentation for Enum

A: Your expectations are wrong.  Asking an Enum for one of its members is going to give you that member:
>>> enumList[enumMemberName]   # if name is 'foo'  (also, notice square brackets)
<EnumList.foo: 1>              # expected output

If you specifically want the value, you have to ask for it:
>>> enumList[enumMemberName].value   # if name is 'foo'
1


text:
Q: QMake and wxWidgets (External Libraries) I'm trying to compile a GUI program based on the wxWidgets libraries. I get a lot of undefined references to "something". I tried to add a few libraries manually on the LIBS variable of QMake without success. How can i add all the wxWidgets libraries to QMake without hard coding each library? Below is my .pro file.
# simple.pro
TARGET = sample

HEADERS += main.h simple.h
SOURCES += main.cpp simple.cpp

LIBS += -LC:/SourceCode/Libraries/wxWidgets2.8/lib/gcc_dll/wxmsw28_core_gcc.dll \
        -LC:/SourceCode/Libraries/wxWidgets2.8/lib/gcc_dll/wxmsw28_gcc.dll \
        -LC:/SourceCode/Libraries/wxWidgets2.8/lib/gcc_dll/wxmsw28_aui_gcc.dll

INCLUDEPATH += C:/SourceCode/Libraries/wxWidgets2.8/include

CONFIG += release

The errors are of the form:

release/simple.o:simple.cpp:(.rdata$_ZTV6Simple[vtable for
  Simple]+0x320): undefined reference to
  `wxFrameBase::SetStatusBar(wxStatusBar*)'

A: First, you need to use the .a files to add to the linker.
Then you need to define WXUSINGDLL if you link against the shared libraries.
Additionally, you forgot
 wxbase29u.a

Hope that helps.


text:
Q: Unable to get firebase current user in kotlin I am integrating FirebaseAuth into an Android app that I am building. I have successfully integrated firebase into the app by adding the SDK, downloading and adding the google-services.json file.
The problem occurs when I try to Sign Up a new user. The user gets added to firebase console but I cannot retrieve the signed in user to update the name. This is the code from the fragment I am using it in.
requireActivity().let {
    val user = authenticationService.signUpWithEmailAndPassword(email, password)

    user?.let {
            authenticationService.updateUser(it, name)
            navigationService.openHomeScreen()//open next creen
    }
}

the signup function in the authenticationService
fun signUpWithEmailAndPassword(email: String, password: String): FirebaseUser? {
    signOutCurrentUser()
     firebaseAuth.createUserWithEmailAndPassword(email, password)
    return firebaseAuth.currentUser
}

the update user function
fun updateUser(user: FirebaseUser?, name: String) {
    val profileUpdates = UserProfileChangeRequest.Builder().apply {
        displayName = name
    }.build()
    user?.updateProfile(profileUpdates)?.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Timber.d("User profile updated.")
        }
    }
}

the sign out current user function
private fun signOutCurrentUser() {
    firebaseAuth.currentUser?.let {
        firebaseAuth.signOut()
    }
}

The issue is that user is Added successfully but firebaseAuth.currentUser returns null always.
Things I have tried:

*

*Adding authStateListener

*Adding onSuccessListener

*Adding onCompleteListener

Please help a brother out

A: Creating a user in Firebase is (like most calls involving cloud-based APIs) an asynchronous operation, which may take time to complete. By the time your return firebaseAuth.currentUser code runs, the user creation has not been completed yet.
If you simply the code to run in a single block, with a completion handler, you'll see that it works fine:
firebaseAuth.createUserWithEmailAndPassword(email, password)
  .addOnCompleteListener(this) { task ->
    if (task.isSuccessful) {
        val user = auth.currentUser

        val profileUpdates = UserProfileChangeRequest.Builder().apply {
            displayName = name
        }.build()
        user?.updateProfile(profileUpdates)?.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Timber.d("User profile updated.")
            }
        }
    } else {
        // If sign in fails, display a message to the user.
        Log.w(TAG, "createUserWithEmail:failure", task.exception)
        Toast.makeText(baseContext, "Authentication failed.",
                Toast.LENGTH_SHORT).show()
        updateUI(null)
    }

    // ...
  }

Also see:

*

*getContactsFromFirebase() method return an empty list

*Firebase retrieve data Null outside method

*Retrieve String out of addValueEventListener Firebase

*Setting Singleton property value in Firebase Listener (which shows using semaphores to make the code block, but which didn't work on Android when I last tried it).


text:
Q: Подключение модулей nestjs Подскажите пожалуйста, как исправить ошибки?
Error:(1, 22) TS2307: Cannot find module '@nestjs/common' or its corresponding type declarations.
Error:(2, 32) TS2307: Cannot find module '@nestjs/common/interfaces' or its corresponding type declarations.


text:
Q: How to make UITableView appear from bottom to top when scroll? I'm looking just for general scenario.The idea is when app launches user can see only first cell of UITableView at the bottom of UIViewController. When user scrolls up full table appears and when scrolls down only first cell is displayed again. Something similar like keyboard in Facebook messenger app, but with tableView. For now I added tableView as subview to scrollView, but problem is tableView appears from top to bottom, and I'm looking for solution how to make this work upside down.. So, tableView have to appear from bottom to top of UIViewController.

A: My idea would be:

*

*Give your UITableView the desired frame at viewDiDLoad (probably the height of 1 cell, at the bottom of your UIView)

*Let your UIViewController implement UIScrollViewDelegate

*At - (void)scrollViewDidScroll:(UIScrollView *)scrollView of UIScrollViewDelegate check which element is scrolling (if its your UITableView) and also check which direction user is scrolling

*Change the frame of the UITableView as you wish, you will also have to come up with some logic to block further changing of the UITableView's frame (a BOOL would do good here I guess)

A: Not sure I understand your correctly but, maybe, this will be helpful
I believe you can try to add zero cell (or first section header view of your UITableView) with transparent background. So that your first cell will be placed on the bottom of screen and UITableView height will be equal to screen height.
In this case, you will have only one scrolling view (UITableView, in particularly). Following method can be used to perform expandable animation and scroll table to top to hide zero cell when user taps on first cell:
[UITableView scrollRectToVisible:animated:]

After that you can leave UITableView as it is and "constrict" your table whenever you need in the same way as it was expanded before.

A: I understand what you want to do.
In general, UITableView shows cells from top to bottom.
You can add transform in tableview:
tableView.transform = CGAffineTransform(scaleX: 1, y: -1)

Then your tableview will show the cells from bottom to top and you can scroll tableview from bottom to top.
But cells will be transformed as tableview, so you have to add same transform to cells also.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")

    **cell.transform = tableView.transform**

    return cell
}

All done. Hope to helpful!


text:
Q: Class-Responsibility-Collaborators (CRC) Cards template I'm struggling with making a CRC card template, as the following one:

May anybody help me?
Ps. Add another row between Superclasses and Subclassess called Interfaces, please.


text:
Q: How to delete only one object within a stringified JSON stored in Localstorage? I am saving my products that belong to the shopping cart on the local storage. Everything has the same key. I am using the following code:
for (let i = 0; i<produkt.length; i++) {
        .
        .
        .
  document.querySelector('a.produktlöschen'+[i]).addEventListener('click', ()=>{
    const parsed = JSON.parse(localStorage.getItem('warenkorb'));
    parsed.splice(parsed.indexOf(i), 1);
    localStorage.setItem('warenkorb', JSON.stringify(parsed));
    location.reload();

the for loop is for the dynamic shopping cart. product1 is i=0, product2 is i=1 ...
My plan is, when the Anchor is clicked, that the product[I] (depends on which Anchor) gets deleted.
With my code, only the last item gets deleted and not the one which anchor is clicked.
     let produkt = [
 {
  name: '3er Set Bambuszahnbürste',
  preis: 10,
  marke: 'LifePanda',
  seit: 2020,
  bild_url: '../img/Produkt_1.jpg',
  id: 1
},
{
name: 'Nachhaltiges Einkaufsnetz',
preis: 19,
marke: 'GreenEarth',
seit: 2019,
bild_url: '../img/Produkt_2.jpg',
id: 2
}];

A: Use an OBJECT
You are having problems in referencing (getting the index of) the Array item you wanted to remove. A better way is to directly use an object instead of an Array. This way you can call them using the name you assigned them instead of finding a way to get the index of the item you wanted.
// Using an object you can just directly assign an id that you can call anytime
const obj = {}
obj['a12e'] = {...} // obj = {a12e:{...}}  // add new properties
obj.a12e.name = ... // change properties
delete obj.a12e = //delete properties

Do not pull your data from the localStorage
Also, it is better if all the items are stored in an Array of Objects or Objects (depends on your preference). That way, when you remove an item you can remove it from the array and then store the Array into localStorage. Better than having to parse the stringed object and stringifies it again when there is a change into products(this consumes so much time)
Let's compare the concepts then

Changing an Item directly from localStorage: 0# onclick
1# get JSON from localStorage 2# parse JSON to Array 3# remove
item from Array 4# convert Array to stringified JSON 5# store
stringified JSON to localStorage
Changing an Item in an Array/object: 0# onclick 1# remove item from Array/Object 2# convert Array/Object to stringified
JSON 3# store stringified JSON to localStorage

Example
// HTML

Cheese cake <button class=remove>x</button>

Chocolate cake <button class=remove>x</button>

Strawberry cake <button class=remove>x</button>

Double Chocolate cake <button class=remove>x</button>

// JavaScript

const productItemsObject = {}

localStorage.setItem('products', JSON.stringify(productItemsObject))

for (let items of document.querySelectorAll('.item')) {

  productItemsObject[items.id]={name: items.children[0].innerText} // store everything in an object

  items.children[1] /*button*/ .addEventListener('click', function() {

    //Using an Object
    delete productItemsObject[items.id] // remove item from array
    localStorage.setItem('productsObj', JSON.stringify(productItemsObject)) // update the data in localStorage only after every change

    items.remove()

    console.log("Object",localStorage.productsObj)
  })
}


text:
Q: WifiManager.ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE not working in samsung 8.0+ Intent wifiAlwaysAvailable = new Intent(WifiManager.ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE);
wifiAlwaysAvailable.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(wifiAlwaysAvailable);

I'm trying to enable programatically the Wifi scanning setting to improve accuracy in our location. This code works fine in other devices but in Samsung devices like A5 or S8 this doesn't work. Any idea?
Edited: I try to use the method startActivityForResult and it works, but you need the Activity context and, in my case I only have the Aplication context.

A: Finally I found the solution.
I create a transparent activity and I started it where I was trying to start this WifiManager.ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE. Then I called the method startActivityForResult(new Intent(WifiManager.ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE),1) in the onCreate of this activity.


text:
Q: MS11-100, MaxHttpCollectionKeys not working Our application is  giving the following error in a large form:

System.InvalidOperationException: Operation is not valid due to the
  current state of the object.    at
  System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded()
  at System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes,
  Encoding  encoding)     at
  System.Web.HttpRequest.FillInFormCollection()

When I investigated the problem, we found it was related to MS11-100.
The recommendationis to the following entry to the appsettings:
<add key="aspnet:MaxHttpCollectionKeys" value="36001" />

However, after adding the key in the Sharepoint Web Application, it is still giving the same error.
I have tried adding the key both manually in the web.config and programmatically using the SPWebConfigModification
Should this setting work in SharePoint?
Could I have something wrong in my infrastucture that SharePoint is simply not taking into consideration the web.config changes?
Any suggestions of how best to investigate this issue please?

Any assistance woul be greatly appreciated.


text:
Q: HazelcastClientCachingProvider class not found exception when requesting hazelcast jcache provider I'm having a strange warning when I try to use Hazelcast-based implementation of JCache (i.e. JSR 107) as follows (original sample code):
// Explicitly retrieve the Hazelcast backed javax.cache.spi.CachingProvider
CachingProvider cachingProvider = Caching.getCachingProvider(name);
// Retrieve the javax.cache.CacheManager
CacheManager cacheManager = cachingProvider.getCacheManager("com.hazelcast.cache.impl.HazelcastCachingProvider");

Here is the logged message:
oct. 30, 2014 5:17:59 PM com.hazelcast.cache.impl.HazelcastCachingProvider
WARNING: Could not load client CachingProvider! Fallback to server one... java.lang.ClassNotFoundException: com.hazelcast.client.cache.impl.HazelcastClientCachingProvider

Why it si trying to load HazelcastClientCachingProvider will I asked for com.hazelcast.cache.impl.HazelcastCachingProvider. Am I using the wrong JCache provider?

A: HazelcastCachingProvider is just a delegate to automatically choose either client based or server bases CachingProvider.
For recent 3.4 SNAPSHOTS HazelcastCachingProvider also was moved to com.hazelcast.cache.HazelcastCachingProvider. For the new documentation please see the just drafted documentation version for 3.4: https://github.com/hazelcast/hazelcast/blob/master/hazelcast-documentation/src/JCache.md
You'll see it got waaaaaaay longer :)


text:
Q: psexec logon failure: "unknown user name or bad password." i'm trying to run an interactive commandline on a remote PC in my LAN using
psexec \\192.168.1.103 -u user2 -p pass1234 -c cmd

and I get
Logon failure: unknown user name or bad password.

is there anything I'm missing here? The user is created, I can connect to it with RDP.
The host is Windows XP, and I'm running the commands from Windows 7, where I have psexec.exe.

A: I was able to reproduce your problem and fix it thus:
Do The following and hit enter

Start>Run>secpol.msc

Navigate to

Local Policies>Security Options

Set the policy "Network Access: Sharing and security model for local accounts" to (Just hit OK: Don't close this out as we will be changing it back).

Guest only – local users authenticate
  as Guest

Open a command box and run (Dont close this either)

gpupdate /force

Go back and set the policy "Network Access: Sharing and security model for local accounts" back to

Classic - local users authenticate as
  themselves

Again run

gpupdate /force

It should work now.

A: I'm not sure whether you're working on your own or part of a larger user domain. I had the same issue and resolved it as follows:
psexec \\REMOTEMACHINE -u DOMAIN\USERNAME ...

Basically, I prefaced my username with the domain name.

A: Even though this has already been answered, I thought i would post a quick test i just did with this same error / result.. As i might find it in google in a year or two when i forget.
Simply, trying the standard command as in the question above.. I got the same response.. But ..
If i mapped a network drive or browsed to the c$ share, this would then allow psexec to work...
So this might be a hack/shortcut around things allow for the required network auth on another level...

A: You must ensure the time is synchronized throughout all the machines. If not, psexec will never work on Windows 7 and will report logon failure.

A: So I've tried

Local Policies → Adding Tokens in Registry → Firewall Rules

and I didn't want to disable my antivirus. It turns out that the problem was syntax:
psexec \\192.168.1.7 -u USERNAMEhere -i -p Passwordhere "C:\Users\Username\Desktop\New Folder\x.bat"

It still returned an error 0, but it worked.


text:
Q: Pandas SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame I keep getting the warning in the subject in the following situations:
Step 1:
df.rename(columns={'one':'one_a'}, inplace=True)

Step 2:
df.drop(['one', 'two', 'three'], axis=1, inplace=True)

How do I fix?

A: I had a similar problem and to fix I did the following:
new_df = df.copy()
new_df.rename(columns={'one':'one_a'}, inplace=True)
new_df.drop(['one', 'two', 'three'], axis=1, inplace=True)

Or you can do
df.is_copy = False

You were probably using a copy of your original DF (ex: you were manipulating your DF before that) and that's why you were receiving the warning. More on copy:
why should I make a copy of a data frame in pandas

A: One way around it is to remove inplace=True, then use:
df = df.drop(['one', 'two', 'three'], axis=1)

A: Easiest fix (and probably good programming practice) would be to not do inplace operations, e.g.
df2 = df.rename(columns={'one':'one_a'})

A: if you are work with jupyter notebook you can restart and runall . when i got this error then restart and run and it works fine with same code.
movies.dropna(inplace=True)


text:
Q: Sender tag is always same data (wrong index?) I have the following code for cell button:
    cell.buttonViewLink.addTarget(self, action: "buttonViewLinkAction:", forControlEvents: UIControlEvents.TouchUpInside)
    cell.buttonViewLink.tag = indexPath.item

So when I tap buttonViewLinkAction I get the correct name/image printed in NSLog, no matter which cell is tapped, it's always the correct data. This works great and creates another button:
    //get buttonViewLinkAction and copy to pasteboard
@IBAction func buttonViewLinkAction(sender: UIButton) {
    print("buttonViewLinkAction tapped")
    let face = self.faces[sender.tag]
    if let imageNAME: String = String(face.name){
        print(imageNAME .uppercaseString)
    }
    if let imageURL = NSURL(string:face.image) {
        print(imageURL)
    }

    UIPasteboard.generalPasteboard().string = face.directLink

    let alertView = SCLAlertView()
    alertView.addButton("Add [img] tags", target:self, selector:Selector("imgtagAction:"))
    alertView.showSuccess((face.name), subTitle: "Image link copied to clipboard")

}

But when I tap imgtagAction, I always get the data from cell 1.
    //get imgtagAction click
func imgtagAction(sender: UIButton!) {
    print("imgtagAction tapped")
    let face = self.faces[sender.tag]

    if let imageNAME: String = String(face.name){
        print(imageNAME .uppercaseString)
    }
    if let imageURL = NSURL(string:face.image) {
        print(imageURL)
    }
    UIPasteboard.generalPasteboard().string = "[img]" + face.directLink + "[/img]"
}

What am I doing wrong?

A: As rmaaddy commented you haven't set tag with your button and I think it is may be not possible to set tag to that custom AlertView button action, So I think you need to declare one Int instance property and set its value inside buttonViewLinkAction method and then use that instance inside imgtagAction method like this.
var selectedItem = 0

Now set selectedItem value inside buttonViewLinkAction method.
@IBAction func buttonViewLinkAction(sender: UIButton) {
    self.selectedItem = sender.tag
    //Your other code
}

Now use this selectedItem inside imgtagAction method.
func imgtagAction(sender: UIButton!) {
    let face = self.faces[selectedItem]
}


text:
Q: nodejs catch finish, close, end events Folks,
  I am trying to write an express middleware which will catch finish events, and when a client has received the data and closed the connection.
In the following , only finish is working.   How do i get the events for clients receiving the data, and closing the socket.
function middleW(req, rsp, next){

  rsp.on('finish', function foo() {
    console.log ('FINISH');
  });

  rsp.on('end', function foo() {
    console.log ('END');
  });

  rsp.on('close', function foo() {
    console.log ('CLOSE');
  });

  return next();
}


text:
Q: case-insensitive поиск в строке, Perl В файле есть строка GCAGcBACGCBgC, я хочу посчитать количество GC без учета регистра.
$count = 0;
$count++ while ($string =~ /GC/gi);

Ожидаю в принт получить 4, получаю 2. Что я делаю не так? Ответивший ниже прав, все работает, у меня видимо ошибка в чем-то другом. Вот та часть, где она возникает:
local $/;
open(FILE, "abcd.txt") or die "Can't read file 'filename' [$!]\n";
$document = <FILE>;

$document =~ tr/contig/#/;

$count1 = 0;
$count1++ while ($document =~ />/g);
print $count1 ;

$count2 = 0;
$count2++ while ($document =~ m/[a-zA-Z]/g);

$count3 = 0;
$count3++ while ($document =~ /GC/gi);
print $count3;

Сделал файл, чтобы посмотреть как работает.
>contig_239
AAaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbAAAbbbbbbbbbbbbb
sdsdsdsddddddddddddddddddddddddddddddddddddddsdsd
sdsdsdsdsdsdsssssssssssssssssssssssssssssssssssssds
FGFGFHSKDJSKDJSKDJSKJDasdaldkalsdkalsdkalsdksaldka
>contig_240
GCAGcBACGCBgC
SDDDDDDDDDDDDDDDDDDDDDDDDDDDDSSDSDSDDDDDDDDDDDDDD
SDSDSDSDSDSDSDSDSDSDS

Нужно в $count3 получить 4, потому что "GC" встречается 4 раза в строке GCAGcBACGCBgC и только в этой строке, которя идет после contig_240. Запуская в принт получаю два.


text:
Q: How to get the source node from the dragover event From the event fired from dragover (using jQuery), how to find the source node (element being dragged)?
Data transfer doesn't seem possible per http://www.w3.org/TR/2008/WD-html5-20080610/editing.html#dragover
EDIT:
So after some additional research, it seems like Mozilla supports in through the mozSourceNode property. Any cross browser solutions?

A: What about binding the source to the function and accessing it via this ?
object.addEventOrWhatever(function(){
  source = $(this);
}.bind(source));

A: I know this question is very old, but wanted to offer a simple cross-browser solution I came up with for exactly this problem:
For the draggable element; on dragstart, add a class name (for example "dragging") to the element, and on dragend remove that class name.
This way, in whichever part of the code you need to, you can just get the element which is currently being dragged by that class name.


text:
Q: Test onClick with Jest Mock Function I built a react app where I'm trying to get myself more confortable with testing, yet I'm quite stuck trying to test a button from my component. The documentation is very vague and I have not found any solution to my case.
The onClick method is simply calls a handleClick method like so at Body.js:
  const handleClick = () => {
      console.log('handling click')
  }

  return (

      I'm the body
      {posts &&
        posts.map((post, i) => {
          return (

{post.title}

{post.body}

          );
        })}
      <Button onClick={handleClick}>Get the posts</Button> // this button

  );
};

I'm using mock function in my test like so:
  it('button triggers handleClick', () => {
    const fn = jest.fn();
    let tree = create();
    // console.log(tree.debug());
    // simulate btn click
    const button = tree.root.findByType('button');
    button.props.onClick();
    // verify callback
    console.log(fn.mock);
    expect(fn.mock.calls.length).toBe(1);
  });

But I cannot assert that the click was made.
expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: 0

The handleClick method is working since I'm getting the desired output with console.log when I run the test.
  console.log
    handling click // it works!

      at Object.onClick (src/components/Body.js:9:15)

  console.log
    { calls: [], instances: [], invocationCallOrder: [], results: [] } // fn.mocks log

I'd appreciate any help.
Fernando,


text:
Q: How do I install the python pymorph module? How can I install pymorph module for my code in Ubuntu? I tried the commands below but they didn't work.
sudo apt-get install pymorp
sudo apt-get install python pymorph

The message just said:
E: Unable to locate package pymorph

How can I install pymorph module?

A: As @dufte has pointed out in his comment to the question, pymorph does not exist in the Ubuntu repositories. However, pymorph does exist in PyPI. The best way to install pymorph is to use pip inside a virtualenv; I would avoid using sudo pip because it is best to get apt manage your system packages and not let pip interfere with that. Assuming you are using Ubuntu 16.04 and Python 2, the code to install pymorph properly is:
sudo apt update
sudo apt install virtualenv
cd ~/<desired directory>  # cd to desired directory
virtualenv venv  # create virtualenv named venv for Python 2
source venv/bin/activate  # activate virtualenv
pip install -U pip  # upgrade pip
pip install pymorph

If you are using older versions of Ubuntu, replace apt with apt-get. If you want to use Python 3, replace virtualenv venv with virtualenv venv -p python3.

A: sudo apt-get install pymorph fails because pymorph does not exist as package in the apt sources.
If you want to know whether a package exists or not, you can run apt-cache search [packagename]. In this instance, running apt-cache search pymorph returns nothing.
parto@subroot:~$ apt-cache search pymorph
parto@subroot:~$

To install pymorph, use pip.

pip - A tool for installing and managing Python packages
pip  is  a  Python package installer, recommended for installing Python packages which are not available in the Debian archive.  It can work with version control repositories (currently only Git, Mercurial, and Bazaar repositories), logs output extensively,  and  prevents  partial installs by downloading all requirements before starting installation.

To install the python pymorph module:

*

*Install pip (if not installed)
sudo apt-get install python-pip

*Use pip to install python pymorph
sudo pip install pymorph

Edit
From @Muru's comment, you can also try:
pip install --user pymorph

instead of
sudo pip install pymorph


text:
Q: iOS Charts Double to Int Swift I am using the Charts library found here.
I have a chart that is showing each bar label as a double like 15.0 instead of 15. I hear you have to use valueFormatter to change the values but not sure how to implement it. So far I have:
let format = NumberFormatter()

    format.numberStyle = .none

    let formatter = DefaultValueFormatter(formatter: format)

   BarChartData.setValueFormatter(formatter) // error here

I am getting:

instance member setValueFormatter can not be used on type ChartData

A: Please check you can use like this :
let chartData = BarChartData(dataSet: chartDataSet)

let format = NumberFormatter()
format.numberStyle = .none
let formatter = DefaultValueFormatter(formatter: format)

chartData.setValueFormatter(formatter)


text: Q: How do I live stream with 2 Cameras and 1 MacBook Air? For live streaming purposes, is it possible to input two cameras (DLSR with HDMI out) into a MacBook Air which only has 2 USB-C ports? Is there a USB C device which can do this? Thanks


text:
Q: Rails4: Can't modify frozen hash The Order model:
class Order < ActiveRecord::Base
  has_many :sales, dependent: :destroy, inverse_of: :order
end

has_many Sales:
class Sale < ActiveRecord::Base
  belongs_to :order, inverse_of: :sales
  validates :order, :product, :product_group, :presence => true
  before_create :price

  def price
    mrr = Warehouse.where(:product => self.product).pluck(:mrr).shift.strip.sub(',', '.').to_f
    self.price = mrr * self.quantity.to_f
  end
end

When I destroy an Order, the associated Sales should also be destroyed, but I ran into an error when doing so:
RuntimeError in OrdersController#destroy
Can't modify frozen hash

This line is highlighted: self.price = mrr * self.quantity.to_f.
Destroying all associated Sales records manually step-by-step works without errors. After no Sale is associated anymore, I can destroy the Order record too.
Any Ideas?

A: On the line that gets highlighted you should make sure that sale is not destroyed when updating its price attribute:
self.price = mrr * quantity.to_f unless destroyed? # notice, no need for self before quantity
# or
write_attribute(:price, mrr * quantity.to_f) unless destroyed?

A: I've encountered the same issue and searched for an answer.  Only found the discussion about destroyed;  However I've determined that if I create a new active record (find_or_create_by) and then create a second object dependent on the first active record, i get the same error.  I resolved it by saving the first active Record before creating/modifying the second.  I don't understand why the create is necessary, although I can see why the second record wants the first to exist before it gets saved/modified.

A: I upgraded Rails from 4.1 to 4.2.5 and got this error when tried save object with tags.
In my case trouble was due gem 'acts-as-taggable-on' which should be upgraded to newer version >= 3.4.


text:
Q: VLC how to play all files that contain specific word I would like to play all files in all subdirectories that contain specific term.
I tried it using:
find . -type f | grep Song | vlc

I think I might be misunderstanding how | works, because it doesn't pass grep output to vlc

A: A pipe | connects the standard output of one command to the standard input of another. However AFAIK vlc does not read a list of filenames from standard input - it expects "items" (the names of files, or streams) to be passed as command line arguments. So either:
find . -type f -name '*Song*' -exec vlc {} +

or
find . -type f -name '*Song*' -print0 | xargs -r0 vlc

Refer to the manual pages (man find, man xargs) for details. Note that you don't need grep - you can do a simple pattern match with find itself.


text:
Q: Converting Gridview into CSV Is this possible to take delimeter other than comma for converting into CSV file....because in my scenario my gridview cell contains data with commas.

A: Well the 'C' in CSV does stand for "Comma".
That said, depending on what the purpose/destination of your "CSV" output is, I can see two options:

*

*If your program is the only recipient, use whatever you like. Heck, something like the built in serialises might be easier.

*Otherwise, follow the CSV format and double quote your values.

There is a lot a more useful information in this question, and this one.


text:
Q: WatchConnectivity on Xcode 14 I made a "todo" app, using core data, and want to extend it to apple watch. The main problem is that when I run the simulator, the watch seems to be not connected with iPhone.
I tried to import WatchConnectivity, use WCSession, delegate, and they are all not working because the watch is not getting connected with the phone in the first place.

*

*I am using SwiftUI, but not storyboard

A: One of the reasons why the WCSession might not be working is because you didn't pair the watch and the iPhone simulators.
If you go to Window > Devices and Simulators > Simulators it will let you also add a watch to each iPhone.

Call it a specific name so it's easy to find it to run on it.
You can also open both devices and go in the Watch app on the iPhone, so you can check that they are actually synced.

Usually when you run the app on that specific watch simulator it will automatically install the app also on the iPhone and it will say something like this:

Be also sure to activate the session on both watch and iPhone with:
let session = WCSession.default

if WCSession.isSupported() {
            session.delegate = self
            session.activate()
     }

This article covers some of the most common errors with connectivity, maybe it might help:
https://medium.com/swlh/how-to-use-watchconnectivity-to-send-data-from-phone-to-watch-plus-most-common-errors-793d41976618


text:
Q: SOQL not returning data when there is a record in DB The following code is called from Opportunity trigger. So the flow is

*

*From opportunity trigger call MyTwiMLController.processoutboundCall()

*After the callout it calls the VF page "TwiMLPage" by passing the OppId as parameter in the url

*Then it goes back to controller method getTwiml()

The problem that I am facing is it is not returning any data in the SOQL even if the record exist from getTwiML method. What I am missing here to understand?
Opportunity Trigger
    if (Trigger.isAfter && Trigger.isUpdate) {

    for (Opportunity opp : Trigger.new) {
        if(opp.Status__c == 'QW-RV'){
            TwilioConnectorController twiMLCon = new TwilioConnectorController();
            twiMLCon.processoutboundCall(opp.Id);
         }
    }
}

Controller
    public with sharing class TwilioConnectorController {
    public User rep {get; set;}
    public String callerName {get; set;}
    public List<Opportunity> oppLst{get;set;}

    public String processoutboundCall(String oppId){
        String toPhNum = [select Contact.MobilePhone FROM OpportunityContactRole
                            WHERE OpportunityId = :oppId AND Role='Primary Contact'].Contact.MobilePhone;
        if(String.isNotEmpty(toPhNum)){
            String formattedtoNum = toPhNum.replaceAll('[^0-9]', '');
            String url = 'http://pk-silo.cs29.force.com/TwiMLPage?oppId='+oppId;   //parameter passed to the URL
            Map<String,String> params = new Map<String,String> {
                    'To'   => formattedtoNum,
                    'From' => '+15629916679',
                    'Url' =>    url
            };
            DoCallout(params);
        }
        else{
            Error_Log__c logCallError = new Error_Log__c(Type__c='Twilio Outbound',
                                            Error_Message__c='No valid primary contact Mobile Number.'+' '+'OppId:'+oppId);
            Insert logCallError;
        }
        return null;
    }

    @future(callout=true)
    private static void DoCallout(Map<String, String> params){
        TwilioConfig__c tw = TwilioConfig__c.getInstance('00eF00000013nqJ');
        String account = tw.AccountSid__c;
        String token   = tw.AuthToken__c;
        TwilioRestClient client = new TwilioRestClient(account, token);
        TwilioCall call = client.getAccount().getCalls().create(params);
        system.debug('TwilioCAL LOG' + call);
    }

    public String getTwiml() {
        String oppId1 = ApexPages.currentPage().getParameters().get('oppId');
        System.debug('getTwiml oppId value'+oppId1);
     /*   String toPhNum1 = [select Contact.MobilePhone FROM OpportunityContactRole
        WHERE OpportunityId = :oppId1 AND Role='Primary Contact'].Contact.MobilePhone;
        System.debug('phonenum from Twiml'+toPhNum1);*/
        oppLst = new List<Opportunity>([SELECT ID FROM Opportunity WHERE Id=: oppId1 ]);
        String acntName = [SELECT Account.Name FROM Contact WHERE Id=: oppId1].Account.Name;
        System.debug('Opp list value is'+acntName);
        return null;
    }

}

**VF Page****
    <?xml version="1.0" encoding="UTF-8" ?>
<apex:page sideBar="false"  showHeader="false" action="{!getTwiml}" controller="TwilioConnectorController" contentType="application/xml">
    <Response>
        <Say>You will be connected to the merchant</Say>
        <!--Dial>
            <Number>516-333-7889</Number>
        </Dial-->
    </Response>
</apex:page>

A: Since you are using with sharing in the apex controller so it obeys the principle where the record is shared to the user.
So, if you login with the user and try to access the opportunity from the URL and check if that user has access to the Opportunity record.
It seems user doesn't have access to the Opportunity record and hence it is not returning any data in the SOQL.
Update based on comments
Site page url is sending OpportunityId which is having parenthesis and needs to be removed before putting that in SOQL.


text:
Q: RaiseError (PERL, DBI) equivalent for unixODBC C API? I have a problem executing some stored procedures/functions in INFORMIX DB. I tried with different clients and they were all the same - no one detects errors on executing, instead of this - return empty responses. And this does not work for me.
Finally, I found that PERL DBI has the option to set RaiseError, something like:
{  PrintError => 0, RaiseError => 1 }

And this works perfect. But is there such equivalent (I couldn't find anything, unfortunately) for the unixODBC C API lib?

In addition: I tried the same query with isql and it's the same! No errors, just empty result :\ Maybe it could be some option, that should be configured (in odbc.ini, I guess..) ?

EDIT: Okay, here are some more details:
Version: unixODBC 2.3.0
CREATE FUNCTION "test".NOK_func_k() RETURNING LVARCHAR(1000);
set debug file to '/home/directory_does_not_exists/unknown.log';
trace off;
trace on;
trace off;
return 'result is set here';
END FUNCTION;

CREATE PROCEDURE "test".NOK_proc_k(pDummy SMALLINT)
set debug file to '/home/directory_does_not_exists/unknown.log';
trace off;
trace on;
LET pDummy = 2;
trace off;
END PROCEDURE;

And the results from isql and ODBC C API are the same. Here's more info about the C API:
Executing: execute procedure NOK_proc_k(1)
retcode = SQL_ERROR     SQL_SUCCEEDED( retcode ) = 0
--------------------------------------------------
Executing: execute function NOK_func_k()
retcode = SQL_SUCCESS       SQL_SUCCEEDED( retcode ) = 1
--------------------------------------------------
--------------------------------------------------
Executing: execute function NOK_proc_k(1)
retcode = SQL_ERROR     SQL_SUCCEEDED( retcode ) = 0
--------------------------------------------------
Executing: execute procedure NOK_func_k()
retcode = SQL_SUCCESS       SQL_SUCCEEDED( retcode ) = 1
--------------------------------------------------
--------------------------------------------------
Executing: call NOK_proc_k(1)
retcode = SQL_ERROR     SQL_SUCCEEDED( retcode ) = 0
--------------------------------------------------
Executing: call NOK_func_k()
retcode = SQL_SUCCESS       SQL_SUCCEEDED( retcode ) = 1

All calls to SQLMoreResults return SQL_NO_DATA, all SQLFetch return SQL_ERROR.
Summary - all calls to wrong procedures are fine - error is returned. But if this error is in stored function - no error is detected; instead of this - EMPTY string is returned. Outch!
SQL_SUCCESS_WITH_INFO is not returned anywhere. And it's like this for many other errors (not all, of course, that's just an example here)

And even more! Procedure or function like:
CREATE PROCEDURE "test".nok_proc_k_2() RETURNING LVARCHAR(1000);
DEFINE vNotDefined VARCHAR(10);
LET vNotDefined = current;
END PROCEDURE;

Does not return any error, while a Aqua DB studio returns
Converted value does not fit into the allotted space

ANSWER:
I'll accept bohica'S answer, as it's correct and it answers right about the PERL DBI part. Also, he really helped me (the hit with strace).
Anyway, the real solution is not here. I have posted it in the related question, that is more specific and isolated about the particular case: The same error is detected in stored **procedure**, but not in stored **function**

A: All that RaiseError in Perl does is say that when a DBD, like DBD::ODBC sees an error DBI will call any registered error handlers and call die with that error (depending on what the error handler returned). It is still up to the DBD to signal the error to DBI via set_err method.
I presume your Perl was using DBD::ODBC. DBD::ODBC will simply check the return status of every ODBC API it calls and if it is SQL_SUCCESS_WITH_INFO it calls DBIs set_err saying it is a warning and if it is !SQL_SUCCEEDED it calls set_err saying there is an error (there are some exceptions like SQL_NO_DATA which is not always an error).
If you are saying your Perl dies with the error you are expecting but your C code does not then you must not be checking an ODBC API return or perhaps (since you mention procedures) you are not ensuring you call SQLMoreResults in a loop after SQLExecute on the SQL to call the procedure. Bear in mind some databases execute each insert/select/update in a procedure one at a time and in ODBC you need to call SQLMoreResults to move through each one. If you don't do that your procedure had not completed and hence you may not have hit the error.


text:
Q: UIButton resize with animation I'm creating a menu and I want the buttons to "pop" I guess on the screen. Basically I want to start at 0px dimensions and then go up to the full size of the buttons. I can animate the alpha and the position if I want to but can't do the dimensions and I think its because its an image on the button.
If I do a UIButtonTypeRoundRect you can see the button being animated behind the image but the image is static.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(20, 20, 0, 0);
button.alpha = 0;
[self.view addSubview:button];
CGRect frame = button.frame;
[UIView beginAnimations:@"button" context:nil];
[UIView setAnimationDuration:1];
button.alpha = 1;
frame.size.width += 53;
frame.size.height += 53;
button.frame = frame;
[UIView setAnimationDelegate:self];
[UIView commitAnimations];

So the Alpha works but the resize doesn't. I've also played with stretchableImageWithLeftCapWidth to try and give it context or something but to no avail.
Cheers for your help.

A: Updated for Swift:
You can insert this in whatever IBAction you've got tied to a button to animate it when it's touched.
    // animate button
    // play with the scale (1.25) to adjust to your liking
    yourButton.transform = CGAffineTransformMakeScale(1.25, 1.25)
    yourButton.alpha = 0.0

    UIView.beginAnimations("yourButton", context: nil)
    // play with the animationDuration to adjust to your liking
    UIView.setAnimationDuration(0.25)
    yourButton.transform = CGAffineTransformMakeScale(1.0, 1.0)
    yourButton.alpha =  1.0

A: Could you try using the following code instead?
button.transform = CGAffineTransformMakeScale(1.5,1.5);
button.alpha = 0.0f;

[UIView beginAnimations:@"button" context:nil];
[UIView setAnimationDuration:1];
     button.transform = CGAffineTransformMakeScale(1,1);
     button.alpha = 1.0f;
[UIView commitAnimations];

Your button should start slightly larger and then shrink back down. If this scales properly, just adjust the scalefactor before and after to suit.


text:
Q: View data by id in laravel with ajax I was make create update and delete, but i get error to view data by ID. please help me :
this is my script.js
function dataModal(){
    var tableDatas = $("#datas");
    var route = "http://localhost:8000/dataLowongan";

    $("#datas").empty();
    $.get(route, function(res){
        $(res).each(function(key,value){
            tableDatas.append("
"+value.id+"	"+
                ""+value.judul+"	" +
                "<button value="+value.id+" onClick='EditModal(this);' class='btn btn-primary' data-toggle='modal' data-target='#myModal'>Edit</button>"+
                " <button value="+value.id+" onClick='HapusModal(this);' class='btn btn-danger' data-toggle='modal' data-target='#dellModal'>Hapus</button>"+
                " <button value="+value.id+" onClick='ViewModal(this);' class='btn btn-default' data-toggle='modal' data-target='#viewModalBlade'>View</button>
"
            );
        });
    });
}

this is function for View
function ViewModal(btn){
    var route = "http://localhost:8000/lowongan/"+btn.value+"/edit";

    $.get(route, function(res){
        $("#id").val(res.id);
        $("#judul").val(res.judul);
    });
}

i getting error on this, my modal.blade to view the view datas.

                {{ $datas->judul}}


text:
Q: adding a simple fragment to android app im new to android, and i'm tryigng to add a simple fragment (that holds a listview) to the main activity.
is the fragment suppose to be inside the MainActivity?
i have checked, and most of the problems, and the solutions here looked like it was a version problem (using android.support.app.v4.Fragment), but it doesn't looks like it here.
im pretty sure it's something simple that im missing.
Thanks!
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends Activity{

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

           FragmentManager fragmentManager = getFragmentManager();
           FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
           PlaceholderFragment phf = new PlaceholderFragment();
           fragmentTransaction.add(R.id.main_fragment_container, phf);
           fragmentTransaction.commit();

   }

   public static class PlaceholderFragment extends Fragment {

           public PlaceholderFragment() {

           }

           @Override
           public View onCreateView(LayoutInflater inflater, ViewGroup vg,
                                    Bundle savedInstanceState) {
               View rootView = inflater.inflate(R.layout.fragment_main, vg);

                   ArrayList<String> tempDataArr = new ArrayList<>();
                   tempDataArr.add("TEMP 1");
                   tempDataArr.add("TEMP 2");
                   ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),R.layout.list_item_fnf,R.id.list_item_fnf_textview,tempDataArr);
                   ListView listView = (ListView)rootView.findViewById(R.id.listview_fnf);
                   listView.setAdapter(arrayAdapter);
               return rootView;

           }
       }
}


text:
Q: The memset() function I am a beginner to C/C++, and I came across the following segment of code:
#define MAX_MSG 1000
char *szBuf = new char[MAX_MSG];
char *szBufRaw = new char[MAX_MSG];
memset(szBuf, '\0', strlen(szBuf));
memset(szBufRaw, '\0', strlen(szBufRaw));

I've read the tutorial about memset here:
http://www.java-samples.com/showtutorial.php?tutorialid=591
and I believe the above code is correct, but the original author of the code believes there is a bug within it, could anybody give me a hint?
Thanks in advance.

A: strlen(szBuf)(and strlen(szBufRaw)) will return correct result only on valid strings. You should pass MAX_MSG instead.

A: strlen() looks for the first null value in the array, which means that you won't memset the right amount of bytes in memory.
Use MAX_MSG instead to set the entire array to null.

A: Both char arrays are uninitialized, the use of strlen() on them is undefined behavior. It will not do what you expect.
strlen() walks through a string, given the pointer to its first character, and return the length of the string, that is, until it finds the terminating zero. After you create these arrays with new, they don't contain anything meaningful. these calls may return anything, and may even crash your program.
What you want is to pass the size of the arrays:
memset(szBuf, '\0', MAX_MSG);
memset(szBufRaw, '\0', MAX_MSG);

A: strlen() returns the length of a string given.
The length is defined as the length between the head and the tail whose value is \0.
In the code above, strlen() will not necessarily returns MAX_MSG, because you haven't initialize or set some value yet.
memset(szBuf, '\0', sizeof(szBuf))

will work.

A: strlen will not behave as you expect because it counts the number of bytes before a NUL (0 ascii code) char. What you need is to pass MAX_MSG instead of strlen. By the way, is this homework?

A: Before calling memset, the two buffers szBuf and szBufRaw are uninitialized.  However, to get the length of memory to clear, the code calls strlen on them.  That won't work because the buffers don't contain valid strings.  The code should be clearing MAX_MSG bytes in the buffers instead of using strlen.

A:
memset(szBuf, '\0', strlen(szBuf));

Whats strlen() doing in there? Where are the strings?
The strlen() function returns the number of characters that precede the terminating null
character in a C style string.
memset(szBuf, '\0', MAX_MSG); should work.

A: Uninitialized memory allocated by new won't behave nice with strlen().
It'd be better if one wrote:
memset(szBuf, 0, MAX_MSG * sizeof *szBuf);

You could also skip sizeof *szBuf since it's guaranteed to be 1, but it doesn't hurt.


text:
Q: Magic for undefined function? Is there such a thing?
Some kind of a magic function that allows you to change stuff before the undefined function call error gets thrown?
Like __call, but for normal functions :)

A: I would do the cheking BEFORE calling the method like this:
$obj = new Foo();
$method = "myMethod";

if(is_callable(array($obj, $method)){
    $obj->$method();
}else{
    // Do some stuff
}


text:
Q: Showing $\left(\frac{z+i}{z-i}\right)^n = -1$ implies $z$ is real I have shown the following identity: $$ \frac{1+e^{i \theta}}{1-e^{i \theta}} = \frac{1}{2}\cot\left(\frac{\theta}{2}\right) $$ And I now need to use this to show that the the equation: $$ \left(\frac{z+i}{z-i}\right)^n = -1$$ has $\Im(z) = 0$.
I'm not sure where to get started on this, I have found a way to do it by conjugating the 2nd equation on both sides and showing that z is equal to its own conjugate, however this does not use the original identity, and I'd really like to see how it follows from that.
Any help would be much appreciated.

A: Something is wrong with your identity  as  $$\frac{1+e^{i2t}}{1-e^{2it}}=\frac{1+\cos2t+i\sin2t}{1-\cos2t-i\sin2t}=\frac{2\cos^2t+i2\sin t\cos t}{2\sin^2t-i2\sin t\cos t}$$
$$=\frac{2\cos t(\cos t+i\sin t)}{-2i\sin t(i\sin t+\cos t)}=i\cot t$$
Now using De Moivre's formula , $$\frac{z+i}{z-i}=(-1)^{\frac1n}=e^{\frac{(2r+1)i\pi}n}$$ where $0\le r<n$
Applying componendo and dividendo, $$\frac z{-i}=\frac{e^{\frac{(2r+1)i\pi}n}+1}{e^{\frac{(2r+1)i\pi}n}-1}=i \cot \frac{(2r+1)\pi}{2n}$$
$$\implies z= \cot \frac{(2r+1)\pi}{2n}$$

A: $$
\frac {1+e^{i \theta}}{1-e^{i \theta}} = -\frac {e^{i\theta/2}+e^{-i\theta/2}}{e^{i\theta/2}-e^{-i\theta/2}} = -\frac {2\cos \frac \theta 2}{2i \sin \frac \theta 2} = -\frac 1i \cot \frac \theta 2 = i \cot \frac \theta 2
$$
You can recheck it here.
As for the second part
$$
\left ( \frac {z+i}{z-i}\right )^n = -1 \\
\frac {z+i}{z-i} = e^{\frac {(2k+1)\pi i}n} \\
z + i = (z-i) e^{\frac {(2k+1)\pi i}n} \\
z \left ( 1-e^{\frac {(2k+1)\pi i}n}\right) = -i \left ( 1+e^{\frac {(2k+1)\pi i}n}\right) \\
z = -i\ \left ( \frac {1+e^{\frac {(2k+1)\pi i}n}}{1-e^{\frac {(2k+1)\pi i}n}} \right )
$$
Based on first result
$$
\frac {1+e^{\frac {(2k+1)\pi i}n}}{1-e^{\frac {(2k+1)\pi i}n}} = i \cot \frac {(2k+1)\pi}{2n}
$$
so
$$
z = -i^2 \cot \frac {(2k+1)\pi}{2n} = \cot \frac {(2k+1)\pi}{2n}
$$
which is real, i.e. $\Im(z) = 0$.


text:
Q: how to remove the "x qty" from product options in email confirmation? I want to hide the 'x' + qty in the table of the options of an item in the email order. It shown only when the qty is bigger than 1. I am using advanced custom options.

A: All email phtml files are located in app/design/frontend/base/default/template/email/order/
You should be able to overwrite that template by copying and pasting it into your theme and remove the qty section.


text:
Q: Compressed image is not going to save using angular js I am trying to compress multiple images using angular js, It also showing compressed images before submitting the button but after uploading those images they are going to save with original size but not of compressed size in database
What corrections are needed? plz help...

<form method='POST' action='/dashboard/ti/' enctype='multipart/form-data'>
{% csrf_token %}

Multiple

        <input id="inputImage" name="file" type="file" accept="image/*" ng-model="imageList" image="imageList" resize-max-height="800" resize-max-width="800" resize-quality="0.7" resize-type="image/jpg" multiple="multiple" ng-image-compress/>

<button type="submit">Submit</button>
</form>

here is demo that what i am doing. and now i want save these images to database but original are going... What to do?


text:
Q: Got exceptions after upgrading environment to use JasperReports with Java 8 and new jdt compiler I want to generate JasperReports's report by using my jrxml and Java code.
I'm using Netbeans 8 and jdk8.
I got a lot of exceptions during template compilation:
Exception in thread "main" net.sf.jasperreports.engine.JRException:
Errors were encountered when compiling report expressions class file:
1. java.lang.Integer cannot be resolved or is not a type
                value = new java.lang.Integer(1); //$JR_EXPR_ID=0$
                                <--------------->
java.util.Date cannot be resolved or is not a type
                value = new java.util.Date(); //$JR_EXPR_ID=9$
                            <------------>
java.sql.Connection cannot be resolved or is not a type
                value = ((java.sql.Connection)parameter_REPORT_CONNECTION.getValue()); //$JR_EXPR_ID=21$
                          <----------------->

I've already added jdt jar files.
The full list of jar files:

*

*org.eclipse.jdt.core-3.7.1

*jdtcore-3.1.0

*org.eclipse.jdt.core-3.11.1.v20150902-1521

*jasper-compiler-jdt-5.5.9

*jtds-1.3.1

*jdt-0.15.0

How to fix this issue?

A: only jasper-compiler-jdt-5.5.9.jar is required. above listed .jar files are not necessary.
i add new jasper library but not removed old jar.
so please remove old jar first than add latest version of jar.


text:
Q: Next Js showing index of build folder when using serve i was trying to run build folder of next js , in react js when i run serve build it works perfectly. but in next js it just shows plain index of files in build folder..

What should i do to get proper results rather than index?

A: serve only supports serving a static build of a site. So to build a static site in next.js you need to edit your package.json file like that:
"scripts": {
  "build": "next build && next export"
}

Then you can try npm run build to generate the static build in the out folder which you can serve easily via serve out command.
Quoting from nextjs site @ https://nextjs.org/docs/advanced-features/static-html-export :

next export allows you to export your Next.js application to static HTML, which can be run standalone without the need of a Node.js server. It is recommended to only use next export if you don't need any of the unsupported features requiring a server.

Thanks.


text:
Q: Inserting figures in triangle I am trying to insert small icons (figures.jpg/png) in a triangle. I have this code:
\documentclass[a4paper,12pt]{article}
\usepackage{tikz}
\usepackage{pgf}
\usepackage[english]{babel}
\usepackage{graphicx}
\definecolor{bluedeep}{RGB}{0, 13, 51}
\begin{document}

\begin{tikzpicture}
\draw[color=bluedeep,line width=0.5mm] (0,6) -- (7,6) -- (7,8) -- (0,8) -- (0,6);
\draw[color=bluedeep,line width=0.5mm] (0,4) -- (7,4) -- (7,6) -- (0,6) -- (0,4);
\draw[color=bluedeep,line width=0.5mm] (0,2) -- (7,2) -- (7,4) -- (0,4) -- (0,2);
\draw[color=bluedeep,line width=0.5mm] (0,0) -- (7,0) -- (7,2) -- (0,2) -- (0,0);

\end{tikzpicture}

\end{document}

which gives the following result:

I want to have a figure like this:

The small icon encircled with black pen is a figure on the hard disk that I have to add using \includegraphics. For your sake just pick any icon you want but it has to be added using \includegraphics because in my case I have specific icons to add to these boxes.
Additionally all small rectangles should have a label just as I have shown in the figure by encircling using red pen.
Thank you in anticipation.

A: You can use \includegraphics in a \node, e.g. \node at (x,y) {\includegraphics{filename}};, and knowing that it's just a matter of picking the right coordinates.
I used some loops to add text and images, if all icons are different, and the positions are not meant to be regular, use separate \node commands, with appropriate coordinates.

\documentclass[a4paper,12pt]{article}
\usepackage{tikz} % loads pgf and graphicx
\usepackage[english]{babel}
\definecolor{bluedeep}{RGB}{0, 13, 51}
\begin{document}

\begin{tikzpicture}
\draw [bluedeep, line width=0.5mm] (0,0) rectangle (7,8);
\foreach \y in {2,4,6}
   \draw (0,\y) -- (7,\y);

\foreach [count=\i] \txt in {
  Text A,
  Text B,
  Text C,
  Text D}
  \node[below] at (3.5,\i*2) {\txt};

\foreach \y in {1,3,5,7}
  {
   \node at (1.5,\y) {\includegraphics[width=1cm]{example-image-a}};
   \node at (3.5,\y) {\includegraphics[width=1cm]{example-image-b}};
   \node at (5.5,\y) {\includegraphics[width=1cm]{example-image-c}};
  }

\end{tikzpicture}
\end{document}


text:
Q: cannot turn on Wi-Fi and hotspot at the same time I have a Redmi 9 (LAVA) android phone. I'm using custom ROMs and I just upgraded my android 12 custom ROM to android 13. Now I only have one problem. I cannot turn on wifi and hotspot at the same time as before. At first I thought it was because of S vendor firmware, so I reinstall R vendor firmware and after hours of searching I found an android 13 Custom ROM that runs on R vendor firmware. but I still have that problem. Does anyone know how to fix it? In older androids like 12 or 11, I don't have this problem in both customs and stock ROM.
Some of those ROMs that I installed and had this problem:
Project Elixir official build
Pixel Experience official build
LineAge OS unofficial android 13 build that can be installed on R vendor firmware


text:
Q: Merging two Data Frames using Fuzzy/Approximate String Matching in R DESCRIPTION
I have two datasets with information that I need to merge. The only common fields that I have are strings that do not perfectly match and a numerical field that can be substantially different
The only way to explain the problem is to show you the data. Here is a.csv and b.csv. I am trying to merge B to A.
There are three fields in B and four in A. Company Name (File A Only), Fund Name, Asset Class, and Assets. So far, my focus has been on attempting to match the Fund Names by replacing words or parts of the strings to create exact matches and then using:
a <- read.table(file = "http://bertelsen.ca/R/a.csv",header=TRUE, sep=",", na.strings=F, strip.white=T, blank.lines.skip=F, stringsAsFactors=T)
b <- read.table(file = "http://bertelsen.ca/R/b.csv",header=TRUE, sep=",", na.strings=F, strip.white=T, blank.lines.skip=F, stringsAsFactors=T)
merge(a,b, by="Fund.Name")

However, this only brings me to about 30% matching. The rest I have to do by hand.
Assets is a numerical field that is not always correct in either and can vary wildly if the fund has low assets. Asset Class is a string field that is "generally" the same in both files, however, there are discrepancies.
Adding to the complication are the different series of funds, in File B. For example:

AGF Canadian Value
AGF Canadian Value-D

In these cases, I have to choose the one that is not seried, or choose the one that is called "A", "-A", or "Advisor" as the match.
QUESTION
What would you say is the best approach? This excercise is something that I have to do on a monthly basis and matching them manually is incredibly time consuming. Examples of code would be instrumental.
IDEAS
One method that I think may work is normalizing the strings based on the first capitalized letter of each word in the string. But I haven't been able to figure out how to pull that off using R.
Another method I considered was creating an index of matches based on a combination of assets, fund name, asset class and company. But again, I'm not sure how to do this with R. Or, for that matter, if it's even possible.
Examples of code, comments, thoughts and direction are greatly appreciated!

A: One quick suggestion: try to do some matching on the different fields separately before using merge.  The simplest approach is with the pmatch function, although R has no shortage of text matching functions (e.g. agrep).  Here's a simple example:
pmatch(c("med", "mod"), c("mean", "median", "mode"))

For your dataset, this matches all the fund names out of a:
> nrow(merge(a,b,x.by="Fund.Name", y.by="Fund.name"))
[1] 58
> length(which(!is.na(pmatch(a$Fund.Name, b$Fund.name))))
[1] 238

Once you create matches, you can easily merge them together using those instead.

A: Approximate string matching is not a good idea since an incorrect match would invalidate the whole analysis. If the names from each source is the same each time, then building indexes seems the best option to me too. This is easily done in R:
Suppose you have the data:
a<-data.frame(name=c('Ace','Bayes'),price=c(10,13))
b<-data.frame(name=c('Ace Co.','Bayes Inc.'),qty=c(9,99))

Build an index of names for each source one time, perhaps using pmatch etc. as a starting point and then validating manually.
a.idx<-data.frame(name=c('Ace','Bayes'),idx=c(1,2))
b.idx<-data.frame(name=c('Ace Co.','Bayes Inc.'), idx=c(1,2))

Then for each run merge using:
a.rich<-merge(a,a.idx,by="name")
b.rich<-merge(b,b.idx,by="name")
merge(a.rich,b.rich,by="idx")

Which would give us:
  idx name.x price     name.y qty
1   1    Ace    10    Ace Co.   9
2   2  Bayes    13 Bayes Inc.  99

A: It's highly recommended to use the dgrtwo/fuzzyjoin package.

stringdist_inner_join(a,b, by="Fund.Name")

A: I'm a Canada local as well, recognize the fund names.
This is a difficult one as each of the data providers picks their own form for the individual fund names. Some use different structure like all end in either Fund or Class others are all over the place. Each seems to choose their own short-forms as well and these change regularly.
That's why so many people like you are doing this by hand on a regular basis. Some of the consulting firms do list indexes to link various sources, not sure if you've explored that route?
As Shane and Marek pointed out this is a matching task more than a straight join. Many companies are struggling with this one. I'm in the middle of my work on this...
Jay


text:
Q: Force NuGet to reference a .net framework 4.0 assembly in a 4.5 project? I have two projects in my solution--one targets .net 4.0, the other targets .net 4.5.  They both reference the same NuGet package which contains both 4.0 and 4.5 binaries.
How can I get NuGet to reference the same version--4.0--in both projects?

A: You can exclude the folder of the framework that you don't want to use (ExcludeAssets), and edit the PackageTargetFallback in your project.
In your project's csproj file:
<PackageTargetFallback Condition="'$(TargetFramework)'=='net45'">
    $(PackageTargetFallback);net40
</PackageTargetFallback >

When referencing the package:
<PackageReference Include={package-ID} Version={version} ExcludeAssets="lib/$(TargetFramework)"/>

This way the package won't bring the binaries that you don't want, and the ones you want will be compatible.
Note: Taking dlls with a different target framework is not recommended.


text:
Q: MYSQL after update trigger I am new to database trigger. I really have no idea why i cant update the Label if the Quantity more than equal to 1000
CREATE TRIGGER TRG_UPDATE_STATUS
AFTER UPDATE ON product
FOR EACH ROW
  BEGIN
    IF NEW.QuantitySold >= 1000 THEN
    SET NEW.Label = 'BestSeller'
    END IF
  END

Here is the trigger I have.

A: You can only make persistent changes to NEW in a before row trigger. An after trigger doesn't fire until the record has already been written to the table.
To change the data that will be written to the table, you must use a before row trigger. Changing NEW in an after row trigger is possible, but pointless, since the contents of NEW get written to the table before an after trigger executes, as is explained in the documentation.


text:
Q: Caused by: java.lang.NoClassDefFoundError: Could not initialize class io.confluent.kafka.serializers.KafkaAvroSerializerConfig since 6.0.0 im working on a flink (v.1.13.2) application which should publish some objects to my Kafka broker.
For schema validation I use the Confluent Schema Registry.
I previously used the library in version 5.2.0 (also tried other 5.x.x versions):
        <dependency>
            <groupId>io.confluent</groupId>
            <artifactId>kafka-avro-serializer</artifactId>
            <!--<version>5.x.x</version>-->
            <version>6.2.0</version>
        </dependency>

This seems to work but there was a strange behaviour while registering the schema to the registry. The schema was just ""bytes"" After investigation I found out that the suspect part in 'AvroSchemaUtils' was changed.
https://github.com/confluentinc/schema-registry/blob/a2f80f30d6713c50ee54c47885bcde2945932660/client/src/main/java/io/confluent/kafka/schemaregistry/avro/AvroSchemaUtils.java#L88
So I've tryed to update the library to the next working version.
After I updated to 6.x.x. I've got the following error:
Caused by: java.lang.NoClassDefFoundError: Could not initialize class io.confluent.kafka.serializers.KafkaAvroSerializerConfig
    at io.confluent.kafka.serializers.KafkaAvroSerializer.configure(KafkaAvroSerializer.java:50)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:369)
    ... 23 more

How to find out what wrong here?

A: This may be the problem. After Kafka Avro Serializer is upgraded, the dependent kafka client is upgraded from kafka_2.12 to kafka_2.13
https://mvnrepository.com/artifact/io.confluent/kafka-avro-serializer/6.2.0


text:
Q: How to create a folder in the AppDataDirectory for a Dotnet Maui app? With UWP one would use ApplicationData.Current.LocalFolder.CreateFolderAsync().
I can find no maui equivalent. The objective is to have seperate user folders (ie user1, user2) within the app data directory.

A: Have you checked the official document about the file system in the maui?
For the windows platform in the maui:

FileSystem.AppDataDirectory
Returns the LocalFolder directory that is backed up to the cloud.

You can try to create the user folder by the following code:
string mainDir =System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "user1") ;
System.IO.Directory.CreateDirectory(mainDir);


text:
Q: Update Activity UI from a running service I currently have a running service that receives messages from sockets every time another user  sends someone a message. Now in the activity I can easily call a dialog to display a notice that a message has been received, however I want to do that from the running service. How can I get about with this?
Here is my running service.
public class MyService extends Service implements ChatCallbackAdapter {

    public StartSocket connect;
    public static Context mContent;
    private ConnectSocket connectsocket;
    final Context context = this;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

     @Override
     public void onStart(Intent intent, int startId) {
        System.out.println("Service is running");
        connectsocket= new ConnectSocket(this);
        connectsocket.start();
        connect=new StartSocket();
    }

    public void startNotification(){
        Intent intent = new Intent(this, ReceiveNotification.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Build notification
        // Actions are just fake
        Notification noti = new Notification.Builder(this)
            .setContentTitle("Received a message")
            .setContentText("Subject").setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .addAction(R.drawable.ic_launcher, "Rply", pIntent)
            .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Hide the notification after its selected
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, noti);
    }

    @Override
    public void callback(JSONArray data) throws JSONException {
        // TODO Auto-generated method stub

    }

    @Override
    public void on(String event, JSONObject data) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMessage(String message) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMessage(JSONObject json) {
        // TODO Auto-generated method stub

    }

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

    }

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

    }

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

    }

    @Override
    public void onMessageReceived(Message m) {
        // TODO Auto-generated method stub
        System.out.println("Received a message in service");
        if(m.status.equals("ready")){
            connectsocket.login(SaveSharedPreference.getUserName(getApplicationContext()), SaveSharedPreference.getUserId(getApplicationContext()));
            connectsocket.subscribe();
        }
        if(m.status.equals("message")){
            //getMsg(m.msg, m.name);
            startNotification();
            System.out.println("Received a message "+m.msg+" and a name "+m.name);
            final String name=m.name;
            final String pid=m.pid;
            final String msg=m.msg;

            //Intent intenter=new Intent(TabExercise.this, CreateNotification.class);
            //startActivity(intenter);

            //runOnUiThread(new Runnable(){

            //public void run(){
            //Handler handler = new Handler(Looper.getMainLooper());

             AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);
             alertDialogBuilder.setTitle(name+" just sent you a message");
             alertDialogBuilder.setMessage("Click yes to go to the message");
             alertDialogBuilder

                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        Intent inte=new Intent(MyService.this, Chat.class);
                        Bundle extras=new Bundle();
                        extras.putString("name", name);
                        extras.putString("pid", pid);
                        extras.putString("msg", msg);
                        inte.putExtras(extras);
                        startActivity(inte);

                        dialog.cancel();
                    }
                  })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            //}
            //});

        }
    }

}

A: You have 2 options:

*

*Use Messenger Pattern as explained in documentation here.

*Use LocalBroadcastManager to send out a broadcast from service, and make the target activity implement BroadcastReceiver to listen to that broadcast.
An advantage the Messenger have is that service can select to notify one particular messenger of all its clients.


text:
Q: Generate an XML output from PHP I have check many sample codes but still struggling to make mine work properly. I am trying to generate an XML output from my PHP script.
login.php
<?php

    mysql_connect("localhost", "root", "") or die("cannot connect");
    mysql_select_db("ConquestOfLancaster") or die("cannot select DB");

    $username = $_REQUEST['username'];
    $password = sha1($_REQUEST['password']);

    $username = mysql_real_escape_string($username);

    $domDoc = new DOMDocument;
    $rootElt = $domDoc->createElement('root');
    $rootNode = $domDoc->appendChild($rootElt);

    $sql = "SELECT user_id, user_name FROM tbl_user WHERE user_name='$username' and user_pass='$password'";
    $result = mysql_query($sql);

    $count=mysql_num_rows($result);

    if($count > 0){

        //echo("welcome");
        $rootAtr = $domDoc->createAttribute('success');
        $rootAtrVal = $domDoc->createTextNode('TRUE');
        $rootAtr->AppendChild($rootAtrVal);
        $rootElt->AppendChild($rootAtr);

        $subElt = $domDoc->createElement('username');
        $subNode = $rootNode->appendChild($subElt);

        $textNode = $domDoc->createTextNode($username);
        $subNode->appendChild($textNode);

        echo htmlentities($domDoc->saveXML());
    } else{

        //echo("not exist");
        $rootAtr = $domDoc->createAttribute('success');
        $rootAtrVal = $domDoc->createTextNode('FALSE');
        $rootAtr->AppendChild($rootAtrVal);
        $rootElt->AppendChild($rootAtr);

        echo htmlentities($domDoc->saveXML());
    }

?>

and the output on browser is
<?xml version="1.0"?> <root success="TRUE"><username>user1</username></root>

My major problem is that my iOS app that interact with this PHP can't parse this result. What I am doing wrong?

A: Did you try to take out htmlentities?
As what you send is :
<xml version ...

not
<?xml version="1.0"?> <root success="TRUE"><username>user1</username></root>

as you think