text:
Q: ArrayIndexOutOfBoundsException inserting JTable data to SQL database I have made a project on railway management system and want to insert values from text fields and Java table to MySQL database. How can I get rid of this error? Please help!!
int rows = jTable1.getRowCount();
for(int row = 0; row<rows ; row++){
    int index=1;
    String S_No = (String) jTable1.getValueAt(row, 1);
    String Name = (String) jTable1.getValueAt(row, 2);
    String Age = (String) jTable1.getValueAt(row, 3);
    String Gender = (String) jTable1.getValueAt(row, 4);
    String berth_preference = (String) jTable1.getValueAt(row, 5);
    String Quota = (String) jTable1.getValueAt(row, 6);
    String tno =(String) cb1.getSelectedItem();
    String tname =(String) cb2.getSelectedItem();
    String clas =(String) cb3.getSelectedItem();
    String tic= tick.getText();
    String frms=frm.getText();
    String tos=to.getText();
    String boarding=bp.getText();
    String reser=ru.getText();
    String jdate=date.getText();
    String pnr=l1.getText();

    try{
        Class.forName("java.sql.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost/railway","root","ridhi");
        st =con.prepareStatement("INSERT INTO pnr(pnr_no,Train_Number,Train_Name,From_m,T_o,Date,Class,Reserved_Upto,Boarding_Pt,no_tickets,S_No,Name,Age,Gender,berth_preference,Quota) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

        st.setString(1, S_No);
        st.setString(2, Name);
        st.setString(3, Age);
        st.setString(4, Gender);
        st.setString(5, berth_preference);
        st.setString(6, Quota);

        st.executeUpdate();
        index++;

        this.setVisible(true);
        new payment().setVisible(true);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null,e.getMessage());

    }
}

Error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 6 >= 6
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
at javax.swing.JTable.convertColumnIndexToModel(JTable.java:2553)
at javax.swing.JTable.getValueAt(JTable.java:2695)
at reservation.reservationActionPerformed(reservation.java:341)
at reservation.access$100(reservation.java:21)
at reservation$2.actionPerformed(reservation.java:245)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6216)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5981)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4583)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

And now I am getting a new error:
java.sql.SQLException: Parameter index out of range (0 < 1 ).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3283)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3272)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4108)
at reservation.reservationActionPerformed(reservation.java:358)
at reservation.access$100(reservation.java:21)
at reservation$2.actionPerformed(reservation.java:245)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6216)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5981)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4583)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

A: change this to this jtable columns are zero index based.if you have 6 columns of jtable then max column index is 5 not 6 .error is because of this but care about row index 2 if you want to get first row then getValueAt(0, n); not getValueAt(1, n);
String S_No = (String) jTable1.getValueAt(row, 0);
String Name = (String) jTable1.getValueAt(row, 1);
String Age = (String) jTable1.getValueAt(row, 2);
String Gender = (String) jTable1.getValueAt(row, 3);
String berth_preference = (String) jTable1.getValueAt(row, 4);
String Quota = (String) jTable1.getValueAt(row, 5);// 5 not 6

you should have same column count in prepared statement also .
 st =con.prepareStatement("INSERT INTO pnr(pnr_no,Train_Number,Train_Name,From_m,T_o,Date,Class,Reserved_Upto,Boarding_Pt,no_tickets,S_No,Name,Age,Gender,berth_preference,Quota) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

...........................................................................................
 st.setString(1, S_No);
 st.setString(2, Name);
 st.setString(3, Age);
 st.setString(4, Gender);
 st.setString(5, berth_preference);
 st.setString(6, Quota);

you should have like, you have missed column phone number train number
 st.setString(1, pnr);
 st.setString(2, tno );

A: When ArrayIndexOutOfBoundsException is shown: If we request for an index that is either negative, or greater than or equal to the size of the array, an ArrayIndexOutOfBoundsException is thrown.
In your case, java.lang.ArrayIndexOutOfBoundsException: 6 >= 6.


text:
Q: What's the recommended MyHDL design pattern for multi-tick operations? I'm trying to learn MyHDL by writing a very simple machine with just a handful of instructions and operations. What I'm struggling with is the best way to design my machine to handle operations that take multiple clock cycles to resolve. Currently, all of the hardware components that I've written need just a single tick to resolve, so it's the control unit that I'm having trouble with.
For example, let's say that all of my machine's operations take between 1 and 3 clock cycles to complete, which means that I'll need to have 3 cycles for every instruction (as I'm not doing any parallelism right now).
This will mean that I need three stages to my machine or, in HDL terms, three clock sensitive logic blocks. One complete iteration of the machine would look like:

*

*Control A

*

*Tick :: Components

*Control B

*

*Tick :: Components

*Control C

*

*Tick :: Components

*Back to A

Since there is no parallelism and each stage is using shared hardware, I want the control blocks to be triggered sequentially and in order. To do this, would I want multiple clocks? One clock for the components and one for the control where the ticking of the components clock is done at the end of each control phase? But then control A, B, and C will all be executed together by each clock tick. Would I then want four clocks, with one for the components and one for each control phase where the component clock and the clock of the next phase is advanced at the end of each control phase? Or do I want just one clock and some boolean signals that tell each phase when they should be going (every control phase would check a flag and if it's set, they would execute and set the flag for the next phase)?

A: From your description I think that you could try to solve you problem using a state machine and spliting your circuits into independent units.
Since you said that you don't want to add any paralelism in your design you could try to keep your design within a single circuit, with only one clock and control the behavior using registers. Try to describe the circuit considering that one action will be taken per clock.
Try to add some example code and more concrete information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bind ListViewItem ContextMenu MenuItem Command to ViewModel of the ListView's ItemsSource I have a ListView of Expanders. Each Expander (representing a database table) will have items under it, in another ListView. I want to Right-Click and have an "Edit" option on the innermost items, which represent records in the corresponding database table.
There is an ICommand named 'Edit' in my MainEditorViewModel. The Datacontext in which this command resides is the same as that of the outermost ListView named "TestGroupsListView"
Here is the XAML markup for the ListView of Expanders. The outermost ListView I've named for referencing in the binding via ElementName for the MenuItem's Binding:
        <ListView Name="TestGroupsListView" ItemsSource="{Binding TestGroups}" Grid.Row="1">
            <ListView.ItemTemplate>
                <DataTemplate>

                    <Expander Style="{StaticResource MaterialDesignExpander}"  >
                        <Expander.Header>
                            <Grid MaxHeight="50">
                                <TextBlock Text="{Binding Name}"/>
                                <Grid.ContextMenu>

                                    <ContextMenu>
                                        <MenuItem Header="Add..." Command="{Binding Add}"/>
                                    </ContextMenu>
                                </Grid.ContextMenu>
                            </Grid>

                        </Expander.Header>

                        <ListView ItemsSource="{Binding Records}" Style="{StaticResource MaterialDesignListView}" Margin="30 0 0 0">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Grid.ContextMenu>
                                            <ContextMenu>
                                                <MenuItem Header="Edit"
                                                          Command="{Binding ElementName=TestGroupsListView, Path=DataContext.Edit}"
                                                          CommandParameter="{Binding }"/>
                                            </ContextMenu>
                                        </Grid.ContextMenu>

                                        <Button Content="{Binding RecordName}" Command="{Binding ElementName=TestGroupsListView, Path=DataContext.Edit}"/>
                                        <!--<TextBlock Text="{Binding RecordName}" AllowDrop="True"/>-->
                                    </Grid>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </Expander>
                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>

I am able to bind a button in the DataTemplate to 'Edit' successfully, but when I attempt to bind the MenuItem's Command to 'Edit', nothing happens. Why might this be that the button command binding works using ElementName but the same binding in the ContextMenu doesn't?

A: I think it will be better to use the context menu globally for ListView and globally for each Child ListView. Ok, here is my solution:
<ListBox ItemsSource="{Binding Groups}">
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Add..." Command="{Binding Add}"/>
        </ContextMenu>
    </ListBox.ContextMenu>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Expander Header="{Binding Name}">
                <ListView ItemsSource="{Binding Records}" SelectedItem="{Binding SelectedRecord}">
                    <ListView.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Edit" Command="{Binding Edit}" IsEnabled="{Binding CanEdit}"/>
                        </ContextMenu>
                    </ListView.ContextMenu>
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}"/>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Expander>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And for better understanding code behind:
public class GroupsVM : ViewModelBase
{
    public ICommand Add
    {
        get => null; //Command implementation
    }

    public ObservableCollection<GroupVM> Groups { get; set; } = new ObservableCollection<GroupVM>()
    {
        new GroupVM { Name = "First" },
        new GroupVM { Name = "Second" },
        new GroupVM { Name = "Third" }
    };
}

public class GroupVM : ViewModelBase
{
    private string _name;

    public string Name
    {
        get => _name;
        set { _name = value; OnPropertyChanged(); }
    }

    public ICommand Edit
    {
        get => null; //Command implementation
    }

    public bool CanEdit => SelectedRecord != null;

    public ObservableCollection<RecordVM> Records { get; set; } = new ObservableCollection<RecordVM>()
    {
        new RecordVM { Name="Record1" },
        new RecordVM { Name="Record2" },
        new RecordVM { Name="Record3" }
    };

    private RecordVM _selectedRecord = null;

    public RecordVM SelectedRecord
    {
        get => _selectedRecord;
        set
        {
            _selectedRecord = value;
            OnPropertyChanged();
            OnPropertyChanged("CanEdit");
        }
    }
}

public class RecordVM : ViewModelBase
{
    private string _name;

    public string Name
    {
        get => _name;
        set { _name = value; OnPropertyChanged(); }
    }
}


text:
Q: IQueryable complex order Only fields are allowed in a $sort I want to sort a list. When it was IEnumerable it was working fine, but I changed it to IQueryable to query MongoDB, it does not work. Giving me this error

System.NotSupportedException: 'Only fields are allowed in a $sort.'

//Query 1
var query = from d in list
        orderby
             d.Item.Value1 + d.Item.Value2 descending
        select d;

