How to set orientation in nativescript

Question: Hello I would like to know how to set device orientation in nativescript.
Specifically I want the application that I am writing to stay in the same orientation (portrait) at all times so that rotating the device does not cause it to go into landscape.
I tried the nativescript-orientation plugin and setOrientation.
var orientation = require('nativescript-orientation');
console.log(JSON.stringify(orientation));// outputs JS: {}
orientation.setOrientation("portrait");

However I get the error "Cannot read property setOrientation of undefined.
tns plugin list shows that the plugin is installed. Also I tried removing the platforms/android directory and running tns platform add android with the same result.
I also tried putting various combinations of android:screenOrientation="portrait" into AndroidManifest.xml without success.
AndroidManifest.xml from inside App_resources looks like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="__PACKAGE__"
    android:versionCode="1"
    android:versionName="1.0">

    <supports-screens
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"/>

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="__APILEVEL__"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:screenOrientation="portrait"
        android:name="com.tns.NativeScriptApplication"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity
            android:name="com.tns.NativeScriptActivity"
            android:label="@string/title_activity_kimera"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:theme="@style/LaunchScreenTheme">
            <meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="@style/AppTheme" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.tns.ErrorReportActivity"/>
    </application>
</manifest>

Comment: after modifying the AndroidManifest.xml did you do a complete `build`? Also you likely need to uninstall the current .apk you have on the device/emulator and then `run` or `livesync` the new build. The manifest option is the better alternative to force one orientation on android apps from what I know. So it will work but if you didn't uninstall the old .apk you likely have a caching issue on the device :)
Comment: I have deleted the apk and run it using `tns run android`. Also I added the android manifest.xml in case I missed something
Answer: You will have to update your AndroidManifest.xml & Info.plist in your App_Resources.
AndroidManifest.xml
Set screenOrientation to portrait on your main activity
<activity android:name="com.tns.NativeScriptActivity"
 ...
 android:screenOrientation="portrait">

Info.plist
Keep only the portrait orientation, remove rest from UISupportedInterfaceOrientations.
<key>UISupportedInterfaceOrientations</key>
<array>
  <string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
  <string>UIInterfaceOrientationPortrait</string>
  <string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>

Note: Make sure you run a clean build after these changes.
Comment: For `iOS` you can go to `app/App_Resources/iOS/Info.plist`. Inside this file you will find `UIInterfaceOrientationPortrait` and Landscape etc... Just comment out or delete the orientations you don't want to support. No need to open Xcode :)
Comment: I put it inside the `activity` tag. Where did you put it?
Comment: Thanks for your suggestion however I added it the flag to the Android manifest already and it does not seem to work. I updated my post with the manifest. perhaps I put the flag in the wrong place? Can you look at it and tell me please?
Comment: I see that you put it inside `application` tag but outside `activity`. Try putting it into `activity`. P/s: edited answer
Comment: Oh wow. Idk I thought I put it in the activity tag. I guess the first time I did it I didn't delete the apk off of the device.
Answer: For iOS: (Without Xcode, just manipulate one file.)

Open file app/App_Resources/iOS/Info.plist
Comment out or delete:
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>

app/App_Resources/iOS/Info.plist
    ...
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>

(Props to @mudlabs, who already mentioned this solution in a comment.)
Answer: In case you are using NativeScript Sidekick it is possible to set orientation for Android an iOS from project properties.
Answer: The top answer is correct but for some cases, adding only android:screenOrientation does not work.
I got it working by adding android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation|screenSize" and take note the order, screenOrientation first before the configChanges.
Actually i've tested it in both android studio and the Nativescript.

How to set orientation in nativescript


display multiple data horizontally

Question: how to display data horizontally in a list box. I had used the properties for reading data from the text box and i have to display these multiple data in to a list box (in one line, horizontally) . my code is shown below..
private void SaveButton_Click(object sender, RoutedEventArgs e)
    {
        LoadData();

    }

private void LoadData()
    {
        List<ItemList> MyList = new List<ItemList>();
        MyList.Add(new ItemList { Subject = subjectText.Text });
        MyList.Add(new ItemList { Createdtext = CreatedText.Text });
        MyList.Add(new ItemList { Calendartext = CalendarText.Text });
        MyList.Add(new ItemList { TimeText = TimeText.Text });
        MyList.Add(new ItemList { AssignedText = AssignedText.Text });
        MyList.Add(new ItemList { DescriptionText = DescriptText.Text });
        MyList.Add(new ItemList { TargetdateText = TargetDateText.Text });

        MyListBox.ItemsSource = MyList;

    }

The property for getting data is:
public class ItemList
{
    private string _subject;
    private string _createdtext;
    private string _calendartext;
    private string _timeText;
    private string _assignedText;
    private string _descriptionText;
    private string _targetdateText;

    public string Subject
    {
        get
        {
            return _subject;
        }
        set
        {
            _subject = value;
        }
    }

    public string Createdtext
    {
        get
        {
            return _createdtext;
        }
        set
        {
            _createdtext = value;
        }
    }

    public string Calendartext
    {
        get
        {
            return _calendartext;
        }

        set
        {
            _calendartext = value;
        }
    }

    public string TimeText
    {
        get
        {
            return _timeText;
        }

        set
        {
            _timeText = value;
        }
    }

    public string AssignedText
    {
        get
        {
            return _assignedText;
        }

        set
        {
            _assignedText = value;
        }
    }

    public string DescriptionText
    {
        get
        {
            return _descriptionText;
        }

        set
        {
            _descriptionText = value;
        }
    }

    public string TargetdateText
    {
        get
        {
            return _targetdateText;
        }

        set
        {
            _targetdateText = value;
        }
    }
}

My XAML code for List box is shown below
<ListBox x:Name="MyListBox" ItemsSource="ItemList" Grid.ColumnSpan="6" HorizontalAlignment="Left"  Grid.Column="1" Grid.Row="8" Width="600" Height="96">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel  Orientation="Horizontal" >
                    <Grid ShowGridLines="True" Width="700">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="25" />

                        </Grid.RowDefinitions>

                     <TextBlock Text="{Binding Subject}" Grid.Column="0"/>
                    <TextBlock Text="{Binding Createdtext}"  Grid.Column="1" />
                    <TextBlock Text="{Binding Calendartext}" Grid.Column="2" />
                    <TextBlock Text="{Binding Timetext}" Grid.Column="3"/>
                    <TextBlock Text="{Binding AssignedText}"  Grid.Column="4"/>
                    <TextBlock Text="{Binding DescriptionText}"  Grid.Column="5" />
                    <TextBlock Text="{Binding TargetdateText}"  Grid.Column="6"/>
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

but i didn't get the output in one line. it displayed in diagonally.. What are the changes required for getting correct output..
Comment: This is a dupe of http://stackoverflow.com/questions/1165236/silverlight-3-list-box
Answer: <ListBox x:Name="MyListBox" ItemsSource="ItemList" Grid.ColumnSpan="6" HorizontalAlignment="Left"  Grid.Column="1" Grid.Row="8" Width="600" Height="96">
...
        <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
...
</ListBox>

try this
Comment: No, unfortunately `VirtualizingStackPanel` is not in Silverlight 2.0 or 3.0. Try to use `StackPanel` instead.
Comment: Is the  tag available on silverlight 2.0??
Comment: you are right, VirtualizingStackPanel only in WPF use StackPanel instead
Answer: Have a look at the MSDN page for the ItemsPanel property. It has an example demonstrating how to create a horizontal list box.

display multiple data horizontally


javafx.scene.media.MediaView cannot be cast to javafx.scene.Parent

Question: I have a MediaView and I want to play a fullscreen video ..  i just can't find the right parent to my MediaView .. it gives me this error
javafx.scene.media.MediaView cannot be cast to javafx.scene.Parent
that's my fxml file
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.media.*?>
<?import javafx.scene.layout.AnchorPane?>

<MediaView fx:id="astrolabe_intro" fitHeight="200.0" fitWidth="200.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="astrolabe.astrolabe_introController" />

and that's my controller
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.Initializable;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class astrolabe_introController implements Initializable {

    String workingDir = System.getProperty("user.dir");
    File video = new File(workingDir, "src/astrolabe/img/astrolab_movie.mp4");
    Media m = new Media(video.toURI().toString());
    MediaPlayer astrolabe_intro = new MediaPlayer(m);

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        // TODO Auto-generated method stub

        astrolabe_intro.play();

    }

}

Answer: You must not use MediaView as the root node, because it doesn't extend from Parent. Try to wrap your MediaView inside a Pane. For example :
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.media.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane fx:id="anchorPane" fitHeight="200.0" fitWidth="200.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="astrolabe.astrolabe_introController" >
    <MediaView fx:id="astrolabe_intro"/>
</AnchorPane>

N.B. You might also want to define different reference name for your MediaView and MediaPlayer. In the above example you have defined fx:id of MediaView and ref for MediaPlayer as astrolabe_intro
A simple example of MediaView/MediaPlayer is here and FXML is here
Comment: Yes that is completely incorrect, you must start learning about how fxml works, start with the examples. I have provided a link, going through it will give you a better idea.
Comment: i thought that giving both the same id will link the media player to media view like saying " play that media on this view " .. is that wrong ?


brew update and or brew doctor throwing errors

Question: When I try brew update, I get the following error. How can I fix it
~$ brew update
Error: undefined method `close!' for nil:NilClass
Please report this bug:
    https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Troubleshooting.md#troubleshooting
/usr/local/Library/Homebrew/extend/pathname.rb:129:in `ensure in atomic_write'
/usr/local/Library/Homebrew/extend/pathname.rb:129:in `atomic_write'
/usr/local/Library/Homebrew/cmd/untap.rb:42:in `unlink_tap_formula'
/usr/local/Library/Homebrew/cmd/update.rb:24:in `update'
/usr/local/Library/brew.rb:136:in `'

Answer: Here is the exact issue closed on homebrew github repo brew update gives NilClass error.
So here's how I got it working:

Full uninstall of brew. For me I just wiped my /usr/local directory
as this is a clean machine at the moment.
Full uninstall of RVM.
Make sure my command line tools are up to date "xcode-select --install"
su to admin account and install Homebrew
update /usr/local and all sub files/dirs to have my account as owner - "sudo chown -R jmcdonald ."
"brew install ..." for all of these RVM/Ruby required libs: autoconf,
automake, libtool, apple-gcc42, libyaml, libxslt, libksba, openssl
(apple-gcc42 gave me errors but doesn't seem to have impact).
Exit su and install RVM.
Install a ruby: "rvm install 1.9.3"

I would guess I could have gotten it working without removals but wanted to make sure I had a clean setup.
Comment: ~$ RUBYOPT= RUBYLIB= brew update
-bash: /usr/local/bin/brew: No such file or directory
Comment: rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
(permission denied) for uninstalling homebrew, as I didn't go the route of http://superuser.com/questions/203707/how-to-uninstall-homebrew-osx-package-manager
Comment: no, for permission denied instructions (from my answer)
Comment: I'll follow the instructions given -


Can't delete amplify app from amplify dashboard

Question: I Can't delete app_name app from the dashboard
Can't delete app_name app: Removing backend envs for app XXX failed
I deleted an associated S3 bucket & CloudFormation manually.
I've tried everything and I can't delete an app
Comment: AWS-Amplify's GitHub forum is having the same question.
https://github.com/aws-amplify/amplify-hosting/issues/882
Comment: did you create the amplify panel or CLI? If you created it in CLI, you must remove it from CLI.
Answer: open AWS CloudShell and  run cmd: aws amplify delete-app --app-id <your_app-id>
you can find amplify app id at amplify app detail
Comment: If you spend more than 10s looking for the app id... just click on the app in the overview and look at the last segment of your URL, that's the app id
Comment: yub, good idea, thank you.
Comment: Note that the `app-id` is separate from the app name, see this post for finding the `app-id` https://stackoverflow.com/questions/67885683/how-to-find-the-aws-amplify-appid
Answer: Try to use AWS CLI and either :

run command "aws amplify delete-app" (you will need appid) or
run command "aws amplify delete-backend-environment (you will need appid and environment name) and after that try to delete the app by using console again.
Comment: I had to disconnect a lot before this command worked for me.
Answer: It appears that you've been having an issue distinct from, but related to this one: AWS Amplify: How to delete the environment, when resources are already partially deleted?
In your case, you mention that you've deleted the S3 bucket & CloudFormation stack associated with the amplify app manually.
As of 9/26/2022 Amplify released an update that fixes issues deleting apps/backends, including issues where the s3 bucket and cloudformation stack was already deleted as you mention you have done.


Selecionar texto do textarea ao clicar

Question: Como posso fazer para, quando clicar em um determinado button, o texto de um determinado textarea ou input ser selecionado?
Queria respostas com soluções com jQuery e também sem jQuery (javascript puro).
Answer: Em jQuery você simplesmente utiliza o evento select();

$('#btnSelecionar').click(function(){
$('#txtInput').select();
});

<textarea rows="4" cols="50" id="txtInput">
Testando textarea stackoverflow.
</textarea>

<input type="button" value="Selecionar" id="btnSelecionar"/>

Em javascript você vai seguir a mesma lógica. Seleciona o elemento e utiliza o método select() para selecionar o texto. Ficando assim:

<textarea rows="4" cols="50" id="txtInput">
Testando textarea stackoverflow.
</textarea>

<button type="button" onclick="myFunction()">Selecionar</button>

Comment: +1 Sem brincadeira, @Randrade, não pensei que fosse tão fácil!
Comment: Agora, tem como mostrar um exemplo em somente javascript?
Comment: @WallaceMaxters Está ai
Comment: Valeu, amigo!!!
Comment: No IE do Windows Phone apertar esse "selecionar" fecha o navegador, hahahaha #partiu reportar bug.
Comment: @renan Quero pelo menos 1% do que ganhar! kkk
Answer: Jquery:
 $(function() {
   $(document).on('click', 'input[type=text][id=example1]', function() {
     this.select();
   });
 });

JS Puro:
document.getElementById("example2").onclick = function(){
  document.getElementById("example2").select();
}

 $(function() {
   $(document).on('click', 'input[type=text][id=example1]', function() {
     this.select();
   });
 });

document.getElementById("example2").onclick = function(){
  document.getElementById("example2").select();
}
JQuery:

<input type="text" id="example1" value="click the input to select" onclick="this.select();"/>

Js Puro:
<input type="text" id="example2" value="click the input to select" onclick="this.select();"/>

Selecionar texto do textarea ao clicar


Can't set policy `ACCEPT' on `FORWARD' in *nat: Bad built-in chain name

Question: I'm on Debian 10 and just tried to apply some firewall rules that I think have worked on older versions of Debian. But now I'm getting an error when I try to apply them. It seems to be related to :FORWARD ACCEPT [0:0], but I can't figure out what the problem is.
My *nat rules:
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -o ens3 -j MASQUERADE
COMMIT

When I try to load them:
$ sudo netfilter-persistent reload
run-parts: executing /usr/share/netfilter-persistent/plugins.d/15-ip4tables start
run-parts: /usr/share/netfilter-persistent/plugins.d/15-ip4tables exited with return code 1

The problem seems to be in line 4:
$ sudo iptables-restore --test  /etc/iptables/rules.v4
iptables-restore v1.6.1: Can't set policy `ACCEPT' on `FORWARD' line 4: Bad built-in chain name

Do I need a different version of a certain package? Any ideas?
Answer: There is no FORWARD chain under nat table in Linux netfilter. You just need to remove the line number 4:
:FORWARD ACCEPT [0:0]


How to Generate Scripts For All Triggers in Database Using Microsoft SQL Server Management Studio

Question: I'd like to generate an SQL Script that contains the SQL to create all of the triggers that exist in our database.  The triggers were added directly via the SSMS query pane so, there is currently no source other than the trigger on the database itself.
I have already tried the method where you right-click the database, select Tasks->Generate Scripts and used the "Script Entire Database and All Objects" option.  While this does create a SQL script for the tables and constraints, it does not generate SQL for the triggers.
I also understand that I can right click on each trigger in the database and select the Generate SQL Script option but, there is currently 46 tables under audit (For Insert, Update, and Delete).
Rather manually generate an insert, update, and delete trigger script for each of the 46 tables, is there an easier way to do this?  Or, should I start clicking, copying, and pasting?
Answer: Database-> Tasks-> Generate Scripts -> Next -> Next
On Choose Script Options UI, under Table/View Options Heading, set Script Triggers to True.
Comment: How do you use this if you wish to generate ONLY the triggers?
Comment: In SSMS2012, the Options dialog is found by clicking Advanced in the Set Scripting Options step.
Comment: It is intensely irritating that Script Triggers is False by default.  It's very counterintuitive, and has probably tripped up many.
Answer: I know the answer has been accepted already, but want to provide another solution for cases when for some reason SSMS wizard is not able to generate script for triggers (in my case it was MSSQL2008R2)
This solution is based on idea from dana above, but uses 'sql_modules' instead to provide the full code of the trigger if it exceeds 4000 chars (restriction of 'text' column of 'syscomments' view)
select [definition],'GO' from sys.sql_modules m
inner join sys.objects obj on obj.object_id=m.object_id
 where obj.type ='TR'

Right click on the results grid and then "Save results as..." saves to file with formatting preserved
Comment: SELECT
  sch.name AS schema_name
 ,parent.name AS table_name
 ,obj.name AS trigger_name
 ,m.[definition] AS trigger_definition
FROM sys.sql_modules AS m
INNER JOIN sys.objects AS obj ON obj.object_id=m.object_id
INNER JOIN sys.objects AS parent ON parent.object_id = obj.parent_object_id
INNER JOIN sys.schemas AS sch ON sch.schema_id = parent.schema_id

WHERE obj.type ='TR'
Answer: How about this?
select text from syscomments where text like '%CREATE TRIGGER%'
EDIT - per jj's comment below, syscomments is deprecated and will be removed in the future.  Please use either the wizard-based or script-based solutions listed above moving forward :)
Comment: Quick note: syscomments is deprecated (will be removed sometime after SQL 2014), Microsoft recommends using sys.sql_modules
Comment: This did appear to pull back the triggers but, everything was in one row of the table and it wasn't formatted.  KPL's answer did the trick for me.  Thanks for the answer though.  I was not aware of the syscomments table.
Comment: @MAW74656 - Uncle... I guess my answer was intended to be more of a quick and dirty way to find triggers w/o using a GUI.  The accepted answer probably works best for most folk.  However, it is sometimes nice to have an low-level alternative.  It looks like Igor has taken things a step further than I did, and at this point I would probably go with what he has.  However, I'll leave up my answer for reference.
Comment: Interesting.  I had not thought of that, but it is a good idea :)
Comment: -1 Results do not contain entire text of my triggers.
Answer: To script all triggers you can define the stored procedure:
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Procedure:
--   [dbo].[SYS_ScriptAllTriggers]
--
-- Parameter:
--   @ScriptMode bit
--     possible values:
--     0 - Script ALTER only
--     1 - Script CREATE only
--     2 - Script DROP + CREATE

ALTER PROCEDURE [dbo].[SYS_ScriptAllTriggers]
    @ScriptMode int = 0
