Programs & Examples On #Autogeneratecolumn

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

Gridview get Checkbox.Checked value

For run all lines of GridView don't use for loop, use foreach loop like:

foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
    if (row.RowType == DataControlRowType.DataRow)
    {
         CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);

         if (chkRow.Checked)
         {
              //if checked do something
         }
    }
}

"Specified argument was out of the range of valid values"

It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");

How to refresh Gridview after pressed a button in asp.net

I was totally lost on why my Gridview.Databind() would not refresh.

My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:

gvServerConfiguration.Databind()
uppServerConfiguration.Update()

uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.

Hope this helps someone.

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

Twitter Bootstrap and ASP.NET GridView

You need to set useaccessibleheader attribute of the gridview to true and also then also specify a TableSection to be a header after calling the DataBind() method on you GridView object. So if your grid view is mygv

mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader

This should result in a proper formatted grid with thead and tbody tags

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);

  private void SumOFEPFWages(GridView grd)
    {
        Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
        /*Sum of the total Amount of the day*/
        foreach (GridViewRow gvr in grd.Rows)
        {
            Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
            lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
        }

    }

Notify ObservableCollection when Item changes

All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems in the NotifyCollectionChangedEventArgs object.

this is the perfect ObservableCollection .

public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
    #region Constructors
    public ObservableCollectionEX() : base()
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(IEnumerable<T> c) : base(c)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(List<T> l) : base(l)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }

    #endregion



    public new void Clear()
    {
        foreach (var item in this)            
            if (item is INotifyPropertyChanged i)                
                i.PropertyChanged -= Element_PropertyChanged;            
        base.Clear();
    }
    private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
            foreach (var item in e.OldItems)                
                if (item != null && item is INotifyPropertyChanged i)                    
                    i.PropertyChanged -= Element_PropertyChanged;


        if (e.NewItems != null)
            foreach (var item in e.NewItems)                
                if (item != null && item is INotifyPropertyChanged i)
                {
                    i.PropertyChanged -= Element_PropertyChanged;
                    i.PropertyChanged += Element_PropertyChanged;
                }
            }
    }
    private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);


    public ListedItemPropertyChangedEventHandler ItemPropertyChanged;

}

ASP.NET Setting width of DataBound column in GridView

add HeaderStyle in your bound field:

    <asp:BoundField HeaderText="UserId"
                DataField="UserId" 
                SortExpression="UserId">

                <HeaderStyle Width="200px" />

</asp:BoundField>

Date formatting in WPF datagrid

first select datagrid and then go to properties find Datagrid_AutoGeneratingColumn and the double click And then use this code

   Datagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
            {
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
            }

I try it it works on WPF

How to delete row in gridview using rowdeleting event?

Your delete code looks like this

Gridview1.DeleteRow(e.RowIndex);
Gridview1.DataBind();

When you call Gridview1.DataBind() you will populate your gridview with the current datasource. So, it will delete all the existent rows, and it will add all the rows from CustomersSqlDataSource.

What you need to do is delete the row from the table that CustomersSqlDataSource querying.

You can do this very easy by setting a delete command to CustomersSqlDataSource, add a delete parameter, and then execute the delete command.

CustomersSqlDataSource.DeleteCommand = "DELETE FROM Customer Where CustomerID=@CustomerID"; // Customer is the name of the table where you take your data from. Maybe you named it different 
CustomersSqlDataSource.DeleteParameters.Add("CustomerID", Gridview1.DataKeys[e.RowIndex].Values["CustomerID"].ToString());
CustomersSqlDataSource.Delete();
Gridview1.DataBind();

But take into account that this will delete the data from the database.

How to find Control in TemplateField of GridView?

Try this:

foreach(GridViewRow row in GridView1.Rows) {
    if(row.RowType == DataControlRowType.DataRow) {
        HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
    }
}

If you are handling RowDataBound event, it's like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
    }
}

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
{
    string id;
    DateTime date;
    public string ID
    {
       get { return id; }
       set { id = value; }
    }
    public DateTime Date
    {
       get { return date; }
       set { date = value; }
    }
}

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList
{
     get...
     set...
}

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
   <DataGrid.Columns>                
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Pls, check if DataGridComboBoxColumn xaml below would work for you:

<DataGridComboBoxColumn 
    SelectedValueBinding="{Binding CompanyID}" 
    DisplayMemberPath="Name" 
    SelectedValuePath="ID">

    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Here you can find another solution for the problem you're facing: Using combo boxes with the WPF DataGrid

DataGrid get selected rows' column values

After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.

private void selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        facultyData row = (facultyData)facultyDataGrid.SelectedItem;
        facultyID_Textbox.Text = row.facultyID;
        lastName_TextBox.Text = row.lastName;
        firstName_TextBox.Text = row.firstName;
        middleName_TextBox.Text = row.middleName;
        age_TextBox.Text = row.age.ToString();
    }

}

class facultyData
{
    public ObjectId _id { get; set; }
    public string facultyID { get; set; }
    public string acadYear { get; set; }
    public string program { get; set; }   
}

How to bind list to dataGridView?

Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:

List<string> filenamesList = ...;
foreach(string filename in filenamesList)
      gvFilesOnServer.Rows.Add(new object[]{filename});

In any case, thanks user927524 for clearing this weird behavior!!

how can I enable scrollbars on the WPF Datagrid?

Add grid with defined height and width for columns and rows. Then add ScrollViewer and inside it add the dataGrid.

GridView sorting: SortDirection always Ascending

To toggle ascending and descending, I use a method in my app's BasePage to cache the sort expression and sort direction:

protected void SetPageSort(GridViewSortEventArgs e)
{
    if (e.SortExpression == SortExpression)
    {
        if (SortDirection == "ASC")
        {
            SortDirection = "DESC";
        }
        else
        {
            SortDirection = "ASC";
        }
    }
    else
    {
        SortDirection = "ASC";
        SortExpression = e.SortExpression;
    }
}

SortExpression and SortDirection are both properties in BasePage that store and retrieve their values from ViewState.

So all of my derived pages just call SetPageSort from the GridView's Sorting method, and bind the GridView:

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
    SetPageSort(e);
    BindGrid();
}

BindGrid checks the SortExpression and uses it and SortDirection to do an ORDERY BY on the grid's data source, something like this:

if (SortExpression.Length > 0)
{
    qry.ORDER_BY(SortExpression + " " + SortDirection);
}

gv.DataSource = qry.ExecuteReader();
gv.DataBind();

So, the base class' SetPageSort removes much of the drudgery of GridView sorting. I feel like I'm forgetting something, but that's the general idea.

Can I convert a boolean to Yes/No in a ASP.NET GridView

Nope - but you could use a template column:

<script runat="server">
  TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
     object o = DataBinder.Eval(Container.DataItem, field);
     if (converter == null) {
        return (TResult)o;
     }
     return converter((T)o);
  }
</script>

<asp:TemplateField>
  <ItemTemplate>
     <%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
  </ItemTemplate>
</asp:TemplateField>

How to overplot a line on a scatter plot in python?

plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

versus

plt.plot(X_plot, X_plot*results.params[1] + results.params[0])

Permission denied for relation

This frequently happens when you create a table as user postgres and then try to access it as an ordinary user. In this case it is best to log in as the postgres user and change the ownership of the table with the command:

alter table <TABLE> owner to <USER>;

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

When should I use git pull --rebase?

I think you should use git pull --rebase when collaborating with others on the same branch. You are in your work ? commit ? work ? commit cycle, and when you decide to push your work your push is rejected, because there's been parallel work on the same branch. At this point I always do a pull --rebase. I do not use squash (to flatten commits), but I rebase to avoid the extra merge commits.

As your Git knowledge increases you find yourself looking a lot more at history than with any other version control systems I've used. If you have a ton of small merge commits, it's easy to lose focus of the bigger picture that's happening in your history.

This is actually the only time I do rebasing(*), and the rest of my workflow is merge based. But as long as your most frequent committers do this, history looks a whole lot better in the end.

(*) While teaching a Git course, I had a student arrest me on this, since I also advocated rebasing feature branches in certain circumstances. And he had read this answer ;) Such rebasing is also possible, but it always has to be according to a pre-arranged/agreed system, and as such should not "always" be applied. And at that time I usually don't do pull --rebase either, which is what the question is about ;)

jQuery selector for inputs with square brackets in the name attribute

The attribute selector syntax is [name=value] where name is the attribute name and value is the attribute value.

So if you want to select all input elements with the attribute name having the value inputName[]:

$('input[name="inputName[]"]')

And if you want to check for two attributes (here: name and value):

$('input[name="inputName[]"][value=someValue]')

Most efficient way to check for DBNull and then assign to a variable?

I have IsDBNull in a program which reads a lot of data from a database. With IsDBNull it loads data in about 20 seconds. Without IsDBNull, about 1 second.

So I think it is better to use:

public String TryGetString(SqlDataReader sqlReader, int row)
{
    String res = "";
    try
    {
        res = sqlReader.GetString(row);
    }
    catch (Exception)
    { 
    }
    return res;
}

How to show a dialog to confirm that the user wishes to exit an Android Activity?

Have modified @user919216 code .. and made it compatible with WebView

@Override
public void onBackPressed() {
    if (webview.canGoBack()) {
        webview.goBack();

    }
    else
    {
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                finish();
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
AlertDialog alert = builder.create();
alert.show();
    }

}

Solving Quadratic Equation

give input through your keyboard

a=float(input("enter the 1st number : "))
b=float(input("enter the 2nd number : "))
c=float(input("enter the 3rd number : "))

calculate the discriminant

d = (b**2) - (4*a*c)

possible solution are

sol_1 = (-b-(0.5**d))/(2*a)
sol_2 = (-b+(0.5**d))/(2*a)

print the result

print('The solution are  %0.f,%0.f'%(sol_1,sol_2))

Java Singleton and Synchronization

Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:

Draconian synchronization:

private static YourObject instance;

public static synchronized YourObject getInstance() {
    if (instance == null) {
        instance = new YourObject();
    }
    return instance;
}

This solution requires that every thread be synchronized when in reality only the first few need to be.

Double check synchronization:

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

Initialization on Demand:

private static class InstanceHolder {
    private static final YourObject instance = new YourObject();
}

public static YourObject getInstance() {
    return InstanceHolder.instance;
}

This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.

Want to download a Git repository, what do I need (windows machine)?