//Query 2
var query = from d in list
       orderby
            RecommendationFormula(d) descending
       select d;

private double RecommendationFormula(IItem d)
{
    var quality = ((int)(d.ValueX) / 18.0) * 50.0;
    var recent = ((DateTime.MinValue - (d.Item.Released ?? DateTime.MinValue)).TotalDays / (DateTime.MinValue - new DateTime(1990, 1, 1)).TotalDays) * 30;
    var rating = ((d.Item.XRating + d.Item.YRating) / 20) * 15;
    var quantity = (Quantity(d) / 1000.0) * 5;
    return quality + rating + recent + quantity;
}

I also understand that it does not support functions(as shown in Query 2),but Query 1 also gives the error, when I try ToList() the list.
How can I write this kind of complex sort for IQueryable list?

A: As it's stated in the exception, the typed way to configure sorting in LINQ supports only fields and not calculated values. It looks like it's a server restriction based on this. So it can be solved by adding projection:
        var query = from d in list
                    select new { Sum = d.Item.Value1 + d.Item.Value2, Item = d.Item } into projected
                    orderby projected.Sum descending
                    select projected;

that triggers this MQL:
{
    "aggregate": "coll",
    "pipeline": [{
            "$project": {
                "Sum": {
                    "$add": ["$Item.Value1", "$Item.Value2"]
                },
                "Item": "$Item",
                "_id": 0
            }
        }, {
            "$sort": {
                "Sum": -1
            }
        }
    ]
}

you can add more complex logic there, but don't expect anything too complicated, in your particular case, supporting for Timespan properties will be triggering an unsupported exception, I'm not sure whether server even has equivalent for Timespan logic in .net.
If you still has to look at more complex scenarios that will trigger an unsupported exception with typed LINQ queries, you have 2 options:

*

*Look at latest LINQ3 implementation. I know it supports more various cases in LINQ queries comparing it with LINQ2 (default), but I don't have experience with it, so it requires more investigation.

*You can look at whether your target can be archived with MQL server query itself (that definitely supports much more cases than can be implemented with LINQ provider). If you can construct query you need with a server syntax and get the result you need in mongo shell, you can pass this raw MQL into c# driver (pay attention that all definitions inside raw MQL should match with how server represents it). See this for details.

UPDATE:

*

*It looks like $substract is supported by LINQ2:
     var query = from d in list
                 select new { Sum = (DateTime.Now - d.Item.Released), Item = d.Item } into projected
                 orderby projected.Sum descending
                 select projected;

but it cannot extract TotalDays and similar properties. However it looks the server stages support it via 2 operators:

*

*Example of how to extract ms from a data via $substact.

*You may look at dateDiff newly introduced operator also.

Idea is to create a raw MQL request that you can check in the shell similar to:
db.coll.aggregate(
[
// stage 1
{
    $addFields: {
        "DateDiff": {
            $dateDiff: {
                startDate: "$Item.Released",
                endDate: ISODate("2010-01-01"),
                unit: "day"
            }
        }
    }
},
// stage 2
{
    $addFields: {
        "ForSorting": {
            $divide : [ { $toInt : "$DateDiff"} , 9] // 9 is a random value, you can calculate it yourself
        }
    }
},
// stage 3
{
    $sort : { "ForSorting" : -1 }
}
]
)

and then pass each stage separately via AppendStage method.
NOTE: you can combine typed stages(if it's supported) and stages with raw MQL similar to:
        var result = coll
            .Aggregate()
            .Match(c => c.Item != null) // just example of supported typed stage
            .AppendStage<BsonDocument>("{ $sort : { Released : 1 } }") // such simple `$sort` is supported in typed way, here is just an example how a raw query can be appended to the pipeline
            .ToList();

The generated MQL for the above LINQ query will be:
{
    "aggregate": "coll",
    "pipeline": [{
            "$match": {
                "Item": {
                    "$ne": null
                }
            }
        }, {
            "$sort": {
                "Released": 1
            }
        }
    ]
}

UPDATE2
if fields in your projected output document match to fields in your input document, you can avoid reprojecting (ie additional server side step) and instead just replace the output serializer on the client side via As:
        var list = coll
            .Aggregate<Original>() // this class has only `Item` field
            .Project(i => new { Sum = i.Item.Value1 + i.Item.Value2, Item = i.Item }) // this expression can be generated dynamically
            .SortByDescending(s=>s.Sum)
            .As<Original>()
            .ToList();

The generated MQL for the above case will be:
{
    "aggregate": "coll",
    "pipeline":
    [
        {
            "$project": {
                "Sum": {
                    "$add": ["$Item.Value1", "$Item.Value2"]
                },
                "Item": "$Item",
                "_id": 0
            }
        },
        {
            "$sort": {
                "Sum": -1
            }
        }
    ]
}

A: I believe the result you are looking for can be achieved by using LINQ lambdas
var query = list.OrderByDescending(d => RecommendationFormula(d));

I believe you can also write it as the following to convert the lambda into a method group but please correct me if I'm wrong:
var query = list.OrderByDescending(RecommendationFormula);

A: It's about the way MongoDB driver works. Can you please cast the IQueryable to a list with ToList() just before using it? It will add an overhead since it needs to load all the elements in the query to memory first.
If the data you are using will create a headache due to the volume, I would suggest either solving it in the database or process the data in memory in chunks, e.g. using Skip() & Take().
P.S: The method RecommendationFormula(IItem d) can be a static method.

A: I was able to sort the issue, in a different way, but avoided bringing the objects to memory for filter and sorting. But it does take 2 queries to MongoDB.

*

*Filter the List, _list is IQueryable

*Sort the list using projection bringing in only Ids

private IQueryable<string> Sort(IQueryable<IItem> list)
    query = from d in list
            select new
            {
                Ranking =
                    ((int)(d.ValueX) / 18.0) * 50.0 +
                    (((d.XRating + d.YRating) / 20) * 15) * 20 +
                    (d.Quantity/ 1000.0) * 5,
                ReleaseYear = d.Item.Released.HasValue ? d.Item.Released.Value.Year : 0,
                d.Id
            }
        into q
            orderby
                q.ReleaseYear descending,
                q.Ranking descending
            select q.Id;

}

*Use Skip and Take the sorted ids to a list.

var itemIds = this.Sort(_list).Skip(_pageSize * _page).Take(_pageSize).ToList();

*Find only the objects in the ids list from MongoDB

var list = _list.Where(q => itemIds.Contains(q.Id)).ToList();

*Order the real objects like the ids.

var list = list.OrderBy(q => itemIds.IndexOf(q.Id));