AS
BEGIN

    DECLARE @script TABLE (script varchar(max), id int identity (1,1))

    DECLARE
        @SQL VARCHAR(8000),
        @Text            NVARCHAR(4000),
        @BlankSpaceAdded INT,
        @BasePos         INT,
        @CurrentPos      INT,
        @TextLength      INT,
        @LineId          INT,
        @MaxID           INT,
        @AddOnLen        INT,
        @LFCR            INT,
        @DefinedLength   INT,
        @SyscomText      NVARCHAR(4000),
        @Line            NVARCHAR(1000),
        @UserName        SYSNAME,
        @ObjID           INT,
        @OldTrigID       INT;

    SET NOCOUNT ON;
    SET @DefinedLength = 1000;
    SET @BlankSpaceAdded = 0;

    SET @ScriptMode = ISNULL(@ScriptMode, 0);

    -- This Part Validated the Input parameters
    DECLARE @Triggers TABLE (username SYSNAME NOT NULL, trigname SYSNAME NOT NULL, objid INT NOT NULL);
    DECLARE @TrigText TABLE (objid INT NOT NULL, lineid INT NOT NULL, linetext NVARCHAR(1000) NULL);

    INSERT INTO
        @Triggers (username, trigname, objid)
    SELECT DISTINCT
        OBJECT_SCHEMA_NAME(B.id), B.name, B.id
    FROM
        dbo.sysobjects B, dbo.syscomments C
    WHERE
        B.type = 'TR' AND B.id = C.id AND C.encrypted = 0;

    IF EXISTS(SELECT C.* FROM syscomments C, sysobjects O WHERE O.id = C.id AND O.type = 'TR' AND C.encrypted = 1)
    BEGIN

        insert into @script select '/*';
        insert into @script select 'The following encrypted triggers were found';
        insert into @script select 'The procedure could not write the script for it';

        insert into
            @script
        SELECT DISTINCT
            '[' + OBJECT_SCHEMA_NAME(B.id) + '].[' + B.name + ']' --, B.id
        FROM
            dbo.sysobjects B, dbo.syscomments C
        WHERE
            B.type = 'TR' AND B.id = C.id AND C.encrypted = 1;

        insert into @script select '*/';
    END;

    DECLARE ms_crs_syscom CURSOR LOCAL forward_only FOR
    SELECT
        T.objid, C.text
    FROM
        @Triggers T, dbo.syscomments C
    WHERE
        T.objid = C.id
    ORDER  BY T.objid,
        C.colid
    FOR READ ONLY;

    SELECT @LFCR = 2;
    SELECT @LineId = 1;

    OPEN ms_crs_syscom;

    SET @OldTrigID = -1;

    FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;

    WHILE @@fetch_status = 0
    BEGIN

        SELECT @BasePos = 1;
        SELECT @CurrentPos = 1;
        SELECT @TextLength = LEN(@SyscomText);

        IF @ObjID <> @OldTrigID
        BEGIN
            SET @LineID = 1;
            SET @OldTrigID = @ObjID;
        END;

        WHILE @CurrentPos != 0
        BEGIN
            --Looking for end of line followed by carriage return
            SELECT @CurrentPos = CHARINDEX(CHAR(13) + CHAR(10), @SyscomText, @BasePos);

            --If carriage return found
            IF @CurrentPos != 0
            BEGIN

                WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @CurrentPos - @BasePos + @LFCR ) > @DefinedLength
                BEGIN
                    SELECT @AddOnLen = @DefinedLength - (ISNULL(LEN(@Line), 0) + @BlankSpaceAdded );

                    INSERT
                        @TrigText
                    VALUES
                        ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));

                    SELECT
                        @Line = NULL,
                        @LineId = @LineId + 1,
                        @BasePos = @BasePos + @AddOnLen,
                        @BlankSpaceAdded = 0;
                END;

                SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @CurrentPos - @BasePos + @LFCR), N'');

                SELECT @BasePos = @CurrentPos + 2;

                INSERT
                    @TrigText
                VALUES
                    ( @ObjID, @LineId, @Line );

                SELECT @LineId = @LineId + 1;

                SELECT @Line = NULL;
            END;
            ELSE
            --else carriage return not found
            BEGIN
                IF @BasePos <= @TextLength
                BEGIN
                    /*If new value for @Lines length will be > then the
                    **defined length
                    */
                    WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @TextLength - @BasePos + 1 ) > @DefinedLength
                    BEGIN
                        SELECT @AddOnLen = @DefinedLength - ( ISNULL(LEN(@Line), 0 ) + @BlankSpaceAdded );

                        INSERT
                            @TrigText
                        VALUES
                            ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));

                        SELECT
                            @Line = NULL,
                            @LineId = @LineId + 1,
                            @BasePos = @BasePos + @AddOnLen,
                            @BlankSpaceAdded = 0;
                    END;

                    SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @TextLength - @BasePos+1 ), N'');

                    IF LEN(@Line) < @DefinedLength AND CHARINDEX(' ', @SyscomText, @TextLength + 1) > 0
                    BEGIN
                        SELECT
                            @Line = @Line + ' ',
                            @BlankSpaceAdded = 1;
                    END;
                END;
            END;
        END;

        FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;
    END;

    IF @Line IS NOT NULL
        INSERT
            @TrigText
        VALUES
            ( @ObjID, @LineId, @Line );

    CLOSE ms_crs_syscom;

    insert into @script select '-- You should run this result under dbo if your triggers belong to multiple users';
    insert into @script select '';

    IF @ScriptMode = 2
    BEGIN

        insert into @script select '-- Dropping the Triggers';
        insert into @script select '';

        insert into @script
        SELECT
            'IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(''[' + username + '].[' + trigname + ']'')'
            + ' AND ObjectProperty(OBJECT_ID(''[' + username + '].[' + trigname + ']''), ''ISTRIGGER'') = 1)'
            + ' DROP TRIGGER [' + username + '].[' + trigname +']' + CHAR(13) + CHAR(10)
            + 'GO' + CHAR(13) + CHAR(10)
        FROM
            @Triggers;
    END;

    IF @ScriptMode = 0
    BEGIN
        update
            @TrigText
        set
            linetext = replace(linetext, 'CREATE TRIGGER', 'ALTER TRIGGER')
        WHERE
            upper(left(replace(ltrim(linetext), char(9), ''), 14)) = 'CREATE TRIGGER'
    END

    insert into @script select '----------------------------------------------';
    insert into @script select '-- Creation of Triggers';
    insert into @script select '';
    insert into @script select '';

    DECLARE ms_users CURSOR LOCAL forward_only FOR
    SELECT
        T.username,
        T.objid,
        MAX(D.lineid)
    FROM
        @Triggers T,
        @TrigText D
    WHERE
        T.objid = D.objid
    GROUP BY
        T.username,
        T.objid
    FOR READ ONLY;

    OPEN ms_users;

    FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;

    WHILE @@fetch_status = 0
    BEGIN

        insert into @script select 'setuser N''' + @UserName + '''' + CHAR(13) + CHAR(10);

        insert into @script
        SELECT
            '-- Text of the Trigger' =
            CASE lineid
                WHEN 1 THEN 'GO' + CHAR(13) + CHAR(10) + linetext
                WHEN @MaxID THEN linetext + 'GO'
                ELSE linetext
            END
        FROM
            @TrigText
        WHERE
            objid = @ObjID
        ORDER
            BY lineid;

        insert into @script select 'setuser';

        FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;
    END;

    CLOSE ms_users;

    insert into @script select 'GO';
    insert into @script select '------End ------';

    DEALLOCATE ms_crs_syscom;
    DEALLOCATE ms_users;

    select script from @script order by id

END

How to execute it:
SET nocount ON
DECLARE @return_value INT

EXEC @return_value = [dbo].[SYS_ScriptAllTriggers] @InclDrop = 1
SELECT 'Return Value' = @return_value

GO
Answer: Using my own version with the combination of answer found in here and other post(can't find the original quetion.
select OBJECT_NAME(parent_obj) AS table_name,sysobj.name AS trigger_name,
[definition],'GO'
from sys.sql_modules m
inner join sysobjects sysobj on sysobj.id=m.object_id
INNER JOIN sys.tables t ON sysobj.parent_obj = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE sysobj.type = 'TR' and sysobj.name like 'NAME_OF_TRIGGER'
order by sysobj.name


golang mongo-go-driver can't increment a previously nil value

Question: I have this kind of query to run. Running this query manually return OK with upsertedCount = 1 when the key not exist
db.test.update({Key: 'random-id'}, {$inc: {Version: 1}},{upsert: true})

I try to convert it to mongodb golang version below
client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017/"))
coll := client.Database("test").Collection("test")
filter := bson.D{bson.E{"Key", "random-id"}}
docs := bson.D{bson.E{"$inc", bson.E{"Version", 1}}}

upsert := true
result, err := coll.UpdateOne(
  context.TODO(),
  filter, docs,
  &options.UpdateOptions{Upsert: &upsert})
if err != nil {
  panic(err)
}
fmt.Print(result)

Unfortunately, this query returns error
multiple write errors: [{write errors: [{Cannot increment with non-numeric argument: {key: "Version"}}]}, {<nil>}]

Why can't it works? It seems that the driver trying to increment it without sending it to mongo
Edit:

change the schema case to Upper, to follow the go code
Use simpler version of code
Comment: Maybe `Version` type in the schema is `non-numeric`
Comment: In the Go version, `"Version"` and `"Key"` should be lowercased, just as in your mongo command.
Comment: @Eklavya I havent set the schema, that's why direct query works
Comment: @icza ah sorry, I want to publish the `Key` and `Version` public, so I set it to uppercase. Gonna update the case.
Answer: The problem is with your docs value. It's supposed to be a valid document. bson.D is a valid document if all its elements are valid. It has an element with $inc key, which requires its value to be a valid document too. bson.E is not a document, it's an element of a document.
Change your docs to this:
docs := bson.D{bson.E{"$inc", bson.D{bson.E{"Version", 1}}}}

And it will work.
If order is not important (it isn't in your case), alternatively you may use bson.M to model your filter and docs like this:
filter := bson.M{"Key": "random-id"}
docs := bson.M{
    "$inc": bson.M{"Version": 1},
}

This is much simpler, clearer and more intuitive.
Also note that there are builders for the options. Obtain your options.UpdateOptions value safely, idiomatically and clearly like this:
options.Update().SetUpsert(true)

Comment: Thank you! Just one clarification I want to know, a single-key object should still be wrapped in bson.D?
Comment: @aaron It's the `$inc`. In your mongo command you use `{}` to specify what you want to increment. That `{}` is a document, so in Go you have to use `bson.D` or `bson.M` for it. Look at it from a way that each `{}` is a document.


Block caching when access-restricted modules are enabled

Question: We have a module that creates a custom navigation block. It runs a metric ton of queries, and it's really affecting performance. (Note that I inherited this site; I did not write this code!)
We want to cache the block, but the built-in block caching (admin/settings/performance) is greyed-out, with a message below that says block caching is inactive when modules defining content access restrictions are enabled. We do have several modules that have access restrictions, and cannot disable those.
Is there any other way to cache the navigation block? I know about the BLOCK_CACHE_* constants, but am assuming that the built-in block caching needs to be turned on, and that those constants modify the default behavior. If we can't turn on the built-in caching, what (if anything) can we do?
Answer: Assuming that the module that creates the block and is this performance heavy is a custom module, a simple solution would be to cache the output of the block from within the block. Take a look at the cache_set and cache_get functions on http://api.drupal.org
Comment: If you do the caching yourself, you can cache based on whatever conditions you want to. The only thing you need to do is make sure that the cache $key, which identifies a single cache entry, contains all these conditions. To cache based on the set of roles a user has, you can use something like: $key = 'yourcachename_ ' . implode('_', array_keys($user->roles));
Comment: @Berdir is spot on. You might want to cache based on permissions instead if you have a lot of different role combinations. Roles is just a collection of permissions anyways.
Comment: Good point about the permissions. Roles can be more than a collection of permissions however, for example node access rules can be based directly on nodes.
Comment: Thanks. I'll take a look at those functions. Hopefully they will let us cache per role, since different roles need to see different versions of the block.
Comment: @Berdir True, I should have added most often, as some modules uses roles and not just the permissions they grant. Most often, using `user_access` is the simplest solution.


"Uncertainty range" versus "confidence interval" - what is the difference, and which is preferred?

Question: The latest edition of The Lancet has a paper reporting on mortality among children under the age of 5 around the world. It is entitled "Global, regional, and national causes of under-5 mortality in 2000–15: an updated systematic analysis with implications for the Sustainable Development Goals." In the abstract, they report something called a "95% uncertainty range" when stating the number of preterm birth complications noted in the study.
What is the difference between a "95% uncertainty range" and a "95% confidence interval"? Are these in fact the same thing? And is there some underlying philosophical reason to prefer the term "uncertainty range" to "confidence interval"? If so, what are the pros and cons of each term?
Comment: Andrew Gelman recently re-sparked discussion of the labelling of confidence-interval-like intervals: http://andrewgelman.com/2016/11/26/reminder-instead-confidence-interval-lets-say-uncertainty-interval/
Comment: I took a look at the paper.  They seem to be using models to determine age specific mortality and evaluate the models using cross-validation and construct bootstrap uncertainty intervals.  They mention using 2.5th percentile and 97.5th percentile to construct the uncertainty intervals.  They do not use the term confidence intervals but it looks like these interval might be bootstrap percentile two-sided 95 percent confidence intervals.
Comment: See also: https://journals.lww.com/epidem/Fulltext/2012/09000/Visualizing_Results_From_Infection_Transmission.15.aspx
Answer: If you look at some other papers from the project "Global burden of diseases", you will see that data imputation for missing cases have been carried out using proxy. As in case of modelling the global burden of diarrhoea, due to unavailability of data from systematic surveillance in countries like Liberia, Libya, Afghanistan, Syria and Haiti; estimates have been carried out by extrapolating spatiotemporal trends from countries or region with better data matching for the geographical and socio-economic condition. Hence, it is likely that due to the uncertainty associated with the estimates, instead of using confidence interval, the term uncertainty interval might have been used.
https://www.sciencedirect.com/science/article/pii/S1473309917302761
https://www.sciencedirect.com/science/article/pii/S1473309917303365


SQL Server:Permissions on Objects

Question: Can we revoke all the privileges to all the objects on SQL Server database and give access to only few tables of a particular schema
Answer: A user, by default, has no permissions apart from what the public ROLE does; so if you've not given them any permissions, you'll just need to give them the right ones.
If you mean you have create and given a USER lots individual permissions, then it may be quicker to DROP the USER and recreate it with the correct ones:
USE Sandbox;
GO

CREATE USER TestUser WITHOUT LOGIN WITH SID = 0x0105000000000009030000003A1272CDF6378A479D2C1EC4E229CB56;
GO

CREATE TABLE dbo.TestTable1 (ID int);

CREATE TABLE dbo.TestTable2 (ID int);
GO

GRANT INSERT, SELECT, UPDATE, DELETE ON dbo.TestTable1 TO TestUser;
GRANT INSERT, SELECT, UPDATE, DELETE ON dbo.TestTable2 TO TestUser;
GO

EXECUTE AS USER = N'TestUser';
GO

INSERT INTO dbo.TestTable1 (ID)
VALUES(1);

INSERT INTO dbo.TestTable2 (ID)
VALUES(11);
GO

SELECT *
FROM dbo.TestTable1;
SELECT *
FROM dbo.TestTable2;
GO

REVERT
GO

DROP USER TestUser;
GO
CREATE USER TestUser WITHOUT LOGIN WITH SID = 0x0105000000000009030000003A1272CDF6378A479D2C1EC4E229CB56;

GRANT INSERT, SELECT, UPDATE, DELETE ON dbo.TestTable2 TO TestUser;
GO

EXECUTE AS USER = N'TestUser';
GO
--Fails
INSERT INTO dbo.TestTable1 (ID)
VALUES(2);
GO
--Succeeds
INSERT INTO dbo.TestTable2 (ID)
VALUES(12);
GO
--Fails
SELECT *
FROM dbo.TestTable1;
GO
--Succeeds
SELECT *
FROM dbo.TestTable2;
GO

REVERT
GO

GO

--Clean up
DROP USER TestUser;
DROP TABLE dbo.TestTable1;
DROP TABLE dbo.TestTable2;

If this is something you find yourself doing often, sounds like you should have Roles, and should add/remove the users from the particular roles.
Answer:
For revoke all privileges you can get script result and run this:

 SELECT 'REVOKE ALL ON "' + TABLE_SCHEMA + '"."' + TABLE_NAME + '" FROM "User"'
 FROM information_schema.tables t

And for grant privileges :

 SELECT 'GRANT SELECT ON "' + TABLE_SCHEMA + '"."' + TABLE_NAME + '" TO "User"'
 FROM information_schema.tables t

SQL Server:Permissions on Objects


How to selectively link certain system libraries statically into Haskell program binary?

Question: I'm currently developing some web application written in Haskell. All Haskell libraries are statically linked; although this "bloats" the executable, it not so much of a problem since it will be the only Haskell programm running on the server.
However, I'd also like to get rid on the dependency on libgmp.so, i.e. I would like to link the multiprecision library statically into the program as well, but keep all the other system libraries (such as pthread, libc, and libm) dynamically linked.
Which linker switches to ghc do that trick?
EDIT to account for a side question
Is it possible to disable default linkage of the standard libraries, that are pulled in by default into every Haskell programm? Something like the GCC-equivalent to -nostdlib?
Answer: dcoutts posted this as a reddit comment:

You can do exactly the same with ghc.

gcc -c prog.c -o prog.o
gcc prog.o libfoo.a -o prog

and lo, with ghc it's the same...

ghc -c prog.hs -o prog.o
ghc prog.o libfoo.a -o prog

Comment: On my tries by `ghc 8.6.3` and for `libffi` this does not work. using `-optl-v` I can see the linker command, somehow it not seems to really realted to the sequence of linker commands I pass, and in this case `ghc` adds two `/tmp/ghcXXXX/ghc_X.o` after the `libffi.a` which they might have reference to `libffi` and an `-lffi` in the end `-l`s series.

here is [the command on pastebin](https://pastebin.com/6fRaUTW5)
Answer: You can use -optl to pass options directly to the linker, so to link everything statically, you can use:
ghc --make Main.hs -optl-static -optl-pthread

or put these in GHC-Options if you're using Cabal.
You can probably tweak this futher to have more fine grained control over what to link statically or dynamically. The -v (verbose) option is helpful here to see the final linker command.
Comment: I'd like to link only libgmp.so statically, but the rest of the system libraries shall remain linked dynamically. Every now and then GMP will undergo some ABI changes, while the other libraries are quite ABI stable. (Note the 'B' I'm not talking about 'P'). I want this so that I don't have to install a full blown Haskell Platform for recompilation on the webserver.
Comment: @datenwolf: I understand, but I'm afraid I don't know how to do that. I'm guessing it probably involves some more use of `-optl` or possibly invoking the linker yourself.


A question on probability of two related evenets

Question: Let $\mathcal{E_1}$,$\mathcal{E_2}$ be two events such that $\mathcal{E_1}\subseteq \mathcal{E_2}$. Is it true that $Pr(\mathcal{E_1})\le Pr(\mathcal{E_2})$ ? Can anyone please justify or provide counter argument. Thanks
Comment: Note that $E_2=E_1\cup(E_2\setminus E_1)$, and that the sets on the right are disjoint.
Comment: @carmichael561 thanks
Comment: Yes, all probability measures have this property (because a probability measure is a *positive* measure).
Answer: $E_1 \subseteq E_2 $ implies that $E_2=E_1 \cup (E_1^c \cap E_2)$
By definition of the probability measure if A and B are disjoint then $P(A \cup B)=P(A)+P(B)$. Therefore, we have
$$P(E_1) \leq P(E_1) + P(E_1^c \cap E_2) = P(E_1 \cup (E_1^c \cap E_2))=P(E_2)$$
where the first inequality is strict if $P(E_1^c \cap E_2)>0$.
Comment: $E_1 \cap E_2 = E_1$. How is the first statement true?
Comment: It is not; it is missing a complement marker. $E_1\subseteq E_2$ iff $E_1=E_1\cap E_2$.  Which implies that  $E_2=E_1\cup(E_1^\complement\cap E_2)$.
Comment: Yeah, silly me. Corrected now.


Hoeffding Inequality.

Question: A drunkard stands on the axis of integer numbers. He flips a coin that gets Head with p probability. If he gets Head, he goes 2 steps right, and if he get tails, he goes one step left. The drunkard flips n times, and the coin flips are independent events. Let $ X_n$ be his position after those n flips. For what value of p,  $P(X_n = 0)$ can be bounded with hoeffding inequality. Calculate the bound, and compare it to the bound from using chebychev inequality.
Basically I started by naming the conditions to use hoeffding inequality, which is having independent variables and having the $Im(X) \in \{1,-1\}$ but this is not the case. So how am I suppose to do it?
Answer: HINT: It looks like the problem is referring to the more general version of Hoeffding's inequality: Let $X_1,\ldots,X_n$ be independent random variables with each $X_i \in [a,b]$.  If we define $\bar{X} = \frac{1}{n}(X_1 + \ldots + X_n)$ then $$\mathbb{P}(|\bar{X} - E[ \bar{X}]| \geq t) \leq \exp\left(-\frac{2n^2 t^2}{n(b-a)^2} \right).$$
What does it say in your case?

Hoeffding Inequality.


Hash code is different for TransformBlock and ComputeHash method in HMAC-SHA1

Question: When I use TransformBlock and TransformFinalBlock for a buffer the hash code is different from Computing hashcode with ComputeHash() method in HMAC-SHA1 . why? And how to solve this.
Comment: Welcome to Stack Overflow! If you have a problem with your code, then you should provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that demonstrates your problem. Help us help you without wasting time on guessing. Also, don't provide a link to your code. Instead, [edit] your question to include the code. Links break all the time and if it does, this question will lose all value.
Comment: You already asked the same question before (https://stackoverflow.com/questions/44588030/how-to-implement-transformblock-and-transformfinalblock-in-hmacsha1-for-uwp#comment76170309_44588030). Please be more specific what you are asking and what you are trying to do. I would again recommend using a solid hardened crypto implementations available.
Answer: Since you don't offer any code it's not possible to say for sure, but psychic debugging says that you assumed TransformFinalBlock returned the HMAC, which it just computes a value into the Hash property.
byte[] data = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };
HMACSHA1 hmac = new HMACSHA1(new byte[] { 1, 2, 3, 4, 5 });
Console.WriteLine($"ComputeHash: {Convert.ToBase64String(hmac.ComputeHash(data))}");
Console.WriteLine($"TransformFinalBlock: {Convert.ToBase64String(hmac.TransformFinalBlock(data, 0, data.Length))}");
Console.WriteLine($"get_Hash: {Convert.ToBase64String(hmac.Hash)}");

Outputs
ComputeHash: 3J86gFtyUDTwqyZdY8dgBPAyL6Q=
TransformFinalBlock: AQECAwUIDRUiNw==
get_Hash: 3J86gFtyUDTwqyZdY8dgBPAyL6Q=

So, the answer is to ignore the result of TransformFinalBlock (which echoes the input), and to call get_Hash afterwards.
Answer: According to documentation HMACSHA1 mixes secret key with input message in order to produce final hash, that is mixed and hashed again...
If you won't provide secret key, it'll be randomly generated that will result in different hash.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Security.Cryptography;
using System.Text;

[TestClass]
public class HashTests
{
    [TestMethod]
    public void HashTest()
    {
        var keyBytes = Encoding.UTF32.GetBytes("my secret key");
        var textBytes = Encoding.UTF32.GetBytes("my tiny little text");

        var hash1 = GetHash1(textBytes, keyBytes);
        var hash2 = GetHash2(textBytes, keyBytes);

        Assert.AreEqual(hash1.Length, hash2.Length);

        for (int i = 0; i < hash1.Length; i++)
            Assert.AreEqual(hash1[i], hash2[i]);
    }

    private byte[] GetHash2(byte[] textBytes, byte[] key)
    {
        using (var alg = new HMACSHA1(key))
            return alg.ComputeHash(textBytes);
    }

    private byte[] GetHash1(byte[] input, byte[] key)
    {
        var size = input.Length;
        using (var alg = new HMACSHA1(key))
        {
            int offset = 0;

            while (input.Length - offset >= size)
                offset += alg.TransformBlock(input, offset, size, input, offset);

            alg.TransformFinalBlock(input, offset, size - offset);
            return alg.Hash;
        }
    }
}


Deleting non distinct rows

Question: I have a table that has a unique non-clustered index and 4 of the columns are listed in this index. I want to update a large number of rows in the table. If I do so, they will no longer be distinct, therefore the update fails because of the index.
I am wanting to disable the index and then delete the oldest duplicate rows. Here's my query so far:
SELECT t.itemid, t.fieldid, t.version, updated
FROM dbo.VersionedFields w
inner JOIN
(
    SELECT itemid, fieldid, version, COUNT(*) AS QTY
    FROM dbo.VersionedFields
    GROUP BY itemid, fieldid, version
    HAVING COUNT(*) > 1
) t
on w.itemid = t.itemid and w.fieldid = t.fieldid and w.version = t.version

The select inside the inner join returns the right number of records that we want to delete, but groups them so there is actually twice the amount.
After the join it shows all the records but all I want to delete is the oldest ones?
How can this be done?
Answer: If you say SQL (Structured Query Language), but really mean SQL Server (the Microsoft relatinonal database system) by it, and if you're using SQL Server 2005 or newer, you can use a CTE (Common Table Expression) for this purpose.
With this CTE, you can partition your data by some criteria - i.e. your ItemId (or a combination of columns) - and have SQL Server number all your rows starting at 1 for each of those partitions, ordered by some other criteria - i.e. probably version (or some other column).
So try something like this:
;WITH PartitionedData AS
(
    SELECT
       itemid, fieldid, version,
       ROW_NUMBER() OVER(PARTITION BY ItemId ORDER BY version DESC) AS 'RowNum'
    FROM dbo.VersionedFields
)
DELETE FROM PartitionedData
WHERE RowNum > 1

Basically, you're partitioning your data by some criteria and numbering each partition, starting at 1 for each new partition, ordered by some other criteria (e.g. Date or Version).
So for each "partition" of data, the "newest" entry has RowNum = 1, and any others that belongs into the same partition (by means of having the same partitino values) will have sequentially numbered values from 2 up to however many rows there are in that partition.
If you want to keep only the newest entry - delete anything with a RowNum larger than 1 and you're done!
Answer: In SQL Server 2005 and above:
WITH    q AS
        (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY itemid, fieldid, version ORDER BY updated DESC) AS rn
        FROM    versionedFields
        )
DELETE
FROM    q
WHERE   rn > 1

Answer: Try something like:
DELETE FROM dbo.VersionedFields w WHERE w.version < (SELECT MAX(version) FROM dbo.VersionedFields)

Ofcourse, you'd want to limit the MAX(version) to only the versions of the field you're wanting to delete.
Answer: You probably need to look at this Stack Overflow answer (delete earlier of duplicate rows).
Essentially the technique uses grouping (or optionally, windowing) to find the minimum id value of a group in order to delete it. It may be more accurate to delete rows where the value <> max(row identifier).
So:

Drop unique index
Load data
Delete data using the grouping mechanism (ideally in a transaction, so that you can rollback if there is a mistake), then commit
Recreate the index.

Note that recreating an index on a big table can take a long time.
Comment: marc_s's solution is an elegant way of doing it.

Deleting non distinct rows


Creating a Temporary vector

Question: I have this method I'm trying to complete,  which when completed should construct a limited list of choices from the options vector passed into the method:
> int Program::SelectFromMenu(int x, int y, std::vector<std::string> options);

For instance, if I wanted to have a menu selection in a bank system, I could add these three strings to my options vector, then the method would display these three choices to the user:
 <"Withdraw", "Deposit", "Statement">

They pick an option, their decision will call a method. Easy right? I've coded that part already. The problem is getting the vector itself into the method:
In an ideal world, I'd create a temporary vector like this, and use it as an argument:
SelectFromMenu(2, 4, <"Withdraw", "Deposit", "Statement">);

but I'm unable to do this. What other ways am I able to achieve passing a vector into the method? I mean, I could make a method that constructs the vector from strings I pass in, but that seems like the wrong way to do this.
Any help would be appreciated, thanks.
Answer: You could use a braced-init-list:
SelectFromMenu(2, 4, {"Withdraw", "Deposit", "Statement"});

Comment: This is literally what the OP is trying to do. +1 (No idea where they got this `<>` idea from)
Comment: Whhops my bad, compiles.
Comment: Sorry, my bad. I removed a paramater earlier called menusize since I could derive that from the options.size(), that'sa why it wouldn't compile. Thanks for the help!

Creating a Temporary vector


Atualizar imagens sem a necessidade de atualizar o site inteiro

Question: Estou utilizando um código javascript que atualiza a foto do locutor(a) de acordo com o dia da semana e o horário que ele(a) está no ar. Porém isto só acontece quando a página é atualizada (F5). Gostaria de saber o que preciso acrescentar no código para a atualização das imagens acontecerem de forma automática, sem que seja necessária a atualização de todo o site?
Segue abaixo o código:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

Answer: Sobre melhorias no código
Não aconselho usar document.write, pois vai apagar o site e manter só a foto, o melhor seria que cada imagem tivesse sua ID e você trocasse por uma função semelhante.
Eu também notei que o domingo todo é apenas o operador, não entendi por que colocou o mesmo pra cada intervalo de horário, não bastava por o período todo? Assim:
if(hora >= 0 && hora < 24){ locutor.src = "/site103fm/imagenshorario/operador.png"}

Como rodar a função em modo automático e disparar sozinho
User setTimeout para repetir o chamado da função a cada segundo e se trocar o horário ele troca a imagem:
Modifique a Tag BODY assim:

Dentro da função rodarImagens() no final, mas dentro, coloque isso:
setTimeout(function(){ rodarImagens() }, 1000);

Código completo:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

Comment: Resolvido! Está funcionando como eu queria. A imagem do locutor atualiza automaticamente sem que o site precise ser atualizado. E agora o site não desaparece após o tempo estabelecido em setTimeout. Obrigado!


what do EPOLLERR and EPOLLHUP really mean and how to deal with them?

Question: I'm reading redis souce code and in ae_epoll.c I found below code:
static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {
    aeApiState *state = eventLoop->apidata;
    int retval, numevents = 0;

    retval = epoll_wait(state->epfd,state->events,eventLoop->setsize,
            tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1);
    if (retval > 0) {
        int j;

        numevents = retval;
        for (j = 0; j < numevents; j++) {
            int mask = 0;
            struct epoll_event *e = state->events+j;

            if (e->events & EPOLLIN) mask |= AE_READABLE;
            if (e->events & EPOLLOUT) mask |= AE_WRITABLE;

            /* so why set AE_WRITABE when EPOLLERR or EPOLLHUP happend? */
            if (e->events & EPOLLERR) mask |= AE_WRITABLE;
            if (e->events & EPOLLHUP) mask |= AE_WRITABLE;
            eventLoop->fired[j].fd = e->data.fd;
            eventLoop->fired[j].mask = mask;
        }
    }
    return numevents;
}

so why set AE_WRITABE when EPOLLERR or EPOLLHUP event happened? I have read the man page about EPOLLERR and EPOLLHUP but I couldn't get it.
EPOLLERR
        Error condition happened on the  associated  file  descriptor.   epoll_wait(2)
        will always wait for this event; it is not necessary to set it in events.

EPOLLHUP
        Hang up happened on the associated file descriptor.  epoll_wait(2) will always
        wait for this event; it is not necessary to set it in events.

Comment: Appears like coded in C,please tag the language in your question.
Answer:
so why set AE_WRITABE when EPOLLERR or EPOLLHUP event happened?

That's presumably to simplify the code that calls aeApiPoll(), e. g. in ae.c:aeProcessEvents():
        numevents = aeApiPoll(eventLoop, tvp);
        for (j = 0; j < numevents; j++) {
            aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];
            int mask = eventLoop->fired[j].mask;
            int fd = eventLoop->fired[j].fd;
            int rfired = 0;

            /* note the fe->mask & mask & ... code: maybe an already processed
             * event removed an element that fired and we still didn't
             * processed, so we check if the event is still valid. */
            if (fe->mask & mask & AE_READABLE) {
                rfired = 1;
                fe->rfileProc(eventLoop,fd,fe->clientData,mask);
            }
            if (fe->mask & mask & AE_WRITABLE) {
                if (!rfired || fe->wfileProc != fe->rfileProc)
                    fe->wfileProc(eventLoop,fd,fe->clientData,mask);
            }
            processed++;
        }

The fe->wfileProc() must handle hang up and error conditions anyway, since they can happen anytime, also when an AE_WRITABLE event is processed; by not having separate event flags for exceptional conditions, the processing loop doesn't need special handling for them.


Matrix differential and differentation

Question: I need to find the differential and derivative of $ f: X\rightarrow (I-X(X'X)^{-1}X')$
Now by the product rule I found that the differential of $d(I-X(X'X)^{-1}X')=-(dX(X'X)^{-1}X' + (X)d(X'X)^{-1}X'+X(X'X)^{-1}d(X')$
Now I have issues with finding $d(X'X)^{-1}$ because I am not sure how to use the chain rule here, and with the first term: $(dX(X'X)^{-1}X'$ because it is not in the standard form $A(dX)B$ where $A$ and $B$ are any matrices.
Could anyone show me how to proceed as to find the derivative of this function?
Comment: I think directional derivatives are the best way here. See http://math.stackexchange.com/questions/1141599/derivative-of-trace-of-inverse-matrix/1141894#1141894
Answer: For convenience, define $M=(X^TX)^{-1}X^T\,\,$ then the function is
$$\eqalign{
  F &= I-XM = \,F^T\cr
}$$
And the differentials are
$$\eqalign{
 dM &= (X^TX)^{-1}dX^T - (X^TX)^{-1}(dX^TX)(X^TX)^{-1}X^T - (X^TX)^{-1}(X^TdX)(X^TX)^{-1}X^T \cr
  &= (X^TX)^{-1}dX^T - (X^TX)^{-1}\,dX^T\,XM - M\,dX\,M \cr
  &= (X^TX)^{-1}dX^T\,F - M\,dX\,M \cr \cr
 dF &= -X\,dM - dX\,M \cr
  &= -X(X^TX)^{-1}\,dX^T\,F+XM\,dX\,M \,-\, dX\,M\cr
  &= -M^T\,dX^T\,F^T - F\,dX\,M \cr
}$$
Apply ${\rm vec}()$ to both sides, but remember that $\,{\rm vec}(dX^T) \neq dx^T$  even though $\,{\rm vec}(dX) = dx$.
Instead, you must use the Kronecker permuation matrix $P$, which depends on the matrix dimensions, to obtain $\,{\rm vec}(dX^T) = P\,dx$.
$$\eqalign{
  df &= -(F\otimes M^T)\,P\,dx - (M^T\otimes F)\,dx \cr
  \frac {\partial\,{\rm vec}(F)}{\partial\,{\rm vec}(X)^T} =\frac {\partial f}{\partial x^T} &= -(F\otimes M^T)\,P - (M^T\otimes F) \cr
}$$
This kind of vec/vec result is typical for matrix-by-matrix derivatives.
Answer: It suffices to derive a product of $3$ terms. Recall that a derivative is a linear function. Let $X\in M_{n,m}$. Then
$Df_X:H\in M_{n,m}\rightarrow -H(X^TX)^{-1}X^T+X(X^TX)^{-1}(H^TX+X^TH)(X^TX)^{-1}X^T-X(X^TX)^{-1}H^T$
We cannot write this expression in tensor form except if we use the function $H\rightarrow H^T$.

Matrix differential and differentation


Find a limit of an integral

Question: $\lim_{n \to \infty} \int_0^{\infty} \frac{1}{1+x^n}$
It seems quite easy, but the problem is that I cannot find a dominating function when $x>1$
Comment: As an aside, for $00$ we have $~\displaystyle\int_0^\infty\frac{x^{k-1}}{a^n+x^n}~dx~=~a^{k-n}~\frac\pi n~\csc\bigg(k~\frac\pi n\bigg)$.
Answer: Let
$$
g(x) = \begin{cases}
1 &: 0\leq x\leq 1 \\
\frac{1}{1+x^2} &: x > 1
\end{cases}
$$
For $n\geq 3$, each integrand is dominated by $g$.
Comment: But what about $n=1$? Shouldn't it be a dominating function for each $n$? I know it is a limit, but still...
Comment: You only care about the limit right? So you can ignore finitely many terms.
Comment: @Prold The constant function $1$ is not in $L^1$.
Answer: $$\frac{1}{1+x^2}$$
is a dominating function when $x >1$.
Answer: The best way is to find a dominating function; alternatively you can notice that if $x > 1$ then $\frac 1{1+x^n}$ tends uniformily to $0$, so you can exchange the limit and the integral for $x > 1$

Find a limit of an integral


AR(2) model is causal

Question: AR(2) model is:
$$X_t=\phi_1X_{t-1}+\phi_2X_{t-2}+W_t$$
Where $W_t\sim N(o,\sigma^2)$
I want to prove AR(2) model is causal. So, I tried as:
$$X_t-\phi_1X_{t-1}-\phi_2X_{t-2}=W_t$$
$$\Rightarrow (1-\phi_1 B-\phi_1 B^2)X_t=W_t$$
where $B$ is back-shift operator, i.e., $B X_t=X_{t-1}$
$$\Rightarrow X_t=(1-\phi_1 B-\phi_1 B^2)^{-1}W_t$$
Then I don't know how can I proceed?
Comment: What is the definition of a causal model?
Comment: Are you referring to Granger causality here, or something else?
Comment: @Glen_b, the term *causal* has a precise meaning in the context of ARIMA models and it is different from both Granger causality and the casual meaning of *causal*. The definition can be looked up in a time series textbook. Zhangxiong gives the relevant answer.
Comment: First, there seem two typos in the post, the latter two $\phi_1$s should be $\phi_2$. Second, some conditions about $\phi_1$ and $\phi_2$ need to be imposed to guarantee the process is causal.
Comment: @AdamO here's a [presentation](http://www.stat.berkeley.edu/~bartlett/courses/153-fall2010/lectures/6.pdf)  defining
Comment: Thanks Richard; that particular usage had quite slipped from my mind.
Answer: A famous theorem (Theorem 3.1.1., Brockwell, Davis. Time series: theory and application)states that an ARMA($p$, $q$) process
$$\phi(B)X_t = \theta(B) W_t$$
is causal if and only if $\phi(z) \neq 0$ for all $z \in \mathbb{C}$ such that $\left|z\right|\leq 1$.
So in order the AR($2$) process to be causal, the coefficients $\phi_1$ and $\phi_2$ must satisfy
$$1 - \phi_1 z - \phi_2 z^2 \neq 0$$
for all $\left|z\right| \leq 1$. It is not a causal process for all $\phi_1, \phi_2$. For example, $\phi_1 = 2, \phi_2 = 0$.
Answer: your final equation leads to the MA representation of an AR process.
Pred[X(t)] = cons + a1*W(t-1) + a2*W(t-2) + .... an*W(t-n) reflecting how previous errors "cause" X.
All ARMA models can be presented as pure AR models (weighted average of the past )
or as a pure MA mode ( weighted average of the past errors )
Answer: You write:
"I want to prove AR(2) model is causal."
Is simply not possible. AR and/or ARMA models are never causal. ARMA models was thinked exactly for describing a process with its own past. These explicitly have merely statistical meaning.
Causality is something the go beyond merely statistical relationship and involve more than one variable. If we are not aware about this, we surely conflate statistical association and causality. At most you can ask about Granger causality (unhappy name) but the univariate nature of ARMA put away this possibility too.
For these reasons I disagree with previous answers that give you other informations without warning about causal meaning.
Comment: The term *causal* has a precise meaning in the context of ARIMA models and it is different from the casual meaning of *causal*, therefore this answer is beyond the point. Zhangxiong gives the relevant answer.
Comment: I agree, and am curious what theorem @Zhanxiong refers to in his answer
Comment: @RichardHardy: I've read enough about the ARIMA models and never i find the property of "causality". However i looking for it and you are right this property exist. However let me say two things: in some references the casuality property conflate with stationarity property; in any case "causality property" is only another misnomer.
Comment: @markowitz: Regarding the "causality" in "Granger causality", perhaps Clive Granger himself should have the last word (from his Nobel acceptance speech): *At that time, I had little idea that so many people had very fixed ideas about causation, but they did agree that my definition was not "true causation" in their eyes, it was only "Granger causation." I would ask for a definition of true causation, but no one would reply. However, my definition was pragmatic and any applied researcher with two or more time series could apply it, so I got plenty of citations. Of course, many ridiculous papers
Answer: AR(2) is causal if :
$$ \phi_1+\phi_2 < 1$$
and
$$ \phi_1 - \phi_2 < 1$$
and
$$ -1 < \phi_2 < 1$$
In this conditions $ \phi_2(B)=0 $ equation roots are outside of unit circle so it's causal.

AR(2) model is causal


Rewrite Email Subject

Question: Is there a way to rewrite a subject of an Email on the receiving MTA (presumably at the Spam Filtering stage).
An example would be if giving Email accounts to young children where certain words need to be blocked/X'd out (Profanity, etc.).
Currently using postfix, sendmail, and spamassassin on Linux.
Thank you.
Answer: You could do that pretty easily with procmail (and formail.)  You could also inspect the contents (message body) at that stage as well.
See: http://john.ellingsworth.org/?p=16
Answer: Postfix header_checks is what you need. For example, with this line you can replace every subject which contains a bad word of your choice:

/^Subject:.*bad word.*/ REPLACE Subject: Censored

Moreover you can drop, redirect or filter bad letters.

Rewrite Email Subject


Java Script Image Slide Show (Annimate function)

Question: I have a problem understanding javascript code.These are my first steps in javascript and I'm trying to make a Javascript slide show. Please explain me how
var timePassed = new Date - start; **and**
var progress = timePassed / opts.duration;

works in this function:-

Answer: timePassed is how much time passed since the beginning of the animation (current date - start date).
progress is the ratio of how much time passed over the total duration of the animation. This value will be between 0 and 1 (1 means the animation is over).
For exemple, if opts.duration is 1000ms, after 500ms elapsed, progress will be 500 / 1000 = 0.5 (= 50% of the total duration of the animation). When progress is 1 (1000 / 1000), the animation is done and the callback is called.


handling ctrl + key event in IE browser

Question: I'm using hotkeys (Ctrl+key) in my flex application. getting problem when my app is running in IE.
when I press Ctrl+D, im getting 'Add a Favorite' window of IE.
How should I override the default behaviour of the browser? if possible, give me some example.
Answer: In your event handler, try
<code>event.returnValue = false;
</code>
See this SO thread: event.preventDefault() function not working in IE

handling ctrl + key event in IE browser


How do I install Flysystem and Flysystem S3?

Question: I'm using the Flysystem module, but I am not able to install the module. I am getting this error:

Dependencies missing: Flysystem, replicate adapter, stream wrapper.

I followed the steps given on https://www.drupal.org/node/2541116, but I am still not able to install the module.
I have installed the Replicate and Stream wrapper modules.
Is there any other method to integrate S3 with Drupal 8?
Answer: That documentation you referenced is outdated and wrong. You should read the official documentation on https://www.drupal.org/node/2404989.
The easiest way to do this is to install the drupal modules with composer, as documented on https://www.drupal.org/node/2718229. Once you've configured the drupal.org repository, installing a module is as simple as composer require drupal/flysystem. That will download that module, including alll dependencies that it needs for you.
You can manage your whole installation, including core, with composer if you use composer create-project drupal-composer/drupal-project:8.x-dev. You can also add contrib modules if you installed drupal core by hand, but when updating core, you need to be careful to not lose your composer.json changes and run composer update again.
Comment: Thank you for the reply, ill try above procedure and check it out.
Answer: There is a module called S3 File System

S3 File System (s3fs) provides an additional file system to your
  drupal site, which stores files in Amazon's Simple Storage Service
  (S3) or any other S3-compatible storage service. You can set your site
  to use S3 File System as the default, or use it only for individual
  fields. This functionality is designed for sites which are
  load-balanced across multiple servers, as the mechanism used by
  Drupal's default file systems is not viable under such a configuration

Hope this helps you.
Comment: Could you please share your opinion to both modules and compare them?


Dbpedia search with SPARQL

Question: I have a problem with SPARQL on dbpedia. I want to collect some data from diffrent kinds of animals and I thought it would be a good idea to use dbpedia, but I don't really understand how it works. I watched a video on youtube and after that I still dont really get it.
My question is now, for example, I want to search for all the frogs (or any kind of animal) and I want it to return with the Kingdom, Phylum, class, order, family, genus and species (these are in the infoboxes). How do I write the line of code?
I saw another post and his solution to get all the movies Tom Hanks played in was this (below), but when I try to search for example here: http://mappings.dbpedia.org/server/ontology/classes/Amphibian then I don't see anything I can use.
<code>SELECT ?f
WHERE {
?f rdf:type dbo:Film .
?f dbo:starring dbr:Tom_Hanks .
}
</code>
Answer: Instead dbpedia, you can use Wikidata Query Service.
It has nice tutorial and by my opinion it's better than dbpedia.
For example this query with movies, where Tom Hanks played (including description and director info):
<code>  SELECT ?item ?itemLabel ?itemDescription ?directorLabel WHERE {
  ?item wdt:P31 wd:Q11424 .
  ?item wdt:P161 wd:Q2263 .
  OPTIONAL{?item wdt:P57 ?director .}
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</code>
You can try it yourself here.
Comment: Thanks alot! i got it working.

But there is something else now. I can only ask for a few things to get in the results, and not everything thats in the infoboxes on wikipedia. Am i doing something wrong or is this the limitation of using this site?

For example: https://en.wikipedia.org/wiki/Sirius

is it possible to ask for the whole infobox from a star like this and maybe the first 5-10 lines?
Comment: you can get everything, what contains here: https://www.wikidata.org/wiki/Q3409, for example following properties: constellation, Commons category and so on. Not sure about infobox.
Comment: infoboxes are just format of information from Wikidata, which actually fields and you can get values of these fields using Wikidata query.
Comment: There is no 1 to 1 correspondence between Wikidata and Wikipedia infoboxes (and transitively DBpedia). There can be an overlap in many cases but each dataset can have a lot more information

Dbpedia search with SPARQL


Como criar os certificados e o provisionamento profile corretamente para uso de Push Notification?

Question: Preciso de ajuda para criar um certificado de provisioning profile corretamente para Push Notification. Pois segui vários tutoriais diferentes, e em todos não tive sucesso. Somente em um momento em que usei o provisioning profile de Team que consegui receber as notificações.
Tenho experiência em criar certificados para iOS, pois já tenho 2 aplicativos publicados que usam push notification. Porém de algum modo não sei o que está acontecendo.
Coincidência ou não, não estou conseguindo depois das recentes atualizações que acompanharam o lançamento do iOS 8.
Comment: O que exatamente não está dando certo? Você chegou a fazer a requisição de *push* e receber alguma resposta no seu servidor mesmo que negativa?
Answer: O lançamento do iOS8 trouxe algumas alterações no modo como os dispositivos recebem notificações. Não sei se o problema que estas a referir é sobre esse aspecto ou mesmo sobre o certificado criado. Por isso vou tentar responder te aos dois.
No primeiro, com o iOS 8, o modo como implementas e processas as notificações é diferente:
<code>if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        {
            [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                                settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                                categories:nil]];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        }
        else
        {
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
             (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
        }
</code>
Sobre os certificados em si, quando pretendes criar uma aplicação com PushNotifications tens que criar um AppID diferente.

O bundle identifier não pode ser uma wildMask(isto é, usar o * para permitir varias aplicações com diferentes nomes).
Ao criar esse AppId tens que pedir autorização para pushNotification(tanto para desenvolvimento como para distribuição).

Este processo obriga te a criar um certificado. Segue a explicação dada na pagina e a partida não deves ter grandes problemas.
Comment: Obrigado da @DaSilva, vou tentar novamente. Tentei varias vezes.... e não tive sucesso. :/
Comment: verificas te se estas a receber o token do dispositivo na app??
Comment: Sim recebo o token normal. Como te falei, meu problema não está no código, está no provisionament profile
Comment: Não é só isso não!


usb cdc device driver

Question: I have CDC device. I develop driver for him.
Part of ini file:
<code>[ClassInstall32]
CopyFiles=ClassInstall.CopyFiles
AddReg=ClassInstall.AddReg

[ClassInstall.CopyFiles]
My_USBDriver.dll,,,0x2000

[ClassInstall.AddReg]
HKR,,,,%DEVICEMANAGERCATEGORY%
HKR,,Icon,,"102"
HKR,,Installer32,,"My_USBDriver.dll,MyUSBPortsClassInstaller"
HKR,,NoInstallClass,,1

[DriverInstall]
include=mdmcpq.inf
CopyFiles=DriverInstall.CopyFiles
AddReg=DriverInstall.AddReg

[DriverInstall.CopyFiles]
usbser.sys,,,0x2000

[DriverInstall.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,%DRIVERFILENAME%.sys

[DriverInstall.Services]
AddService=usbser, 0x00000002, DriverService

[DriverService]
DisplayName=%SERVICE%
ServiceType=1
StartType=3
ErrorControl=1
ServiceBinary=%12%\%DRIVERFILENAME%.sys
</code>
Installer function have code:
<code>c->ConnectionIndex = iPort;
c->SetupPacket.bmRequest = 0x80;
c->SetupPacket.wValue = (USB_STRING_DESCRIPTOR_TYPE<<8)|descriptorNum;
c->SetupPacket.wLength = n;
Success = DeviceIoControl(
    hRoot,
    IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION,
    c, n,
    c, n,
    &returnBytes,
    NULL);
///Sometime GetLastError == 31 // Device not working
</code>
This code normal work on desctop(PC) always, but only sometime work on laptop(notebook) during the installation the device(installation function calling by system). OS of these mashines is Windows7.
BUT if i call installation function from my progrm(created for debuggin) this code always work correctly (on notebook and on pc).
Does anyone have ideas on this issue?
Comment: Error code 31 means "This device is not working properly because Windows cannot load the drivers required for this device." - Is the machine running a 64-bit OS? If so, it'll need driver signature verification switched off and test signing enabled.
Comment: My actions: 1) bcdedit /set testsigning on                            2)reboot                                                            3)press f8 on load and select Don't need driver check                            But this is not help me.
Answer: You said Desktop and Laptop, but I don't think the shape of the computer matters. Is one 32 bit OS and the other is 64 bit? I don't see the 64bit INF section.

usb cdc device driver


How do I pass parameters to the form builder?

Question: I have the following routes in module_name.routing.yml.
module_name.usergroup_delete:
  path: 'module_name/usergroup/delete/{arg1}'
  defaults:
    _form: '\Drupal\module_name\Form\DeleteUserGroup'
    _title: 'Delete User group'
  requirements:
    _permission: 'access admin menus'

This is the code in module_name/src/Form/DeleteUserGroup.php.
namespace Drupal\module_name\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class DeleteUserGroup extends ConfigFormBase {

  public function getFormId() {
    return 'delete_user_group';
  }
/**
 * General form for switching all nodes from one user to another.
 */
  public function buildForm(array $form, FormStateInterface $form_state,$product_code) {
  $form['_product'] = array(
        '#type' => 'value',
        '#value' => $product_code,);
//get the user group and username to display the confirmation message
$result = db_query('select field_p_group_name_value from {content_type_usergroup} ctu'
        . ' where vid=%d',$product_code);
    while ($row = $result->fetchObject()) {
      $user_group = $row->field_p_group_name_value;
    }

return confirm_form($form,t('Are you sure you want to delete "' .$user_group. '" User Group?'),
        isset($_GET['destination']) ? $_GET['destination'] : "function_name",t('This action cannot be undone.'),t('Delete'),t('Cancel'));

  }
/**
 * #submit callback for node_adoption_transfer_form().
 */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
  //if ($form_state['values']['confirm']) {
    $param = $form_state->getValue('_product');
    drupal_set_message(t('Group ' .$param.' will get deleted.'));
    db_query('DELETE FROM {content_type_usergroup} WHERE vid = %d', $param);
    //delete the users of the usergroup too
    db_query('DELETE FROM {usergroup_user_map} WHERE group_id=%d', $param);
    drupal_set_message(t('usergroup has been deleted.'));
    drupal_goto('function_name');
  }

  protected function getEditableConfigNames() {
    return "delete_user_group";
  }

}

I am getting the following error:

DeleteUserGroup::buildForm() must be compatible with
  Drupal\Core\Form\FormInterface::buildForm(array $form,
  Drupal\Core\Form\FormStateInterface $form_state)

Why?
Comment: Can anyone explain how this equates when using the WebForm module? I have no module specifically for the form I have built using the module, so what would the point '_form' to within the routing.yml file ?
Answer: The parameter has to have the same name in routing.yml and build method. And when using parameters in forms you have to set a null value in the parameter list:
public function buildForm(array $form, FormStateInterface $form_state, $arg1 = NULL) {

Comment: Ah yes! The additional parameters always have to be `NULL` to be compatible with `Drupal\Core\Form\FormInterface::buildForm`.
Comment: @leymannx I would be even concrete that additional parameters should be optional (nullable) with defaults like `NULL`, 'some_string', '2' and so on.
See for example `core/modules/comment/src/Form/CommentAdminOverview.php`

BTW: it is true for any method that follows interface where you want to add extra parameters.
Comment: Is this and second highest rated answer still valid (D9/D10)? It seems to me you explicitly need to state the parameter under defaults in the routing.yml and it's been put to '' instead of NULL (in form class too). Like can be seen: https://git.drupalcode.org/project/drupal/-/blob/6a19b3a01ffcabeee34e0499456cbd86a0dae96f/core/modules/ban/ban.routing.yml and https://git.drupalcode.org/project/drupal/-/blob/6a19b3a01ffcabeee34e0499456cbd86a0dae96f/core/modules/ban/src/Form/BanAdmin.php#L61
Comment: Ah okay, seems to depend on form class from which you derive, ConfigFormBase seems to require the param in the defaults in routing.yml, while just FormBase does not. That said, not sure why the BanAdmin Route uses this, seems not necessary.
Answer: First create a routing.yml file
admin_notes.form:
  path: '/example_module/form/{arg}'
  defaults:
    _form: '\Drupal\example_module\Form\ExampleForm'
  requirements:
    _permission: 'access content'

Then create a .php file under folder structure /src/Form/ExampleForm.php. Then build a form
public function buildForm(array $form, FormStateInterface $form_state, $arg = NULL) {
  $form['example_note'] = [
    '#type' => 'textarea',
    '#title' => $this->t('Block contents'),
    '#description' => $this->t('This text will appear in the example block.'),
    '#default_value' => $arg,
  ];
  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['delete'] = [
    '#type' => 'submit',
    '#value' => $this->t('Delete'),
  ];
  return $form;
}

Comment: default `arg:` should be passed in route definition.
Answer: This is not asked in the question. Maybe it could also help, I had to pass a parameter to a form that was not loaded by a route. The form is integrated into a template loaded by a controller.
In custom_module.routing.yml:
path: '/lorem/{arg}'
defaults:
    _controller: '\Drupal\my_module\Controller\LoremController::testLorem'

In the controller, the form is called and the parameter $arg is passed to the form builder.
public function testLorem($arg) {
     $form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\testForm', $arg);
     $build = [
         '#theme' => 'custom_theme',
         '#form' => $form,
         '#arg' => $arg,
     ];

     return $build;
}

And in the form :
public function buildForm(array $form, FormStateInterface   $form_state, $arg = null) {
}

Comment: I came here looking for exactly this. Thank you!


Changing CSS depending on how much of the page is scrolled

Question: I tried to do this on my own but I didn't get anywhere. All I have is:
if($("body").scrollTop() > 100) {
    $("header").css("display", "none");
}

It's within a document ready. What I want to do is add "display:none" to the header element when the page has scrolled 100px.
Learning jQuery slowly. Thank you.
Edit: The HTML is simply

  ...
  ...

#wrap is tall enough to need scrolling. When scrolling passed 100px I want to hide header.
Answer: You need to hook onto the windows's scroll event and in there, check that object's scrollTop() value:
var $window = $(window),
    $header = $('header');

$window.scroll(function() {
    if ($window.scrollTop() > 100)
        $header.hide();
    else
        $header.show();
});

Comment: This works! Thank you. Would you explaining what "hook onto the window's scroll event" means?
Comment: With the above `$(window).scroll(...)` call, your telling the browser (with jQuery) to call the given function everytime the window updates its scrolling position. It's basically firing 'scroll' events at every scroll updates, and you want your function to be called when that happens.
Answer: $("header") it should be $("#header") where header is id of header div
Comment: I am not using an id for my header. I want to hide the  element that I am using.


Image statistics in PHP: average column values

Question: I want to calculate the average pixel values in each column of an image. I am considering using ImagickPixelIterator Imagick::getPixelIterator but, if I understand it correctly, it iterates row by row.
Do you think it is a good way to face the problem? Do you know a better way?
Comment: With some basic math you can go row by row and still calculate column avarage.
Comment: @Marek I know. What I don't know is if this is the most efficient way or I am missing something.
Comment: Efficiency depends on the efficiency of the library, less on your code. You have to measure it.
Answer: Use the image library of your choosing to resize the image to be 1 pixel high, after that you just read the pixels to have average column colors. Good luck!
Answer: This is my alternative using Imagick::getPixelIterator :
<code>        $v_row = array();
        $v_column = array();
        $pxit = $img->getPixelIterator();
        foreach($pxit as $row => $pixels) {
            foreach ($pixels as $column => $pixel) {
                $color = $pixel->getColorValue(Imagick::COLOR_RED);
                $v_row[$row] += $color;
                $v_column[$column] += $color;
            };
        };
        foreach($v_row as &$v){ $v /= count($v_column); }
        foreach($v_column as &$v){ $v /= count($v_row); }
</code>
It calculates averages for columns and rows.


sprite kit enter/exit region

Question: I need to know when the player enters or exits a (polygon) region. This region is constructed from SKShapeNodes. Each SKShapeNode is a single straight line.
A good approach seemed to do collision detection between the player and these lines via SKPhysicsBody.  I keep track via a flag if the player is inside or outside the region.
<code>SKPhysicsBody *pilotPhysics = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(0.1, 0.1)];
    [pilotPhysics setCategoryBitMask:   pilotCategory];
    [pilotPhysics setCollisionBitMask:  pilotCategory];
    [pilotPhysics setContactTestBitMask:    airspaceCategory];
</code>
But even with a size of 0.1 x 0.1, my SKPhysicsContactDelegate gets multiple beginContact messages. Sometimes the flagged has been flipped so many times within a short interval, it has the wrong value after passing through the perimeter.
What is the correct way to determine when a SKNode enters or exits another SKNode?
Answer: I'm not sure why the contact delegate is being called multiple times, but I'd guess it had something to do with the physicsBody size being set to be so tiny.
I'd try making the regions' physicsBodies fill the entire region rather than just being a line at the edge, and then use didBeginContact to set the flag to YES and didEndContact to set the flag to NO, rather than just flipping the BOOL every time the delegate is called.
Answer: Could you put a CGRect in the same spot as your node that needs to detect if there is another node inside of it? And then use the contains function from the CGRect in the update function to determine whether there is a node inside of it.

sprite kit enter/exit region


Transformation from skewed to symmetric distribution

Question: Let us consider a positive valued random variable $X$ which is following a positively skewed probability distribution.
Is it possible to a get a function $f$ (one-to-one) for which $f(X)$ follow a symmetric distribution?
Comment: You could apply the inverse CDF of Y to obtain a uniformly distributed randdom variable and then apply any symmetric CDF. Assuming continuity this should be one-to-one.
Comment: Maybe you should specify to which reference point you wish symmetry (zero, mean (which I had in mind), etc.). The proof should be straightforward: The resulting r.v. will have exactly the CDF you imply, so if this is symmetric you are good to go.
Comment: @Janak: in this case you won't even need to shift the U[0,1] variable, and as long as you CDF has a mean, it will be symmetric about it.
Comment: Once you have the $U[0,1]$ r.v. you could also easily make it symmetric by shifting it by $1/2$ to the left.
Comment: @InfiniteVariance. How  we can prove: any symmetric CDF composed of inverse CDF to X is gives a symmetric distribution?
Comment: @InfiniteVariance. Thank you. I got the point. The point of symmetry I am looking for is the mean.
Answer: There are some interesting special cases. Think of the log-normal distribution, which satisfies your conditions on $X$, and can be transformed into a symmetric normal distribution via the one-to-one transformation $\ln$.
Comment: This special case is fine, but I am trying to find the transformation in general case. The log transformation of my data is seems to be not following normal   distribution.
Comment: Indeed, one should not expect that a log-transformation would work in general!


Criando elementos HTML via JavaScript/JQuery

Question: Oi! Criei um form em HTML para um gerador de curriculos e no campo "experiência profissional" tem apenas inputs para registro de uma experiência.
HTML:
 <fieldset id="professional-info">
            <legend>
Experiência profissional
</legend>

                 Cargo: <input type="text" name="cargo" id="cargo">

                 Empresa: <input type="text" name="empresa" id="empresa">

                 Início: <input type="date" name="data-inicio" id="data-inicio">
                 Término: <input type="date" name="data-fim" id="data-fim">
                <input type="checkbox" name="atual" id="atual">Ainda trabalho aqui

                 Descrição: <textarea name="descricao" id="descricao" cols="40" rows="1"></textarea>

            <button type="button" form="main" id="add-exp">Adicionar outra experiência</button>
        </fieldset>

JAVASCRIPT:
function addRemoveExp() {
$(".prof-exp").clone().appendTo("#professional-info");}document.getElementById("add-exp").onclick = function(){addRemoveExp()};

Como podem ver, deixei um botão de adicionar outra experiência, para que o usuário possa cadastrar novas experiências se assim desejar.
Até agora estou tentando usar os metodos clone() e appendTo() do jQuery, mas esta """solução""" não está funcionando porque:

A cada clique no botão adicionar, ele duplica a quantidade atual de divs com a classe .prof-exp;
Uma vez que ele tenha preenchido a 1a experiência e clicar no botão "adicionar outra experiência", todos os dados serão clonados para as experiências abaixo.

Ou seja, não serve. O que eu quero é simplesmente REPLICAR os campos em branco para que o usuário os preencha com suas outras experiencias. Como faço isso?
Como resolvo isso? Não sei mais o que fazer, quero muito resolver esse desafio! Muito obrigado, pessoal, por qualquer tentativa de ajuda.
Sou novo em desenvolvimento e ainda não sei muita coisa, então se eu estiver sendo muito leigo, desculpe-me
Answer: Por que isso acontece? Quando você busca pela classe de um elemento, você está retornando todos os elementos que tem aquela classe, inclusive os que você acabou de colar.
Como resolver? Eu sugiro que você faça as coisas um pouquinho diferentes. Não use a tag principal para ser clonada, mas uma outra criada exclusivamente com esta finalidade.
Exemplo:
Crie uma section ou div com o id "templates" ou utilize a tag <template> que já é suportada pela maioria dos browsers  modernos.
Crie uma section com o id templates e que tenha display none. Dentro dela você coloca todos os elementos que servirão de modelo para serem clonados. Como ela nunca será editada você não precisará limpar os campos antes de clonar. Além disso ela pode ter as classes que você quer sem causar conflitos porque serão identificadas pelo id da tag pai.
Algo mais ou menos assim:

function addRemoveExp() {
  $("#templates .prof-exp").clone().appendTo("#professional-info");}document.getElementById("add-exp").onclick = function(){addRemoveExp()};

<fieldset id="professional-info">
  <legend>
Experiência profissional
</legend>

     Cargo: <input type="text" name="cargo" id="cargo">

     Empresa: <input type="text" name="empresa" id="empresa">

     Início: <input type="date" name="data-inicio" id="data-inicio">
     Término: <input type="date" name="data-fim" id="data-fim">
    <input type="checkbox" name="atual" id="atual">Ainda trabalho aqui

     Descrição: <textarea name="descricao" id="descricao" cols="40" rows="1"></textarea>

  <button type="button" form="main" id="add-exp">Adicionar outra experiência</button>
</fieldset>

     Cargo: <input type="text" name="cargo" id="cargo">

     Empresa: <input type="text" name="empresa" id="empresa">

     Início: <input type="date" name="data-inicio" id="data-inicio">
     Término: <input type="date" name="data-fim" id="data-fim">
    <input type="checkbox" name="atual" id="atual">Ainda trabalho aqui

     Descrição: <textarea name="descricao" id="descricao" cols="40" rows="1"></textarea>

Seu código ficaria mais elegante e mais fáci de manter se você já inserisse o primeiro formulário usando a mesma função dos demais:

function addRemoveExp() {
  $("#templates .prof-exp").clone().appendTo("#professional-info");}document.getElementById("add-exp").onclick = function(){addRemoveExp()};
  addRemoveExp();

<fieldset id="professional-info">
  <legend>
Experiência profissional
</legend>
  <button type="button" form="main" id="add-exp">Adicionar outra experiência</button>
</fieldset>

     Cargo: <input type="text" name="cargo" id="cargo">

     Empresa: <input type="text" name="empresa" id="empresa">

     Início: <input type="date" name="data-inicio" id="data-inicio">
     Término: <input type="date" name="data-fim" id="data-fim">
    <input type="checkbox" name="atual" id="atual">Ainda trabalho aqui

     Descrição: <textarea name="descricao" id="descricao" cols="40" rows="1"></textarea>


script not found or unable to stat: /usr/lib/cgi-bin/php-cgi

Question: I have just seen a new series  of error in the /var/log/apache2/error.log

[Thu Oct 31 06:59:04 2013] [error] [client 22.214.171.124] script not found or unable to stat: /usr/lib/cgi-bin/php
[Thu Oct 31 06:59:08 2013] [error] [client 126.96.36.199] script not
  found or unable to stat: /usr/lib/cgi-bin/php5
[Thu Oct 31 06:59:09 2013] [error] [client 22.214.171.124] script not
  found or unable to stat: /usr/lib/cgi-bin/php-cgi
[Thu Oct 31 06:59:14 2013] [error] [client 18.104.22.168] script not
  found or unable to stat: /usr/lib/cgi-bin/php.cgi
[Thu Oct 31 06:59:14 2013] [error] [client 184.108.40.206] script not
  found or unable to stat: /usr/lib/cgi-bin/php4

This server is running Ubuntu 12.04lts.
I have never seen this sort of attack before, should i be concerned or securing my system in any way for them?
Thanks,
John
Answer: If you're running a default configuration of Apache on Ubuntu (or have used the default config as a blind template for other virtualhost directives) you'll likely find that you have a ScriptAlias directive mapping /cgi-bin/ (relative to the apache document root) to the filesystem location of /usr/lib/cgi-bin/ - so what they're actually trying to load is http://your.host.name/cgi-bin/php4.
If you're not using your cgi-bin for anything, you're unlikely to lose anything you care about by commenting out the sections relating to it (and the more defined to your needs your configuration is, the smaller any potential attack surface).
You'll find the relevant directives for the default site in /etc/apache2/sites-available/000-default, if memory serves.
Comment: In Ubuntu 13.10's default apache config, I found the `ScriptAlias` directive hiding in `/etc/apache2/conf-enabled/serve-cgi-bin.conf`
Answer: Seems theres someone trying to find a php cgi binary in your cgi-bin path. As long as there's nothing exploitable in there, there's nothing to worry about.
Comment: But with apache running are they effectively attempting to access WEBROOT/usr/lib/cgi-bin/php4   ?
Comment: see Phil's reply, the default ScriptAlias directive is responsible for this.
Answer: You can disable the default server cgi-bin like so:
a2disconf serve-cgi-bin
systemctl reload apache2