Install mysysgit. (Same as Greg Hewgill's answer.)

Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

How to recompile with -fPIC

I had this problem when building FFMPEG static libraries (e.g. libavcodec.a) for Android x86_64 target platform (using Android NDK clang). When statically linking with my library the problem occured although all FFMPEG C -> object files (*.o) were compiled with -fPIC compile option:

x86_64/libavcodec.a(h264_qpel_10bit.o): 
requires dynamic R_X86_64_PC32 reloc against 'ff_pw_1023' 
which may overflow at runtime; recompile with -fPIC

The problem occured only for libavcodec.a and libswscale.a.

Source of this problem is that FFMPEG has assembler optimizations for x86* platforms e.g. the reported problem cause is in libavcodec/h264_qpel_10bit.asm -> h264_qpel_10bit.o.

When producing X86-64 bit static library (e.g. libavcodec.a) it looks like assembler files (e.g. libavcodec/h264_qpel_10bit.asm) uses some x86 (32bit) assembler commands which are incompatible when statically linking with x86-64 bit target library since they don't support required relocation type.

Possible solutions:

  1. compile all ffmpeg files with no assembler optimizations (for ffmpeg this is configure option: --disable-asm)
  2. produce dynamic libraries (e.g. libavcodec.so) and link them in your final library dynamically

I chose 1) and it solved the problem.

Reference: https://tecnocode.co.uk/2014/10/01/dynamic-relocs-runtime-overflows-and-fpic/

When is null or undefined used in JavaScript?

Regarding this topic the specification (ecma-262) is quite clear

I found it really useful and straightforward, so that I share it: - Here you will find Equality algorithm - Here you will find Strict equality algorithm

I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.

I hope you find it useful.

Text-align class for inside a table

You can use this CSS below:

.text-right {text-align: right} /* For right align */
.text-left {text-align: left} /* For left align */
.text-center {text-align: center} /* For center align */

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

For me it was a missing static keyword in one of the JUnit annotated methods, e.g.:

@AfterClass
public static void cleanUp() {
    // ...
}

scroll up and down a div on button click using jquery

For the go up, you just need to use scrollTop instead of scrollBottom:

$("#upClick").on("click", function () {
    scrolled = scrolled - 300;
    $(".cover").stop().animate({
        scrollTop: scrolled
    });
});

Also, use the .stop() method to stop the currently-running animation on the cover div. When .stop() is called on an element, the currently-running animation (if any) is immediately stopped.

FIDDLE DEMO

What precisely does 'Run as administrator' do?

Things like "elevates the privileges", "restricted access token", "Administrator privilege" ... what the heck is administrator privilege anyway? are nonsense.

Here is an ACCESS_TOKEN for a process normally run from a user belonging to Administrators group.

0: kd> !process 0 1 test.exe
PROCESS 87065030  SessionId: 1  Cid: 0d60    Peb: 7ffdf000  ParentCid: 0618
    DirBase: 2f22e1e0  ObjectTable: a0c8a088  HandleCount:   6.
    Image: test.exe
    VadRoot 8720ef50 Vads 18 Clone 0 Private 83. Modified 0. Locked 0.
    DeviceMap 8936e560
    Token                             935c98e0
0: kd> !token -n 935c98e0
_TOKEN 935c98e0
TS Session ID: 0x1
User: S-1-5-21-2452432034-249115698-1235866470-1000 (no name mapped)
User Groups: 
 00 S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
    Attributes - Mandatory Default Enabled 
 01 S-1-1-0 (Well Known Group: localhost\Everyone)
    Attributes - Mandatory Default Enabled 
 02 S-1-5-32-544 (Alias: BUILTIN\Administrators)
    Attributes - Mandatory Default Enabled Owner 
 03 S-1-5-32-545 (Alias: BUILTIN\Users)
    Attributes - Mandatory Default Enabled 
 04 S-1-5-4 (Well Known Group: NT AUTHORITY\INTERACTIVE)
    Attributes - Mandatory Default Enabled 
 05 S-1-2-1 (Well Known Group: localhost\CONSOLE LOGON)
    Attributes - Mandatory Default Enabled 
 06 S-1-5-11 (Well Known Group: NT AUTHORITY\Authenticated Users)
    Attributes - Mandatory Default Enabled 
 07 S-1-5-15 (Well Known Group: NT AUTHORITY\This Organization)
    Attributes - Mandatory Default Enabled 
 08 S-1-5-5-0-85516 (no name mapped)
    Attributes - Mandatory Default Enabled LogonId 
 09 S-1-2-0 (Well Known Group: localhost\LOCAL)
    Attributes - Mandatory Default Enabled 
 10 S-1-5-64-10 (Well Known Group: NT AUTHORITY\NTLM Authentication)
    Attributes - Mandatory Default Enabled 
 11 S-1-16-12288 (Label: Mandatory Label\High Mandatory Level)
    Attributes - GroupIntegrity GroupIntegrityEnabled 
Primary Group: S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
Privs: 
 05 0x000000005 SeIncreaseQuotaPrivilege          Attributes - 
 08 0x000000008 SeSecurityPrivilege               Attributes - 
 09 0x000000009 SeTakeOwnershipPrivilege          Attributes - 
 10 0x00000000a SeLoadDriverPrivilege             Attributes - 
 11 0x00000000b SeSystemProfilePrivilege          Attributes - 
 12 0x00000000c SeSystemtimePrivilege             Attributes - 
 13 0x00000000d SeProfileSingleProcessPrivilege   Attributes - 
 14 0x00000000e SeIncreaseBasePriorityPrivilege   Attributes - 
 15 0x00000000f SeCreatePagefilePrivilege         Attributes - 
 17 0x000000011 SeBackupPrivilege                 Attributes - 
 18 0x000000012 SeRestorePrivilege                Attributes - 
 19 0x000000013 SeShutdownPrivilege               Attributes - 
 20 0x000000014 SeDebugPrivilege                  Attributes - 
 22 0x000000016 SeSystemEnvironmentPrivilege      Attributes - 
 23 0x000000017 SeChangeNotifyPrivilege           Attributes - Enabled Default 
 24 0x000000018 SeRemoteShutdownPrivilege         Attributes - 
 25 0x000000019 SeUndockPrivilege                 Attributes - 
 28 0x00000001c SeManageVolumePrivilege           Attributes - 
 29 0x00000001d SeImpersonatePrivilege            Attributes - Enabled Default 
 30 0x00000001e SeCreateGlobalPrivilege           Attributes - Enabled Default 
 33 0x000000021 SeIncreaseWorkingSetPrivilege     Attributes - 
 34 0x000000022 SeTimeZonePrivilege               Attributes - 
 35 0x000000023 SeCreateSymbolicLinkPrivilege     Attributes - 
Authentication ID:         (0,14e4c)
Impersonation Level:       Anonymous
TokenType:                 Primary
Source: User32             TokenFlags: 0x2000 ( Token in use )
Token ID: d166b            ParentToken ID: 0
Modified ID:               (0, d052f)
RestrictedSidCount: 0      RestrictedSids: 00000000
OriginatingLogonSession: 3e7

... and here is an ACCESS_TOKEN for a process normally run by the same user with "Run as administrator".

TS Session ID: 0x1
User: S-1-5-21-2452432034-249115698-1235866470-1000 (no name mapped)
User Groups: 
 00 S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
    Attributes - Mandatory Default Enabled 
 01 S-1-1-0 (Well Known Group: localhost\Everyone)
    Attributes - Mandatory Default Enabled 
 02 S-1-5-32-544 (Alias: BUILTIN\Administrators)
    Attributes - Mandatory Default Enabled Owner 
 03 S-1-5-32-545 (Alias: BUILTIN\Users)
    Attributes - Mandatory Default Enabled 
 04 S-1-5-4 (Well Known Group: NT AUTHORITY\INTERACTIVE)
    Attributes - Mandatory Default Enabled 
 05 S-1-2-1 (Well Known Group: localhost\CONSOLE LOGON)
    Attributes - Mandatory Default Enabled 
 06 S-1-5-11 (Well Known Group: NT AUTHORITY\Authenticated Users)
    Attributes - Mandatory Default Enabled 
 07 S-1-5-15 (Well Known Group: NT AUTHORITY\This Organization)
    Attributes - Mandatory Default Enabled 
 08 S-1-5-5-0-85516 (no name mapped)
    Attributes - Mandatory Default Enabled LogonId 
 09 S-1-2-0 (Well Known Group: localhost\LOCAL)
    Attributes - Mandatory Default Enabled 
 10 S-1-5-64-10 (Well Known Group: NT AUTHORITY\NTLM Authentication)
    Attributes - Mandatory Default Enabled 
 11 S-1-16-12288 (Label: Mandatory Label\High Mandatory Level)
    Attributes - GroupIntegrity GroupIntegrityEnabled 
Primary Group: S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
Privs: 
 05 0x000000005 SeIncreaseQuotaPrivilege          Attributes - 
 08 0x000000008 SeSecurityPrivilege               Attributes - 
 09 0x000000009 SeTakeOwnershipPrivilege          Attributes - 
 10 0x00000000a SeLoadDriverPrivilege             Attributes - 
 11 0x00000000b SeSystemProfilePrivilege          Attributes - 
 12 0x00000000c SeSystemtimePrivilege             Attributes - 
 13 0x00000000d SeProfileSingleProcessPrivilege   Attributes - 
 14 0x00000000e SeIncreaseBasePriorityPrivilege   Attributes - 
 15 0x00000000f SeCreatePagefilePrivilege         Attributes - 
 17 0x000000011 SeBackupPrivilege                 Attributes - 
 18 0x000000012 SeRestorePrivilege                Attributes - 
 19 0x000000013 SeShutdownPrivilege               Attributes - 
 20 0x000000014 SeDebugPrivilege                  Attributes - 
 22 0x000000016 SeSystemEnvironmentPrivilege      Attributes - 
 23 0x000000017 SeChangeNotifyPrivilege           Attributes - Enabled Default 
 24 0x000000018 SeRemoteShutdownPrivilege         Attributes - 
 25 0x000000019 SeUndockPrivilege                 Attributes - 
 28 0x00000001c SeManageVolumePrivilege           Attributes - 
 29 0x00000001d SeImpersonatePrivilege            Attributes - Enabled Default 
 30 0x00000001e SeCreateGlobalPrivilege           Attributes - Enabled Default 
 33 0x000000021 SeIncreaseWorkingSetPrivilege     Attributes - 
 34 0x000000022 SeTimeZonePrivilege               Attributes - 
 35 0x000000023 SeCreateSymbolicLinkPrivilege     Attributes - 
Authentication ID:         (0,14e4c)
Impersonation Level:       Anonymous
TokenType:                 Primary
Source: User32             TokenFlags: 0x2000 ( Token in use )
Token ID: ce282            ParentToken ID: 0
Modified ID:               (0, cddbd)
RestrictedSidCount: 0      RestrictedSids: 00000000
OriginatingLogonSession: 3e7

As you see, the only difference is the token ID:

Token ID: d166b            ParentToken ID: 0
Modified ID:               (0, d052f)

vs