text:
Q: Best practices for packaging resources (jpg's, sound, video) in an iPhone app? I'm a newb iPhone developer writing an app that has several large JPGs and sound files. Everything works ok if I drag these non-code resources into my project. But I am wondering if this is the right way to package my app.
In Windows development, I would create a "resource DLL" that keeps the .exe size small. What is the equivalent for iPhone? I think I should be creating a "bundle" - can someone please give me some pointers to using these and how to link them into my main project?
Thanks!

A: JPEG images, audio files (if they're in MP3, AAC or similar compressed format) and video files (MPEG-4) are already highly compressed.
Packing them in an archive using a compression archive format like zip will not reduce the size of the files any further, plus it's more difficult to work with the files in your app. In fact, an iPhone app is already a zipped bundle so any compression you implemented would be redundant.
You should just continue to do what you're doing, it's standard procedure.

A: In iPhone development everything is already bundled together.  Your executable, resources, config files are all packaged up into your .app.  So just keep doing what you're doing, XCode automatically separates your resources and your executable (A few times I've noticed that a .app file in OSX actually shows up as a folder in Windows)


text:
Q: How to search with Spotlight more effectively I'm used to using various flags to modify the results of Google searches, to only show results from a particular site, or only certain kinds of files.
For example you can restrict Spotlight searches to only look for pdf files like this example, when I'm looking for a pdf cheatsheet for using YUI's grid system css framework on my computer.
YUI grid kind:pdf

I'd be amazed if Apple's Spotlight didn't have loads of other handy flags to fine tune a search in the same way - what tricks do you use, or where do you look to find more tips to improve your Spotlight-fu?

A: There's a whole article regarding this subject here. In short:

*

*you use boolean operators, such as AND, OR, NOT

*applying quotation marks will search for exactly the phrase you want

*using name: keyword will only search file names

*author: keyword allows you to search files by file author (Spotlight will find only files produced by programs that save this attribute—Mail, iChat, Word, Excel, Pages, Numbers, and a few others)

*you can use date:today, created: date and modified: date to search for files by a particular date

*you can refine your search to only find certain file types using kind: filetype (the article I linked to contains all the possible file types you might need)

A: Spotlight menu and Finder

*

*name:filename

*kind:kindle (kind:mobi and *.mobi cannot be used)

*kind:image

*date:today (date:week and date:month don't work)

*date:12/31/11 (other formats like date:2011-12-31 don't work)

*date:12/1/11-12/31/11

*kind:mp3 AND bitrate:<192000
Common metadata attribute keys
mdls -name $attribute $file shows the value of a single attribute and mdls $file lists all attributes.

*

*kMDItemContentType: the uniform type identifier like public.plain-text

*kMDItemContentTypeTree: the UTI and its parent UTIs

*kMDItemDisplayName: the name of a file without an extension if its extension is set to be hidden

*kMDItemDurationSeconds: for example the duration of audio or video files

*kMDItemFinderComment: the Spotlight comment that can be set in Finder's information windows

*kMDItemFSContentChangeDate: modification date

*kMDItemFSCreationDate: creation date

*kMDItemFSInvisible: the visibility of a file

*kMDItemFSName: the name of a file with a filename extension

*kMDItemFSSize: the size of a file in bytes

*kMDItemKind: a kind description like HTML document

*kMDItemLastUsedDate: date last opened

*kMDItemNumberOfPages: for example the number of pages in a PDF file

*kMDItemPageWidth: for example the width of a PDF document in points

*kMDItemPath: the full path of a file

*kMDItemTextContent: contents of the file

*kMDItemTitle: for example the title of a PDF document or a website

*kMDItemURL: for example the URL of a webloc file

*kMDItemWhereFroms: a URL a file was downloaded from

mdfind query expressions

*

*mdfind . -onlyin ~/Pictures

*mdfind 'kMDItemFSContentChangeDate == $time.this_week(-1)'

*mdfind 'kMDItemTextContent == "*expose*"cd' (ignore case and diacritics)

*mdfind 'kMDItemFSSize >= 5000 && kMDItemFSSize <= 5005)'

*mdfind 'kMDItemFSContentChangeDate >= $time.iso(2012-04-13T13:44Z)'

*mdfind 'kMDItemFSCreationDate >= $time.now(-3600)'

*mdfind 'kMDItemKind == "*movie" && kMDItemPixelHeight >= 720'


text:
Q: setting permissions on folders created through group policy I have a domain controller running server 2012 std. In the default domain policy I set up a folder in User Configuration>Windows Settings>Folders The path is \\MyServer\MyShare\%USERNAME%
This works well. Any user that logs in gets a folder on the server the same as their user name. I'm also automatically mapping to that folder. What I can't figure out is how to set each folder so that only that user (and the admin) has access to it. Is this possible through Group Policy?

A: The following article details how to set the Share and NTFS permissions for folder redirection. The same should be applicable to what you're doing. The article was written for Windows Server 2003 but should be applicable to any share, regardless of host OS.
http://technet.microsoft.com/en-us/library/cc781907(v=ws.10).aspx


text:
Q: Xcode 5, why isn't the image resizing? Hello I am trying to resize a UIImage, but even though I'm not getting any errors it is not working.
hers the code of .h file
IBOutlet UIImageView *Fish;

heres the code of .m file
Fish.frame = CGRectMake(0, 0, 300, 293);

What am I doing wrong?
Thanks for any help

A: The image is probably not resizing because you are just resizing the image view. Make sure in your storyboard that you make the image view (Fish), have the move ScaleToFill. I can't do screenshot due to reputation ( sorry :( )
Alternately, if your goal is not to resize the image view but to resize the image it is holding, you can do this:
UIImage *image = Fish.image;
UIImage *image = YourImageView.image;
    UIImage *tempImage = nil;
    CGSize targetSize = CGSizeMake(80,60);
    UIGraphicsBeginImageContext(targetSize);

    CGRect thumbnailRect = CGRectMake(0, 0, 0, 0);
    thumbnailRect.origin = CGPointMake(0.0,0.0);
    thumbnailRect.size.width  = targetSize.width;
    thumbnailRect.size.height = targetSize.height;

    [image drawInRect:thumbnailRect];

    tempImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    YourImageView.image = tempImage;

and you would set thumbnailRect to whatever size you want.
Hope this helps! Please search Nerdy Lime on the app store to find all of my apps! Thanks!

A: I bet your outlet is not hooked up.  In your "viewDidLoad" method, try doing this:
if(Fish)
{
    Fish.frame = CGRectMake(0, 0, 300, 293);
} else {
    NSLog(@"Fish is null; why did I forget to connect the outlet in my storyboard or xib?");
}

And this isn't the best way to resize your UIImageView.  If you're using regular springs & struts, you can grow an outlet by clicking the springs & struts to grow based on the superview's size, e.g.:

And if you're doing AutoLayout, there's a different thing you can do (basically pin your view to all four sides of the superview).
Here is how I do it:
1) select the outlet / object you want to add constraints to (in your case, it'll be the fish image view)
2) see the segmented control at the bottom of the Interface Builder window?  Click on the second one and you'll see a popover view open up with a list of possible constraints to add.
3) In my example, I'm adding constraints in my ImageView to always be 10 pixels from each edge of the superview (note the four "10"s and solid red lines meaning I'm adding four constraints).
AutoLayout is a pain to get accustomed to (and I'm still learning it myself), but I suspect that once one gets the hang of it, it'll be a powerful new tool especially as Apple brings in additional iOS screen sizes in the very near future.


text:
Q: Escape Character while using @ In C# im using:
Console.WriteLine(@"Line 0
Line 1
Line 2
Line 3
\"Escape these quotes!\"
Line 5
")

I want to escape these quotes, but have not found out how to yet.
I'm trying out a few ideas now, but hopefully someone already knows.
Mona

A: Wait, found it out: just need to double the quotes:
Console.WriteLine(@"Line 0
Line 1
Line 2
Line 3
""Escape these quotes!""
Line 5
")

Anyhow thanks!


text:
Q: Dict with array key in julia In julia language (ver 1.1.0), I am experimenting what would happen when I mutate a dictionary key.
Before mutation, both the variable x and [1,2,3] is recognized.
x = [1,2,3]; d = Dict(x=>"x")
haskey(d, x)
# true

haskey(d, [1,2,3])
# true

Once I mutate x, neither the variable x nor [1,2,3,4] is recognized.
push!(x, 4)
haskey(d, x)
# false

haskey(d, [1,2,3,4])
# false

haskey(d, [1,2,3])
# false

Value-wise, the key is "equal" to x, so I guess this has something to do with the hash function, but could not understand the source code.
collect(keys(d))[1] == x == [1,2,3,4]
# true

Can someone explain what makes this behavior, or suggest resources that I should look at?

A: The key function to look into is ht_keyindex.
There you can see that in order for the key to be found it must both:

*

*Match hash value (via hashindex).

*Match identity or value.

There is a non-negligible probability that after mutating x it will have the same hashindex value and the key would be found. For example here you could set index 4 of x to 5 and all seemingly would work:
julia> x[4] = 5
5

julia> x
4-element Array{Int64,1}:
 1
 2
 3
 5

julia> haskey(d, x)
true

Therefore - as in any programming language supporting dictionaries in a similar way - mutating keys of the dictionary should not be done. The above discussion should be in practice only a theoretical one.


text:
Q: Access violation after going out of a RTTI-related function: Result disappears Previously I had one function to get object property through RTTI and set it's value. Now I decided to split it up in TRTTI.GetObjProp and TRTTI.SetObjPropValue in order to cache value returned by TRTTI.GetObjProp and speed up data processing.
Strange things happen after that. First of all, I suddenly noticed that ctx.GetType works and has always worked although I never initialized the ctx variable. Ok, if I initialize it with TRttiContext.Create(), nothing changes in the second weirdness:
I call the TRTTI.GetObjProp function and as long as I am in this function, Result is defined, and I can request it's properties with debugger. When I go out of the function, I try to request the same properties of rprop variable and get Access Violation error. According to debugger, rprop is defined.
procedure TConfManager._setValue(indicator: TComponent; name: string; value: OleVariant);
var
  rprop: TRttiProperty;
begin
  rprop := TRTTI.GetObjProp(indicator, name);
  //Access violation here when I try to use rprop
  TRTTI.SetObjPropValue(indicator, rprop, value);
end;

class function TRTTI.GetObjProp(obj: TObject; propName: string): TRttiProperty;
var
  ctx: TRttiContext;
  rtyp: TRttiType;
begin
  if obj = nil then Exit(nil);
  rtyp := ctx.GetType(obj.ClassType);
  Result := rtyp.GetProperty(propName);
end;

Why the function result is properly defined when I am in the function, but isn't properly defined when I go out of it?

A: The TRttiProperty instance is owned by the TRttiContext object. When your local variable ctx leaves scope, that TRttiContext object is destroyed, taking with it all the objects it owns, including your TRttiProperty instance.
You need to make sure that the TRttiContext object that owns any RTTI objects that you use lives at least as long as any references to those owned objects. The simplest way to achieve that is probably to make the TRttiContext object be a global variable.


text:
Q: How to lower composite reliability at the moment I'm evaluating a survey which contains some constructs with too high composite reliability values. The CR (composite reliability) values are above .95 which indicates redundant items. In consequence to this I nneed to reduce the CR because it is indicating that there are redundant items. I want to identify which items are redudant.
My question is:
Is there a solid way to solve this problem?

A: Items are redundant as a function of other items.
If I ask your height in inches, and your height in cm, one of them is redundant. Which one? Both, or neither.  It doesn't matter which one you use, just pick one.
Are you trying to reduce the length of your scale?  Typically shorter versions of scales are developed through validity methods, not reliability methods. However, I have never heard anyone worrying that their reliability is too high - you might worry that your scale is too long, but that (seems to be) the other side of the coin.


text:
Q: When using Alamofire, what does value of tuple type has no member validate mean? I'm working towards a solution to authenticate with Microsoft Azure using JWT bearer tokens which doesn't use a simple username and password but rather a client id, client secret, and two other parameters.  The authentication process works when ran in Postman however when I recreate the solution in Xcode using Alamofire, it displays a 400 error.  I'd like to print out to the console, the Alamofire request so that we can see how Alamofire is structuring the URL.
When I attempt to put Alamofire's request class method inside a print function, it won't compile and I receive the Xcode error:
Value of tuple type '()' has no member 'validate'

Here is the line of code where I'm attempting to print to the console:
print(Alamofire.request(authorizationURL, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: headers))

A: I realized I placed the print statement within the Alamofire request block before my .validate statement. By moving the print statement to outside of the request statement it works.
import UIKit
import Alamofire
import SwiftyJSON

class Stackoverflow: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Stackoverflow.getAzureTokenOld()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @objc class func getAzureTokenOld(){

        let authorizationPath: String = "https://login.microsoftonline.com/tenantID/oauth2/token"
        if let authorizationURL: URL = URL.init(string: authorizationPath){
            //do stuff with your authorization url
            let parameters: [String: Any] = [
                "grant_type" : "client_credentials",
                "client_id" : "testID",
                "client_secret" : "testSecret",
                "resource" : "https://rest.media.azure.net"
            ]

            let headers = [
                "Content-Type": "application/x-www-form-urlencoded",
                "Keep-Alive": "true"
            ]
            Alamofire.request(authorizationURL, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: headers)

                .validate(statusCode: 200..<300)
                .responseJSON { response in
                    switch response.result {
                    case .success:
                        print("Validation Successful")
                        let value = response.result.value
                        print("The valued response is: \(String(describing: value))")
                    case .failure(let error):
                        print(error.localizedDescription)
                    }
                    debugPrint("checking checking: \(response)")
            }
            print(Alamofire.request(authorizationURL, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: headers))
        }

    }
}


text:
Q: Python Numpy: Sub-arrays to one list I have a numpy array x that looks like this:
In: x
Out:
array([[array([ 1.]), 0.0],
       [array([-0.00770808]), array([ 0.90825723])],
       [array([-0.0358526]), array([ 0.59267366])],
       [array([ 0.0088844]), array([ 0.89480382])],
       [array([ 0.0387529]), array([ 0.56483939])],
       [array([-0.08508252]), array([ 0.20664826])],
       [array([-0.04159874]), array([ 0.538443])],
       [array([ 0.07626737]), array([ 0.25998565])],
       [array([ 0.00222671]), array([ 0.97386301])],
       [array([-0.12652962]), array([ 0.0621885])],
       [array([ 0.01404373]), array([ 0.83703121])]], dtype=object)

You see that there are 11 tuples. I want to create a list with each of the first elements from each tuples. That would be a list that looks like this:
[1, -0.00770808, -0.0358526, 0.0088844, 0.0387529 ... ]. How can I do this?

A: You can do something like this:
>>> x[:,0].astype('float')
array([ 1.        , -0.00770808, -0.0358526 ,  0.0088844 ,  0.0387529 ,
       -0.08508252, -0.04159874,  0.07626737,  0.00222671, -0.12652962,
        0.01404373])

A: You can simply issue
mylist = [a[0][0] for a in x]

where x is your array. Demo:
>>> mylist = [a[0][0] for a in x]
>>> mylist
[1.0, -0.00770808, -0.035852599999999998, 0.0088844000000000006, 0.0387529, -0.085082519999999995, -0.041598740000000002, 0.076267370000000001, 0.0022267099999999998, -0.12652962000000001, 0.014043730000000001]


text:
Q: How to get rid of this error? SynchronousOnlyOperation: You can't call this from an asynchronous context - use a thread or sync_to_async I use asynchrony in django and I ran into the following problem:
It is possible to execute a aget() request for the AccountUser model, but the CabinetUser model is not.
When executing a aget() request for the CabinetUser model, I get an error:
SynchronousOnlyOperation: You cannot call this from an asynccontext - use a thread or sync_to_async.
My mоdels:
class AccountUser(AbstractUser):
    """Модель для пользователей"""
    username_validator = UnicodeUsernameValidator()
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4(),
        editable=False)
    username = models.CharField(
        gettext_lazy("username"),
        max_length=150,
        unique=True,
        help_text=gettext_lazy(
            "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
        ),
        validators=[username_validator, validate_phone_number],
        error_messages={
            "unique": gettext_lazy("A user with that username already exists."),
        },
    )
    class Meta:
        db_table = 'account_user'
        verbose_name = 'Пользователь'
        verbose_name_plural = 'Пользователи'

    def __str__(self):
        return f'Пользователь -> {self.username}'

class CabinetUser(models.Model):
    """ Модель кабинета пользователя"""
    WORK_STATUS_WORKING = 'working'
    WORK_STATUS_FIRED = 'fired'
    WORK_STATUS_VACATION = 'vacation'
    WORK_STATUS_CHOICES = (
        (WORK_STATUS_WORKING, 'Работает'),
        (WORK_STATUS_FIRED, 'Уволен'),
        (WORK_STATUS_VACATION, 'В отпуске')
    )
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4(),
        editable=False)
    is_payment = models.BooleanField(
        default=True,
        verbose_name='Выплаты включены'
        )
    work_rules = models.ForeignKey(
        to=WorkRules,
        verbose_name='Условия работы',
        on_delete=models.CASCADE,
        related_name='cabinet_user',
        )
    role = models.CharField(
        max_length=20,
        choices=[
            ('Director', 'Директор'),
            ('Operator', 'Оператор'),
            ('Driver', 'Водитель'),
            ('Courier', 'Курьер'),
                ],
        verbose_name='Должность',)

    # Для миграций
    cabinet_park = models.ForeignKey(
        to='partner.CabinetPark',
        related_name='cabinet_user',
        verbose_name='Кабинет парка',
        on_delete=models.CASCADE,
        blank=True,
        null=True
    )

    group_commission = models.ForeignKey(
        to='partner.GroupCommission',
        on_delete=models.CASCADE,
        verbose_name='Группа коммиссий',
        blank=True,
        null=True
        )

    phone = models.ManyToManyField(
        to=PhoneNumber,
        verbose_name='Номер телефона',
        help_text='Номер телефона в международном формате (+7 ...)',
        related_name='cabinet_user',)
    profile_user = models.ForeignKey(
        to='ProfileUser',
        on_delete=models.CASCADE,
        related_name='cabinet_user',
        verbose_name='Профиль пользователя'
    )
    work_status = models.CharField(
        choices=WORK_STATUS_CHOICES,
        max_length=9,
        default=WORK_STATUS_WORKING,
        verbose_name='Рабочий статус')
    current_status = models.BooleanField(
        default=False,
        verbose_name='Статус',
        help_text='Статус "на Сайте" Online / Offline')
    balance = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
        verbose_name='Баланс')
    is_new_user = models.BooleanField(
        verbose_name='Новый пользователь',
        blank=True,
        null=True,
        default=True,
        )

    class Meta:
        db_table = 'cabinet_user'
        verbose_name = 'Кабинет пользователя'
        verbose_name_plural = 'Кабинеты пользователей'

    def __str__(self):
        return f'Кабинет пользователя -> {self.profile_user.account_user.username}'

