text:
Q: During DC restoration of a video signal how is the first sync pulse detected? DC restoration of an AC coupled video signal can be performed by clamping to
some reference voltage, during the horizontal sync periods of the video. This
all seems fine in a running system, when the hsync is detected, clamp to the
reference for a short time and everything runs smoothly.
My question is: How is the first sync detected?
Without having DC restored the signal when the circuit starts operating, isn't
the ADC's output unreliable, hence the sync pulses can't be detected?
In fact, the input to the ADC may well be out of specification: Consider the
case of driving an
AD9200,
with a 1v peak to peak AC coupled video signal. The absolute minimum voltage of
the analog sense pin (relative to analog ground) in this chip is -0.3v, with an
unrestored video signal isn't it quite possible that a -0.5v is present on the
analog sense pin? This could be prevented by adding a diode to ground to
maintain a positive difference between ground and the analog sense pin; is this
commonly done?
For reference there exist ICs to perform sync detection, for example the
LM1881. Is it necessary to use
one of these ICs or equivalent circuitry to detect sync pulses prior to any
ADC, or can a more simple solution help with the clamp-bootstrapping?

A: You're over-thinking this.
The Wikipedia article on Analog television has a lot more detail, but basically the sync pulses are the most negative (or most positive if the signal is inverted) voltage that appears at any time. Therefore, a simple peak-detector circuit is all that is needed to find them, and a "slicer" (comparator) separates them from anything else in the video stream by establishing a threshold that is slightly below the peak.
This dates from the early days of analog broadcast TV, where the AGC circuits depended on the sync pulses of the inverted video signal being at a constant (maximum) level, regardless of the actual video content.
Once you have sync, it is straightforward to sample within the front/back porch intervals to get the reference black level.


text:
Q: DataTable Bootstrap is not working with AngularJs I'm trying to use DataTable Bootstrap with AngularJs, but DataTable works like there is no data in the table. In the code below, I've got two tables. The first one uses AngularJs and the second is only plain HTML.
What do I need to do to make the first table work like the second?
Thanks, People!

<!DOCTYPE html>

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />

     Name
     Country

     {{x.Name}}
     {{x.Country}}	>

     Rendering engine
     Browser
     Platform(s)
     Engine version
     CSS grade

     Trident
     Internet Explorer 4.0
     Win 95+
     4
     X

     Trident
     Internet Explorer 5.0
     Win 95+
     5
     C

     Trident
     Internet Explorer 5.5
     Win 95+
     5.5
     A

     Trident
     Internet Explorer 6
     Win 98+
     6
     A

     Trident
     Internet Explorer 7
     Win XP SP2+
     7
     A

     Trident
     AOL browser (AOL desktop)
     Win XP
     6
     A

     Gecko
     Firefox 1.0
     Win 98+ / OSX.2+
     1.7
     A

     Gecko
     Firefox 1.5
     Win 98+ / OSX.2+
     1.8
     A

     Gecko
     Firefox 2.0
     Win 98+ / OSX.2+
     1.8
     A

     Gecko
     Firefox 3.0
     Win 2k+ / OSX.3+
     1.9
     A

     Gecko
     Camino 1.0
     OSX.2+
     1.8
     A

     Gecko
     Camino 1.5
     OSX.3+
     1.8
     A

     Gecko
     Netscape 7.2
     Win 95+ / Mac OS 8.6-9.2
     1.7
     A

     Gecko
     Netscape Browser 8
     Win 98SE+
     1.7
     A

     Gecko
     Netscape Navigator 9
     Win 98+ / OSX.2+
     1.8
     A

     Gecko
     Mozilla 1.0
     Win 95+ / OSX.1+
     1
     A

     Gecko
     Mozilla 1.1
     Win 95+ / OSX.1+
     1.1
     A

     Gecko
     Mozilla 1.2
     Win 95+ / OSX.1+
     1.2
     A

     Gecko
     Mozilla 1.3
     Win 95+ / OSX.1+
     1.3
     A

     Gecko
     Mozilla 1.4
     Win 95+ / OSX.1+
     1.4
     A

     Gecko
     Mozilla 1.5
     Win 95+ / OSX.1+
     1.5
     A

     Gecko
     Mozilla 1.6
     Win 95+ / OSX.1+
     1.6
     A

     Gecko
     Mozilla 1.7
     Win 98+ / OSX.1+
     1.7
     A

     Gecko
     Mozilla 1.8
     Win 98+ / OSX.1+
     1.8
     A

     Gecko
     Seamonkey 1.1
     Win 98+ / OSX.2+
     1.8
     A

     Gecko
     Epiphany 2.20
     Gnome
     1.8
     A

     Webkit
     Safari 1.2
     OSX.3
     125.5
     A

     Webkit
     Safari 1.3
     OSX.3
     312.8
     A

     Webkit
     Safari 2.0
     OSX.4+
     419.3
     A

     Webkit
     Safari 3.0
     OSX.4+
     522.1
     A

     Webkit
     OmniWeb 5.5
     OSX.4+
     420
     A

     Webkit
     iPod Touch / iPhone
     iPod
     420.1
     A

     Webkit
     S60
     S60
     413
     A

     Presto
     Opera 7.0
     Win 95+ / OSX.1+
     -
     A

     Presto
     Opera 7.5
     Win 95+ / OSX.2+
     -
     A

     Presto
     Opera 8.0
     Win 95+ / OSX.2+
     -
     A

     Presto
     Opera 8.5
     Win 95+ / OSX.2+
     -
     A

     Presto
     Opera 9.0
     Win 95+ / OSX.3+
     -
     A

     Presto
     Opera 9.2
     Win 88+ / OSX.3+
     -
     A

     Presto
     Opera 9.5
     Win 88+ / OSX.3+
     -
     A

     Presto
     Opera for Wii
     Wii
     -
     A

     Presto
     Nokia N800
     N800
     -
     A

     Presto
     Nintendo DS browser
     Nintendo DS
     8.5
     C/A1

     KHTML
     Konqureror 3.1
     KDE 3.1
     3.1
     C

     KHTML
     Konqureror 3.3
     KDE 3.3
     3.3
     A

     KHTML
     Konqureror 3.5
     KDE 3.5
     3.5
     A

     Tasman
     Internet Explorer 4.5
     Mac OS 8-9
     -
     X

     Tasman
     Internet Explorer 5.1
     Mac OS 7.6-9
     1
     C

     Tasman
     Internet Explorer 5.2
     Mac OS 8-X
     1
     C

     Misc
     NetFront 3.1
     Embedded devices
     -
     C

     Misc
     NetFront 3.4
     Embedded devices
     -
     A

     Misc
     Dillo 0.8
     Embedded devices
     -
     X

     Misc
     Links
     Text only
     -
     X

     Misc
     Lynx
     Text only
     -
     X

     Misc
     IE Mobile
     Windows Mobile 6
     -
     C

     Misc
     PSP browser
     PSP
     -
     C

     Other browsers
     All others
     -
     -
     U

     Rendering engine
     Browser
     Platform(s)
     Engine version
     CSS grade