Token ID: ce282            ParentToken ID: 0
Modified ID:               (0, cddbd)

Sorry, I can't add much light into this yet, but I am still digging.

How to add additional libraries to Visual Studio project?

Add #pragma comment(lib, "Your library name here") to your source.

final keyword in method parameters

final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense

Why can't overriding methods throw exceptions broader than the overridden method?

What explanation do we attribute to the below

class BaseClass {

    public  void print() {
        System.out.println("In Parent Class , Print Method");
    }

    public static void display() {
        System.out.println("In Parent Class, Display Method");
    }

}


class DerivedClass extends BaseClass {

    public  void print() throws Exception {
        System.out.println("In Derived Class, Print Method");
    }

    public static void display() {
        System.out.println("In Derived Class, Display Method");
    }
}

Class DerivedClass.java throws a compile time exception when the print method throws a Exception , print () method of baseclass does not throw any exception

I am able to attribute this to the fact that Exception is narrower than RuntimeException , it can be either No Exception (Runtime error ), RuntimeException and their child exceptions

JavaScript DOM remove element

removeChild should be invoked on the parent, i.e.:

parent.removeChild(child);

In your example, you should be doing something like:

if (frameid) {
    frameid.parentNode.removeChild(frameid);
}

Laravel is there a way to add values to a request array

you can use laravel helper and request() magic method ...

request()->request->add(['variable1'=>'value1','variable2'=>'value2']);

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

Get month and year from date cells Excel

I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,

=CONCATENATE(YEAR(C2),MONTH(C2)) 

Get all variables sent with POST?

you should be able to access them from $_POST variable:

foreach ($_POST as $param_name => $param_val) {
    echo "Param: $param_name; Value: $param_val<br />\n";
}

Select From all tables - MySQL

You get all tables containing the column product using this statment:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('Product')
        AND TABLE_SCHEMA='YourDatabase';

Then you have to run a cursor on these tables so you select eachtime:

Select * from OneTable where product like '%XYZ%'

The results should be entered into a 3rd table or view, take a look here.

Notice: This can work only if the structure of all table is similar, otherwise aou will have to see which columns are united for all these tables and create your result table / View to contain only these columns.

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Is there a date format to display the day of the week in java?

Yep - 'E' does the trick

http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-E");
System.out.println(df.format(date));

What are Keycloak's OAuth2 / OpenID Connect endpoints?

After much digging around we were able to scrape the info more or less (mainly from Keycloak's own JS client lib):

  • Authorization Endpoint: /auth/realms/{realm}/tokens/login
  • Token Endpoint: /auth/realms/{realm}/tokens/access/codes

As for OpenID Connect UserInfo, right now (1.1.0.Final) Keycloak doesn't implement this endpoint, so it is not fully OpenID Connect compliant. However, there is already a patch that adds that as of this writing should be included in 1.2.x.

But - Ironically Keycloak does send back an id_token in together with the access token. Both the id_token and the access_token are signed JWTs, and the keys of the token are OpenID Connect's keys, i.e:

"iss":  "{realm}"
"sub":  "5bf30443-0cf7-4d31-b204-efd11a432659"
"name": "Amir Abiri"
"email: "..."

So while Keycloak 1.1.x is not fully OpenID Connect compliant, it does "speak" in OpenID Connect language.

Submitting HTML form using Jquery AJAX

If you add:

jquery.form.min.js

You can simply do this:

<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>

NOTE:

You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.

How can I find the dimensions of a matrix in Python?

You simply can find a matrix dimension by using Numpy:

import numpy as np

x = np.arange(24).reshape((6, 4))
x.ndim

output will be:

2

It means this matrix is a 2 dimensional matrix.

x.shape

Will show you the size of each dimension. The shape for x is equal to:

(6, 4)

How to change the application launcher icon on Flutter?

I would suggest You to use this website Linked Below

App Icon Creator

Step-1: upload The Image,

Step-2: Make necessary Changes And Click on download(dont change the file name)

Step-3: Extract the Downloaded Zip File In the respective folder

android/app/src/main/res

Unable to merge dex

In my case a library makes this problem, library was successfully added to project but when i run my app it shows me this error. So if this happens to you too, you can go to github and check issues or raise new issue. If you do not find any solution regarding the library i suggest you to replace it.

"A referral was returned from the server" exception when accessing AD from C#

A referral is sent by an AD server when it doesn't have the information requested itself, but know that another server have the info. It usually appears in trust environment where a DC can refer to a DC in trusted domain.

In your case you are only specifying a domain, relying on automatic lookup of what domain controller to use. I think that you should try to find out what domain controller is used for the query and look if that one really holds the requested information.

If you provide more information on your AD setup, including any trusts/subdomains, global catalogues and the DNS resource records for the domain controllers it will be easier to help you.

What is the difference between Python's list methods append and extend?

append appends a single element. extend appends a list of elements.

Note that if you pass a list to append, it still adds one element:

>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

SQL Server JOIN missing NULL values

Try using additional condition in join:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1 
    OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
   )

Reset the Value of a Select Box

What worked for me was:

$('select option').each(function(){$(this).removeAttr('selected');});   

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

Get text from pressed button

The view you get passed in on onClick() is the Button you are looking for.

public void onClick(View v) {
    // 1) Possibly check for instance of first 
    Button b = (Button)v;
    String buttonText = b.getText().toString();
}

1) If you are using a non-anonymous class as onClickListener, you may want to check for the type of the view before casting it, as it may be something different than a Button.

How to delay the .keyup() handler until the user stops typing?

Delay Multi Function Calls using Labels

This is the solution i work with. It will delay the execution on ANY function you want. It can be the keydown search query, maybe the quick click on previous or next buttons ( that would otherwise send multiple request if quickly clicked continuously , and be not used after all). This uses a global object that stores each execution time, and compares it with the most current request.

So the result is that only that last click / action will actually be called, because those requests are stored in a queue, that after the X milliseconds is called if no other request with the same label exists in the queue!

function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  delayed_methods[label]=""; callback();}}, time||500);
  }

You can set your own delay time ( its optional, defaults to 500ms). And send your function arguments in a "closure fashion".

For example if you want to call the bellow function:

function send_ajax(id){console.log(id);}

To prevent multiple send_ajax requests, you delay them using:

delay_method( "check date", function(){ send_ajax(2); } ,600);

Every request that uses the label "check date" will only be triggered if no other request is made in the 600 miliseconds timeframe. This argument is optional

Label independency (calling the same target function) but run both:

delay_method("check date parallel", function(){send_ajax(2);});
delay_method("check date", function(){send_ajax(2);});

Results in calling the same function but delay them independently because of their labels being different

Good ways to manage a changelog using git?

This was about 3-4 years ago, but for the sake of future searchers, it's now possible to generate gorgeous logs with:

git log --oneline --decorate

Or, if you want it even prettier (with color for terminal):

git log --oneline --decorate --color

Piping that output to ChangeLog is what I currently use in all my projects, it's simply amazing.

How do I look inside a Python object?

Try ppretty

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), indent='    ', depth=2, width=30, seq_length=6,
              show_protected=True, show_private=False, show_static=True,
              show_properties=True, show_address=True)

Output:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5
)

Case insensitive string as HashMap key

One approach is to create a custom subclass of the Apache Commons AbstractHashedMap class, overriding the hash and isEqualKeys methods to perform case insensitive hashing and comparison of keys. (Note - I've never tried this myself ...)

This avoids the overhead of creating new objects each time you need to do a map lookup or update. And the common Map operations should O(1) ... just like a regular HashMap.

And if you are prepared to accept the implementation choices they have made, the Apache Commons CaseInsensitiveMap does the work of customizing / specializing AbstractHashedMap for you.


But if O(logN) get and put operations are acceptable, a TreeMap with a case insensitive string comparator is an option; e.g. using String.CASE_INSENSITIVE_ORDER.

And if you don't mind creating a new temporary String object each time you do a put or get, then Vishal's answer is just fine. (Though, I note that you wouldn't be preserving the original case of the keys if you did that ...)

Struct like objects in Java

Re: aku, izb, John Topley...

Watch out for mutability issues...

It may seem sensible to omit getters/setters. It actually may be ok in some cases. The real problem with the proposed pattern shown here is mutability.

The problem is once you pass an object reference out containing non-final, public fields. Anything else with that reference is free to modify those fields. You no longer have any control over the state of that object. (Think what would happen if Strings were mutable.)

It gets bad when that object is an important part of the internal state of another, you've just exposed internal implementation. To prevent this, a copy of the object must be returned instead. This works, but can cause massive GC pressure from tons of single-use copies created.

If you have public fields, consider making the class read-only. Add the fields as parameters to the constructor, and mark the fields final. Otherwise make sure you're not exposing internal state, and if you need to construct new instances for a return value, make sure it won't be called excessively.

See: "Effective Java" by Joshua Bloch -- Item #13: Favor Immutability.

PS: Also keep in mind, all JVMs these days will optimize away the getMethod if possible, resulting in just a single field-read instruction.

Twitter bootstrap scrollable modal

/* Important part */
.modal-dialog{
    overflow-y: initial !important
}
.modal-body{
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

This works for Bootstrap 3 without JS code and is responsive.

Source

Checking for an empty field with MySQL

There's a difference between an empty string (email != "") and NULL. NULL is null and an Empty string is something.

How do I use a pipe to redirect the output of one command to the input of another?

This should work:

for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i

If running in a batch file, you need to use %%i instead of just %i (in both places).

Hide element by class in pure Javascript

var appBanners = document.getElementsByClassName('appBanner');

for (var i = 0; i < appBanners.length; i ++) {
    appBanners[i].style.display = 'none';
}

JSFiddle.

How to draw a dotted line with css?

.myclass {
    border-bottom: thin red dotted;
}

Java: How to access methods from another class

I have another solution. If Alpha and Beta are your only extra class then why not make a static variable with the image of the class.

Like in Alpha class :

public class Alpha{
        public static Alpha alpha;
        public Alpha(){
                this.alpha = this;
}

Now you you can call the function in Beta class by just using these lines :

new Alpha();
Alpha.alpha.DoSomethingAlpha();

calculate the mean for each column of a matrix in R

You can try this:

mean(as.matrix(cluster1))

Application not picking up .css file (flask/python)

One more point to add on to this thread.

If you add an underscore in your .css file name, then it wouldn't work.

What are the differences between delegates and events?

In addition to the syntactic and operational properties, there's also a semantical difference.

Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.

Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.

Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).

Checking during array iteration, if the current element is the last element

$myarray = array(
  'test1' => 'foo',
  'test2' => 'bar',
  'test3' => 'baz',
  'test4' => 'waldo'
);

$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);

// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
  if($key != $last) {
    echo "$key -> $value\n";
  }
}

Since array_pop works on the temporary array created by array_keys it doesn't modify the original array at all.

$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz

Android: How to Programmatically set the size of a Layout

my sample code

wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

How to locate the php.ini file (xampp)

Put a script somewhere in your document root

<?php
phpinfo();

Among others the output of the function will tell you which php.inis are parsed before the script got executed.

Given a starting and ending indices, how can I copy part of a string in C?

Use strncpy

e.g.

strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)