It is necessary to get cabinets, for this I use the method:
class DBPayout:

    async def get_cabinet_user(self, cabinet_id):
        try:
            cabinet = await CabinetUser.objects.aget(id=cabinet_id)
            return cabinet
        except CabinetUser.DoesNotExist as err:
            print(err)
        except SynchronousOnlyOperation as err:
            print(err)
        except Exception as err:
            print(err)

I get an error: SynchronousOnlyOperation: You can't call this from an asynchronous context - use a thread or sync_to_async.
I tried to execute a request from the AccountUser model:
class DBPayout:

    async def get_cabinet_user(self, cabinet_id):
        try:
            cabinet = await AccountUser.objects.aget(id=cabinet_id)
            return cabinet
        except AccountUser.DoesNotExist as err:
            print(err)
        except SynchronousOnlyOperation as err:
            print(err)
        except Exception as err:
            print(err)

Here the request is processed and gives a response: AccountUser matching query does not exist.
This is correct, since there is no such entry there. I don't understand why when accessing the CabinetUser model, it writes an asynchronous error.
In settings.py ASGI_APPLICATION is installed.


text:
Q: Maintain cell reference when substituting new sheet I am performing a portfolio calculation based upon a daily spreadsheet which contains values in the same cell locations.
I would like to be able to substitute daily a new sheet via the copy function, yet maintain the cell reference.
EG, I have a 'control' sheet which references cells D4, E4 and F4 in sheet B.  Every day a new Sheet B is published with the relevant values in the same cells.  Is there a way I can maintain the references in the Control sheet when inserting this new sheet daily?

A: Depending on how the new sheets are named, you can probably use the INDIRECT() function.
If the newly-published sheet will be the same name every time, then to refer to B3 on that sheet use:
=INDIRECT("SheetName!B3", TRUE)

If the name changes predictably, in this example if each day's sheet is named after that day's date, use a formula within the INDIRECT function to adapt the sheet name as required, like so:
=INDIRECT(TEXT(TODAY(), "dd.mm.yy") & "!B3")

(where TEXT(TODAY(), "dd.mm.yy") is the sheet name)


text:
Q: How do you spell Vitral - meaning saying bad inaccurate things I believe? I'm trying to find the word, which I believe is something like "Vitral", like when someone is saying bad and/or inaccurate things, such as:

This guy has been spewing a bunch of inaccurate vitral

Am I thinking of the right term here? If so, how do you spell it - not having any luck finding it in Google.

A: The correct spelling would be vitriol.
https://www.dictionary.com/browse/vitriol


text:
Q: How to compare a variable against two values at the same time? I need to improve this statement by either correcting it or making it shorter
if (0 <= age <= 100) // age is between 0 and 100)

I am totally confused about spending 20 minutes on the question. It seems really simple but the only revision I could think of is
if (0 <= age && age <= 100)

and that doesn't seem right. Am I just missing something obvious? Can someone help me please?
Thanks

A: Your revision is correct. if (0 <= age && age <= 100) is the correct way to do it. There really isn't a simpler way.


text:
Q: finding plus "+" character with number like +90 90+ in string I tried so many preg_replace and preg_match codes but i cant do.
I try to find strings contain +18 , 18+ or (+18)
I cant explain but you can understand when see my codes.
//inputs
$product='example: 18 kg apple'; // my hope output: EVERYONE
$product='water pipe (18) meters'; // my hope output: EVERYONE
//outputs: OVER 18

$product='product +18 dress';   // my hope output: OVER 18
$product='product 18+ dress';   // my hope output: OVER 18
$product='product (+18) dress';     // my hope output: OVER 18
//outputs are already OVER 18
//Because of contain 18
//not +18 or 18+. it doesnt work truly

    preg_match('/\b(\w*18\w*)\b/', $product, $match);

        if( $match[1]=='+18' || $match[1]=='18+' ) {

                echo "OVER 18
";
    }
       else{
               echo "EVERYONE
";

                }

A: Use this: (\+18|18\+)- it checks if +18 or 18+ exists in the string.
So something like this:
preg_match('(\+18|18\+)', $product, $match); should work.
Only tested it here https://regex101.com/ (a very good place to test regexp

A: In this simple case, I wouldn't use an regex. Just using strpos would also do the job.
if (strpos($product, '18+') !== false || strpos($product, '+18') !== false) {
    // over 18
}