A: I solved my problem using the code below. The filtering, pagination and sorting are working good.
Download angular-datatable and put angular-datatables.min.js file in your project as I did in the line

        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <link rel="stylesheet" href="http://cdn.datatables.net/1.10.7/css/jquery.dataTables.css">

                        Name
                        City
                        Country

                        {{name.Name}}
                        {{name.City}}
                        {{name.Country}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to theme a preference dialog? I am using a custom theme for dialogs in my app.
The custom theme applies to the alert dialogs just fine.
But the theme does not apply on the preference dialogs like ListPreference, CheckboxPreference etc.
Currently i am applying the dialog theme using the materialAlertDialogTheme attribute like this:
Main app theme:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:navigationBarColor">?attr/colorPrimary</item>
    <item name="android:windowTranslucentStatus">true</item>

    <!-- Material Dialog theme -->
    <item name="materialAlertDialogTheme">@style/ThemeOverlay.App.MaterialAlertDialog</item>
</style>

MaterialDialog styles:
<!-- Styles for Material Dialogs -->
<style name="ThemeOverlay.App.MaterialAlertDialog" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="colorSurface">@android:color/white</item>
    <item name="alertDialogStyle">@style/MaterialAlertDialog.App</item>
    <item name="materialAlertDialogTitleTextStyle">@style/MaterialAlertDialog.App.Title.Text</item>
    <item name="buttonBarPositiveButtonStyle">@style/Widget.App.PositiveButton</item>
</style>

<style name="MaterialAlertDialog.App" parent="MaterialAlertDialog.MaterialComponents">
    <item name="shapeAppearance">@style/ShapeAppearance.App.MediumComponent</item>
</style>

<style name="MaterialAlertDialog.App.Title.Text" parent="MaterialAlertDialog.MaterialComponents.Title.Text">
    <item name="android:textStyle">bold</item>
</style>

<style name="Widget.App.PositiveButton" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="materialThemeOverlay">@style/ThemeOverlay.App.Button</item>
    <item name="shapeAppearance">@style/ShapeAppearance.App.SmallComponent</item>
    <item name="android:textAllCaps">false</item>
</style>

<style name="ThemeOverlay.App.Button" parent="">
    <item name="colorPrimary">@android:color/black</item>
</style>

<style name="ShapeAppearance.App.MediumComponent" parent="ShapeAppearance.MaterialComponents.MediumComponent">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">8dp</item>
</style>

<style name="ShapeAppearance.App.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">4dp</item>
</style>

Here is a dialog perfectly getting themed:

And here is a preference dialog which is not getting themed (notice the corners):

I have also tried setting alertDialog attribute in the main theme, but its not working.
Any suggestions?

A: What I needed to resolve this issue was to add
<item name="alertDialogTheme">@style/AppTheme.AlertDialogTheme</item>

to my base style and
<style name="AppTheme.AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="dialogCornerRadius">20dp</item>
</style>

as a style. Sad that this made my whole AlertDialog.Builder to MaterialAlertDialogBuilder migration somehow pointless (at least in the cases cornerFamily is rounded), hopefully we will see a better integration between preferences and material theme in future.
reference: https://www.reddit.com/r/androiddev/comments/dg8jfo/styling_androidx_preference_dialogs_using/


text:
Q: How to get properties from an object without initializing or constructing the object It don't sound like something that should be possible, but I'd like to ask prior to writing it off.
I am writing an app with a plugin system, I would like to get the properties contained inside the plugin class prior to initializing or constructing it
Interface:
public interface IMPlugin
{
    string PluginName { get; }
    string PluginSafeName { get; }
    string PluginDescription { get; }
    Version PluginVersion { get; }
    string PluginAuthorName { get; }

    [DefaultValue(null)]
    string PluginAuthorEmail { get; }

    [DefaultValue(null)]
    string PluginAuthorURL { get; }

    [DefaultValue(false)]
    bool PluginActive { get; set; }
    /// <summary>
    /// Plugin ID issued by InputMapper. Used for updates. </summary>
    int PluginID { get; }
}

Plugin:
   public class InputMonitor : IMPlugin,ApplicationPlugin
    {
        public string PluginName { get { return "My Plugin"; } }
        public string PluginSafeName { get { return "MyPlugin"; } }
        public string PluginDescription { get { return "My Plugin."; } }
        public Version PluginVersion { get { return new Version("0.1.0.0"); } }
        public string PluginAuthorName { get { return "John Doe"; } }
        public string PluginAuthorEmail { get { return "foo@bar.com"; } }
        public string PluginAuthorURL { get { return ""; } }
        public int PluginID { get { return 0; } }

        public bool PluginActive { get; set; }

        public InputMonitor()
        {

        }
    }

My issue is I want my application to be able to retrieve the plugin info prior to initializing it so users can activate and deactivate plugins at will but the details of the plugin still be visible in a plugin browser. But I don't want to have to rely on the plugin developers to not do anything in their constructor and only put their code in other interfaced methods.
Can a object be initialized and forcibly have its constructor ignored, or is there something to disallow constructors all together?

A: It sounds like your plugins should be configured via attributes rather than via exposing properties:
[Plugin(Name = "My Plugin", SafeName = "MyPlugin" ...)]
public class InputMonitor

You can access the attributes via reflection without creating an instance of the class.
After all, this is metadata about the type - not information about any one instance of the type.

A: Initializing a class and calling its constructor is the same thing.
Either you construct an instance of your plugin class just to read its properties and throw it away afterwards.
Or
You have a second helper/describer class. (which I understood you don't want)


text:
Q: 404 Page wont show / no .htaccess Wordpress I want to show my 404 error page when ever someone gets on a non working / non created page. After a long time of searching on the web I couldnt find any solution so I post one myself. I dont have any .htaccess file either i created it filled it in but in my FTP it kept saying nothing was safed in there and it didnt show any bytes so thats something im also worried of.
So how can i get my .htaccess file to work and show my 404 Error page template? I followed all the steps to make a 404.php file but i dont mind it to be redirected to the same template I made for it but then as a page any of those solutions is fine.

A: You've got some rewrite rules in your .htaccess file that are preventing a 404 error from every truly happening...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

That basically states that if the requested resource is neither a file nor a directory (basically a 404 error), redirect to /index.php
Try this in your .htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# delete the line below to have /index.php/anything trigger a 404
RewriteRule ^index\.php$ - [L]

</IfModule>
# END WordPress

#404 redirect
ErrorDocument 404 /httpdocs/wp-content/themes/avian/404.php

Note
This may make Wordpress quite unhappy however, I'm not sure how it uses internal routing, it may rely on breaking 404s to determine which pages to load by using fake (RESTful) URLs - reinstating 404 errors make cause Wordpress to stop working properly ... I am, however, no expert on it having barely ever touched it.


text:
Q: Scala combinations function not terminating I need to generate the combinations for a list of 30,000 items using scalas combinations method on a stream / list
1 to 30000.toStream.combinations(2).size

This function never completes. When I try the same operation in python
r = list(range(1,30000))
z = itertools.combinations(r, 2)
%time sum(1 for _ in z)

The operation completes in 26.2 seconds.
Whats going on here? How can I generate the combinations of a very large list in scala?

A: @TomasMikula provided an alternative, I was interested to see why combinations was inefficient in generating the result.
A quick look using Mission Control and Flight Recorder revealed the problem:

The CombinationItr iterator invokes IndexedSeqOptimized.slice each iteration of next(). ArrayBuilder creates a new builder each time it runs with number of elements it needs to iterate, which means it will allocate 30,000 Array[Int], each of them containing n - 1 elements, causing a total of 11.10GB in a 1 minute sample. This causes massive amounts of GC pressure and is generally not very effecient.

A: I don't know why the implementation in stdlib takes so long. However, this straightforward implementation (specialized to pairs and Lists), is comparable to the Python one:
def combinations2[A](l: List[A]): Iterator[(A, A)] =
  l.tails.flatMap(_ match {
    case h :: t => t.iterator.map((h, _))
    case Nil => Iterator.empty
  })

Then
scala> {
     |   val t0 = System.nanoTime
     |   val res = combinations2((1 to 30000).toList).size
     |   val secs = (System.nanoTime - t0) / 1000000.0
     |   s"$res (computed in $secs seconds)"
     | }
res11: String = 449985000 (computed in 24992.487638 seconds)


text:
Q: Form validation not working in Spring MVC I am new for Spring MVC. I need to validate the form with the help of <Spring:bind> tag. But it is not validating the input fields. please help me.
Student.java
public class Student {

    @Size(min=2,max=30)
    private String studentName;

    @NotNull
    private String studentHobby;

    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentHobby() {
        return studentHobby;
    }
    public void setStudentHobby(String studentHobby) {
        this.studentHobby = studentHobby;
    }
}

StudentController.java
@Controller
public class StudentController {

    @RequestMapping(value="/admissionForm.html", method = RequestMethod.GET)
    public ModelAndView getAdmissionForm() {
        ModelAndView model = new ModelAndView("AdmissionForm");
        model.addObject("student1",new Student());
        return model;
    }

    @RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
    public ModelAndView submitAdmissionForm(@Valid @ModelAttribute("student1") Student student1,BindingResult result) {

        if (result.hasErrors()) {
            ModelAndView model1 = new ModelAndView("AdmissionForm");
            return model1;
        }
        ModelAndView model = new ModelAndView("AdmissionSuccess");
        return model;
    }

}

Spring-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

  <context:component-scan base-package="com.ram.StudentController" />
  <mvc:annotation-driven/>

  <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
 </bean>

 <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

        <property name="basename" value="/WEB-INF/studentmessages" />
    </bean>
</beans>

AdmissionForm.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

User Registration

    <form action="/FirstSpringMVCProject/submitAdmissionForm.html"
        method="post">

        <spring:bind path="student1.studentName">
             <input value="${status.value}" name="${status.expression}">
        <c:if test="${status.error}">
            Error codes:
            <c:forEach items="${status.errorMessages}" var="error">
                <c:out value="${error}"/>
            </c:forEach>
        </c:if>

        </spring:bind>
        <spring:bind path="student1.studentHobby">
             <input value="${status.value}" name="${status.expression}">
        <c:if test="${status.error}">
            Error codes:
            <c:forEach items="${status.errorMessages}" var="error">
                <c:out value="${error}"/>
            </c:forEach>
        </c:if>
        </spring:bind>
<input type="submit" value="Submit this form by clicking here" />
    </form>

studentmessages.properties
Size.student1.studentName = please enter a value for {0} field between {2} and {1} characters.
NotNull.student1.studentHobby = HObby should not be Enmpty

Here the sample code. Thanks in advance.

A: The binding error are stored inside a result.getModel(), but by creating your ModelAndView instance you're destroying that model, you should do like ModelAndView("AdmissionForm", result.getModel());
@RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
    public ModelAndView submitAdmissionForm(@Valid @ModelAttribute("student1") Student student1,BindingResult result) {

        if (result.hasErrors()) {
            ModelAndView model1 = new ModelAndView("AdmissionForm", result.getModel());
            return model1;
        }
        ModelAndView model = new ModelAndView("AdmissionSuccess");
        return model;
    }


text:
Q: Hide properties of an Image in PropertyGrid I have an image that I want to display based on specific choices the user makes. This image shows up as a property in the PropertyGrid. Like this:

The problem is that I am getting all this extraneous information, including the label to the right of the image (System.Drawing.Bitmap) and Image properties underneath it. Is there a way to hide this information in the end product?
UPDATE:
I figure it would be relevant to include the code I'm working with.
[TypeConverter(typeof(ImagePropertiesConverter))]
public Image Unsupported
{
    get
    {
        Image image = MyProject.Properties.Resources.Unsupported;
        return image;
    }
}

So this property is only shown if the user makes a selection that is unsupported for what they are currently working on. As you can see the property returns an image. I would also like to be able to set the label of the image, currently it shows up in the PropertyGrid as "System.Drawing.Bitmap." If I could take it one step further, I'd like to be able to set the background color of the label. So "System.Drawing.Bitmap" would show up on a red background. I've managed to get rid of the subproperties.

A: You can implement a custom TypeConverter and flag the Image property with the TypeConverter attribute. See here for an example.
To get rid of the System.Drawing.Bitmap you use some code like this to override the ConvertTo method in your TypeConverter:
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (value is Image && destinationType.Equals(typeof(string)))
        {
            return "Text to replace System.Drawing.Bitmap";
        }
        else
        {
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }


text:
Q: Particular solution to a $n$th order inhomogenous equation
Consider the single $n$th order inhomogenous equation
  $$u^{(n)}+a_1(t) u^{(n-1)}+ \cdots +a_n(t) u = f(t),$$
  where $a_1(t), \dots , a_n(t)$ and $f(t)$ are continuous functions of $t$ for $a \leq t \leq b.$

(i). Show that this is equivalent to the first order system $x'=A(t)x+g(t).$
(ii). Show that a particular solution is
$$u_p(t)=\int_{a}^{b} U_0(t,s)f(s)~ds,$$
where $U_0(t,s)$ is a Green's function.
I've done the first part, using the usual transformation
$$x_1=u, x_2=u', \dots , x_n=u^{(n-1)}.$$ But I don't know how to go by and prove the part (ii). Any help is much appreciated.

A: Hint:
You can plug $u_p(t)$ into the original ODE (writing it as $Lu(t)=f(t)$) and use the fact that
$$LU_0(t,s)=\delta(t-s),$$
where $\delta$ is the dirac delta function which satisfies
$$\int^b_a \delta(t-s)f(s)ds=f(t).$$
Plugging $u_p$ into the left hand side, we get
$$\int_a^b(U_0^{(n)}(t,s)+a_1(t)U_0^{(n-1)}(t,s)+\cdots+a_n(t)U_0(t,s))f(s)ds=\int_a^b\delta(t-s)f(s)ds.$$
This equals the right hand side.


text:
Q: How to uncommit changes to a specific file two commits ago I committed and pushed changes to my package-lock.json file two commits ago.
How do I uncommit the changes to this specific file?
I've looked at commands like $ git reset HEAD~2  but can't figure out how to target the specific file only.

A: I am assuming you committed changes in a file, which should not have been commited, and now you want to rewrite history to undo this.
I would recommend using interactive rebase. Like this:
git rebase --interactive HEAD~3

Then it will give you a file to edit (like commit) where you can choose for each commit (the last three in this case) what to do. Then you chose amend for the commit where you did the stuff you want to erase from history.
Then you undo the damage, and put git rebase --continue.


text:
Q: firebase cli serve cant access the project from different device I have install firebase cli etcetc. I can start the project and develop using firebase serve. I can visit the page of the project through localhost:5000 but if i try from different device in my network (mobile phone) to access network-ip:5000 I get connection refused.
Anyone knows what configuration/command it needs to forward port 5000 ? (different projects like creat-react-app works fine)

A: firebase serve -o 0.0.0.0

The -o flag sets the host.
For more information, see Server Fault: What's the difference between IP address 0.0.0.0 and 127.0.0.1?

A: With a local IP 192.168.0.10
I launched firebase serve -o 192.168.0.10 and it works perfectly on port 5000 from other device
In my javascript app :
functions.useFunctionsEmulator('http://192.168.0.10:5000')

A: If you run firebase serve --help, it will give you the information needed to listen on a different port or IP address:
Usage: serve [options]

start a local server for your static assets

Options:

-p, --port <port>   the port on which to listen (default: 5000) (default: 5000)
-o, --host <host>   the host on which to listen (default: localhost) (default: localhost)
--only <targets>    only serve specified targets (valid targets are: functions, hosting)
--except <targets>  serve all except specified targets (valid targets are: functions, hosting)
-h, --help          output usage information

You can use -p and -o on the command line to change the host and port where it listens for connections.  For your case, you won't be able use localhost for the host because that's only visible to other processes on the same machine.

A: This worked for me. I found the config.json file for the functions-emulator (It's in user/.config/configstore/@googlecloud/functions-emulator/config.json on mac or windows) and changed "bindHost": "localhost", to "bindHost": "0.0.0.0" and then I could access served functions from other devices on my network via localip:5000 which wasn't working before.

Tivoli commented on Aug 20, 2017 •
Digging around the code I figured this out, it's because the
  firebase-tools is only setting the projectId as part of the
  functions-emulator config. This fixes it in my Dockerfile
ADD config.json
  /root/.config/configstore/@google-cloud/functions-emulator/config.json
and the config.json looks like this
{
  "bindHost": "0.0.0.0" }
You can change the 0.0.0.0 to any host you want, but this works for
  Docker.
For reference
  https://github.com/firebase/firebase-tools/blob/master/lib/serve/functions.js#L71
  is the offending block, it needs to set the above parameter to the
  same as the --host command line parameter.
If you are running on your own local machine then you need to set it
  to the configstore folder for your respective OS on OS X it would be
  ~/.config/configstore/@google-cloud/functions-emulator/config.json.
Reference for the default config values
  https://github.com/GoogleCloudPlatform/cloud-functions-emulator/blob/master/src/defaults.json


text:
Q: NpgsqlCommand over NpgsqlDataAdapter Why would you use NpgsqlCommand over NpgsqlDataAdapter?
NpgsqlCommand usage, using reader
var _command = new NpgsqlCommand();
var _reader = _command.ExecuteReader();
...
while (_reader.Read())
{
...

NpgsqlDataAdapter usage, using Datasets
IDbDataAdapter dbDataAdapter = new NpgsqlDataAdapter();
dbDataAdapter.SelectCommand = selectCommand;
...
dbDataAdapter.Fill (dataSet);

Basic usage does not mention DataAdapter.
Is NpgsqlCommand and reader more efficient and should be preferred choice?

A: NpgsqlCommand is the more low-level API - you're responsible for providing the raw SQL, and also for reading the resultset via NpgsqlDataReader. DataAdapter/DataTable are a layer above that; it has some shortcomings (e.g. resultsets are buffered in memory) and in general is considered somewhat old/legacy. If what you want is to send SQL and read the results back, consider using NpgsqlCommand unless there's a good reason to use NpgsqlAdapter.


text:
Q: Enumerating DOM nodes in TChromium I am trying to enumerate DOM nodes using the following code (under XE2).
I have borrowed most of this from answers given here in SO, but for some reason it's not doing anything.
IOW, ProcessDOM() is not ever getting called.
And, I am at my wits end.
Could someone show me what I am doing wrong here.
Thanks in advance.
procedure ProcessNode(ANode: ICefDomNode);
var
  Node1: ICefDomNode;
begin
  if Assigned(ANode) then begin
    Node1 := ANode.FirstChild;
    while Assigned(Node1) do begin
      {Do stuff with node}
      ProcessNode(Node1);
      Node1 := Node1.NextSibling;
    end;
  end;
end;

procedure ProcessDOM(const ADocument: ICefDomDocument);
begin
  ProcessNode(ADocument.Body);
end;

procedure TMainForm.Chrome1LoadEnd(Sender: TObject; const ABrowser: ICefABrowser; const AFrame: ICefAFrame; AStatus: Integer);
begin
  if Assigned(AFrame) then AFrame.VisitDomProc(ProcessDOM);
end;

A: I had the same problem and I used the demo guiclient it comes with dcef3. With the following it works.
type TCustomRenderProcessHandler = class(TCefRenderProcessHandlerOwn)
  protected
    function OnProcessMessageReceived(const browser: ICefBrowser; sourceProcess: TCefProcessId; const message: ICefProcessMessage): Boolean; override;
end;

Chromium1.browser.SendProcessMessage(PID_RENDERER, TCefProcessMessageRef.New('visitdom'));

function TCustomRenderProcessHandler.OnProcessMessageReceived(browser: ICefBrowser; sourceProcess: TCefProcessId; message: ICefProcessMessage): Boolean;
begin
  if (message.Name = 'visitdom') then begin
    browser.MainFrame.VisitDomProc(
        procedure(const doc: ICefDomDocument)
        begin
          ProcessNode(Doc.Body);
        end);
    Result := True;
  end;
end;

initialization
  CefRenderProcessHandler := TCustomRenderProcessHandler.Create;

A: You need to add a procedure to the handler.
procedure ProcessNode(ANode: ICefDomNode);
Read this: 1

A: As this blog point out, The main difficulty when accessing a rendered page's DOM is that you can only do so in the same process as the associated renderer for that page.
You can't access dom from browser thread, you have to do it in renderer thread.
First, Forward a message (like visitdom) from browser process to rendering process
procedure TMainForm.crmLoadEnd(Sender: TObject; const browser: ICefBrowser;
  const frame: ICefFrame; httpStatusCode: Integer);
var
  msg : ICefProcessMessage;
begin
  if IsMain(browser, frame) then
    FLoading := False;

  msg := TCefProcessMessageRef.New('visitdom');
  browser.SendProcessMessage(PID_RENDERER, msg);
end;

Second, create a TCustomRenderProcessHandler to handle the message, send the result back to the browser processs.
function TCustomRenderProcessHandler.OnProcessMessageReceived(
  const browser: ICefBrowser; sourceProcess: TCefProcessId;
  const message: ICefProcessMessage): Boolean;
begin
  Result := False;
  if (message.Name = 'visitdom') then
  begin
      browser.MainFrame.VisitDomProc(
        procedure(const doc: ICefDomDocument)
          function ProcessNode(ANode: ICefDomNode) : String;
          var
            Node: ICefDomNode;
          begin
            Result := 'Not Found';
            if Assigned(ANode) then
            begin
              Node := ANode.FirstChild;
              while Assigned(Node) do
              begin
                if Node.ElementTagName='DIV' then
                begin
                  if Node.GetElementAttribute('class')='tv-panels' then
                  begin
                    Result := 'Found';
                    Exit;
                  end;
                end;
                ProcessNode(Node);
                Node := Node.NextSibling;
              end;
            end;
          end;
        var msg : ICefProcessMessage;
        begin
          msg := TCefProcessMessageRef.New('visitdom');
          msg.ArgumentList.SetString(0, processNode(doc.Body));
          browser.SendProcessMessage(PID_BROWSER, msg);
        end);
      Result := True;
  end;
end;

Third, On browser process, create an handler to process the messenage sent back from render process.
procedure TMainForm.crmProcessMessageReceived(Sender: TObject;
  const browser: ICefBrowser; sourceProcess: TCefProcessId;
  const message: ICefProcessMessage; out Result: Boolean);
begin
  Result := False;
  if (message.Name = 'visitdom') then
  begin
    StatusBar.SimpleText := message.ArgumentList.GetString(0);
    Result := True;
  end;
end;

Be careful, while debuging, placing a breakpoint in rendering process never work. It will never reached there.


text:
Q: Predictive text in Richtextbox in vb I have almost finished with my text editor in Visual basic.. And the last thing I want to add in my project is a sub which will show a Drop-Down menu each time the user adds a letter(character) in the richtextbox..For example when the user types a in the richtextbox, the program will show a Drop-Down menu with all words whose first letter is a.. Then if user types b after a then the Drop-Down menu will have all words whose first two letters are ab..The Drop-Down menu will get its words from a text file in that path: C:/Desktop/txtfile.txt

A: You can use TextBox.AutoCompleteMode Property to suggest or append the Predictive text in the textbox or richtextbox.

(source: net-informations.com)
The following VB.Net program add some string values to AutoCompleteStringCollection and display as Autocomplete TextBox while entering text:
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox1.AutoCompleteMode = AutoCompleteMode.Suggest
        TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource

        ' You can read the custom source file
        ' for example: File.ReadAllLine("C://Desktop//txtfile.txt")
        Dim DataCollection As New AutoCompleteStringCollection()

        addItems(DataCollection)
        TextBox1.AutoCompleteCustomSource = DataCollection
    End Sub
    Public Sub addItems(ByVal col As AutoCompleteStringCollection)
        col.Add("Abel")
        col.Add("Bing")
        col.Add("Catherine")
        col.Add("Varghese")
        col.Add("John")
        col.Add("Kerry")
    End Sub
End Class

Reference Here


text:
Q: Kibana 5.1 link We are having Kibana 5.1 and I would like to create a link to specific dashboard with filter parameter.
I've found out that in old version you added "_q" (as query) and parameter. But this is not working:
http://127.0.0.1:5601/app/kibana#/dashboard/Overview?_q=from:name
Any idea how to do it?

A: Yo need to create visualisation or dashboard, and filter the data as you want by click on the chart, when you finish, you need to press on the save button on the top navbar then press on the share button on the top, copy the link, and share it


text:
Q: How to bind and unbind events jquery: carousel script modification I have a jQuery Carousel script and I want to modify it's behavior slightly. Here is the script and test case in jsfiddle: http://jsfiddle.net/A4vHf/1/ . Below is the JS code.
(function($) {

    $.fn.easyPaginate = function(options){

        var defaults = {
            step: 4,
            delay: 100,
            numeric: true,
            nextprev: true,
            auto:false,
            pause:4000,
            clickstop:true,
            controls: 'pagination',
            current: 'current'
        };

        var options = $.extend(defaults, options);
        var step = options.step;
        var lower, upper;
        var children = $(this).children();
        var count = children.length;
        var obj, next, prev;
        var page = 1;
        var timeout;
        var clicked = false;

        function show(){
            clearTimeout(timeout);
            lower = ((page-1) * step);
            upper = lower+step;
            $(children).each(function(i){
                var child = $(this);
                child.hide();
                if(i>=lower && i<upper){ setTimeout(function(){ child.fadeIn('fast') }, ( i-( Math.floor(i/step) * step) )*options.delay ); }
                if(options.nextprev){
                    if(upper >= count) { next.fadeOut('fast'); } else { next.fadeIn('fast'); };
                    if(lower >= 1) { prev.fadeIn('fast'); } else { prev.fadeOut('fast'); };
                };
            });
            $('li','#'+ options.controls).removeClass(options.current);
            $('li[data-index="'+page+'"]','#'+ options.controls).addClass(options.current);

            if(options.auto){
                if(options.clickstop && clicked){}else{ timeout = setTimeout(auto,options.pause); };
            };
        };

        function auto(){
            if(upper <= count){ page++; show(); }
        };

        this.each(function(){

            obj = this;

            if(count>step){

                var pages = Math.floor(count/step);
                if((count/step) > pages) pages++;

                var ol = $('

').insertAfter(obj);

                if(options.nextprev){
                    prev = $('
Previous
')
                        .hide()
                        .appendTo(ol)
                        .click(function(){
                            clicked = true;
                            page--;
                            show();
                        });
                };

                if(options.numeric){
                    for(var i=1;i<=pages;i++){
                    $('
'+ i +'
')
                        .appendTo(ol)
                        .click(function(){
                            clicked = true;
                            page = $(this).attr('data-index');
                            show();
                        });
                    };
                };

                if(options.nextprev){
                    next = $('
Next
')
                        .hide()
                        .appendTo(ol)
                        .click(function(){
                            clicked = true;
                            page++;
                            show();
                        });
                };

                show();
            };
        });

    };

})(jQuery);

My goal is to make the class="prev" and class="next" buttons always visible. I removed the hide(); methods from the code, but I also need to remove the click event handlers because otherwise I can still click on the buttons even when I'm on the last or first pages accordingly - and that's here things get messed up. I have to bind and unbind the click events but don't know how to do it properly. So here is my modified version:
(function($) {

$.fn.easyPaginate = function(options){

    var defaults = {
        step: 4,
        delay: 100,
        numeric: true,
        nextprev: true,
        auto:false,
        pause:4000,
        clickstop:true,
        controls: 'pagination',
        current: 'current'
    };

    var options = $.extend(defaults, options);
    var step = options.step;
    var lower, upper;
    var children = $(this).children();
    var count = children.length;
    var obj, next, prev;
    var page = 1;
    var timeout;
    var clicked = false;

    function show(){
        clearTimeout(timeout);
        lower = ((page-1) * step);
        upper = lower+step;
        $(children).each(function(i){
            var child = $(this);
            child.hide();
            if(i>=lower && i<upper){ setTimeout(function(){ child.fadeIn('fast') }, ( i-( Math.floor(i/step) * step) )*options.delay ); }
            if(options.nextprev){
                if(upper >= count) { next.fadeOut('fast'); } else { next.fadeIn('fast'); };
                if(lower >= 1) { prev.fadeIn('fast'); } else { prev.fadeOut('fast'); };
            };
        });
        $('li','#'+ options.controls).removeClass(options.current);
        $('li[data-index="'+page+'"]','#'+ options.controls).addClass(options.current);

        if(options.auto){
            if(options.clickstop && clicked){}else{ timeout = setTimeout(auto,options.pause); };
        };
    };

    function auto(){
        if(upper <= count){ page++; show(); }
    };

    this.each(function(){

        obj = this;

        if(count>step){

            var pages = Math.floor(count/step);
            if((count/step) > pages) pages++;

            var ol = $('

').insertAfter(obj);

            if(options.nextprev){
                prev = $('
Previous
')
                    .appendTo(ol)
                    .bind('click', function() {
                        clicked = true;
                        page--;
                        show();
                    });
            };

            if(options.numeric){
                for(var i=1;i<=pages;i++){
                $('
'+ i +'
')
                    .appendTo(ol)
                    .click(function(){
                        clicked = true;
                        page = $(this).attr('data-index');
                        show();
                    });
                };
            };

            if(options.nextprev){
                next = $('
Next
')
                    .appendTo(ol)
                    .bind('click', function() {
                        clicked = true;
                        page++;
                        show();
                    });
            };

            show();
        };
    });

};

})(jQuery);

A: What about just checking inside your event handlers if the user has reached the bounds of the pages?
        if(options.nextprev){
            prev = $('
Previous
')
                .appendTo(ol)
                .bind('click', function() {

                    //check to see if there are any more pages in the negative direction
                    if (page > 0) {
                        clicked = true;
                        page--;
                        show();
                    }
                });
        }

        if(options.nextprev){
            next = $('
Next
')
                .appendTo(ol)
                .bind('click', function() {

                    //check to see if there are any pages in the positive direction
                    if ((page + 1) < count) {
                        clicked = true;
                        page++;
                        show();
                    }
                });
        }

Update
If you want the previous and next buttons to never dissapear then you need to remove the code in the show() function that fades the elements in and out. That section of code is this:
        if(options.nextprev){
            if(upper >= count) { next.fadeOut('fast'); } else { next.fadeIn('fast'); };
            if(lower >= 1) { prev.fadeIn('fast'); } else { prev.fadeOut('fast'); };
        };

A simple fix is to just comment this section-out, here is a demo: http://jsfiddle.net/A4vHf/18/


text:
Q: WxWidgets Thread crashes random during run I'm writing a wxwidget multi-threaded application. But the code crashes randomly of which I have no clue. I've posted my code here. This program creates a thread each time a button is pressed. And this thread is intended to write something on the parent text area. When I run the code, only the destructor message gets printed, ie the Entry section is not executed. I've been struggling with this problem for a lot of time. Any help would be greatly appreciated.
Thanking you in advance..
   void threadFrame::addthread(wxCommandEvent &event)
{
    mythread *th = new mythread(this);
    th->Create();
    th->Run();
}
mythread::mythread(GUIFrame *frame) : wxThread(wxTHREAD_DETACHED)
{
    m_frame = frame;
}
;
mythread::~mythread()
{
    WriteText(wxT("destructor"));
}
void mythread::WriteText(const wxString& text)
{
    m_frame->m_textCtrl1->SetValue(text);
}

void *mythread::Entry()
{
    WriteText(wxT("thread started"));
    return NULL;
}

A: You should not use any GUI-routines from threads other than the main thread.
This means you should replace the ->SetValue(..) call by some other mechanism (e.g. notify the main thread via event).
I never tried to do that, so I don't know if this can cause the thread to crash.
Do you call any functions which are not appropriate for detached threads?

A: You can access the GUI from from other threads provided that you use Mutex functions : wxMutexGuiEnter () and wxMutexGuiLeave () .
Are you sure GUIFrame and threadFrame can cast into each over implicitly?  You call mythread(threadFrame);
Are you sure your Entry() function is declared in your mythread class?
Finally, I declare the entry() function as follow my ".h" file : virtual void * Entry();


text:
Q: Ionic Change color of item based on if statement ngStyle and ngFor So I am a real beginner and I am obviously missing something.
I am creating a quiz style app and I have a list with a radio group in that loops through an array using ngfor to present the answers
The list is a list of answers and what I am trying to do is change the color of the item when they click on it, i.e. green for correct and red for incorrect.
It works but the problem is that it changes the whole list (i.e. every item, not just the item I have clicked on)
Here is my code
html

<button ion-item  *ngFor="let answer of question.answers; let i = index ;"  [ngStyle]="{'background-color': answerColor}"  wrap-text>

    <ion-label  class="my-label" text-wrap>{{answer.answer}}</ion-label>
    <ion-radio  (click)="selectAnswer(answer, question)" [checked]="answer.selected" [disabled]="hasAnswered"></ion-radio>

</button>

ts
    if(answer.correct){
        this.score++;
        this.answerColor = '#025c25'; //correct Green Color

    }
    else{
        this.answerColor = '#AB2020'; //Wrong Red Color
    }
    this.slides.lockSwipes(false);

So there are no errors it just makes the whole list green or red depending on the answer whereas I just want the item I am clicking on to change color.
I have read loads of stuff about ng-class and lots of links but cant quite get my head around it.
Apologies if this is a really dumb question or I have approached it all wrong

A: This is happening because you only have a single answerColor variable that all of your answers are using, instead of having one answerColor per answer.
If you can add a color variable to your answer objects and change your code to use answer.answerColor instead of this.answerColor, then the colors should work as you expect they would. In the following snippet, I have updated your logic to use answer.answerColor.
if(answer.correct){
    this.score++;
    answer.answerColor = '#025c25'; //correct Green Color
}
else{
    answer.answerColor = '#AB2020'; //Wrong Red Color
}

Finally, if your answer object is declared to be a specific type (instead of any), then you may need to update the type definition.
export interface Answer {
    correct: boolean
    selected: boolean;
    answer: string;
    color: string; // Add this line!
}


text:
Q: Undefined index: sub I have problem with upload field. Error page image
Actualy when I add upload field to form script gives an error.
The server gives an error for this line: $filenamefields[$group]['sub']
foreach ($fields as $group => $fieldlist) {
    if (isset($fieldlist['active']) && $fieldlist['active']) {
        $min_req = true;
        if (isset($fieldlist['sub'])) {
            $this->customrule_addrec(
                $fieldlist['sub'],
                $required, $title,
                $type,
                $gprefix.'[' . $group . '][sub]',
                $filenamefields[$group]['sub'],
                $filetypefields[$group]['sub'],
                $filetmpnamefields[$group]['sub'],
                $fileerrorfields[$group]['sub'],
                $filesizefields[$group]['sub']);

and this line: $this->files['size']['fields']);
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
      $this->files['name']['fields'],
      $this->files['type']['fields'],
      $this->files['tmp_name']['fields'],
      $this->files['error']['fields'],
      $this->files['size']['fields']);

if (!$min_req)
      $this->addError($attribute, 'Select a group');

file codes :
<?php
class Orders extends CActiveRecord
{
public $fields;
public $files;
public $file;
public $remove;

public function tableName()
{
    return 'orders';
}

public function rules()
{
    return array(
        array(
            'name, start_date, ordertype, user',
            'required'
        ),
        array(
            'status, ordertype, user',
            'numerical',
            'integerOnly' => true
        ),
        array(
            'name',
            'length',
            'max' => 200
        ),
        array(
            'finish_date, desc',
            'safe'
        ),
        array(
            'id, name, start_date, finish_date, status, ordertype, user, desc',
            'safe',
            'on' => 'search'
        ),
        array(
            'fields,files',
            'safe'
        ),
        array(
            'fields',
            'customrule_add',
            'on' => 'add'
        ),
        array(
            'fields',
            'customrule_edit',
            'on' => 'edit'
        ),
        array(
            'file, remove',
            'safe',
            'on' => 'answer'
        )
    );
}

public function customrule_add($attribute, $params)
{
    $fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
    $required = CHtml::listData($fieldtypes, 'id', 'required');
    $title = CHtml::listData($fieldtypes, 'id', 'name');
    $type = CHtml::listData($fieldtypes, 'id', 'type');
    $fields = $this->$attribute;

    $min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
        $this->files['name']['fields'],
        $this->files['type']['fields'],
        $this->files['tmp_name']['fields'],
        $this->files['error']['fields'],
        $this->files['size']['fields']);
    if (!$min_req)
        $this->addError($attribute, 'Select a group');
}

private function customrule_addrec($fields, $required, $title, $type, $gprefix, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
    $min_req = false;
    foreach ($fields as $group => $fieldlist) {
        if (isset($fieldlist['active']) && $fieldlist['active']) {
            $min_req = true;
            if (isset($fieldlist['sub'])) {
                $this->customrule_addrec(
                    $fieldlist['sub'],
                    $required, $title,
                    $type,
                    $gprefix.'[' . $group . '][sub]',
                    $filenamefields[$group]['sub'],
                    $filetypefields[$group]['sub'],
                    $filetmpnamefields[$group]['sub'],
                    $fileerrorfields[$group]['sub'],
                    $filesizefields[$group]['sub']);
              foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
                  if (isset($sfieldlist['active']) && $sfieldlist['active']) {
                     foreach ($sfieldlist as $key => $value) {
                         if (($key != 'active') && ($key != 'sub') && $required[$key]) {
                              if ($type[$key] != 2) {
                                 if (!$value)
                                  $this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
                          } else if (!isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) || !$this->files['name']['fields'][$group]['sub'][$sgroup][$key]) {
                                $this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
                             }
                        }
                     }
                }
             }
            }
            foreach ($fieldlist as $key => $value) {
                if (($key != 'active') && ($key != 'sub') && $required[$key]) {
                    if ($type[$key] != 2) {
                        if (!$value)
                            $this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
                    } else if (!isset($filenamefields[$group][$key]) || !$filenamefields[$group][$key]) {
                        $this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
                    }
                }
            }
        }
    }
    return $min_req;
}

public function customrule_edit($attribute, $params)
{
    $fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
    $required = CHtml::listData($fieldtypes, 'id', 'required');
    $title = CHtml::listData($fieldtypes, 'id', 'name');
    $type = CHtml::listData($fieldtypes, 'id', 'type');
    $groups = CHtml::listData(Ordergroup::model()->findAll(array(
        'select' => 'id,name,orderform',
        'condition' => 'orderform = \'' . $this->ordertype . '\''
    )), 'id', 'name');
    $fields = $this->$attribute;
    $min_req = false;
    foreach ($fields as $group => $fieldlist) {
        if (isset($fieldlist['active']) && $fieldlist['active']) {
            $min_req = true;
            if (isset($fieldlist['sub'])) {
                foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
                    if (isset($sfieldlist['active']) && $sfieldlist['active']) {
                        foreach ($sfieldlist as $key => $value) {
                            if (($key != 'active') && ($key != 'sub') && $required[$key]) {
                                if ($type[$key] != 2) {
                                    if (!$value)
                                        $this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'value ' . $title[$key] . ' Can not be empty');
                                }
                            }
                        }
                    }
                }
            }
            foreach ($fieldlist as $key => $value) {
                if (($key != 'active') && $required[$key]) {
                    if ($type[$key] != 2) {
                        if (!$value)
                            $this->addError('fields[' . $group . '][' . $key . ']', 'value ' . $title[$key] . 'Can not be empty');
                    }
                }
            }
        }
    }
    if (!$min_req)
        $this->addError($attribute, 'Choose a group');
}

public function add()
{
    $name = $this->name;
    $exists = Orders::model()->exists('`name` = \'' . $name . '\'');
    if ($exists) {
        $count = Orders::model()->count('`name` regexp \'^' . $name . ' - [0-9]+$\'');
        $this->name = $name . ' - ' . ($count + 2);
    }

    $status = $this->save();

    $status = $this->addsub(
        $this->fields,
        $status,
        $this->files['name']['fields'],
        $this->files['type']['fields'],
        $this->files['tmp_name']['fields'],
        $this->files['error']['fields'],
        $this->files['size']['fields']
    );

    if (!$status) {

    Ordervalues::model()->deleteAllByAttributes(array(
            'order' => $this->id
        ));
        GroupOfOrder::model()->deleteAllByAttributes(array(
            'order' => $this->id
        ));
        $this->delete();
        return false;
    }
    return true;
}

private function addsub($thisfields, $status, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
    foreach ($thisfields as $group => $fieldlist) {
        if (isset($fieldlist['active']) && $fieldlist['active'] && $status) {
            $gofo = new GroupOfOrder('insert');
            $gofo->group = $group;
            $gofo->order = $this->id;
            $gofo->save();

            if (isset($fieldlist['sub'])) {
                $status = $this->addsub(
                    $fieldlist['sub'],
                    $status,
                    $filenamefields[$group]['sub'],
                    $filetypefields[$group]['sub'],
                    $filetmpnamefields[$group]['sub'],
                    $fileerrorfields[$group]['sub'],
                    $filesizefields[$group]['sub']
                );
                if(!$status)
                    return false;
            }
            foreach ($fieldlist as $key => $value) {
                if ($key != 'active' && $key != 'sub' && $status) {
                    $ftype = Orderfield::model()->findByPk($key);
                    if (!$ftype) {
                        $this->addError('fields', 'Field type error');
                        Ordervalues::model()->deleteAllByAttributes(array(
                            'order' => $this->id
                        ));
                        GroupOfOrder::model()->deleteAllByAttributes(array(
                            'order' => $this->id
                        ));
                        $this->delete();
                        return false;
                    }
                    if (!empty($value)) {
                        $field = new Ordervalues('insert');
                        $field->field = $key;
                        $field->order = $this->id;
                        $field->value = $value;
                        $status = ($status && $field->save());
                    } elseif (isset($filenamefields[$group][$key]) && !empty($filenamefields[$group][$key])) {
                        $file = new CUploadedFile($filenamefields[$group][$key], $filetmpnamefields[$group][$key], $filetypefields[$group][$key], $filesizefields[$group][$key], $fileerrorfields[$group][$key]);
                        if ($ftype->file_type) {
                            $all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
                            $allowed = false;
                            foreach ($all as $ex) {
                                if ($ex == $file->extensionName) {
                                    $allowed = true;
                                    break;
                                }
                            }
                            if (!$allowed) {
                                $this->addError('files', 'This format' . $file->extensionName . 'is not true');
                                Ordervalues::model()->deleteAllByAttributes(array(
                                    'order' => $this->id
                                ));
                                GroupOfOrder::model()->deleteAllByAttributes(array(
                                    'order' => $this->id
                                ));
                                $this->delete();
                                return false;
                            }
                        }
                        $ffield = new Ordervalues('insert');
                        $ffield->field = $key;
                        $ffield->order = $this->id;
                        $ffield->value = $file->name;
                        $ffield->file_size = $file->size;
                        $status = ($status && $ffield->save());
                        $status = ($status && $file->saveAs('files/' . $ffield->id));
                    }
                }
            }
        }
    }
    return true;
}

public function edit()
{
    $status = true;
    foreach ($this->fields as $group => $fieldlist) {
        if (isset($fieldlist['active']) && $fieldlist['active']) {
            $gofo = GroupOfOrder::model()->findByAttributes(array(
                'order' => $this->id,
                'group' => $group
            ));
            if (!$gofo) {
                $gofo = new GroupOfOrder('insert');
                $gofo->group = $group;
                $gofo->order = $this->id;
                $gofo->save();
            }

            if (isset($fieldlist['sub'])) {
                foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
                    if (isset($sfieldlist['active']) && $sfieldlist['active']) {
                        $sgofo = GroupOfOrder::model()->findByAttributes(array(
                            'order' => $this->id,
                            'group' => $sgroup
                        ));
                        if (!$sgofo) {
                            $sgofo = new GroupOfOrder('insert');
                            $sgofo->group = $sgroup;
                            $sgofo->order = $this->id;
                            $sgofo->save();
                        }
                        foreach ($sfieldlist as $key => $value) {
                            if ($key != 'active' && $key != 'sub' && $status) {
                                $ftype = Orderfield::model()->findByPk($key);
                                if (!$ftype) {
                                    $this->addError('fields', 'Field type error');
                                    return false;
                                }
                                if (!empty($value)) {
                                    $field = Ordervalues::model()->findByAttributes(array(
                                        'order' => $this->id,
                                        'field' => $key
                                    ));
                                    if (!$field) {
                                        $field = new Ordervalues('insert');
                                        $field->field = $key;
                                        $field->order = $this->id;
                                    }
                                    $field->value = $value;
                                    $status = ($status && $field->save());
                                } elseif (isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) && !empty($this->files['name']['fields'][$group]['sub'][$sgroup][$key])) {
                                    $file = new CUploadedFile($this->files['name']['fields'][$group]['sub'][$sgroup][$key], $this->files['tmp_name']['fields'][$group]['sub'][$sgroup][$key], $this->files['type']['fields'][$group]['sub'][$sgroup][$key], $this->files['size']['fields'][$group]['sub'][$sgroup][$key], $this->files['error']['fields'][$group]['sub'][$sgroup][$key]);
                                    if ($ftype->file_type) {
                                        $all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
                                        $allowed = false;
                                        foreach ($all as $ex) {
                                            if ($ex == $file->extensionName) {
                                                $allowed = true;
                                                break;
                                            }
                                        }
                                        if (!$allowed) {
                                            $this->addError('files', 'This format ' . $file->extensionName . ' is not true');
                                            return false;
                                        }
                                    }
                                    $ffield = Ordervalues::model()->findByAttributes(array(
                                        'order' => $this->id,
                                        'field' => $key
                                    ));
                                    if (!$ffield) {
                                        $ffield = new Ordervalues('insert');
                                        $ffield->field = $key;
                                        $ffield->order = $this->id;
                                    }
                                    $ffield->value = $file->name;
                                    $ffield->file_size = $file->size;
                                    $status = ($status && $ffield->save());
                                    $status = ($status && $file->saveAs('files/' . $ffield->id));
                                }
                            }
                        }
                    }
                }
            }
            foreach ($fieldlist as $key => $value) {
                if ($key != 'active' && $key != 'sub' && $status) {
                    $ftype = Orderfield::model()->findByPk($key);
                    if (!$ftype) {
                        $this->addError('fields', 'Field error');
                        return false;
                    }
                    if (!empty($value)) {
                        $field = Ordervalues::model()->findByAttributes(array(
                            'order' => $this->id,
                            'field' => $key
                        ));
                        if (!$field) {
                            $field = new Ordervalues('insert');
                            $field->field = $key;
                            $field->order = $this->id;
                        }
                        $field->value = $value;
                        $status = ($status && $field->save());
                    } elseif (isset($this->files['name']['fields'][$group][$key]) && !empty($this->files['name']['fields'][$group][$key])) {
                        $file = new CUploadedFile($this->files['name']['fields'][$group][$key], $this->files['tmp_name']['fields'][$group][$key], $this->files['type']['fields'][$group][$key], $this->files['size']['fields'][$group][$key], $this->files['error']['fields'][$group][$key]);
                        if ($ftype->file_type) {
                            $all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
                            $allowed = false;
                            foreach ($all as $ex) {
                                if ($ex == $file->extensionName) {
                                    $allowed = true;
                                    break;
                                }
                            }
                            if (!$allowed) {
                                $this->addError('files', 'This format ' . $file->extensionName . ' is not true');
                                return false;
                            }
                        }
                        $ffield = Ordervalues::model()->findByAttributes(array(
                            'order' => $this->id,
                            'field' => $key
                        ));
                        if (!$ffield) {
                            $ffield = new Ordervalues('insert');
                            $ffield->field = $key;
                            $ffield->order = $this->id;
                        }
                        $ffield->value = $file->name;
                        $ffield->file_size = $file->size;
                        $status = ($status && $ffield->save());
                        $status = ($status && $file->saveAs('files/' . $ffield->id));
                    }
                }
            }
        } else {
            $gofo = GroupOfOrder::model()->findByAttributes(array(
                'order' => $this->id,
                'group' => $group
            ));
            if ($gofo) {
                $gofo->delete();
                $ovs = Ordervalues::model()->findAll('order = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where ordergroup=' . $group . ')');
                foreach ($ovs as $ov) {
                    if ($ov->field0->type == 2)
                        unlink(Yii::app()->getBasePath() . '/../files/' . $ov->id);
                    $ov->delete();
                }
            }
        }
    }
    $status = ($status && $this->save());
    return $status;
}

public function answer()
{
    if ($this->remove) {
        foreach ($this->remove as $id => $f) {
            if ($f) {
                $filemodel = Orderfiles::model()->findByAttributes(array(
                    'id' => $id,
                    'order_id' => $this->id
                ));
                if ($filemodel) {
                    $filemodel->delete();
                    $path = Yii::app()->basePath . '/../files/answers/' . $id;
                    if (file_exists($path))
                        unlink($path);
                }
            }
        }
    }
    $file = CUploadedFile::getInstance($this, 'file');
    if ($file) {
        $fm = new Orderfiles('insert');
        $fm->name = $file->name;
        $fm->size = $file->size;
        $fm->order_id = $this->id;
        if ($fm->save() && $this->save())
            return $file->saveAs('files/answers/' . $fm->id);
        return false;
    }
    return $this->save();
}

public function fill_in_fields()
{
    $this->fields = array();
    foreach ($this->ordervalues as $field) {
        $f = $field->field0;
        if (!isset($this->fields[$f->ordergroup]['active']))
            $this->fields[$f->ordergroup]['active'] = true;
        $this->fields[$f->ordergroup][$f->id] = $field->value;
    }
}

public function getPrice()
{
    return Yii::app()->db->createCommand('select sum(price) from ' . Ordergroup::model()->tableName() . ' where id in (select `group` from ' . GroupOfOrder::model()->tableName() . ' where `order` = ' . $this->id . ')')->queryScalar();
}

public function deleteTree()
{
    $ovsff = Ordervalues::model()->findAll('`order` = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where type = 2)');
    if ($ovsff) {
        foreach ($ovsff as $value) {
            $path = Yii::app()->getBasePath() . '/../files/' . $value->id;
            if (file_exists($path))
                unlink($path);
        }
    }

    Ordervalues::model()->deleteAll('`order` = ' . $this->id);
    GroupOfOrder::model()->deleteAll('`order` = ' . $this->id);
    $status = true;
    $ovsff = Orderfiles::model()->findAll('`order_id`  = ' . $this->id); // files of answered orders
    if ($ovsff) {
        foreach ($ovsff as $value) {
            $path = Yii::app()->getBasePath() . '/../files/answers/' . $value->id;
            if (file_exists($path))
                unlink($path);
            $status = $status && $value->delete();
        }
    }
    $trans = $this->trackCode;
    $status = $this->delete();
    $trans->delete();
    return $status;
}

public function relations()
{
    return array(
        'orderfiles' => array(
            self::HAS_MANY,
            'Orderfiles',
            'order_id'
        ),
        'ordertype0' => array(
            self::BELONGS_TO,
            'Orderform',
            'ordertype'
        ),
        'trackCode' => array(
            self::BELONGS_TO,
            'Transaction',
            'track_code'
        ),
        'user0' => array(
            self::BELONGS_TO,
            'Users',
            'user'
        ),
        'ordervalues' => array(
            self::HAS_MANY,
            'Ordervalues',
            'order'
        ),
        'tickets' => array(
            self::HAS_MANY,
            'Ticket',
            'order_id'
        )
    );
}

public function attributeLabels()
{
    return array(
        'id' => 'Code',
        'name' => 'Name',
        'start_date' => 'Date',
        'finish_date' => 'End Date',
        'status' => 'status',
        'ordertype' => 'Type',
        'user' => 'User',
        'track_code' => 'Pay code',
        'desc' => 'Description',
        'file' => 'File'
    );
}

public function getStatus()
{
    $status = array(
        0 => 'Waiting for pay',
        1 => 'In progress',
        2 => 'Completed',
        3 => 'Draft'
    );
    return $status[$this->status];
}

public function getButton()
{
    $status = array(
        0 => 'Waiting for pay',
        1 => 'In progress',
        2 => 'Completed',
        4 => 'Draft'
    );
    if ($this->status == 0) {
        return CHtml::button('Pay', array(
            'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('financial/invoice', array(
                    'id' => $this->track_code
                )) . '\''
        ));
    }
    return CHtml::button('Details', array(
        'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('service/order', array(
                'id' => $this->id
            )) . '\''
    ));
}

public function search()
{
    $criteria = new CDbCriteria();

    $criteria->compare('id', $this->id);
    $criteria->compare('name', $this->name, true);
    $criteria->compare('start_date', $this->start_date, true);
    $criteria->compare('finish_date', $this->finish_date, true);
    $criteria->compare('status', $this->status);
    $criteria->compare('ordertype', $this->ordertype);
    $criteria->compare('user', $this->user);
    $criteria->compare('track_code', $this->track_code);
    $criteria->compare('desc', $this->desc, true);

    return new CActiveDataProvider($this, array(
        'criteria' => $criteria
    ));
}

public static function model($className = __CLASS__)
{
    return parent::model($className);
}

}


text:
Q: Reactjs array loop not working if the condition fails or in the negative condition I want to loop the array below.
Conditions:
If system: TEST ID is "No Number" i want to display "system": "ALT ID" id as "123456789" else I should display system: TEST ID "id"
Current status:
This code works fine when TEST ID has value "No Number", but if TEST ID has any number like "2345678" this code is not working.
"FindId": [
    {
        "id": "No Number",
        "system": "TEST ID"
    },
    {
        "id": "123456789",
        "system": "ALT ID"
    }
]

let result = FindId && FindId.find(data => data.system === "TEST ID").id
if (result === "No Number") {
    result = FindId.find(data => data.system === "ALT ID").id
}

return { result }

A: This should work.

FindId = [
  {
    id: "No Number",
    system: "TEST ID",
  },
  {
    id: "123456789",
    system: "ALT ID",
  },
];

const testId = FindId?.find((data) => data.system === "TEST ID")?.id;
const altId = FindId?.find((data) => data.system === "ALT ID")?.id;
const result = testId === "No Number" ? altId : "id";

console.log(`TEST ID: ${result}`);


text:
Q: Extend Ext.data.Model (add fields dynamically) I extended an existing Model by adding fields using the prototype. Everything works fine, the data can be received from the server side and can be used on client side. But, when I now update my data and send it back to the server side, the "new" fields are not recognized by the writer of the proxy.
To be more specific: I have a model like this:
    Ext.define('Osgaar', {
      extend: 'Ext.data.Model',
      fields: [
        { name: 'first', type: 'string' },
        { name: 'second', type: 'string' },
        { name' 'third', type: 'string' }
      ],

      proxy: {
        type: 'rest',
        url: 'public/svcmethod',
        reader: {
          type: 'json',
          root: 'data'
        },
        writer: {
          type: 'json',
          writeAllFields: false
        }
      }
    });

I am extending the model like that:
    Osgaar.prototype.fields.add({ name: 'fourth', type: 'string' });

I tried to set writeAllFields to false to get all attributes transferred, there are just those from the defined model, not the one added using the prototype (Fiddler confirms that).
Does anybody now a way to solve this without defining a new model?
Thank you in advance.

A: I think the best solution here is the following:
Osgaar.prototype.fields.add(new Ext.data.Field({ name: 'fifth', type: 'string'})); // create Ext.data.Field constructor, not just simple Object

I did a quick look on the Writer implementation, and here is a method that is called by write() when you write data:
getRecordData: function(record) {
        var isPhantom = record.phantom === true,
            writeAll = this.writeAllFields || isPhantom,
            nameProperty = this.nameProperty,
            fields = record.fields,            // <- look here
            data = {},
            changes,
            name,
            field,
            key;

        if (writeAll) {
            fields.each(function(field){
                if (field.persist) {           // <- checks the persist property!
                    name = field[nameProperty] || field.name;
                    data[name] = record.get(field.name);
                }
            });

Then I checked the value of persist property of a field that's added to the prototype after the model is defined and turned out it's undefined. This is because you are not truly creating an Ext.data.Field instance that would inherit all Field defaults and other useful stuff, you're simply adding a plain Object to the fields collection. Osgaar.prototype.fields is just a MixedCollection and since you're working with it directly, there's no place where Ext.data.Field constructor might be called implicitly.
If it's common for your application logic to add Model fields on the fly, consider implementing an addField() method to your custom Models (create another base class in the inheritance chain).
Hope this helps, good luck!
I've been using ExtJS for quite a while so this was like a quiz to me :)

A: I found another solution for my original issue.
Instead of adding the fields to the prototype of the model I did the following:
Osgaar_Temp = Osgaar;
delete Osgaar;

Ext.define('Osgaar', {
    extend: 'Osgaar_Temp',
    fields:
    [
        { name: 'typeCategories', type: 'string' }
    ]
});

This seems to be the best solution.


text:
Q: Extjs6.2 Modern toolkit- Extend a textbox I am still learning EXTJs and one of the thing I was trying to to was extend a component. Below is my example:
Ext.define('MyApp.view.CustomTextField',{
extend: 'Ext.field.Text',
xtype: 'customtextfield',

config:
{
    fieldID: null,
    langID: null
},
initialize: function() {
    alert("init"); //1. called before I navigate to view
     Call a controller method here
    this.callParent(arguments);
},
initComponent: function () {
    alert("initComp"); //2. not called at all
    Call a controller method here
    this.callParent(arguments);

}

I want to call a controller method to validate if user has permission to see this field and accordingly do next actions. I want this validation to happen when I navigate to the view
I used this custom field in my View as:
xtype: 'fieldset',
        margin: 10,
        bind: '{workOrders}',
        title: 'Dispatch Information',
        items: [
            {
                id: 'Tag',
                xtype: 'customtextfield',
                name: 'Tag',
                label: 'Tag',
                bind: '{Tag}',
                labelAlign: 'top'
            },

But the initComponent is never fired.
The initialize is fired to soon ,even before my stores are loaded. How do I properly extend this control?

A: In ExtJS 6 modern there is no initComponent event for textfield . initComponent event have
 in classic for textfield.
For calling events in controller you need to create controller and define to you view.
In this FIDDLE, I have created a demo using form, ViewController, textfield and ViewModel. I hope this will help/guide you to achieve your requirements.
For more details please refer ExtJS Docs.
CODE SNIPPET
Ext.application({
    name: 'Fiddle',

    launch: function () {

        //Define the cutsometext from extending {Ext.field.Text}
        Ext.define('CustomText', {
            extend: 'Ext.field.Text',
            xtype: 'customtext',
            labelAlign: 'top',
            listeners: {
                initialize: 'onInitializeCutsomText'
            }
        });

        Ext.define('FormModel', {
            extend: 'Ext.app.ViewModel',
            alias: 'viewmodel.formmodel',

            data: {
                user: {
                    firstName: 'Narendra',
                    lastName: 'Jadhav',
                    email: 'narendrajadhav105@gmail.com'
                },
                permissionCng: {
                    firstName: false,
                    lastName: false,
                    email: true,
                    isAdmin: false
                }
            }

        });
        //Define the FormController from extending {Ext.app.ViewController}
        Ext.define('FormController', {
            extend: 'Ext.app.ViewController',
            alias: 'controller.formctn',

            onInitializeCutsomText: function (textfield) {
                var permissionCng = this.getViewModel().get('permissionCng');
                // Here is just basic example for disabled textfield on initialize event.
                //In your case you can put your requirement.
                textfield.setDisabled(permissionCng[textfield.getName()]);
            }
        });

        //Creating form
        Ext.create('Ext.form.Panel', {
            fullscreen: true,
            viewModel: {
                type: 'formmodel'
            },
            controller: 'formctn',
            items: [{
                xtype: 'fieldset',
                title: 'Personal Info',
                defaults: {
                    xtype: 'customtext' //Here I am using {customtext}
                },
                items: [{
                    label: 'First Name',
                    name: 'firstName',
                    bind: {
                        value: '{user.firstName}',
                        //You can also use like property
                        //hidden:'{permissionCng.firstName}'
                    }
                }, {
                    label: 'Last Name',
                    name: 'lastName',
                    bind: {
                        value: '{user.lastName}',
                        //You can also use like property
                        //hidden:'{permissionCng.firstName}'
                    }
                }, {
                    label: 'Email Id',
                    name: 'email',
                    bind: {
                        value: '{user.email}',
                        //You can also use like property
                        //hidden:'{permissionCng.firstName}'
                    }
                }, {
                    label: 'Admin Name',
                    name: 'isAdmin',
                    bind: {
                        value: '{user.isAdmin}',
                        //You can also use like property
                        hidden: '{!permissionCng.isAdmin}'
                    }
                }]
            }]
        });
    }
});


text:
Q: Get Application exe size easily Is there a way in Delphi to get the currect application's exe size in one or two lines of code?

A: It's not as small as you want, but it needs no handles.  I use this in all my "SFX" archivers and programs that must know their size.  IIRC it requires the Windows unit.
function GetExeSize: cardinal;
var
  p: pchar;
  i, NumSections: integer;
const
  IMAGE_PE_SIGNATURE  = $00004550;
begin
  result := 0;
  p := pointer(hinstance);
  inc(p, PImageDosHeader(p)._lfanew + sizeof(dword));
  NumSections := PImageFileHeader(p).NumberOfSections;
  inc(p,sizeof(TImageFileHeader)+ sizeof(TImageOptionalHeader));
  for i := 1 to NumSections do
  begin
    with PImageSectionHeader(p)^ do
      if PointerToRawData+SizeOfRawData > result then
        result := PointerToRawData+SizeOfRawData;
    inc(p, sizeof(TImageSectionHeader));
  end;
end;

A: For the sake of future compatibility, you should choose an implementation that does not require pointers or Windows API functions when possible. The TFileStream based solution provided by skamradt looks good to me.
But... You shouldn't worry too much whether the routine is 1 or 10 lines of code, because you're going to encapsulate it anyway in a function that takes a filename as a parameter and returns an Int64, and put it in your personal library of reusable code. Then you can call it like so:
GetMyFileSize(Application.ExeName);

A: Unfortunatly it is not possible to do that with only one or two lines of code without using some library.
The easy part is getting the application's exe file. You can find it in Application.ExeName
In general there are several possibilities for retrieving the file size:

*

*Open the file and read the size of the stream. This can be accomplished using the 'old' Delphi functions FileOpen and FileSize, or with TFileStream (use the size property) or with Win32 API functions CreateFile and GetFileSize function. (Platform dependend!) Make sure you open the file with read-only access.

*In a pure Win32 envinronment you can use FindFirst to get the file size. You can read it from TSearchRec.FindData.nFileSizeLow. If you want to be prepared for files larger than 2 GB (you should be) you have to use also the nFileSizeHigh part.

*In Delphi.NET you can use the System.IO.FileInfo, like this: FileInfo.Create(filename).Length (one-liner)

*In Linux you can use the lstat64 function (Unit Libc) and get the size from TStatBuf64.st_size.  (two-liner if you don't count the variable declaration)

In the JCL library you can find many useful functions, including a simple function which returns the file size of a given file name. (It uses a method which suits the given platform)

A: You can try this:
  if FindFirst(ExpandFileName(Application.exename), faAnyFile, SearchRec) = 0 then
    MessageDlg(Format('Tamaño: <%d>',[SearchRec.Size]), mtInformation, [mbOK], 0);
  FindClose(SearchRec);

===============
Neftalí

A: Streams can also be used without a TFileStream variable:
with TFilestream.create(paramstr(0), fmOpenRead or fmShareDenyNone) do
  aFileSize := Size;
  Free;
end;

Ugly, yes.
I prefer using DSiFileSize from DSiWin32. It uses CreateFile internally:
function DSiFileSize(const fileName: string): int64;
var
  fHandle: DWORD;
begin
  fHandle := CreateFile(PChar(fileName), 0, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if fHandle = INVALID_HANDLE_VALUE then
    Result := -1
  else try
    Int64Rec(Result).Lo := GetFileSize(fHandle, @Int64Rec(Result).Hi);
  finally CloseHandle(fHandle); end;
end; { DSiFileSize }

A: uses IdGlobalProtocols;

var
  ExeSize: Int64;
begin
  ExeSize := FileSizeByName(ParamStr(0));
  // or
  ExeSize := FileSizeByName(Application.ExeName);
end;

A: Just for grins...you can also do this with streams  Just slightly more than 2 lines of code.  Generally the application filename including path is also stored into Paramstr(0).
var
  fs : tFilestream;
begin
  fs := tFilestream.create(paramstr(0),fmOpenRead or fmShareDenyNone);
  try
    result := fs.size;
  finally
    fs.free;
  end;
end;

A: I would like to modify the code provided by skamradt, to make it two lines of code as you requested ;-)
  with tFilestream.create(paramstr(0),fmOpenRead or fmShareDenyNone) do
    ShowMessage(IntToStr(size));

but I would prefer to use the code as skamradt wrote, because it's more safe

A: Shortest I could do.  Note that the .Size is in bytes, so for kilobytes, divide by 1024.
procedure TForm1.Button1Click(Sender: TObject);
begin
  with TFileStream.Create(Application.ExeName,fmShareDenyNone) do
    ShowMessage(FloatToStr(Size/1024));
end;

Check out this link.


text:
Q: Modify an imported framework source code I want to add this library to my project without using Pods. I also want to be able to modify its source code. In their git they explain that the most suitable way to do it is to drag the Charts.xcodeproj file to the project:

Yes you can copy it the classes like before. However it's more
  comfortable to drag the xcodeproj to the project. It's not recommended
  to drag the sources themselves, as this will make updating Chrats in
  your project more difficult.

I added the xcodeproj file to my project, compiled it and added it to My Project -> Build Phases -> Link Binary With Libraries. When I build the project the app crashed with a signal SIGABRT error. I googled the problem and than I added the Charts.framework in General -> Embedded Binaries. The App compiled and worked fine after that but modifying the source code in Charts.xcodeproj -> Charts -> Source dose not have any effect on the library. I am confused. How can I add the library to my project in a way that other people will not have to do it again when they download the project, and also to be able to modify the project source code?


text:
Q: ASP.NET CORE DI in model I'm trying to understand how DI works in the new ASP Core. With a tutorial, I made it work for controllers, but can't make it work for models. For example, I have an AuthController, and I injected the database context to it, but now, as I have more controllers, sharing the same model, which is Authentication, I'd like to inject the context to the model itself. Here's some piece of code I've:
From the Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddDbContext<GameContext>(options => options.UseSqlServer(@"Data Source=DESKTOP-USER\SQLEXPRESS;Initial Catalog=Db7;Integrated Security=True;Connect Timeout=30;"));
}

And here's how I used it from controllers:
[Route("api/[controller]")]
public class AuthController : Controller
{
    public GameContext db;
    public AuthController(GameContext context)
    {
        db = context;
    }

    [HttpPost]
    [Route("login")]
    public LoginResponseModel Login([FromBody] LoginModel user) //public Models.VM.LoginModel Login([FromBody] Models.VM.LoginModel user)
    {
        //query user
        var detectedUser = db.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == HelperClass.Md5(user.Password);

If I remove the context part from the controller, and move it to the model, I won't be able to instatntiate it again as the constructor needs an argument (which would be injected automatically?)
public class Authentication
{
    public GameContext db;

    public Authentication(GameContext context)
    {
        db = context;
    }
    ...

How could I reach the database from the model?
EDIT:
This is how my Authentication class would look like (constructor may look different based on the solution):
public class Authentication
{
    public GameContext db;

    public Authentication(GameContext context)
    {
        db = context;
    }

    public LoginResponseModel Login(LoginModel user)
    {
        //query user
        var detectedUser = db.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == HelperClass.Md5(user.Password));

And here's how I would like to use this model from controllers:
[Route("api/[controller]")]
public class AuthController : Controller
{

    public AuthController(GameContext context)
    {
    }

    // POST api/login
    [HttpPost]
    [Route("login")]
    public LoginResponseModel Login([FromBody] LoginModel user) //public Models.VM.LoginModel Login([FromBody] Models.VM.LoginModel user)
    {
        Authentication auth = new Authentication(); //throws error since no parameter passed

        return auth.Login(user);
    }

A: You basically making a reusable service for other controllers.
start by creating an abstraction of the functionality you want.
public interface IAuthenticationService {
    LoginResponseModel Login(LoginModel user);
}

and have the implementation inherit from this interface
public class Authentication : IAuthenticationService {
    private readonly GameContext db;

    public Authentication(GameContext context) {
        db = context;
    }

    public LoginResponseModel Login(LoginModel user) {
        //query user
        var detectedUser = db.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == HelperClass.Md5(user.Password));
        //...other code that creates and returns an instance of LoginResponseModel
    }
}

with that in place you need to register the interface with the service collection so that the DI framework is aware of what to inject whenever it sees that interface.
Source: Asp.Net Core Fundamentals: Dependency Injection
public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddDbContext<GameContext>(options => options.UseSqlServer(@"Data Source=DESKTOP-USER\SQLEXPRESS;Initial Catalog=Db7;Integrated Security=True;Connect Timeout=30;"));
    // Add application services.
    services.AddTransient<IAuthenticationService, Authentication>();
}

and now any controller that needs access to the service can have it injected into its constructor
[Route("api/[controller]")]
public class AuthController : Controller {
    private readonly IAuthenticationService auth;

    public AuthController(IAuthenticationService auth) {
        this.auth = auth;
    }

    // POST api/login
    [HttpPost]
    [Route("login")]
    public LoginResponseModel Login([FromBody] LoginModel user) {
        return auth.Login(user);
    }
}

The DI framework will handle all the heavy lifting of creating and injecting the service. You now don't have to create the instances yourself.


text:
Q: Azure SQL database data archive solution We have Azure SQL database , we need build data archival solution to manage data more than 2 years old.
Requirement:

*

*Archive and delete more than 2 years data from certain transaction tables.

*Should archive the data in low cost storage.

*Should be able to quickly restore the data if required.

*Looking for recurring job need to execute on every week.

Please recommend an azure solution to achieve this.

A: Here are the approaches you can try:

*

*If you want to archive the complete database, you can Export a bacpac directly from Azure Portal. This bacpac file will be stored in existing Azure Storage account. Once done, you can delete the data from database. Refer Export to a BACPAC file - Azure SQL Database.

If you need to only archive 2 years of data, you can create a Stored Procedure for each table in your database. You can run that SP using Stored Procedure activity in Azure Data Factory.

*The cheapest (free) option to store archive data is by creating bacpac file and store it in local machine. Or else you can use Blob Storage cold storage service for archiving data.

*To restore data from bacpac, just simply import the bacpac file in your database. To restore from Blob Storage, update the container from cool to hot and use ADF to copy from that file into destination database.

*If you are using SP activity in ADF as mentioned in point 1, you can trigger the ADF pipeline to run your SP weekly/monthly or whenever as per your requirement. Refer Schedule Trigger in ADF.


text:
Q: Can't mysql autocast encoding in query data? i am getting error "Illegal mix of collations"
i know either i need to change db tables to utf8 or convert user input to latin1 or ansii
so i want to know, can mysql do this automatically so i won't need to change table encoding and also no need to modify my exiting queries with COLLATE expression.

A: There are good explanations why MySQL can't do it automatically:
https://stackoverflow.com/a/12260863/1261575
https://stackoverflow.com/a/21061305/1261575


text:
Q: Override autofocus attribute with Javascript/JQuery If I have two input fields, one with the autofocus attribute and one without, how do I focus on the one without the autofocus attribute on document load? For instance:

<input name="foo" type="text">

<input autofocus name="bar" type="text">

When I load the page, the cursor is fixed on the second input field instead of the first. I have tried the commented out lines to try and fix this somehow but I have had no success.
Edit:
I have tried the solution mentioned in the "duplicate question", which was to use .blur() on the element, but that did not work. Additionally, the duplicate question only answers how to disable the autofocus and does not answer how to re-focus on another input field afterwards.

A: After spending some more time with this, I finally figured out that 'focus' was firing too early. To solve this problem, all I had to do was wrap it in a settimeout:
setTimeout(function() {
    $("#myTags input[type=\"text\"]").focus();
}, 20);
$("input[autofocus]").blur();


text:
Q: netty 4: set default endianness of ByteBuf Is there a way to tell Netty 4 that all ByteBuf instances it creates should have LITTLE_ENDIAN endianness?
Calling order(ByteOrder) in every handler is annoying.
It looks like Netty 3 supported this: Netty and ByteOrder

A: I wouldn't expect one: big-endian is the ordering of network protocols, so makes sense as the default. And exposing a static variable to set the default would be an invitation for hard-to-diagnose bugs (particularly in a shared server).
I think your best approach is to create a new factory class, to produce the buffers you need. Assuming that you're currently using Unpooled (per recommendation), it should be a simple search-and replace operation.
You could also update Unpooled itself, providing variants that take a byte-order param, and submit it back to the project.