How to escape a while loop in C#

break or goto

while ( true ) {
  if ( conditional ) {
    break;
  }
  if ( other conditional ) {
    goto EndWhile;
  }
}
EndWhile:

MetadataException when using Entity Framework Entity Connection

As Shiraz Bhaiji answered, the metadata=res:///Model.csdl|res:///Model.ssdl|res://*/Model.msl was the case. However I still had problems with constructing the proper string based on my Model localization, namespaces and assemby name. The very simple solution was to rename the .edmx file in Visual Studio(after than rename and get back to the original name), which triggered the automatic refreshing of the string in my Web.config

Count all values in a matrix greater than a value

The numpy.where function is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide.

Using numpy.where directly will yield a boolean mask indicating whether certain values match your conditions:

>>> data
array([[1, 8],
       [3, 4]])
>>> numpy.where( data > 3 )
(array([0, 1]), array([1, 1]))

And the mask can be used to index the array directly to get the actual values:

>>> data[ numpy.where( data > 3 ) ]
array([8, 4])

Exactly where you take it from there will depend on what form you'd like the results in.

How do you find out the type of an object (in Swift)?

For Swift 3.0

String(describing: <Class-Name>.self)

For Swift 2.0 - 2.3

String(<Class-Name>)

Returning an array using C

You can't return arrays from functions in C. You also can't (shouldn't) do this:

char *returnArray(char array []){
 char returned [10];
 //methods to pull values from array, interpret them, and then create new array
 return &(returned[0]); //is this correct?
} 

returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.

You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.

Option 1:

dynamically allocate the memory inside of the function (caller responsible for deallocating ret)

char *foo(int count) {
    char *ret = malloc(count);
    if(!ret)
        return NULL;

    for(int i = 0; i < count; ++i) 
        ret[i] = i;

    return ret;
}

Call it like so:

int main() {
    char *p = foo(10);
    if(p) {
        // do stuff with p
        free(p);
    }

    return 0;
}

Option 2:

fill a preallocated buffer provided by the caller (caller allocates buf and passes to the function)

void foo(char *buf, int count) {
    for(int i = 0; i < count; ++i)
        buf[i] = i;
}

And call it like so:

int main() {
    char arr[10] = {0};
    foo(arr, 10);
    // No need to deallocate because we allocated 
    // arr with automatic storage duration.
    // If we had dynamically allocated it
    // (i.e. malloc or some variant) then we 
    // would need to call free(arr)
}

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

If you don't want to use a separate JS library to create a custom control for that, you could use two confirm dialogs to do the checks:

if (confirm("Are you sure you want to quit?") ) {
    if (confirm("Save your work before leaving?") ) {
        // code here for save then leave (Yes)
    } else {
        //code here for no save but leave (No)
    }
} else {
    //code here for don't leave (Cancel)
}

How should I unit test multithreaded code?

(if possible) don't use threads, use actors / active objects. Easy to test.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I change my APIs as * cglib --- to ---> cglib-nodep-2.2.jar * cglib-asm --- to ---> cglib-asm.jar (i.e. latest one )

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

C++ Structure Initialization

After my question resulted in no satisfying result (because C++ doesn't implement tag-based init for structures), I took the trick I found here: Are members of a C++ struct initialized to 0 by default?

For you it would amount to do that:

address temp_address = {}; // will zero all fields in C++
temp_address.city = "Hamilton";
temp_address.prov = "Ontario";

This is certainly the closest to what you wanted originally (zero all the fields except those you want to initialize).

Stopping python using ctrl+c

  • Forcing the program to close using Alt+F4 (shuts down current program)
  • Spamming the X button on CMD for e.x.
  • Taskmanager (first Windows+R and then "taskmgr") and then end the task.

Those may help.

matplotlib does not show my drawings although I call pyplot.show()

Just type:

plt.ion()

See https://www.youtube.com/watch?v=1zmV8lZsHF4 at 23:30 !

plt is used because of my import: import matplotlib.pyplot as plt

I'm using python2.7 on a mac with iTerm2.

Log to the base 2 in python

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

How to insert multiple rows from array using CodeIgniter framework?

You can do it with several ways in codeigniter e.g.

First By loop

foreach($myarray as $row)
{
   $data = array("first"=>$row->first,"second"=>$row->sec);
   $this->db->insert('table_name',$data);
}

Second -- By insert batch

$data = array(
       array(
          'first' => $myarray[0]['first'] ,
          'second' => $myarray[0]['sec'],
        ),
       array(
          'first' => $myarray[1]['first'] ,
          'second' => $myarray[1]['sec'],
        ),
    );

    $this->db->insert_batch('table_name', $data);

Third way -- By multiple value pass

$sql = array(); 
foreach( $myarray as $row ) {
    $sql[] = '("'.mysql_real_escape_string($row['first']).'", '.$row['sec'].')';
}
mysql_query('INSERT INTO table (first, second) VALUES '.implode(',', $sql));

How to construct a REST API that takes an array of id's for the resources

 api.com/users?id=id1,id2,id3,id4,id5
 api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.

RESTful attempt:

POST http://example.com/api/batchtask

   [
    {
      method : "GET",
      headers : [..],
      url : "/users/id1"
    },
    {
      method : "GET",
      headers : [..],
      url : "/users/id2"
    }
   ]

Server will reply URI of newly created batchtask resource.

201 Created
Location: "http://example.com/api/batchtask/1254"

Now client can fetch batch response or task progress by polling

GET http://example.com/api/batchtask/1254


This is how others attempted to solve this issue:

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

The issue is because your data source is not setup properly, to do that please verify your data source connection, in order to do that first navigate to Report Service Configuration Manager through

clicking on the start -> Start All -> Microsoft SQL Server ->Configuration Tool -> “Report Service Configuration Manager”

The open Report Manager URL and then navigate to the Data Source folder, see in the picture below

Then Create a Data Source or configure the one that is already there by right click on your database source and select "Manage" as is shown below

Now on the properties tab, on your left menu, fill out the data source with your connection string and username and password, after that click on test connection, and if the connection was successful, then click "Apply"

Navigate to the folder that contains your report in this case "SurveyLevelReport"

And Finally set your Report to the Data Source that you set up previously, and click Apply

MongoDB: How to query for records where field is null or not set?

If you want to ONLY count the documents with sent_at defined with a value of null (don't count the documents with sent_at not set):

db.emails.count({sent_at: { $type: 10 }})

What is declarative programming?

It depends on how you submit the answer to the text. Overall you can look at the programme at a certain view but it depends what angle you look at the problem. I will get you started with the programme: Dim Bus, Car, Time, Height As Integr

Again it depends on what the problem is an overall. You might have to shorten it due to the programme. Hope this helps and need the feedback if it does not. Thank You.

Deleting array elements in JavaScript - delete vs splice

The difference can be seen by logging the length of each array after the delete operator and splice() method are applied. For example:

delete operator

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];

console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5

The delete operator removes the element from the array, but the "placeholder" of the element still exists. oak has been removed but it still takes space in the array. Because of this, the length of the array remains 5.

splice() method

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);

console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4

The splice() method completely removes the target value and the "placeholder" as well. oak has been removed as well as the space it used to occupy in the array. The length of the array is now 4.

Java array assignment (multiple values)

On declaration you can do the following.

float[] values = {0.1f, 0.2f, 0.3f};

When the field is already defined, try this.

values = new float[] {0.1f, 0.2f, 0.3f};

Be aware that also the second version creates a new array. If values was the only reference to an already existing field, it becomes eligible for garbage collection.

datetimepicker is not a function jquery

I had the same problem with bootstrap datetimepicker extension. Including moment.js before datetimepicker.js was the solution.

`require': no such file to load -- mkmf (LoadError)

Have you tried:

sudo apt-get install ruby1.8-dev

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

What's the best way to generate a UML diagram from Python source code?

Epydoc is a tool to generate API documentation from Python source code. It also generates UML class diagrams, using Graphviz in fancy ways. Here is an example of diagram generated from the source code of Epydoc itself.

Because Epydoc performs both object introspection and source parsing it can gather more informations respect to static code analysers such as Doxygen: it can inspect a fair amount of dynamically generated classes and functions, but can also use comments or unassigned strings as a documentation source, e.g. for variables and class public attributes.

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

How to remove new line characters from data rows in mysql?

UPDATE test SET log = REPLACE(REPLACE(log, '\r', ''), '\n', '');

worked for me.

while its similar, it'll also get rid of \r\n

http://lists.mysql.com/mysql/182689

How do I detect "shift+enter" and generate a new line in Textarea?

Using ReactJS ES6 here's the simplest way

shift + enter New Line at any position

enter Blocked

_x000D_
_x000D_
class App extends React.Component {_x000D_
_x000D_
 constructor(){_x000D_
    super();_x000D_
    this.state = {_x000D_
      message: 'Enter is blocked'_x000D_
    }_x000D_
  }_x000D_
  onKeyPress = (e) => {_x000D_
     if (e.keyCode === 13 && e.shiftKey) {_x000D_
        e.preventDefault();_x000D_
        let start = e.target.selectionStart,_x000D_
            end = e.target.selectionEnd;_x000D_
        this.setState(prevState => ({ message:_x000D_
            prevState.message.substring(0, start)_x000D_
            + '\n' +_x000D_
            prevState.message.substring(end)_x000D_
        }),()=>{_x000D_
            this.input.selectionStart = this.input.selectionEnd = start + 1;_x000D_
        })_x000D_
    }else if (e.keyCode === 13) { // block enter_x000D_
      e.preventDefault();_x000D_
    }_x000D_
    _x000D_
  };_x000D_
_x000D_
  render(){_x000D_
    return(_x000D_
      <div>_x000D_
      New line with shift enter at any position<br />_x000D_
       <textarea _x000D_
       value={this.state.message}_x000D_
       ref={(input)=> this.input = input}_x000D_
       onChange={(e)=>this.setState({ message: e.target.value })}_x000D_
       onKeyDown={this.onKeyPress}/>_x000D_
      </div>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Creating layout constraints programmatically

Regarding your second question about properties, you can use self.myView only if you declared it as a property in class. Since myView is a local variable, you can not use it that way. For more details on this, I would recommend you to go through the apple documentation on Declared Properties,

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

What are all the escape characters?

These are escape characters which are used to manipulate string.

\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a form feed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

Read more about them from here.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

libz.so.1: cannot open shared object file

For Fedora (can be useful for someone)

sudo dnf install zlib-1.2.8-10.fc24.i686 libgcc-6.1.1-2.fc24.i686

Include PHP inside JavaScript (.js) files

PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.

Strip last two characters of a column in MySQL

Why not using LEFT(string, length) function instead of substring.

LEFT(col,char_length(col)-2) 

you can visit here https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_left to know more about Mysql String Functions.

How do you cache an image in Javascript

Even though your question says "using javascript", you can use the prefetch attribute of a link tag to preload any asset. As of this writing (Aug 10, 2016) it isn't supported in Safari, but is pretty much everywhere else:

<link rel="prefetch" href="(url)">

More info on support here: http://caniuse.com/#search=prefetch

Note that IE 9,10 aren't listed in the caniuse matrix because Microsoft has discontinued support for them.

So if you were really stuck on using javascript, you could use jquery to dynamically add these elements to your page as well ;-)

How do I display image in Alert/confirm box in Javascript?

Alert boxes in JavaScript can only display pure text. You could use a JavaScript library like jQuery to display a modal instead?

This might be useful: http://jqueryui.com/dialog/

You can do it like this:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <script>
  body {
    font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
    font-size: 62.5%;
}

  </script>
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>Image:</p>
  <img src="http://placehold.it/50x50" alt="Placeholder Image" />

</div>


</body>
</html>

Adding an .env file to React Project

So I'm myself new to React and I found a way to do it.

This solution does not require any extra packages.

Step 1 ReactDocs

In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file

1.1 create Root/.env

#.env file
REACT_APP_SECRET_NAME=secretvaluehere123

Important notes it MUST start with REACT_APP_

1.2 Access ENV variable

#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>

handleFetchData() { // access in API call
  fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
    .then((res) => res.json())
    .then((data) => console.log(data))
}

1.3 Build Env Issue

So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.

Exact difference between CharSequence and String in java

CharSequence is a contract (interface), and String is an implementation of this contract.

public final class String extends Object 
    implements Serializable, Comparable<String>, CharSequence

The documentation for CharSequence is:

A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.

"The page has expired due to inactivity" - Laravel 5.5

I have figured out two solution to avoid these error 1)by adding protected $except = ['/yourroute'] possible disable csrf token inspection from defined root. 2)just comment \App\Http\Middleware\VerifyCsrfToken::class line in protected middleware group in kernel

How to check the multiple permission at single request in Android M?

I am late, but i want tell the library which i have ended with.

RxPermission is best library with reactive code, which makes permission code unexpected just 1 line.

RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.CAMERA,
         Manifest.permission.READ_PHONE_STATE)
.subscribe(granted -> {
    if (granted) {
       // All requested permissions are granted
    } else {
       // At least one permission is denied
    }
});

add in your build.gradle

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

You can use this command: ECHO >> filename.txt

it will create a file with the given extension in the current folder.

UPDATE:

for an empty file use: copy NUL filename.txt

TypeError: p.easing[this.easing] is not a function

You need to include jQueryUI for the extended easing options.

I think there may be an option to only include the easing in the download, or at least just the base library plus easing.

Forward host port to docker container

A simple but relatively insecure way would be to use the --net=host option to docker run.

This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.

This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.

For example, you can test it out by running the following command, which assumes your image is called my_image, your image includes the telnet utility, and the service you want to connect to is on port 25:

docker run --rm -i -t --net=host my_image telnet localhost 25

If you consider doing it this way, please see the caution about security on this page:

https://docs.docker.com/articles/networking/

It says:

--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.

How to use JavaScript regex over multiple lines?

[\\w\\s]*

This one was beyond helpful for me, especially for matching multiple things that include new lines, every single other answer ended up just grouping all of the matches together.

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

i am using like this.. its easy to understand first argument is mapStateToProps and second argument is mapDispatchToProps in the end connect with function/class.

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);

How can I run multiple curl requests processed sequentially?

It would most likely process them sequentially (why not just test it). But you can also do this:

  1. make a file called curlrequests.sh

  2. put it in a file like thus:

    curl http://example.com/?update_=1
    curl http://example.com/?update_=3
    curl http://example.com/?update_=234
    curl http://example.com/?update_=65
    
  3. save the file and make it executable with chmod:

    chmod +x curlrequests.sh
    
  4. run your file:

    ./curlrequests.sh
    

or

   /path/to/file/curlrequests.sh

As a side note, you can chain requests with &&, like this:

   curl http://example.com/?update_=1 && curl http://example.com/?update_=2 && curl http://example.com?update_=3`

And execute in parallel using &:

   curl http://example.com/?update_=1 & curl http://example.com/?update_=2 & curl http://example.com/?update_=3

MySQL duplicate entry error even though there is no duplicate entry

Your code is work well on this demo:

http://sqlfiddle.com/#!8/87e10/1/0

I think you are doing second query (insert...) twice. Try

select * from my_table

before insert new row and you will get that your data already exist or not.

Finding smallest value in an array most efficiently

If they are unsorted, you can't do much but look at each one, which is O(N), and when you're done you'll know the minimum.


Pseudo-code:

small = <biggest value> // such as std::numerical_limits<int>::max
for each element in array:
    if (element < small)
        small = element

A better way reminded by Ben to me was to just initialize small with the first element:

small = element[0]
for each element in array, starting from 1 (not 0):
    if (element < small)
        small = element

The above is wrapped in the algorithm header as std::min_element.


If you can keep your array sorted as items are added, then finding it will be O(1), since you can keep the smallest at front.

That's as good as it gets with arrays.

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Secondary axis with twinx(): how to add to legend?

You can easily get what you want by adding the line in ax:

ax.plot([], [], '-r', label = 'temp')

or

ax.plot(np.nan, '-r', label = 'temp')

This would plot nothing but add a label to legend of ax.

I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.

The whole code is as below:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)

fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()

#---------- look at below -----------

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')

ax2.plot(time, temp, '-r')  # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp')  # Make an agent in ax

ax.legend(loc=0)

#---------------done-----------------

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

The plot is as below:

enter image description here


Update: add a better version:

ax.plot(np.nan, '-r', label = 'temp')

This will do nothing while plot(0, 0) may change the axis range.


One extra example for scatter

ax.scatter([], [], s=100, label = 'temp')  # Make an agent in ax
ax2.scatter(time, temp, s=10)  # The true scatter in ax2

ax.legend(loc=1, framealpha=1)

Count the cells with same color in google spreadsheet

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = book.getActiveSheet();
 var range_input = sheet.getRange("B3:B4");
 var range_output = sheet.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for(var r = 0; r < cell_colors.length; r++) {
   for(var c = 0; c < cell_colors[0].length; c++) {
     if(cell_colors[r][c] == color) {
       count = count + 1;
     }
   }
 }
    range_output.setValue(count);
 }

How do I get the type of a variable?

#include <typeinfo>

...
string s = typeid(YourClass).name()

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

Counting DISTINCT over multiple columns

Edit: Altered from the less-than-reliable checksum-only query I've discovered a way to do this (in SQL Server 2005) that works pretty well for me and I can use as many columns as I need (by adding them to the CHECKSUM() function). The REVERSE() function turns the ints into varchars to make the distinct more reliable

SELECT COUNT(DISTINCT (CHECKSUM(DocumentId,DocumentSessionId)) + CHECKSUM(REVERSE(DocumentId),REVERSE(DocumentSessionId)) )
FROM DocumentOutPutItems

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

How do you convert CString and std::string std::wstring to each other?

to convert CString to std::string. You can use this format.

std::string sText(CW2A(CSText.GetString(), CP_UTF8 ));

Java method to sum any number of ints

 public static void main(String args[])
 {
 System.out.println(SumofAll(12,13,14,15));//Insert your number here.
   {
      public static int SumofAll(int...sum)//Call this method in main method.
          int total=0;//Declare a variable which will hold the total value.
            for(int x:sum)
          {
           total+=sum;
           }
  return total;//And return the total variable.
    }
 }

POST request send json data java HttpUrlConnection

the correct answer is good , but

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

not work for me , instead of it , use :

byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = con.getOutputStream();
os.write(outputBytes);

Get selected option text with JavaScript

There are two solutions, as far as I know.

both that just need using vanilla javascript

1 selectedOptions

live demo

_x000D_
_x000D_
const log = console.log;_x000D_
const areaSelect = document.querySelector(`[id="area"]`);_x000D_
_x000D_
areaSelect.addEventListener(`change`, (e) => {_x000D_
  // log(`e.target`, e.target);_x000D_
  const select = e.target;_x000D_
  const value = select.value;_x000D_
  const desc = select.selectedOptions[0].text;_x000D_
  log(`option desc`, desc);_x000D_
});
_x000D_
<div class="select-box clearfix">_x000D_
  <label for="area">Area</label>_x000D_
  <select id="area">_x000D_
    <option value="101">A1</option>_x000D_
    <option value="102">B2</option>_x000D_
    <option value="103">C3</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2 options

live demo

_x000D_
_x000D_
const log = console.log;_x000D_
const areaSelect = document.querySelector(`[id="area"]`);_x000D_
_x000D_
areaSelect.addEventListener(`change`, (e) => {_x000D_
  // log(`e.target`, e.target);_x000D_
  const select = e.target;_x000D_
  const value = select.value;_x000D_
  const desc = select.options[select.selectedIndex].text;_x000D_
  log(`option desc`, desc);_x000D_
});
_x000D_
<div class="select-box clearfix">_x000D_
  <label for="area">Area</label>_x000D_
  <select id="area">_x000D_
    <option value="101">A1</option>_x000D_
    <option value="102">B2</option>_x000D_
    <option value="103">C3</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_


multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

ArrayBuffer to base64 encoded string

This works fine for me:

var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));

In ES6, the syntax is a little simpler:

let base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));

As pointed out in the comments, this method may result in a runtime error in some browsers when the ArrayBuffer is large. The exact size limit is implementation dependent in any case.

Merge (with squash) all changes from another branch as a single commit

Another option is git merge --squash <feature branch> then finally do a git commit.

From Git merge

--squash

--no-squash

Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the HEAD, nor record $GIT_DIR/MERGE_HEAD to cause the next git commit command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

How to Convert a Text File into a List in Python

This looks like a CSV file, so you could use the python csv module to read it. For example:

import csv

crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]

Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.

iTerm2 keyboard shortcut - split pane navigation

Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.

Marker content (infoWindow) Google Maps

We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:

Create a new function with your information for the infoWindow in it:

function addInfoWindow(marker, message) {

            var infoWindow = new google.maps.InfoWindow({
                content: message
            });

            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.open(map, marker);
            });
        }

Then call the function with the array ID and the marker you want to create:

addInfoWindow(marker, hotels[i][3]);

Using Custom Domains With IIS Express

This method has been tested and worked with ASP.NET Core 3.1 and Visual Studio 2019.

.vs\PROJECTNAME\config\applicationhost.config

Change "*:44320:localhost" to "*:44320:*".

<bindings>
    <binding protocol="http" bindingInformation="*:5737:localhost" />
    <binding protocol="https" bindingInformation="*:44320:*" />
</bindings>

Both links work:

Now if you want the app to work with the custom domain, just add the following line to the host file:

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 customdomain

Now:

  • https://customdomain:44320

NOTE: If your app works without SSL, change the protocol="http" part.

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

How to handle a single quote in Oracle SQL

Use two single-quotes

SQL> SELECT 'D''COSTA' name FROM DUAL;

NAME
-------
D'COSTA

Alternatively, use the new (10g+) quoting method:

SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;

NAME
-------
D'COSTA

How to test if a DataSet is empty?

Fill is command always return how many records inserted into dataset.

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
var count = da.Fill(ds);
if(count > 0)
{
   Console.Write("It is not Empty");
}

How do I escape spaces in path for scp copy in Linux?

Sorry for using this Linux question to put this tip for Powershell on Windows 10: the space char escaping with backslashes or surrounding with quotes didn't work for me in this case. Not efficient, but I solved it using the "?" char instead:

for the file "tasks.txt Jun-22.bkp" I downloaded it using "tasks.txt?Jun-22.bkp"

How do I find the caller of a method using stacktrace or reflection?

An alternative solution can be found in a comment to this request for enhancement. It uses the getClassContext() method of a custom SecurityManager and seems to be faster than the stack trace method.

The following program tests the speed of the different suggested methods (the most interesting bit is in the inner class SecurityManagerMethod):

/**
 * Test the speed of various methods for getting the caller class name
 */
public class TestGetCallerClassName {

  /**
   * Abstract class for testing different methods of getting the caller class name
   */
  private static abstract class GetCallerClassNameMethod {
      public abstract String getCallerClassName(int callStackDepth);
      public abstract String getMethodName();
  }

  /**
   * Uses the internal Reflection class
   */
  private static class ReflectionMethod extends GetCallerClassNameMethod {
      public String getCallerClassName(int callStackDepth) {
          return sun.reflect.Reflection.getCallerClass(callStackDepth).getName();
      }

      public String getMethodName() {
          return "Reflection";
      }
  }

  /**
   * Get a stack trace from the current thread
   */
  private static class ThreadStackTraceMethod extends GetCallerClassNameMethod {
      public String  getCallerClassName(int callStackDepth) {
          return Thread.currentThread().getStackTrace()[callStackDepth].getClassName();
      }

      public String getMethodName() {
          return "Current Thread StackTrace";
      }
  }

  /**
   * Get a stack trace from a new Throwable
   */
  private static class ThrowableStackTraceMethod extends GetCallerClassNameMethod {

      public String getCallerClassName(int callStackDepth) {
          return new Throwable().getStackTrace()[callStackDepth].getClassName();
      }

      public String getMethodName() {
          return "Throwable StackTrace";
      }
  }

  /**
   * Use the SecurityManager.getClassContext()
   */
  private static class SecurityManagerMethod extends GetCallerClassNameMethod {
      public String  getCallerClassName(int callStackDepth) {
          return mySecurityManager.getCallerClassName(callStackDepth);
      }

      public String getMethodName() {
          return "SecurityManager";
      }

      /** 
       * A custom security manager that exposes the getClassContext() information
       */
      static class MySecurityManager extends SecurityManager {
          public String getCallerClassName(int callStackDepth) {
              return getClassContext()[callStackDepth].getName();
          }
      }

      private final static MySecurityManager mySecurityManager =
          new MySecurityManager();
  }

  /**
   * Test all four methods
   */
  public static void main(String[] args) {
      testMethod(new ReflectionMethod());
      testMethod(new ThreadStackTraceMethod());
      testMethod(new ThrowableStackTraceMethod());
      testMethod(new SecurityManagerMethod());
  }

  private static void testMethod(GetCallerClassNameMethod method) {
      long startTime = System.nanoTime();
      String className = null;
      for (int i = 0; i < 1000000; i++) {
          className = method.getCallerClassName(2);
      }
      printElapsedTime(method.getMethodName(), startTime);
  }

  private static void printElapsedTime(String title, long startTime) {
      System.out.println(title + ": " + ((double)(System.nanoTime() - startTime))/1000000 + " ms.");
  }
}

An example of the output from my 2.4 GHz Intel Core 2 Duo MacBook running Java 1.6.0_17:

Reflection: 10.195 ms.
Current Thread StackTrace: 5886.964 ms.
Throwable StackTrace: 4700.073 ms.
SecurityManager: 1046.804 ms.

The internal Reflection method is much faster than the others. Getting a stack trace from a newly created Throwable is faster than getting it from the current Thread. And among the non-internal ways of finding the caller class the custom SecurityManager seems to be the fastest.

Update

As lyomi points out in this comment the sun.reflect.Reflection.getCallerClass() method has been disabled by default in Java 7 update 40 and removed completely in Java 8. Read more about this in this issue in the Java bug database.

Update 2

As zammbi has found, Oracle was forced to back out of the change that removed the sun.reflect.Reflection.getCallerClass(). It is still available in Java 8 (but it is deprecated).

Update 3

3 years after: Update on timing with current JVM.

> java -version
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
> java TestGetCallerClassName
Reflection: 0.194s.
Current Thread StackTrace: 3.887s.
Throwable StackTrace: 3.173s.
SecurityManager: 0.565s.

Is it necessary to assign a string to a variable before comparing it to another?

Do I really have to create an NSString for "Wrong"?

No, why not just do:

if([statusString isEqualToString:@"Wrong"]){
    //doSomething;
}

Using @"" simply creates a string literal, which is a valid NSString.

Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?

Yes, you can do something like:

UILabel *label = ...;
if([someString isEqualToString:label.text]) {
    // Do stuff here 
}

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

JavaScript get window X/Y position for scroll

Using pure javascript you can use Window.scrollX and Window.scrollY

window.addEventListener("scroll", function(event) {
    var top = this.scrollY,
        left =this.scrollX;
}, false);

Notes

The pageXOffset property is an alias for the scrollX property, and The pageYOffset property is an alias for the scrollY property:

window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true

Here is a quick demo

_x000D_
_x000D_
window.addEventListener("scroll", function(event) {_x000D_
  _x000D_
    var top = this.scrollY,_x000D_
        left = this.scrollX;_x000D_
  _x000D_
    var horizontalScroll = document.querySelector(".horizontalScroll"),_x000D_
        verticalScroll = document.querySelector(".verticalScroll");_x000D_
    _x000D_
    horizontalScroll.innerHTML = "Scroll X: " + left + "px";_x000D_
      verticalScroll.innerHTML = "Scroll Y: " + top + "px";_x000D_
  _x000D_
}, false);
_x000D_
*{box-sizing: border-box}_x000D_
:root{height: 200vh;width: 200vw}_x000D_
.wrapper{_x000D_
    position: fixed;_x000D_
    top:20px;_x000D_
    left:0px;_x000D_
    width:320px;_x000D_
    background: black;_x000D_
    color: green;_x000D_
    height: 64px;_x000D_
}_x000D_
.wrapper div{_x000D_
    display: inline;_x000D_
    width: 50%;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    line-height: 64px_x000D_
}_x000D_
.horizontalScroll{color: orange}
_x000D_
<div class=wrapper>_x000D_
    <div class=horizontalScroll>Scroll (x,y) to </div>_x000D_
    <div class=verticalScroll>see me in action</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to trigger SIGUSR1 and SIGUSR2?

terminal 1

dd if=/dev/sda of=debian.img

terminal 2

killall -SIGUSR1 dd

go back to terminal 1

34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s

jQuery - Appending a div to body, the body is the object?

Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

var holdyDiv = $('<div />').appendTo('body');
holdyDiv.attr('id', 'holdy');

.appendTo() reference: http://api.jquery.com/appendTo/

Alernatively you can try this also.

$('<div />', { id: 'holdy' }).appendTo('body');
               ^
             (Here you can specify any attribute/value pair you want)

Why won't eclipse switch the compiler to Java 8?

It cause eclipse kepler SR1 does not support new Java™ 8 language enhancements like lambda expression.

From information here: http://www.eclipse.org/downloads/java8/
I think you should use kepler SR2 with support plugin, or change to Eclipse Luna.


Updated link 16/09/2016: https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler

Comparing two files in linux terminal

Here is my solution for this :

mkdir temp
mkdir results
cp /usr/share/dict/american-english ~/temp/american-english-dictionary
cp /usr/share/dict/british-english ~/temp/british-english-dictionary
cat ~/temp/american-english-dictionary | wc -l > ~/results/count-american-english-dictionary
cat ~/temp/british-english-dictionary | wc -l > ~/results/count-british-english-dictionary
grep -Fxf ~/temp/american-english-dictionary ~/temp/british-english-dictionary > ~/results/common-english
grep -Fxvf ~/results/common-english ~/temp/american-english-dictionary > ~/results/unique-american-english
grep -Fxvf ~/results/common-english ~/temp/british-english-dictionary > ~/results/unique-british-english

PHP cURL not working - WAMP on Windows 7 64 bit

Ensure that your system PATH environment variable contains the directory in which PHP is installed. Stop the Apache server and restart it once more. With luck CURL will start working.

How to find whether a number belongs to a particular range in Python?

To check whether some number n is in the inclusive range denoted by the two number a and b you do either

if   a <= n <= b:
    print "yes"
else:
    print "no"

use the replace >= and <= with > and < to check whether n is in the exclusive range denoted by a and b (i.e. a and b are not themselves members of the range).

Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.

What is more efficient? Using pow to square or just multiply it with itself?

I have been busy with a similar problem, and I'm quite puzzled by the results. I was calculating x?³/² for Newtonian gravitation in an n-bodies situation (acceleration undergone from another body of mass M situated at a distance vector d) : a = M G d*(d²)?³/² (where d² is the dot (scalar) product of d by itself) , and I thought calculating M*G*pow(d2, -1.5) would be simpler than M*G/d2/sqrt(d2)

The trick is that it is true for small systems, but as systems grow in size, M*G/d2/sqrt(d2) becomes more efficient and I don't understand why the size of the system impacts this result, because repeating the operation on different data does not. It is as if there were possible optimizations as the system grow, but which are not possible with pow

enter image description here

how to set start value as "0" in chartjs?

If you need use it as a default configuration, just place min: 0 inside the node defaults.scale.ticks, as follows:

defaults: {
  global: {...},
  scale: {
    ...
    ticks: { min: 0 },
  }
},