text:
Q: android/webkit text-overflow: ellipsis not working i am trying to get the following code to work on an androind 2.1 phone (HTC Sense UI):
h1 {
    font-size: 14px;
    font-weight: bold;
    color: #FFF;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

however, the text-overflow property does not seem to work. has anybody else had this problem, or found a way to work around it?

A: on Android 2.2 and 4, I use a line height greater than the font size (always em) with a display type "-webkit-box" and a vertical orientation.
Here is an example:
.myClass{
display     : -webkit-box;
-webkit-box-orient  : vertical;
text-overflow   : ellipsis;
-webkit-line-clamp  : 3;
overflow        : hidden;
font-size       : 0.9em;
line-height     : 1.2em;
}

A: I see you have no width defined. If the element is allowed to get arbitrarily wide there is never going to be any overflow >within> the element. The element overflowing its parent wil not give you the desired effect.

A: It seems that the 'ellipsis' is not working when your 'display' is set to '-webkit-box', reset to 'block' will do.
This may help: https://bugzilla.mozilla.org/show_bug.cgi?id=672944#c0


text:
Q: Sorting Emails by Received time before processing C# Outlook I need to sort my emails by Received time before processing them as I am processing emails and entering data from it into a database.
I need it so the newest email to be received gets put into the database to overwrite the older version (If there is an older version).
Microsoft.Office.Interop.Outlook.Items item = (Outlook.Items)source.Items;
Source is the folder with the emails in it that I wanted sorted
I have tried these four ways:
            items.Sort("ReceivedTime", false);
            items.Sort("[ReceivedTime]", Outlook.OlSortOrder.olAscending);
            items.Sort("ReceivedTime", Outlook.OlSortOrder.olSortNone);
            items.Sort("[ReceivedTime]");

Which does not seem to sort it as It still puts the oldest into the database second, overwriting the newest submission.
Any Ideas?

A: it should be
items.Sort("[ReceivedTime]", false);

or true if you want them descending

A: I spent so much time trying to figure out the same problem.
It appears there is some sort of bug in Microsoft Interop.outlook that if you directly try to sort from folder it does not work at all.

Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
  Microsoft.Office.Interop.Outlook._NameSpace ns = app.GetNamespace("MAPI");
        Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
  inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

        inboxFolder.Items.Sort("[ReceivedTime]", false);
        foreach (var item in inboxFolder.Items)
        {
            // ITEMS ARE NOT SORTED
        }

To make it work you must copy them in different list and then sort. The example below will work.

 Outlook.Application app = new Outlook.Application();
 Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");
 Outlook.MAPIFolder emailFolder =        outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

 Outlook.Items myItems = emailFolder.Items;

 myItems.Sort("[ReceivedTime]", false);

  foreach (var item in myItems)
  {
       var itemObj = item as MailItem;
       if (itemObj != null)
       {
                   // This time it will work
       }
  }

A: Now I don't know what class your item-Object is, but maybe the "Sort"-Method does not have return type "void", but it returns a new list itself.
So you should assign your list like so:
items = items.Sort();

You could then try, which of your four approaches fits your needs.
I hope this helps!

A: Sub SortByDueDate()
 Dim myNameSpace As Outlook.NameSpace
 Dim myFolder As Outlook.Folder
 Dim myItem As Outlook.TaskItem
 Dim myItems As Outlook.Items

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myFolder = myNameSpace.GetDefaultFolder(olFolderTasks)
 Set myItems = myFolder.Items
 myItems.Sort "[DueDate]", False
 For Each myItem In myItems
 MsgBox myItem.Subject &; "-- " &; myItem.DueDate
 Next myItem
End Sub

This code is come from MSDN. I am confused as to why at beginning it sets myItmes=myFolder.Items. After trying many times, I know this is a trap. If you use myFolder.Items.sort... directly, the sort function does not work.


text:
Q: Creating a Python local server in Windows I'm trying to use this commmand:
python -m SimpleHTTPServer

but it's not working. I'm guessing that it isn't working because I'm running that through Windows Command Prompt. How does one make that function?
The error I am getting from Command Prompt is:
"'python' is not recognized as an internal or external command, operable program or batch file"

A: By default, python is not registered as a command in the windows command prompt. (Be it a file in the PATH, a macro or something else entirely).
The solution is to simply type the whole path to the python.exe. I installed Python to C:\Python27 so all I need to type is
C:\Python27\python.exe /m SimpleHTTPServer

A: Based on the error you provided, it looks like you didn't add Python to your path environment variable.

A: If you recently installed Python 3.x, try searching for "Python" in windows file explorer.  Mine was installed under:
C:\Users\XXXX\AppData\Local\Programs\Python\Python36-32\
Use Command prompt to navigate to this directory, and then type "Python.exe - m http.server"
You should be good to go.


text: Q: Why does my VSCode randmonly have white frost looking lines around icons in explorer? Randomly when I am working, VSCode will have white lines that look like frost around my icons. It goes away when I click on something, but it is very odd and distracting. I have attached a picture showing what is happening. What is this from, and how can I get rid of it?


text:
Q: Chart.js doughnut text visibility Chart.js doughnut text visibility. Tell me how to make it so that when the values intersect, the text comes out and changes its position.
const myChart = new Chart(canvas,
        {
            type: 'doughnut',
            data: {
                labels: dataNameDB,
                datasets: [{
                    data: dataCountDB,
                    backgroundColor: backgroundColor,
                    borderWidth: 0,
                }],
            },
            plugins: [ChartDataLabels, DoughnutLabel],
            options: {
                cutout: 340,
                responsive: true,
                animation: false,

                plugins: {
                    legend: {
                        display: false,
                    },
                    datalabels: {
                        formatter: (val, ctx) => {
                            return Math.round((ctx.chart.data.datasets[0].data[ctx.dataIndex] * 100) / summChart()) + "%";
                        },
                        display: (val,ctx) =>{
                            return 'auto';
                        },
                        clamp: true,
                        clip: true,
                        anchor: 'center',
                        align: 'center',
                        offset: 1,
                        font: {
                            size: 65,
                            weight: 'bold',
                            color: '000000'
                        },
                        color: '000000',
                        labels: {
                            value: {
                                color: '#000000'
                            }
                        }
                    },
                    doughnutlabel: {
                        labels: [{
                            text: summChart,
                            font: {
                                size: 140,
                                weight: 'bold',
                                color: '000000'
                            }
                        }]
                    }
                }
            }
        },
    );

Now it outputs something like this, but I need it to be like this:

Although the documentation says that display 'auto' is responsible for this, how to catch it when the text is hidden in order to move it?


text:
Q: Read Hadoop SequenceFile: weird hex number stream I am trying to convert a piece of Hadoop SequenceFile into plain text with the following code:
    Configuration config = new Configuration();
    Path path = new Path( inputPath );
    SequenceFile.Reader reader = new SequenceFile.Reader(FileSystem.get(config), path, config);
    WritableComparable key = (WritableComparable) reader.getKeyClass().newInstance();
    Writable value = (Writable) reader.getValueClass().newInstance();

    File output = new File(outputPath);
    if(!output.exists()) output.createNewFile();

    FileOutputStream fos = new FileOutputStream(output);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));

    int count = 0;

    try {
        while(reader.next(key,value) && count < 1000)
        {
            bw.write("Key::: " + key);
            bw.newLine();
            bw.write("Value::: " + value);
            bw.newLine();
            bw.newLine();
            count++;
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    reader.close();
    bw.close();

The keys can be properly converted. However, the values are converted into weired HEX number stream. A sample is:
Value::: 1f 8b 08 00 00 00 00 00 00 03 e5 bd f9 7b 13 47 d6 28 fc 73 e6 79 e6 7f e8 28 17 6c 5f bc 68 5f 6c e4 5c 96 64 26 33 c9 24 37 cb bc ef 3b 0c 9f 9f 56 77 cb ee 58 96 34 5a 20 8e e3 3f 46 56 c2 10 30 c4 8b e4 4d 5e b1 6c 4b f2 22 59 b2 65 63 48 08 04 42 12 c2 9e 00 21 cb f3 9d 53 d5 2d b5 64 4b 16 33

The real stream is much longer than this. What I know is that the keys are stored as Hadoop Text format and the values are stored as Hadoop BytesWritable. And the values might be in Chinese, but I am not sure about this.
Does anybody know what is going on?

A: You say the values are stored as BytesWritable. That maps to byte[] in Java, a byte array -- and that is exactly what's being printed, since the toString() method is overloaded to do that.
You also mention that the bytes might be text in Chinese. If you want to output that, you'll need to encode the bytes to String. You should change the line
bw.write("Value::: " + value);

to a couple of others.
byte[] strBytes = ((BytesWritable) value).getBytes();
bw.write("Value::: " + new String(strBytes, Charset.forName("UTF-8")));

This assumes the Chinese string is encoded using "UTF-8", which might now be the case. You'll have to try different encodings and see what works if you don't know the exact one.


text:
Q: Are there some pitfalls in my spark structured streaming code which causes slow response after several hours running? The spark job has the correct functions and logic. However, after several hours running, it becomes slower and slower. Are there some pitfalls in the below code?
val query = "(select * from meta_table) as meta_data"
val meta_schema = new StructType()
       .add("config_id", BooleanType)
       .add("threshold", LongType)
var meta_df = spark.read.jdbc(url, query, connectionProperties)
var meta_df_explode=meta_df.select(col("id"), from_json(col("config"), meta_schema).as("config")).select("config_id", "thresold", "config.*")

//rules_imsi_df: joining of kafka ingestion with the meta_df_explode

//rules_monitoring_df: static dataframe for monitoring purpose

val rules_monitoring_stream =
            rules_imsi_df.writeStream
                        .outputMode("append")
                          .format("memory")
                        .trigger(Trigger.ProcessingTime("120  seconds"))
                         .foreachBatch {
                              (batchDF: DataFrame, batchId: Long) =>
                                    if(!batchDF.isEmpty)                                                     {

printf("At %d, the microbatch has %d records \n", Instant.now.getEpochSecond, batchDF.count())
batchDF.show()
 batchDF.persist()                                                                var batchDF_group = batchDF.groupBy("id").sum("volume").withColumnRenamed("sum(volume)", "total_volume_id")
rules_monitoring_df = rules_monitoring_df.join(batchDF_group, rules_monitoring_df("id") === batchDF_group("id"), "left").select(rules_monitoring_df("id"), batchDF_group("total_volume_id")).na.fill(0)
rules_monitoring_df = rules_monitoring_df.withColumn("volume", rules_monitoring_df("volume")+rules_monitoring_df("total_volume_id"))                                                               batchDF.unpersist()                                                                          }                                          }.start()

      while(rules_monitoring_stream.isActive)    {
Thread.sleep(240000)
... //Periodically load meta data from database
meta_df = spark.read.jdbc(url, query, connectionProperties)
meta_df_explode=meta_df.select(col("id"), from_json(col("config"), meta_schema).as("config")).select("config_id", "thresold", "config.*")
}

A: Below points are my observation from the above code. I will add incase if I find anything.

*

*Remove format("memory") as its for debugging purpose not for production use case.

*Remove all var from the code.

*Don't assign DataFrame back to rules_monitoring_df inside foreachBatch as this foreachBatch will be invoked by multiple threads at the same time, You might get wrong results. Instead try to save result into hdfs or hive table & read back whenever you need.

*Try to move below code to spark streaming listener if possible & avoid extra while loop.

while(rules_monitoring_stream.isActive)    {
Thread.sleep(240000)
... //Periodically load meta data from database
meta_df = spark.read.jdbc(url, query, connectionProperties)
meta_df_explode=meta_df.select(col("id"), from_json(col("config"), meta_schema).as("config")).select("config_id", "thresold", "config.*")
}


text:
Q: Backup SQL 2008 DB to restore on SQL 2000 .NET We have cutomers interested in sending their Sql 2008 data to other customers with SQL 2000. Now obviously this does not currently work, so I'm attempting to create a "generic" backup process that allows us to backup and restore our data on Server 2000 and up (since SQL2000 is the least common denominator of all or customers). Right now we are generating our backups this way (C#):
 Server server = new Server( GetServerConnection( serverName, userName, password ) );
 Backup backup = new Backup();
 backup.Action = BackupActionType.Database;
 backup.Database = GetDatabasePrefix() + databaseName;
 backup.Devices.AddDevice( fileName, DeviceType.File );
 backup.Initialize = true;

 backup.SqlBackup( server );

My first question is, is there any way to "force" the backup to be run as SQL 2000, even if the database is SQL 2005 or 2008?
Also, we were thinking of avoiding this by using the bcp procedure on the database to package up and unpackage the tables and zip them together. In the zip process I'd put a header flag in to declare it a "generic" backup. Does this seem reasonable, or is there a simpler way of doing this? Since the application is the same regardless of server, all of the columns and tables should be the same. Thanks for the help!

A: If you are porting data only, BCP or a custom SSIS package sounds like your most likely options that will be reusable.  You may want to peek at the SSIS import/export wizard, it is pretty simple to use and may accomplish what you want.

A: It's not possible to restore a backup from a newer version of SQL Server to an older version.
You can generate SSMS 2000 SQL scripts from SSMS 2008:

*

*Open Tools -> Options in SSMS 2008

*Go to SQL Server Object Explorer -> Scripting

*Set "Script for server version" to 2000

*Right click your database, choose Tasks -> Generate Scripts

*Script all objects in your database

*Execute the script on your 2000 server

Then link the servers together, and copy the data like:
insert ChefDb.dbo.MyTable from ChefServer.ChefDb.dbo.MyTable

Alternatively, consider purchasing RedGate SQL Data Compare.


text:
Q: Melhor maneira de modelar o banco de dados de um chat Tenho uma aplicação que trabalho com webServices e o banco mysql, estou colocando um chat nela, a parte de como pegar mensagens, exibir notificações e procurar usuários que já tenho, minha dúvida é:
Como eu devo armazenar as mensagens no banco?
Pensei em algumas formas, mas não acho interessante.
A primeira foi, criaria uma tabela mensagens no meu banco e nela teria remetente, destinatário e a mensagem, mas não acredito ser interessante, pois as mensagens podem ocupar muito espaço no meu banco.
A segunda foi, não usaria meu banco externo, e sim o SQLite, nele eu salvaria o histórico das conversas, assim cada usuário teria apenas suas mensagens em seu banco. Mas isso não posso fazer, pois se meu usuário logar na sua conta em outro aparelho, as mensagens não estariam lá.

A: Uma outra solução seria você utilizar o Dropbox. Se caso o usuário desejasse ter histórico de mensagem o mesmo poderia efetuar o login através do Dropbox e daí, você teria acesso a salvar arquivos na conta dele através da API do Dropbox. Sendo assim, você não ocuparia espaço na sua base de dados :D


text:
Q: Are there any type of representation on filesystem for network ports? Say I wish to feed some data into a certain network port created on my system and do that manually.  Is there any interface for it on filesystem?
Maybe a special type of file that I could write into? If not how does it all work?
(I am asking this question despite the risk of sounding ridiculous and not making sense at all. I'd gladly accept link to some good article on the topic.)

A: In short
You cannot do what you describe in a way such as using cat to write to a file and have it send out over the network. However there are tools that can do this. I'd recommend looking into either netcat or socat (socat is more flexible, but slightly more confusing). Either will likely be in your distributions repos.
Explanation
In Linux, IP sockets exist in userspace and do not have a file in the filesystem per se.
To demonstrate this I ran $ lsof -i :15115 (port 15115 is associated with Skype):
COMMAND  PID     USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
skype   3836 eightbit   43u  IPv4 9020794      0t0  TCP *:15115 (LISTEN)
skype   3836 eightbit   44u  IPv4 9020795      0t0  UDP *:15115

So process 3836 has a file descriptor numbered 43 for the TCP socket 15115 (the 'u' just means the file is open with r+w permissions).
So if I do $ ls -l /proc/3836/fd/43 && file /proc/3836/fd/43 I get:
lrwx------ 1 eightbit eightbit 64 Sep 26 00:37 /proc/3836/fd/43 -> socket:[9020794]
/proc/3836/fd/43: broken symbolic link to socket:[9020794]

As you can see the socket is not really a file.


text:
Q: Android: switch layouts or activities? I can implement both variants - it's easy. But I'm interested: what approach is better?
I mean if my application contains several screens I can make them as several layouts (XML-files) and switch using setContentView(). Or they can be several classes like MyActivity1, MyActivity2 etc., and I will switch them using Intent class.
So I'm curious: what's the best practice?

A: Remember this as the Rule of Thumb:
It's better to have similar behaviors, under single Activity, but always prefer different Activities when behaviors differ.

A: If you are using several different screens, I would argue that fragments/activities would be a better solution.  Not only did Android include this to help people with multiple activities, but it also makes your code much cleaner.  Mitra sums it up quite well.

A: I think before Fragments using setContentView() was a handy way to move between sibling "screens" when you did not want the Back button to change the screen.  On the other hand, Activities launched via Intents will be poped off the stack with the Back button.

To be clear, note that within Activity B, you can use setContentView to change layouts, and the Back button takes you back to Activuty A.
ActivityA

  |
  |
  |
  V

ActivityB,Layout1  <---> ActivityB,Layout2  <---> ActivityB,Layout3


text:
Q: Apps targeting Android 12 and higher are required to specify an explicit value for 'android:exported' `
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.core_project"
    xmlns:tools="http://schemas.android.com/tools"
    >
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:name=".Application"
        android:label="My App"
        android:icon="@mipmap/ic_launcher"
        android:usesCleartextTraffic="true"
        tools:replace="allowBackup"
        android:allowBackup="false"
        android:requestLegacyExternalStorage="true">

        <meta-data
            android:name="io.flutter.embedding.android.SplashScreenDrawable"
            android:resource="@drawable/launch_background"/>
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_default_tray" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorIconNotificationTray" />

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <provider
            android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
            android:authorities="${applicationId}.flutter_downloader.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

        <!-- Begin FlutterDownloader customization -->
        <!-- disable default Initializer -->
        <provider
            android:name="androidx.startup.InitializationProvider"
            android:authorities="${applicationId}.androidx-startup"
            android:exported="false"
            tools:node="merge">
            <meta-data
                android:name="androidx.work.WorkManagerInitializer"
                android:value="androidx.startup"
                tools:node="remove" />
        </provider>

        <!-- declare customized Initializer -->
        <provider
            android:name="vn.hunghd.flutterdownloader.FlutterDownloaderInitializer"
            android:authorities="${applicationId}.flutter-downloader-init"
            android:exported="false">
            <meta-data
                android:name="vn.hunghd.flutterdownloader.MAX_CONCURRENT_TASKS"
                android:value="5" />
        </provider>

        <activity
            android:screenOrientation="portrait"
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize"
            android:exported="true"
            >

            <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="channel id"/>
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
             <meta-data
            android:name="com.google.firebase.ml.vision.DEPENDENCIES"
            android:value="barcode" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

              <!-- Branch URI Scheme -->
            <intent-filter>
                <data android:scheme="mydestiny" android:host="open" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>

            <!-- Branch App Links -->
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="https" android:host="mydestiny.app.link" />
                <!-- example-alternate domain is required for App Links when the Journeys/Web SDK and Deepviews are used inside your website.  -->
                <data android:scheme="https" android:host="mydestiny-alternate.app.link" />
            </intent-filter>
        </activity>
         <!-- Branch init -->
        <meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_XXXXXXXXXXXXXXXXXXXXXXXXXX" />
        <meta-data android:name="io.branch.sdk.BranchKey.test" android:value="secret_live_XXXXXXXXXXXXXXXXXXXXXXXXXX" />
        <meta-data android:name="io.branch.sdk.TestMode" android:value="false" />
    </application>
</manifest>

`
My build.gradle(:app) file:
`
 defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.core_project"
        minSdkVersion 23
        targetSdkVersion 31
        versionCode 1
        versionName "1.0."
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

`
The errors shown
`
Execution failed for task ':app:processDebugMainManifest'.

Manifest merger failed : Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

`
Any idea how I could resolve this issue?
Any idea how I could resolve this issue?
I am already add android:exported="true"

A: In your AndroidManifest.xml the first shared file add android:exported="true" in your activity under application
such as follow:
<activity
    android:name=".MainActivity"
    android:exported="true"


text:
Q: Как разделить переменную на переменную с таким же типом? Почему я не могу разделить переменные друг друга с одним и тем же типом? У них разные значения но один и тот же тип. Я работал с библиотекой tkinter и не нашёл подходящего для переменной другого типа. Я когда запускаю код у меня появляется ошибка "TypeError: unsupported operand type(s) for /: 'IntVar' and 'IntVar'" Помогите чем можете вот если что код:
    Label(root1, textvariable = "Вы должны переплавить" + value1 / value2 + "булыжника")

value1 = IntVar(root1)
value2 = IntVar(root1)

A: IntVar возвращает тебе object, а не int значение.
Для получения значения нужно использовать value1.get().
Также, по-моему, ты не сможешь суммировать int и str, поэтому нужно привести типы. Итоговое выражение для параметра будет выглядеть примерно так:
textvariable = "Вы должны переплавить" + str(value1.get() / value2.get()) + "булыжника"


text: Q: Show major tick on google meter gauge chart with amount as $1k , $2.5 M I am creating visualforce page which contains a google meter gauge chart as shown above. I am showing trying to show amount in gauge but as you know representation of amount in 1K , 1M ,1B will give it more specific information rather then displaying about 10 digit number. Has any body inserted a google chart in visual force page with an amount. If yes pls give an guidance so that it will be an easy solution for me.


text:
Q: "Extra argument in call" Spacer() I am very new to swiftui, and am making a simple game for learning reasons. I have no idea why this error would show because I did basically the same thing a couple of lines up. If you want to check the code yourself just use some random images. I cant post this post because it has to much code. it is telling me that I have to add more text so that is what I am doing right now, you do not have to read this.
import SwiftUI
struct ContentView: View {
    var body: some View {
        ZStack{
            Image("background")
                .ignoresSafeArea()
            VStack{
                Spacer()
                Image("logo")
                Spacer()
                HStack {
                    Spacer()
                    Image("card3")
                    Spacer()
                    Image("card4")
                    Spacer()
                        }
                Spacer()
                Image("dealbutton")
                Spacer()
                HStack{
                    Spacer()
                    Text("Player")
                    Spacer()
                    Text("CPU")
                    Spacer()
                }
                .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
                .foregroundColor(.white)
                Spacer()
                HStack{
                    Spacer()
                    Text("0")
                    Spacer()
                    Text("0")
                    Spacer()
                }
                Spacer() //here is the error
            }
    }
    }
    }
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: Note Spacer() is a view, and so you are exceeding the number of views (10) allowed inside another view. Try some variations of this, or use Group {...}:
struct ContentView: View {

    var cardView: some View {
        Group {
            Spacer()
            HStack {
                Spacer()
                Image("card3")
                Spacer()
                Image("card4")
                Spacer()
            }
            Spacer()
        }
    }

    var textview: some View {
        Group {
            Spacer()
            HStack{
                Spacer()
                Text("0")
                Spacer()
                Text("0")
                Spacer()
            }
            Spacer()
        }
    }

    var devView: some View {
        Group {
            Spacer()
            HStack{
                Spacer()
                Text("Player")
                Spacer()
                Text("CPU")
                Spacer()
            }
            Spacer()
        }
    }

    var body: some View {
        ZStack{
            Image("background")
                .ignoresSafeArea()
            VStack{
                Spacer()
                Image("logo")
                Spacer()
                cardView
                Image("dealbutton")
                devView
                    .font(.title)
                    .foregroundColor(.white)
                textview
                Spacer()
            }
        }
    }
}


text:
Q: How to add multilevel expandable menu in drawer I was trying to find a way to add sub-menus to this drawer and to collapse them on tap.
Ie: I want to call this widget with a title and 3 subtitles like :

*

*Flutter

*

*List item

*List item

*List item

Any help would be appreciated.
Thank you.
    class DrawerListTile extends StatelessWidget {
  const DrawerListTile({
    Key key, @required this.title,@required this.svgSrc,@required this.press,
  }) : super(key: key);

  final String title,svgSrc;
  final VoidCallback press;
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap:press,
      horizontalTitleGap: 0.0,
      leading: SvgPicture.asset(
        svgSrc,
        color: Colors.black,
        height:16,
      ),
      title:Text(
        title,
        style: TextStyle(color: Colors.black),
      ),
      trailing: Icon(Icons.arrow_drop_down,size:15),
    );
  }
}

A: I think the ExpansionTile widget is what you're looking for.
This would provide a tile that hides/shows the child tiles when it's tapped. You can also specify a custom trailing icon with the trailing parameter. Below is a quick example pulled from the docs.
Widget build(BuildContext context) {
    return ExpansionTile(
        title: Text('ExpansionTile'),
        subtitle: Text('Expanding tile subtitle'),
        children: <Widget>[
          ListTile(title: Text('This is tile number 1')),
          ListTile(title: Text('This is tile number 2')),
          ListTile(title: Text('This is tile number 3')),
          ListTile(title: Text('This is tile number 4')),
        ],
    );
}


text:
Q: Using jQuery to able/disable RequiredFieldValidators I'm trying to disable some RequiredFieldValudators on this way:
var emailEmpty = $("#registerContent").find("[id$=email_blank]");
company.click(function () {
    ValidatorEnable(emailEmpty, false);
});

I've read a lot about how to able/disable validators and it seems as simple as type  ValidatorEnable(yourValidator, false) but that isn't working for me, because the ErrorMessage still fire. Where is my mistake?? Ty.

A: Try this instead:
var $id= $('[id$=email_blank]');

var emailEmpty = $("#registerContent").find($id);
company.click(function () {
    ValidatorEnable(emailEmpty, false);
});


text:
Q: Meteor : Iron-Router error request entity too large I'm trying to send data from a node js server to a meteor app. In the node js app I'm doing this :
axios.put('http://localhost:3000/api/project/'+id,{"data" :data, "idExtractor":idExtractor, "version":getVersion()})

where data is a string of the XML given by our server
And in my meteor app I'm receiving this on a server route in lib/Router.js file, but when the data is too large, the meteor server gives me the errors "socket hang up" and "request entity too large".
I tried solutions from the issues of Iron Router on github, doing the following code in the Router.js file.
if (Meteor.isServer) {
  Router.onBeforeAction(Iron.Router.bodyParser.raw({
    type: '/',
    only: ['creditReferral'],
    verify: function(req, res, body){
      req.rawBody = body.toString();
    },
    where: 'server'
  }));
  Router.onBeforeAction(Iron.Router.bodyParser.urlencoded({
    extended: true,
    limit : '10mb'
  }));
  Router.onBeforeAction(Iron.Router.bodyParser.urlencoded({
    extended: true,
    limit : '10mb'
  }),
  { where: 'server'});
}

I tried to put it before all routes definitions, before server routes, after all routes, I also tried to put it in server/main.js in the startup block.
I also tried to change these limits in the node server with this
express.urlencoded({
  limit: '10mb',
  extended: true,
  type: "application/x-www-form-urlencoded"
})
express.json({
  limit: '10mb',
  strict: false,
  type: "application/json"
})

and this
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit :'10mb' }));

But I always have the same problem, all help would be greatly appreciated.

A: After trying many solutions, I fixed this problem with this in my Router.js :
if (Meteor.isServer) {
    Router.onBeforeAction( Iron.Router.bodyParser.json({
        limit: '50mb'
    }), {
        except: ['creditReferral'],
        where: 'server'
    });
    Router.onBeforeAction( Iron.Router.bodyParser.raw({
        type: '*/*',
        only: ['creditReferral'],
        verify: function(req, res, body){
            req.rawBody = body.toString();
        },
        where: 'server'}));
}

This fixed the entity too large error, but because the data is xml in this request, I couldn't directly parse it to json, so I needed to change my
var json = JSON.parse(this.request.body)

to the following :
var stringify = JSON.stringify(this.request.body);
var json = JSON.parse(stringify);

and it worked. Hope this could help someone having the same issue.


text:
Q: Return All Months & Years Between Date Range - SQL I'm a bit stumped how I might go about this.
I have a very basic query, that currently returns sales for each product, by year and month.
It is grouping by year/month, and summing up the quantity.
This returns one row for each product/year/month combo where there was a sale.
If there was no sale for a month, then there is no data.
I'd like my query to return one row of data for each product for each year/month in my date range, regardless of whether there was actually an order.
If there was no order, then I can return 0 for that product/year/month.
Below is my example query.
Declare @DateFrom datetime, @DateTo Datetime
Set @DateFrom = '2012-01-01'
set @DateTo = '2013-12-31'