Reference: https://www.chartjs.org/docs/latest/axes/

What's the difference between .bashrc, .bash_profile, and .environment?

According to Josh Staiger, Mac OS X's Terminal.app actually runs a login shell rather than a non-login shell by default for each new terminal window, calling .bash_profile instead of .bashrc.

He recommends:

Most of the time you don’t want to maintain two separate config files for login and non-login shells — when you set a PATH, you want it to apply to both. You can fix this by sourcing .bashrc from your .bash_profile file, then putting PATH and common settings in .bashrc.

To do this, add the following lines to .bash_profile:

if [ -f ~/.bashrc ]; then 
    source ~/.bashrc 
fi

Now when you login to your machine from a console .bashrc will be called.

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

How can I find my Apple Developer Team id and Team Agent Apple ID?

If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

enter image description here

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.

How to Apply Corner Radius to LinearLayout

Layout

<LinearLayout 
    android:id="@+id/linearLayout"
    android:layout_width="300dp"
    android:gravity="center"
    android:layout_height="300dp"
    android:layout_centerInParent="true"
    android:background="@drawable/rounded_edge">
 </LinearLayout>

Drawable folder rounded_edge.xml

<shape 
xmlns:android="http://schemas.android.com/apk/res/android">
    <solid 
        android:color="@android:color/darker_gray">
    </solid>
    <stroke 
         android:width="0dp" 
         android:color="#424242">
    </stroke>
    <corners 
         android:topLeftRadius="100dip"
         android:topRightRadius="100dip"
         android:bottomLeftRadius="100dip"
         android:bottomRightRadius="100dip">
    </corners>
</shape>

What's the complete range for Chinese characters in Unicode?

The Unicode code blocks that the others answers gave certainly cover most of the Chinese Unicode characters, but check out some of these other code blocks, too.

CJK_UNIFIED_IDEOGRAPHS
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E
CJK_COMPATIBILITY
CJK_COMPATIBILITY_FORMS
CJK_COMPATIBILITY_IDEOGRAPHS
CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT
CJK_RADICALS_SUPPLEMENT
CJK_STROKES
CJK_SYMBOLS_AND_PUNCTUATION
ENCLOSED_CJK_LETTERS_AND_MONTHS
ENCLOSED_IDEOGRAPHIC_SUPPLEMENT
KANGXI_RADICALS
IDEOGRAPHIC_DESCRIPTION_CHARACTERS

See my fuller discussion here. And this site is convenient for browsing Unicode.

Download single files from GitHub

I used the following format, and I feel it's important to inform about the path.

https://github.com/user/repository/raw/branch/filename

^^^the above is not very complete in my mind

https://github.com/<user>/<repoROOTname>/blob/master/<path>/<filename>?raw=true

some said raw.github.com or raw instead of blob, but the 2nd line works for me and I hope will help others...

How to add icons to React Native app

You can import react-native-elements and use the font-awesome icons to your react native app

Install

npm install --save react-native-elements

then import that where you want to use icons

import { Icon } from 'react-native-elements'

Use it like

render() {
   return(
    <Icon
      reverse
      name='ios-american-football'
      type='ionicon'
      color='#517fa4'
    />
 );
}

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

"Stack overflow in line 0" on Internet Explorer

I had this problem, and I solved it. There was an attribute in the <%@ Page tag named MaintainScrollPositionOnPostback and after removing it, the error disapeared. I added it before to prevent scrolling after each postback.

What is the difference between precision and scale?

Scale is the number of digit after the decimal point (or colon depending your locale)

Precision is the total number of significant digits

scale VS precision

YouTube embedded video: set different thumbnail

No. Most YouTube videos only have one pre-generated "poster" thumbnail (480x360). They usually have several other lower resolution thumbnails (120x90). So even if there were an embedding parameter to use an alternate poster image (which there isn't), it's result wouldn't be acceptable.

You can theoretically use the Player API to seek the video to whatever location you want, but this would be a major hack for a minor result.

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Adding placeholder text to textbox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace App_name
{
   public class CustomTextBox : TextBox
    {
        private string Text_ = "";
        public CustomTextBox() : base()
        {}

        public string setHint
        {
            get { return Text_; }
            set { Text_ = value; }
        }
        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);
            if (Text_.Equals(this.Text))
                this.Clear();
        }
        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            if (String.IsNullOrWhiteSpace(this.Text))
                this.Text = Text_;
        }
    }
}
>    xmlns:local="clr-namespace:app_name"
>  <local:CustomTextBox
>                 x:Name="id_number_txt"
>                 Width="240px"
>                 Height="auto"/>

Get difference between two lists

The existing solutions all offer either one or the other of:

  • Faster than O(n*m) performance.
  • Preserve order of input list.

But so far no solution has both. If you want both, try this:

s = set(temp2)
temp3 = [x for x in temp1 if x not in s]

Performance test

import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000)
print timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000)
print timeit.timeit('[item for item in temp1 if item not in temp2]', init, number = 100000)

Results:

4.34620224079 # ars' answer
4.2770634955  # This answer
30.7715615392 # matt b's answer

The method I presented as well as preserving order is also (slightly) faster than the set subtraction because it doesn't require construction of an unnecessary set. The performance difference would be more noticable if the first list is considerably longer than the second and if hashing is expensive. Here's a second test demonstrating this:

init = '''
temp1 = [str(i) for i in range(100000)]
temp2 = [str(i * 2) for i in range(50)]
'''

Results:

11.3836875916 # ars' answer
3.63890368748 # this answer (3 times faster!)
37.7445402279 # matt b's answer

How to convert empty spaces into null values, using SQL Server?

Did you try this?

UPDATE table 
SET col1 = NULL 
WHERE col1 = ''

As the commenters point out, you don't have to do ltrim() or rtrim(), and NULL columns will not match ''.

File.Move Does Not Work - File Already Exists

What you need is:

if (!File.Exists(@"c:\test\Test\SomeFile.txt")) {
    File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
}

or

if (File.Exists(@"c:\test\Test\SomeFile.txt")) {
    File.Delete(@"c:\test\Test\SomeFile.txt");
}
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");

This will either:

  • If the file doesn't exist at the destination location, successfully move the file, or;
  • If the file does exist at the destination location, delete it, then move the file.

Edit: I should clarify my answer, even though it's the most upvoted! The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires. So, your second parameter should be c:\test\Test\SomeFile.txt.

Get Memory Usage in Android

Since the OP asked about CPU usage AND memory usage (accepted answer only shows technique to get cpu usage), I'd like to recommend the ActivityManager class and specifically the accepted answer from this question: How to get current memory usage in android?

Simple way to compare 2 ArrayLists

As far as I understand it correctly, I think it's easiest to work with 4 lists: - Your sourceList - Your destinationList - A removedItemsList - A newlyAddedItemsList

How do I get LaTeX to hyphenate a word that contains a dash?

I answered something similar here: LaTeX breaking up too many words

I said:

you should set a hyphenation penalty somewhere in your preamble:

\hyphenpenalty=750

The value of 750 suited my needs for a two column layout on letter paper (8.5x11 in) with a 12 pt font. Adjust the value to suit your needs. The higher the number, the less hyphenation will occur. You may also want to have a look at the hyphenatpackage, it provides a bit more than just hyphenation penalty

JPA entity without id

I know that JPA entities must have primary key but I can't change database structure due to reasons beyond my control.

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?

If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id in JPA.

If your table has no unique columns at all, you can use all of the columns as the Id.

And if your table has some id but your entity doesn't, make it an Embeddable.

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

illegal character in path

try

"C:/Program Files (x86)/test software/myapp/demo.exe"

How to automatically generate unique id in SQL like UID12345678?

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

Download a specific tag with Git

You can use git archive to download a tar ball for a given tag or commit id:

git archive --format=tar --remote=[hostname]:[path to repo] [tag name] > tagged_version.tar

You can also export a zip archive of a tag.

  1. List tags:

    git tag
    
    0.0.1
    0.1.0
    
  2. Export a tag:

    git archive -o /tmp/my-repo-0.1.0.zip --prefix=my-repo-0.1.0/ 0.1.0
    
  3. Notes:

    • You do not need to specify the format. It will be picked up by the output file name.
    • Specifying the prefix will make your code export to a directory (if you include a trailing slash).

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

jQuery adding 2 numbers from input fields

Use this code for adding two numbers by using jquery

<!DOCTYPE html>
    <html lang="en-US">
    <head>
        <title>HTML Tutorial</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <meta charset="windows-1252">
    <script>

    $(document).ready(function(){
        $("#submit").on("click", function(){
        var a = parseInt($('#a').val());
        var b = parseInt($('#b').val());
           var sum = a + b;
            alert(sum);
        })
    })
    </script>
    </head>
    <body>
       <input type="text" id="a" name="option">
       <input type="text" id="b" name="task">
    <input id="submit" type="button" value="press me">

    </body>

    </html>

How do I convert a decimal to an int in C#?

decimal d = 2;
int i = (int) d;

This should work just fine.

HTML/CSS: Making two floating divs the same height

This works for me in IE 7, FF 3.5, Chrome 3b, Safari 4 (Windows).

Also works in IE 6 if you uncomment the clearer div at the bottom. Edit: as Natalie Downe said, you can simply add width: 100%; to #container instead.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <style type="text/css">
        #container {
            overflow: hidden;
            border: 1px solid black;
            background-color: red;
        }
        #left-col {
            float: left;
            width: 50%;
            background-color: white;
        }
        #right-col {
            float: left;
            width: 50%;
            margin-right: -1px; /* Thank you IE */
        }
    </style>
</head>
<body>
    <div id='container'>
        <div id='left-col'>
            Test content<br />
            longer
        </div>
        <div id='right-col'>
            Test content
        </div>
        <!--div style='clear: both;'></div-->
    </div>
</body>
</html>

I don't know a CSS way to vertically center the text in the right div if the div isn't of fixed height. If it is, you can set the line-height to the same value as the div height and put an inner div containing your text with display: inline; line-height: 110%.

Can anyone explain what JSONP is, in layman terms?

Say you had some URL that gave you JSON data like:

{'field': 'value'}

...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback). Then it would return:

myCallback({'field':'value'})

...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction and execute this script, it will be called with the data from the URL.

The cool thing about this is: you can create a script tag and use your URL (complete with callback parameter) as the src attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).

This is what jQuery does when you make an ajax request (using .ajax with 'jsonp' as the value for the dataType property). E.g.

$.ajax({
  url: 'http://example.com/datasource',
  dataType: 'jsonp',
  success: function(data) {
    // your code to handle data here
  }
});

Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.

Unable to run Java GUI programs with Ubuntu