select
Convert(CHAR(4),order_header.oh_datetime,120) + '/' + Convert(CHAR(2),order_header.oh_datetime,110) As YearMonth,
variant_detail.vad_variant_code,
sum(order_line_item.oli_qty_required) as 'TotalQty'

From
variant_Detail
join order_line_item on order_line_item.oli_vad_id = variant_detail.vad_id
join order_header on order_header.oh_id = order_line_item.oli_oh_id

Where
(order_header.oh_datetime between @DateFrom and @DateTo)

Group By
Convert(CHAR(4),order_header.oh_datetime,120) + '/' + Convert(CHAR(2),order_header.oh_datetime,110),
variant_detail.vad_variant_code

A: Thank your for your suggestions.
I managed to get this working using another method.
Declare @DateFrom datetime, @DateTo Datetime
Set @DateFrom = '2012-01-01'
set @DateTo = '2013-12-31'

select
YearMonthTbl.YearMonth,
orders.vad_variant_code,
orders.qty

From
(SELECT  Convert(CHAR(4),DATEADD(MONTH, x.number, @DateFrom),120) + '/' + Convert(CHAR(2),DATEADD(MONTH, x.number, @DateFrom),110) As YearMonth
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'
AND     x.number <= DATEDIFF(MONTH, @DateFrom, @DateTo)) YearMonthTbl

left join
    (select variant_Detail.vad_variant_code,
    sum(order_line_item.oli_qty_required) as 'Qty',
    Convert(CHAR(4),order_header.oh_datetime,120) + '/' + Convert(CHAR(2),order_header.oh_datetime,110) As 'YearMonth'
    FROM order_line_item
    join variant_detail on variant_detail.vad_id = order_line_item.oli_vad_id
    join order_header on order_header.oh_id = order_line_item.oli_oh_id
    Where
    (order_header.oh_datetime between @DateFrom and @DateTo)
    GROUP BY variant_Detail.vad_variant_code,
    Convert(CHAR(4),order_header.oh_datetime,120) + '/' + Convert(CHAR(2),order_header.oh_datetime,110)
    ) as Orders on Orders.YearMonth = YearMonthTbl.YearMonth

A: You can generate this by using CTE.
You will find information on this article :
http://blog.lysender.com/2010/11/sql-server-generating-date-range-with-cte/
Especially this piece of code :
WITH CTE AS
(
    SELECT @start_date AS cte_start_date
    UNION ALL
    SELECT DATEADD(MONTH, 1, cte_start_date)
    FROM CTE
    WHERE DATEADD(MONTH, 1, cte_start_date) <= @end_date
)
SELECT *
FROM CTE

A: This is what I put together. It will certainly need some debugging, but I think that this will lead you in the right direction. I broke up the queries into different parts in order to attempt to make it easier to read. Hope this helps.
DECLARE @dateFrom DATETIME, @dateTo DATETIME

SELECT @dateFrom = MIN(oh_datetime) FROM order_header
SELECT @dateTo = MAX(oh_datetime) FROM order_header

;WITH
y AS
(
    SELECT YEAR(@dateFrom) AS [Year]
    UNION ALL
    SELECT [Year] + 1
    FROM y
    WHERE
          [Year] < YEAR (GETDATE())
),
m AS
(
    SELECT 1 AS [Month]
    UNION ALL
    SELECT [Month] + 1
    FROM m
    WHERE
          [Month] < 12
),
dates AS
(
SELECT
    CAST(y.[Year] AS nvarchar(4)) + N'/' + RIGHT(N'00' + CAST(m.[Month] AS nvarchar(2)), 2) AS YearMonth
FROM
    y CROSS JOIN m
),
qty AS
(
SELECT
    YEAR(oh.oh_datetime) + N'/' + MONTH(oh.oh_datetime) AS YearMonth,
    v.vad_variant_code,
    oli.oli_qty_required AS Qty
FROM
    variant_Detail AS v
        INNER JOIN order_line_item AS oli ON oil.oli_vad_id = v.vad_id
        INNER JOIN order_header AS oh ON oh.oh_id = oli.oli_oh_id
)
SELECT
    d.YearMonth,
    qty.vad_variant_code,
    SUM(qty.Qty) AS TotalQty
FROM
    dates AS d LEFT OUTER JOIN qty
        ON d.YearMonth = qty.YearMonth
GROUP BY
    d.YearMonth,
    qty.vad_variant_code

A: Here is another twist, if you find all months of a year
;WITH DateYear AS (
    SELECT 0 AS num
    UNION ALL
    SELECT num + 1 FROM DateYear
    WHERE num < 11
)
Select FirstDateOfTheMonth, DATENAME(mm,FirstDateOfTheMonth), num from
(SELECT CONVERT(DATE,DATEADD(MONTH,num,'2017'))  AS FirstDateOfTheMonth, num from DateYear)
cte

and the result will be

Another twist:
Declare @dateFrom datetime ='2019-03-21', @dateTo datetime ='2019-12-31'
;WITH CTE AS
(
    SELECT @dateFrom AS cte_start_date
    UNION ALL
    SELECT DATEADD(MONTH, 1, cte_start_date)
        FROM CTE
        WHERE ( DATEADD(MONTH, 1, cte_start_date) <=  EOMONTH( @dateTo)   )
        --or ( DATENAME(MONTH, cte_start_date) =DATENAME(MONTH, @dateTo) and DATENAME(year, cte_start_date) =DATENAME(year, @dateTo) ) )
)
SELECT *
FROM CTE

This below is work for sqlserver 2012 and above to get the last day of the month :-
Select EOMONTH('2020-02-15')


text:
Q: Domains and shares(Share a DVD-ROM drive?) As a part of my college studies, I configured an AD DS for me to put around and enjoy while my review license lasts. My wife had recently purchased a laptop with out a DVD-ROM and with a puny 32 GB SSD. I decided to make available a tower to serve her both storage space and a disc drive. I get how to administer shares with those two resources, what I'm having troubles with is, is it possible to create and ad-hoc network between her laptop and the computer tower? I'm not sure if a computer on a domain has options other than running router and remote services to share outside of a domain.
Resources on the network:

*

*Linksys 54G AP (Wifi physical destroyed and used only as an unmanaged
switch)

*Tower: Windows Server 2008 R2 (gig port/100 MB port)

*Laptop: Windows 7 Ultimate (WiFi/Gig port:Server remote management tools)

*Tower: Windows 7 Ultimate *intended for the wife.(WNIC 802.11g:100 MB
port)

*Laptop: Windows 8.1 OEM (WiFi).

Can some one please refer me to a link that explains how to properly style a question. I hate leaving these things globbed up with no style and formatting.


text:
Q: Getting Audio Data From MP3 File using NAudio I want to be able to get audio data from an MP3 file with NAudio, average out the data in the left and right channels to create one dataset and then resample the averaged 44.1KHz audio data to 8Khz but I am having trouble understanding how data is represented in an NAudio Wavestream.
If I had 1 sec worth of MP3 audio, then how many bytes would I have in the WaveStream? By looking at a few code samples it seems one sample is 4 bytes and audio is sampled at 44100Hz and we have 2 different channels, so would that mean we would have (44100 * 4 * 2) bytes in the wavestream, is that right?
Which of the following 3 streams - AStream,PCM and inputStream - should I use to get audio data from? And how to I access left and right channel data separately?
var AStream = new MP3FileReader(myFilePath);
var PCM = new WaveConversionStream.Createpcm(AStream);
var inputStream = new WaveChannel32(new BlockAlignStream(PCM));

I have been thinking of converting the WaveStream using the WaveFormatConversionStream but the code below throws a NAudio.MmException with a message saying "AcmNotPossible calling Acmstreamopen".
 var targetFormat = new WaveFormat(8000,1);
 var resampled = new WaveFormatConversionStream(targetFormat, inputStream);

The above code doesn't even work if targetFormat is equal to inputStream's format, so I don't know what I am doing wrong here.
//Still throws NAudio.MmException
var resampled = new WaveFormatConversionStream(inputStream.WaveFormat, inputStream);

Other Info: VS2012, WPF, NAudio 1.6.

A: You seem to have copied a code sample that belongs to a much earlier version of NAudio. The Mp3FileReader class will emit 16 bit samples, and uses the ACM MP3 frame decompressor by default. If you'd prefer your samples directly in floating point, then you can make use of the AudioFileReader.
Resampling 44.1kHz straight down to 8kHz is not a particularly good idea, as you'd end up with a lot of aliasing, so a low pass filter would ideally be applied first. Left and right channels are stored interleaved, so you get a left sample, followed by a right sample, and so on.


text:
Q: If i use a separated ASP.NET Membership database how should i handle the relations to the user tables? If i use a separated ASP.NET Membership database what is the correct way to define the relations between the user tables and application data tables?. Should i create copies of the user tables and sync? or is ok to just create the Guid columns and enforce validation in the application code?, Are there any issues with performance that i should be aware of when separating databases?

A: You can Create two database , one for Membership control and other for Web-site use.
I have Many sites which are running on same concept. No need to worry. web-site will be fast and secure.
If you want to learn more on this or want a live demo then download a classified starter kit for asp.net

A: Just make the join on databases(with double dots) when you need data.
No need to change, just handle the userid, role etc but need to create two different connection string in your app.
OR Copy the tables in your original db


text:
Q: How can l set frames for 12 buttons with loop (programatically)? I'm trying to make Concentration game (with matching cards) and my task is to set frames for the array of 12 UIButtons with for-loop (I tried to realize it with switches, but it wan't right as my mentor said).
So maybe you can help me with this. The code added below works correctly, but l have to escape of switch and make it works with the help of for-loop and universal formulas.
  func setFrames() {
    for i in 0...11{
      var x = CGFloat()
      var y = CGFloat()
      switch i {
      case 0...2:
        y = 50
      case 3...5:
        y = (7/36 * view.bounds.height + 50);
      case 6...8:
        y = (7/18 * view.bounds.height + 50);
      default:
        y = (7/12 * view.bounds.height + 50);
      }
      switch i {
      case 0, 3, 6, 9:
        x = 1/18 * view.bounds.width; //20
      case 1, 4, 7, 10:
        x = 3/8 * view.bounds.width; //3/8
      default:
        x = 3/4 * view.bounds.width - 20;
      }
      buttonsArray[i].frame = CGRect(x: x, y: y, width: (1/4 * view.bounds.width), height: (1/6 * view.bounds.height))

    }
  }

A: You can use something like so:
func placeBtnsIn(frame: CGRect, padding: CGFloat) {

    let numCols = 3
    let numRows = 4

    let buttonWidth = (frame.width - CGFloat(numCols - 1) * padding) / CGFloat(numCols)
    let buttonHeight = (frame.height - CGFloat(numRows - 1) * padding) / CGFloat(numRows)

    var x: CGFloat
    var y: CGFloat

    for row in 0...(numRows - 1) {
        y = frame.origin.y + (buttonHeight + padding) * CGFloat(row)
        for col in 0...(numCols - 1) {
            x = frame.origin.x + (buttonWidth + padding) * CGFloat(col)
            let button = UIButton()
            button.frame = CGRect(x: x, y: y, width: buttonWidth, height: buttonHeight)
            self.addSubview(button)
        }
    }
}

Then in your code use it like so:

placeBtnsIn(frame: yourFrame, padding: 5)

Where yourFrame is a rectangle in which buttons should be drawn, and padding is the distance between button "cells"