Use JFrame instead of Frame. And do not extend from JFrame. Just write a class that has a JFrame property named gui, which configures this JFrame with the available methods, because it is better style doing it like this. Extending here is wrong the use of OOP.

MySQL: Convert INT to DATETIME

select from_unixtime(column,'%Y-%m-%d') from myTable; 

how to display full stored procedure code?

You can also get by phpPgAdmin if you are configured it in your system,

Step 1: Select your database

Step 2: Click on find button

Step 3: Change search option to functions then click on Find.

You will get the list of defined functions.You can search functions by name also, hope this answer will help others.

How can I make an image transparent on Android?

Image alpha sets just opacity to ImageView which makes Image blurry, try adding tint attribute in ImageView

 android:tint="#66000000"

It can also be done programatically :

imageView.setColorFilter(R.color.transparent);

where you need to define transparent color in your colors.xml

<color name="transparent">#66000000</color>

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

Installing PIL with pip

I take it you're on Mac. See How can I install PIL on mac os x 10.7.2 Lion

If you use [homebrew][], you can install the PIL with just brew install pil. You may then need to add the install directory ($(brew --prefix)/lib/python2.7/site-packages) to your PYTHONPATH, or add the location of PIL directory itself in a file called PIL.pth file in any of your site-packages directories, with the contents:

/usr/local/lib/python2.7/site-packages/PIL

(assuming brew --prefix is /usr/local).

Alternatively, you can just download/build/install it from source:

# download
curl -O -L http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
# extract
tar -xzf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
# build and install
python setup.py build
sudo python setup.py install
# or install it for just you without requiring admin permissions:
# python setup.py install --user

I ran the above just now (on OSX 10.7.2, with XCode 4.2.1 and System Python 2.7.1) and it built just fine, though there is a possibility that something in my environment is non-default.

[homebrew]: http://mxcl.github.com/homebrew/ "Homebrew"

How to update one file in a zip archive

7zip (7za) can be used for adding/updating files/directories nicely:

Example: Replacing (regardless of file date) the MANIFEST.MF file in a JAR file. The /source/META-INF directory contains the MANIFEST.MF file that you want to put into the jar (zip):

7za a /tmp/file.jar /source/META-INF/

Only update (does not replace the target if the source is older)

7za u /tmp/file.jar /source/META-INF/

XAMPP on Windows - Apache not starting

I had my Apache service not start same as MySQL one. Please follow these steps if none of above tips works :

  1. Open regedit.exe on any windows this available . Run as administrator. (Only on windows 7 and later editions )
    1. Go to local machine/system/controlset001/services
    2. Find and delete folders of services apache and mysql .
    3. Uninstall xampp . Delete folder of xampp.
    4. Restart computer and reinstall Xampp . After that your Xampp apache and Mysql should work.

Note: Ports 80 and 443 must be unused by any program. 
      If it is in use . Just edit ports. There is a lot of tutorials about that .

TortoiseGit-git did not exit cleanly (exit code 1)

This is Just because you have made changes on your remote repository which was not pulled on your local repository.

To resolve simply 1. Pull from remote repository to local repository. It will not undo any changes locally. It will just update local repository. 2. Now push the changes to remote repository. It will work

Converting a sentence string to a string array of words in Java

I already did post this answer somewhere, i will do it here again. This version doesn't use any major inbuilt method. You got the char array, convert it into a String. Hope it helps!

import java.util.Scanner;

public class SentenceToWord 
{
    public static int getNumberOfWords(String sentence)
    {
        int counter=0;
        for(int i=0;i<sentence.length();i++)
        {
            if(sentence.charAt(i)==' ')
            counter++;
        }
        return counter+1;
    }

    public static char[] getSubString(String sentence,int start,int end) //method to give substring, replacement of String.substring() 
    {
        int counter=0;
        char charArrayToReturn[]=new char[end-start];
        for(int i=start;i<end;i++)
        {
            charArrayToReturn[counter++]=sentence.charAt(i);
        }
        return charArrayToReturn;
    }

    public static char[][] getWordsFromString(String sentence)
    {
        int wordsCounter=0;
        int spaceIndex=0;
        int length=sentence.length();
        char wordsArray[][]=new char[getNumberOfWords(sentence)][]; 
        for(int i=0;i<length;i++)
        {
            if(sentence.charAt(i)==' ' || i+1==length)
            {
            wordsArray[wordsCounter++]=getSubString(sentence, spaceIndex,i+1); //get each word as substring
            spaceIndex=i+1; //increment space index
            }
        }
        return  wordsArray; //return the 2 dimensional char array
    }


    public static void main(String[] args) 
    {
    System.out.println("Please enter the String");
    Scanner input=new Scanner(System.in);
    String userInput=input.nextLine().trim();
    int numOfWords=getNumberOfWords(userInput);
    char words[][]=new char[numOfWords+1][];
    words=getWordsFromString(userInput);
    System.out.println("Total number of words found in the String is "+(numOfWords));
    for(int i=0;i<numOfWords;i++)
    {
        System.out.println(" ");
        for(int j=0;j<words[i].length;j++)
        {
        System.out.print(words[i][j]);//print out each char one by one
        }
    }
    }

}

How to write PNG image to string with the PIL?

For Python3 it is required to use BytesIO:

from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")

byte_io = BytesIO()

image.save(byte_io, 'PNG')

Read more: http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image

How to set underline text on textview?

Simple and easy way to display underline in TextView is:

yourTextView.getPaint().setUnderlineText(true);

And if you want to remove underlining for that view, you can write below code:

yourTextView.getPaint().setUnderlineText(false);

It will work even though you set android:textAllCaps="true"

What are .a and .so files?

Wikipedia is a decent source for this info.

To learn about static library files like .a read Static libarary

To learn about shared library files like .so read Library_(computing)#Shared_libraries On this page, there is also useful info in the File naming section.

While loop in batch

set /a countfiles-=%countfiles%

This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:

set /a countfiles-=1

I'm not sure if the for loop will work, better try something like this:

:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop

What is the difference between YAML and JSON?

This question is 6 years old, but strangely, none of the answers really addresses all four points (speed, memory, expressiveness, portability).

Speed

Obviously this is implementation-dependent, but because JSON is so widely used, and so easy to implement, it has tended to receive greater native support, and hence speed. Considering that YAML does everything that JSON does, plus a truckload more, it's likely that of any comparable implementations of both, the JSON one will be quicker.

However, given that a YAML file can be slightly smaller than its JSON counterpart (due to fewer " and , characters), it's possible that a highly optimised YAML parser might be quicker in exceptional circumstances.

Memory

Basically the same argument applies. It's hard to see why a YAML parser would ever be more memory efficient than a JSON parser, if they're representing the same data structure.

Expressiveness

As noted by others, Python programmers tend towards preferring YAML, JavaScript programmers towards JSON. I'll make these observations:

  • It's easy to memorise the entire syntax of JSON, and hence be very confident about understanding the meaning of any JSON file. YAML is not truly understandable by any human. The number of subtleties and edge cases is extreme.
  • Because few parsers implement the entire spec, it's even harder to be certain about the meaning of a given expression in a given context.
  • The lack of comments in JSON is, in practice, a real pain.

Portability

It's hard to imagine a modern language without a JSON library. It's also hard to imagine a JSON parser implementing anything less than the full spec. YAML has widespread support, but is less ubiquitous than JSON, and each parser implements a different subset. Hence YAML files are less interoperable than you might think.

Summary

JSON is the winner for performance (if relevant) and interoperability. YAML is better for human-maintained files. HJSON is a decent compromise although with much reduced portability. JSON5 is a more reasonable compromise, with well-defined syntax.

Oracle: Import CSV file

Somebody asked me to post a link to the framework! that I presented at Open World 2012. This is the full blog post that demonstrates how to architect a solution with external tables.

How to display a confirmation dialog when clicking an <a> link?

Most browsers don't display the custom message passed to confirm().

With this method, you can show a popup with a custom message if your user changed the value of any <input> field.

You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  let unsaved = false;_x000D_
  // detect changes in all input fields and set the 'unsaved' flag_x000D_
  $(":input").change(() => unsaved = true);_x000D_
  // trigger popup on click_x000D_
  $('.dangerous-link').click(function() {_x000D_
    if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {_x000D_
      return; // user didn't confirm_x000D_
    }_x000D_
    // either there are no unsaved changes or the user confirmed_x000D_
    window.location.href = $(this).data('destination');_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<input type="text" placeholder="Nuclear code here" />_x000D_
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">_x000D_
    Launch nuke!_x000D_
</a>
_x000D_
_x000D_
_x000D_

Try changing the input value in the example to get a preview of how it works.

How do I make a composite key with SQL Server Management Studio?

Open up the table designer in SQL Server Management Studio (right-click table and select 'Design')

Holding down the Ctrl key highlight two or more columns in the left hand table margin

Hit the little 'Key' on the standard menu bar at the top

You're done..

:-)

javascript object max size limit

Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:

var str;

document.getElementById('theButton').onclick = function() {
  var build, counter;

  if (!str) {
    str = "0123456789";
    build = [];
    for (counter = 0; counter < 900; ++counter) {
      build.push(str);
    }
    str = build.join("");
  }
  else {
    str += str;
  }
  display("str.length = " + str.length);
};

Live copy

Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:

str.length = 9000
str.length = 18000
str.length = 36000
str.length = 72000
str.length = 144000
str.length = 288000
str.length = 576000
str.length = 1152000
str.length = 2304000
str.length = 4608000
str.length = 9216000
str.length = 18432000

...and I'm quite sure I could got a lot higher than that.

So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET which means you're running into the length limit of a GET request, because GET parameters are put in the query string. Details here.

You need to switch to using POST instead. In a POST request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.

How can I convert string to double in C++?

One of the most elegant solution to this problem is to use boost::lexical_cast as @Evgeny Lazin mentioned.

For loop in multidimensional javascript array

An efficient way to loop over an Array is the built-in array method .map()

For a 1-dimensional array it would look like this:

function HandleOneElement( Cuby ) {
   Cuby.dimension
   Cuby.position_x
   ...
}
cubes.map(HandleOneElement) ; // the map function will pass each element

for 2-dimensional array:

cubes.map( function( cubeRow ) { cubeRow.map( HandleOneElement ) } )

for an n-dimensional array of any form:

Function.prototype.ArrayFunction = function(param) {
  if (param instanceof Array) {
    return param.map( Function.prototype.ArrayFunction, this ) ;
  }
  else return (this)(param) ;
}
HandleOneElement.ArrayFunction(cubes) ;

jQuery Force set src attribute for iframe

While generating the links set the target to the iframes name property and you probably wont have to deal with jquery at all.

<a href="inventory.aspx" target="contentframe"  title="Title Inventory">
<iframe id="iframe1" name="contentframe"  ></iframe>