Programs & Examples On #Oledb

OLE DB (Object Linking and Embedding, Database, sometimes written as OLEDB or OLE-DB) is an API designed by Microsoft for accessing data from a variety of sources in a uniform manner.

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

I had no luck until I installed the 2010 version link here: https://www.microsoft.com/en-us/download/details.aspx?id=13255

I tried installing the 32 bit version, it still errored, so I uninstalled it and installed the 64 bit version and it started working.

DataAdapter.Fill(Dataset)

You need to do this:

OleDbConnection connection = new OleDbConnection(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();

string query = 
    @"SELECT tbl_Computer.*,  tbl_Besitzer.*
    FROM tbl_Computer 
    INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
    WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection); 
DBAdapter.Fill(DS);

By the way, what is this DataSet1? This should be "DataSet".

How to import an Excel file into SQL Server?

You can also use OPENROWSET to import excel file in sql server.

SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                        'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
                        'SELECT * FROM [Data$]')

How to connect to a MS Access file (mdb) using C#?

Here's how to use a Jet OLEDB or Ace OLEDB Access DB:

using System.Data;
using System.Data.OleDb;

string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=C:\myPath\myFile.mdb;" +                                    
                           "Persist Security Info=True;" +
                           "Jet OLEDB:Database Password=myPassword;";
try
{
    // Open OleDb Connection
    OleDbConnection myConnection = new OleDbConnection();
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    // Execute Queries
    OleDbCommand cmd = myConnection.CreateCommand();
    cmd.CommandText = "SELECT * FROM `myTable`";
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete

    // Load the result into a DataTable
    DataTable myDataTable = new DataTable();
    myDataTable.Load(reader);
}
catch (Exception ex)
{
    Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I ran into this issue with my desktop application ('Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine). I did not have the option to build as a 32 bit app. Hoping this would help others in the same situation.

I did the following and the issue went away:

  1. Installed the 64 bit version of Microsoft Access Database Engine 2010 Redistributable, as suggested by neo

  2. Changed my provider to Microsoft.ACE.OLEDB.12.0

how to resolve DTS_E_OLEDBERROR. in ssis

Solution for this issue is:

  1. Create another connection manager for your excel or flat files else you just have to pass variable values in connection string:

  2. Right Click on Connection Manager>>properties>>Expression >>Select "ConnectionString" from drop down and pass the input variable like path , filename ..

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

Note: I am running SQL 2016 Developer 64bit, Office 2016 64bit.

I had the same issue and solved it by downloading the following:

  1. Download and install this: https://www.microsoft.com/en-us/download/details.aspx?id=54920

  2. Whatever file you are trying to access/import, make sure you select it as a Office 2010 file (even though it might be a Office 2016 file).

It works.

Source

Microsoft.ACE.OLEDB.12.0 provider is not registered

I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.

after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.

Import Excel to Datagridview

try this following snippet, its working fine.

private void button1_Click(object sender, EventArgs e)
{
     try
     {
             OpenFileDialog openfile1 = new OpenFileDialog();
             if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
             {
                   this.textBox1.Text = openfile1.FileName;
             }
             {
                   string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
                   OleDbConnection conn = new OleDbConnection(pathconn);
                   OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
                   DataTable dt = new DataTable();
                   MyDataAdapter.Fill(dt);
                   dataGridView1.DataSource = dt;
             }
      }
      catch { }
}

Optimal way to Read an Excel file (.xls/.xlsx)

I realize this question was asked nearly 7 years ago but it's still a top Google search result for certain keywords regarding importing excel data with C#, so I wanted to provide an alternative based on some recent tech developments.

Importing Excel data has become such a common task to my everyday duties, that I've streamlined the process and documented the method on my blog: best way to read excel file in c#.

I use NPOI because it can read/write Excel files without Microsoft Office installed and it doesn't use COM+ or any interops. That means it can work in the cloud!

But the real magic comes from pairing up with NPOI Mapper from Donny Tian because it allows me to map the Excel columns to properties in my C# classes without writing any code. It's beautiful.

Here is the basic idea:

I create a .net class that matches/maps the Excel columns I'm interested in:

        class CustomExcelFormat
        {
            [Column("District")]
            public int District { get; set; }

            [Column("DM")]
            public string FullName { get; set; }

            [Column("Email Address")]
            public string EmailAddress { get; set; }

            [Column("Username")]
            public string Username { get; set; }

            public string FirstName
            {
                get
                {
                    return Username.Split('.')[0];
                }
            }

            public string LastName
            {
                get
                {
                    return Username.Split('.')[1];
                }
            }
        }

Notice, it allows me to map based on column name if I want to!

Then when I process the excel file all I need to do is something like this:

        public void Execute(string localPath, int sheetIndex)
        {
            IWorkbook workbook;
            using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
            {
                workbook = WorkbookFactory.Create(file);
            }

            var importer = new Mapper(workbook);
            var items = importer.Take<CustomExcelFormat>(sheetIndex);
            foreach(var item in items)
            {
                var row = item.Value;
                if (string.IsNullOrEmpty(row.EmailAddress))
                    continue;

                UpdateUser(row);
            }

            DataContext.SaveChanges();
        }

Now, admittedly, my code does not modify the Excel file itself. I am instead saving the data to a database using Entity Framework (that's why you see "UpdateUser" and "SaveChanges" in my example). But there is already a good discussion on SO about how to save/modify a file using NPOI.

Using Excel OleDb to get sheet names IN SHEET ORDER

This worked for me. Stolen from here: How do you get the name of the first page of an excel workbook?

object opt = System.Reflection.Missing.Value;
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(WorkBookToOpen,
                                         opt, opt, opt, opt, opt, opt, opt,
                                         opt, opt, opt, opt, opt, opt, opt);
Excel.Worksheet worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
string firstSheetName = worksheet.Name;

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

Received this same error on SQL Server 2017 trying to link to Oracle 12c. We were able to use Oracle's SQL Developer to connect to the source database, but the linked server kept throwing the 7302 error.

In the end, we stopped all SQL Services, then re-installed the ODAC components. Started the SQL Services back up and voila!

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

For me, I was accessing my XLS file from a network share. Moving the file for my connection manager to a local folder fixed the issue.

what is the difference between OLE DB and ODBC data sources?

According to ADO: ActiveX Data Objects, a book by Jason T. Roff, published by O'Reilly Media in 2001 (excellent diagram here), he says precisely what MOZILLA said.

(directly from page 7 of that book)

  • ODBC provides access only to relational databases
  • OLE DB provides the following features
    • Access to data regardless of its format or location
    • Full access to ODBC data sources and ODBC drivers

So it would seem that OLE DB interacts with SQL-based datasources THRU the ODBC driver layer.

alt text

I'm not 100% sure this image is correct. The two connections I'm not certain about are ADO.NET thru ADO C-api, and OLE DB thru ODBC to SQL-based data source (because in this diagram the author doesn't put OLE DB's access thru ODBC, which I believe is a mistake).

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

How can I export data to an Excel file

With Aspose.Cells library for .NET, you can easily export data of specific rows and columns from one Excel document to another. The following code sample shows how to do this in C# language.

// Open the source excel file.
Workbook srcWorkbook = new Workbook("Source_Workbook.xlsx");

// Create the destination excel file.
Workbook destWorkbook = new Workbook();
   
// Get the first worksheet of the source workbook.
Worksheet srcWorksheet = srcWorkbook.Worksheets[0];

// Get the first worksheet of the destination workbook.
Worksheet desWorksheet = destWorkbook.Worksheets[0];

// Copy the second row of the source Workbook to the first row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 1, 0);

// Copy the fourth row of the source Workbook to the second row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 3, 1);

// Save the destination excel file.
destWorkbook.Save("Destination_Workbook.xlsx");

Copy Rows Data from one Excel Document to another

The following blog post explains in detail how to export data from different sources to an Excel document.
https://blog.conholdate.com/2020/08/10/export-data-to-excel-in-csharp/

Python dict how to create key or append an element to key?

dictionary['key'] = dictionary.get('key', []) + list_to_append

What's the purpose of META-INF?

Just to add to the information here, in case of a WAR file, the META-INF/MANIFEST.MF file provides the developer a facility to initiate a deploy time check by the container which ensures that the container can find all the classes your application depends on. This ensures that in case you missed a JAR, you don't have to wait till your application blows at runtime to realize that it's missing.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Java: is there a map function?

There is no notion of a function in the JDK as of java 6.

Guava has a Function interface though and the
Collections2.transform(Collection<E>, Function<E,E2>)
method provides the functionality you require.

Example:

// example, converts a collection of integers to their
// hexadecimal string representations
final Collection<Integer> input = Arrays.asList(10, 20, 30, 40, 50);
final Collection<String> output =
    Collections2.transform(input, new Function<Integer, String>(){

        @Override
        public String apply(final Integer input){
            return Integer.toHexString(input.intValue());
        }
    });
System.out.println(output);

Output:

[a, 14, 1e, 28, 32]

These days, with Java 8, there is actually a map function, so I'd probably write the code in a more concise way:

Collection<String> hex = input.stream()
                              .map(Integer::toHexString)
                              .collect(Collectors::toList);

Angular/RxJs When should I unsubscribe from `Subscription`

Since seangwright's solution (Edit 3) appears to be very useful, I also found it a pain to pack this feature into base component, and hint other project teammates to remember to call super() on ngOnDestroy to activate this feature.

This answer provide a way to set free from super call, and make "componentDestroyed$" a core of base component.

class BaseClass {
    protected componentDestroyed$: Subject<void> = new Subject<void>();
    constructor() {

        /// wrap the ngOnDestroy to be an Observable. and set free from calling super() on ngOnDestroy.
        let _$ = this.ngOnDestroy;
        this.ngOnDestroy = () => {
            this.componentDestroyed$.next();
            this.componentDestroyed$.complete();
            _$();
        }
    }

    /// placeholder of ngOnDestroy. no need to do super() call of extended class.
    ngOnDestroy() {}
}

And then you can use this feature freely for example:

@Component({
    selector: 'my-thing',
    templateUrl: './my-thing.component.html'
})
export class MyThingComponent extends BaseClass implements OnInit, OnDestroy {
    constructor(
        private myThingService: MyThingService,
    ) { super(); }

    ngOnInit() {
        this.myThingService.getThings()
            .takeUntil(this.componentDestroyed$)
            .subscribe(things => console.log(things));
    }

    /// optional. not a requirement to implement OnDestroy
    ngOnDestroy() {
        console.log('everything works as intended with or without super call');
    }

}

When should an IllegalArgumentException be thrown?

Treat IllegalArgumentException as a preconditions check, and consider the design principle: A public method should both know and publicly document its own preconditions.

I would agree this example is correct:

void setPercentage(int pct) {
    if( pct < 0 || pct > 100) {
         throw new IllegalArgumentException("bad percent");
     }
}

If EmailUtil is opaque, meaning there's some reason the preconditions cannot be described to the end-user, then a checked exception is correct. The second version, corrected for this design:

import com.someoneelse.EmailUtil;

public void scanEmail(String emailStr, InputStream mime) throws ParseException {
    EmailAddress parsedAddress = EmailUtil.parseAddress(emailStr);
}

If EmailUtil is transparent, for instance maybe it's a private method owned by the class under question, IllegalArgumentException is correct if and only if its preconditions can be described in the function documentation. This is a correct version as well:

/** @param String email An email with an address in the form [email protected]
 * with no nested comments, periods or other nonsense.
 */
public String scanEmail(String email)
  if (!addressIsProperlyFormatted(email)) {
      throw new IllegalArgumentException("invalid address");
  }
  return parseEmail(emailAddr);
}
private String parseEmail(String emailS) {
  // Assumes email is valid
  boolean parsesJustFine = true;
  // Parse logic
  if (!parsesJustFine) {
    // As a private method it is an internal error if address is improperly
    // formatted. This is an internal error to the class implementation.
    throw new AssertError("Internal error");
  }
}

This design could go either way.

  • If preconditions are expensive to describe, or if the class is intended to be used by clients who don't know whether their emails are valid, then use ParseException. The top level method here is named scanEmail which hints the end user intends to send unstudied email through so this is likely correct.
  • If preconditions can be described in function documentation, and the class does not intent for invalid input and therefore programmer error is indicated, use IllegalArgumentException. Although not "checked" the "check" moves to the Javadoc documenting the function, which the client is expected to adhere to. IllegalArgumentException where the client can't tell their argument is illegal beforehand is wrong.

A note on IllegalStateException: This means "this object's internal state (private instance variables) is not able to perform this action." The end user cannot see private state so loosely speaking it takes precedence over IllegalArgumentException in the case where the client call has no way to know the object's state is inconsistent. I don't have a good explanation when it's preferred over checked exceptions, although things like initializing twice, or losing a database connection that isn't recovered, are examples.

How can I embed a YouTube video on GitHub wiki pages?

Complete Example

Expanding on @MGA's Answer

While it's not possible to embed a video in Markdown you can "fake it" by including a valid linked image in your markup file, using this format:

[![IMAGE ALT TEXT](http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](http://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE "Video Title")

Explanation of the Markdown

If this markup snippet looks complicated, break it down into two parts:

an image
![image alt text](https://example.com/link-to-image)
wrapped in a link
[link text](https://example.com/my-link "link title")

Example using Valid Markdown and YouTube Thumbnail:

Everything Is AWESOME

We are sourcing the thumbnail image directly from YouTube and linking to the actual video, so when the person clicks the image/thumbnail they will be taken to the video.

Code:

[![Everything Is AWESOME](https://img.youtube.com/vi/StTqXEQ2l-Y/0.jpg)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

OR If you want to give readers a visual cue that the image/thumbnail is actually a playable video, take your own screenshot of the video in YouTube and use that as the thumbnail instead.

Example using Screenshot with Video Controls as Visual Cue:

Everything Is AWESOME

Code:

[![Everything Is AWESOME](http://i.imgur.com/Ot5DWAW.png)](https://youtu.be/StTqXEQ2l-Y?t=35s "Everything Is AWESOME")

 Clear Advantages

While this requires a couple of extra steps (a) taking the screenshot of the video and (b) uploading it so you can use the image as your thumbnail it does have 3 clear advantages:

  1. The person reading your markdown (or resulting html page) has a visual cue telling them they can watch the video (video controls encourage clicking)
  2. You can chose a specific frame in the video to use as the thumbnail (thus making your content more engaging)
  3. You can link to a specific time in the video from which play will start when the linked-image is clicked. (in our case from 35 seconds)

Taking and uploading a screenshot takes a few seconds but has a big payoff.

Works Everywhere!

Since this is standard markdown, it works everywhere. try it on GitHub, Reddit, Ghost, and here on Stack Overflow.

Vimeo

This approach also works with Vimeo videos

Example

Little red riding hood

Code

[![Little red riding hood](http://i.imgur.com/7YTMFQp.png)](https://vimeo.com/3514904 "Little red riding hood - Click to Watch!")

Notes:

Cannot get a text value from a numeric cell “Poi”

Using the DataFormatter this issue is resolved. Thanks to "Gagravarr" for the initial post.

DataFormatter formatter = new DataFormatter();

String empno = formatter.formatCellValue(cell0);

How to install and run phpize

For ubuntu 14.04LTS with php 7, issue:

sudo apt-get install php-dev

Then install:

pecl install memcache

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

How can I specify a branch/tag when adding a Git submodule?

The only effect of choosing a branch for a submodule is that, whenever you pass the --remote option in the git submodule update command line, Git will check out in detached HEAD mode (if the default --checkout behavior is selected) the latest commit of that selected remote branch.

You must be particularly careful when using this remote branch tracking feature for Git submodules if you work with shallow clones of submodules. The branch you choose for this purpose in submodule settings IS NOT the one that will be cloned during git submodule update --remote. If you pass also the --depth parameter and you do not instruct Git about which branch you want to clone -- and actually you cannot in the git submodule update command line!! -- , it will implicitly behave like explained in the git-clone(1) documentation for git clone --single-branch when the explicit --branch parameter is missing, and therefore it will clone the primary branch only.

With no surprise, after the clone stage performed by the git submodule update command, it will finally try to check out the latest commit for the remote branch you previously set up for the submodule, and, if this is not the primary one, it is not part of your local shallow clone, and therefore it will fail with

fatal: Needed a single revision

Unable to find current origin/NotThePrimaryBranch revision in submodule path 'mySubmodule'

How can we draw a vertical line in the webpage?

<hr> is not from struts. It is just an HTML tag.

So, take a look here: http://www.microbion.co.uk/web/vertline.htm This link will give you a couple of tips.

Invalid attempt to read when no data is present

I would check to see if the SqlDataReader has rows returned first:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
   ...
}

How do you Encrypt and Decrypt a PHP String?

I'm late to the party, but searching for the correct way to do it I came across this page it was one of the top Google search returns, so I will like to share my view on the problem, which I consider it to be up to date at the time of writing this post (beginning of 2017). From PHP 7.1.0 the mcrypt_decrypt and mcrypt_encrypt is going to be deprecated, so building future proof code should use openssl_encrypt and openssl_decrypt

You can do something like:

$string_to_encrypt="Test";
$password="password";
$encrypted_string=openssl_encrypt($string_to_encrypt,"AES-128-ECB",$password);
$decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$password);

Important: This uses ECB mode, which isn't secure. If you want a simple solution without taking a crash course in cryptography engineering, don't write it yourself, just use a library.

You can use any other chipper methods as well, depending on your security need. To find out the available chipper methods please see the openssl_get_cipher_methods function.

Sort objects in an array alphabetically on one property of the array

You have to pass a function that accepts two parameters, compares them, and returns a number, so assuming you wanted to sort them by ID you would write...

objArray.sort(function(a,b) {
    return a.id-b.id;
});
// objArray is now sorted by Id

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

C# difference between == and Equals()

When == is used on an expression of type object, it'll resolve to System.Object.ReferenceEquals.

Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Setting locales in terminal resolved the issue for me. Open the terminal and

  1. Check if locale settings are missing

    > locale
    LANG=
    LC_COLLATE="C"
    LC_CTYPE="UTF-8"
    LC_MESSAGES="C"
    LC_MONETARY="C"
    LC_NUMERIC="C"
    LC_TIME="C"
    LC_ALL=
    
  2. Edit ~/.profile or ~/.bashrc

    export LANG=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    
  3. Run . ~/.profile or . ~/.bashrc to read from the file.

  4. Open a new terminal window and check that the locales are properly set

    > locale
    LANG="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_CTYPE="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_ALL="en_US.UTF-8"
    

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

php artisan serve 

this command get the env contents for the first time and if you update .env file need to restart it.

in my case my username and dbname is valid and php artisan migrate worked

but need to cntrl+c , to cancel php artisan serve , and run it again

php artisan serve

ArrayList or List declaration in Java

Possibly you can refer to this link http://docs.oracle.com/javase/6/docs/api/java/util/List.html

List is an interface.ArrayList,LinkedList etc are classes which implement list.Whenyou are using List Interface,you have to itearte elements using ListIterator and can move forward and backward,in the List where as in ArrayList Iterate using Iterator and its elements can be accessed unidirectional way.

How to get SQL from Hibernate Criteria API (*not* for logging)

This answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:

public static String toSql(Criteria criteria)
{
    String sql = "";
    Object[] parameters = null;
    try
    {
        CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
        SessionImpl sessionImpl = (SessionImpl) criteriaImpl.getSession();
        SessionFactoryImplementor factory = sessionImpl.getSessionFactory();
        String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
        OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister(implementors[0]);
        LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers();
        CriteriaLoader loader = new CriteriaLoader(persister, factory,
            criteriaImpl, implementors[0].toString(), loadQueryInfluencers);
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String) f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("translator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    if (sql != null)
    {
        int fromPosition = sql.indexOf(" from ");
        sql = "\nSELECT * " + sql.substring(fromPosition);

        if (parameters != null && parameters.length > 0)
        {
            for (Object val : parameters)
            {
                String value = "%";
                if (val instanceof Boolean)
                {
                    value = ((Boolean) val) ? "1" : "0";
                }
                else if (val instanceof String)
                {
                    value = "'" + val + "'";
                }
                else if (val instanceof Number)
                {
                    value = val.toString();
                }
                else if (val instanceof Class)
                {
                    value = "'" + ((Class) val).getCanonicalName() + "'";
                }
                else if (val instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss.SSS");
                    value = "'" + sdf.format((Date) val) + "'";
                }
                else if (val instanceof Enum)
                {
                    value = "" + ((Enum) val).ordinal();
                }
                else
                {
                    value = val.toString();
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
        " and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
        "!=").replaceAll("<", " < ").replaceAll(">", " > ");
}

How to change the display name for LabelFor in razor in mvc3?

Decorate the model property with the DisplayName attribute.

How to set a value to a file input in HTML?

As everyone else here has stated: You cannot upload just any file automatically with JavaScript.

HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.

What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...

function uploadFile (data) {
        // define data and connections
    var blob = new Blob([JSON.stringify(data)]);
    var url = URL.createObjectURL(blob);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'myForm.php', true);
    
        // define new form
    var formData = new FormData();
    formData.append('someUploadIdentifier', blob, 'someFileName.json');
        
        // action after uploading happens
    xhr.onload = function(e) {
        console.log("File uploading completed!");
    };
    
        // do the uploading
    console.log("File uploading started!");
    xhr.send(formData);
}

    // This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});

So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.

How to align an input tag to the center without specifying the width?

You can also use the tag, this works in divs and everything else:

<center><form></form></center>

This link will help you with the tag:

Why is the <center> tag deprecated in HTML?

How can I play sound in Java?

I wrote the following code that works fine. But I think it only works with .wav format.

public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
          Main.class.getResourceAsStream("/path/to/sounds/" + url));
        clip.open(inputStream);
        clip.start(); 
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}

Permanently add a directory to PYTHONPATH?

Shortest path between A <-> B is a straight line;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']

C++ - Hold the console window open?

I use std::getwchar() in my environment which is with mingw32 - gcc-4.6.2 compiler, Here is a sample code.

#include <iostream>
#include "Arithmetics.h"

using namespace std;

int main() {
    ARITHMETICS_H::testPriorities();

    cout << "Press any key to exit." << endl;
    getwchar();
    return 0;
}

What exactly does the .join() method do?

To append a string, just concatenate it with the + sign.

E.g.

>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world

join connects strings together with a separator. The separator is what you place right before the join. E.g.

>>> "-".join([a,b])
'Hello, -world'

Join takes a list of strings as a parameter.

Conda activate not working?

To use "conda activate" via Windows CMD, not the Anaconda Prompt:
(in response to okorng's question, although using the Anaconda Prompt is the preferred option)

First, we need to add the activate.bat script to your path:
Via CMD:

set PATH=%PATH%;<your_path_to_anaconda_installation>\Scripts

Or via Control Panel, open "User Accounts" and choose "Change my environment variables".

Then calling directly from Windows CMD:

activate <environment_name>

without using the prefix "conda".

(Tested on Windows 7 Enterprise with Anaconda3-5.2.0)

Query to convert from datetime to date mysql

Try to cast it as a DATE

SELECT CAST(orders.date_purchased AS DATE) AS DATE_PURCHASED

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

installing Microsoft Visual C++ 2010 SP1 Redistributable Fixed it

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

How to find and replace with regex in excel

As an alternative to Regex, running:

Sub Replacer()
   Dim N As Long, i As Long
   N = Cells(Rows.Count, "A").End(xlUp).Row

   For i = 1 To N
      If Left(Cells(i, "A").Value, 9) = "texts are" Then
         Cells(i, "A").Value = "texts are replaced"
      End If
   Next i
End Sub

will produce:

enter image description here

SVN undo delete before commit

The simplest solution I could find was to delete the parent directory from the working copy (with rm -rf, not svn delete), and then run svn update in the grandparent. Eg, if you deleted a/b/c, rm -rf a/b, cd a, svn up. That brings everything back. Of course, this is only a good solution if you have no other uncommitted changes in the parent directory that you want to keep.

Hopefully this page will be at the top of the results next time I google this question. It would be even better if someone suggested a cleaner method, of course.

Calculate the date yesterday in JavaScript

"Date.now() - 86400000" won't work on the Daylight Saving end day (which has 25 hours that day)

Another option is to use Closure:

var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));

Redirecting a page using Javascript, like PHP's Header->Location

The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.

You need to do the redirect in JavaScript too

$('.entry a:first').click(function()
{
    window.location.replace("http://www.google.com");
});

Two values from one input in python?

The easiest way that I found for myself was using split function with input Like you have two variable a,b

a,b=input("Enter two numbers").split()

That's it. there is one more method(explicit method) Eg- you want to take input in three values

value=input("Enter the line")
a,b,c=value.split()

EASY..

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long is equivalent to long int, just as short is equivalent to short int. A long int is a signed integral type that is at least 32 bits, while a long long or long long int is a signed integral type is at least 64 bits.

This doesn't necessarily mean that a long long is wider than a long. Many platforms / ABIs use the LP64 model - where long (and pointers) are 64 bits wide. Win64 uses the LLP64, where long is still 32 bits, and long long (and pointers) are 64 bits wide.

There's a good summary of 64-bit data models here.

long double doesn't guarantee much other than it will be at least as wide as a double.

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

Just use this website: http://ticons.fokkezb.nl :)

It makes it easier for you, and generates the correct sizes directly

Break or return from Java 8 stream forEach?

Either you need to use a method which uses a predicate indicating whether to keep going (so it has the break instead) or you need to throw an exception - which is a very ugly approach, of course.

So you could write a forEachConditional method like this:

public static <T> void forEachConditional(Iterable<T> source,
                                          Predicate<T> action) {
    for (T item : source) {
        if (!action.test(item)) {
            break;
        }
    }
}

Rather than Predicate<T>, you might want to define your own functional interface with the same general method (something taking a T and returning a bool) but with names that indicate the expectation more clearly - Predicate<T> isn't ideal here.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I just bumped into this problem, tried all above suggestions but still failed. Without repeat what have been suggested above, here are the things I (you) may be missing: In case you are using maven, likely you'll state the dependencies i.e:

<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.1.1</version>

Please be careful with the version. It must be compatible with the server instance you are running.

I solved my case by giving up on what maven dependencies provided and manually adding external jar from "%JAVA_HOME%\db\lib", the same source of my running server. In this case I'm testing using my Local.

So if you're testing with remote server instance, look for the derbyclient.jar that come with server package.

Best way to pass parameters to jQuery's .load()

As Davide Gualano has been told. This one

$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")

use GET method for sending the request, and this one

$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.

For example: url length limits the amount of sending data in GET method.

Global environment variables in a shell script

Run your script with .

. myscript.sh

This will run the script in the current shell environment.

export governs which variables will be available to new processes, so if you say

FOO=1
export BAR=2
./runScript.sh

then $BAR will be available in the environment of runScript.sh, but $FOO will not.

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

If you need a single quote inside of a string, since \' is undefined by the spec, use \u0027 see http://www.utf8-chartable.de/ for all of them

edit: please excuse my misuse of the word backticks in the comments. I meant backslash. My point here is that in the event you have nested strings inside other strings, I think it can be more useful and readable to use unicode instead of lots of backslashes to escape a single quote. If you are not nested however it truly is easier to just put a plain old quote in there.

How do I copy an entire directory of files into an existing directory using Python?

Here's a solution that's part of the standard library:

from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")

See this similar question.

Copy directory contents into a directory with python

Does delete on a pointer to a subclass call the base class destructor?

The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.

class A
{
    char *someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { delete[] someHeapMemory; }
};

class B
{
    A* APtr;
public:
    B() : APtr(new A()) {}
    ~B() { delete APtr; }
};

class C
{
    A Amember;
public:
    C() : Amember() {}
    ~C() {} // A is freed / destructed automatically.
};

int main()
{
    B* BPtr = new B();
    delete BPtr; // Calls ~B() which calls ~A() 
    C *CPtr = new C();
    delete CPtr;
    B b;
    C c;
} // b and c are freed/destructed automatically

In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.

auto_ptr, unique_ptr and shared_ptr etc... are great for making this lifetime management much easier:

class A
{
    shared_array<char> someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { } // someHeapMemory is delete[]d automatically
};

class B
{
    shared_ptr<A> APtr;
public:
    B() : APtr(new A()) {}
    ~B() {  } // APtr is deleted automatically
};

int main()
{
    shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically

Git Cherry-Pick and Conflicts

Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.

So you could something like this git cherry-pick --strategy=recursive -X theirs commit or git cherry-pick --strategy=recursive -X ours commit

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex (to find the entry's index) or Array#find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

Array#find:

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

Array#findIndex stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1 if the callback never returns a truthy value. Array#find also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined if the callback never returns a truthy value).

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

Android Percentage Layout Height

You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.

plot is not defined

If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:

import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()

In your solution

from matplotlib import*

This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as

from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()

Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.

I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

CSS rotate property in IE

Usefull Link for IE transform

This tool converts CSS3 Transform properties (which almost all modern browsers use) to the equivalent CSS using Microsoft's proprietary Visual Filters technology.

SQL WHERE.. IN clause multiple columns

If you want for one table then use following query

SELECT S.* 
FROM Student_info S
  INNER JOIN Student_info UT
    ON S.id = UT.id
    AND S.studentName = UT.studentName
where S.id in (1,2) and S.studentName in ('a','b')

and table data as follow

id|name|adde|city
1   a   ad  ca
2   b   bd  bd
3   a   ad  ad
4   b   bd  bd
5   c   cd  cd

Then output as follow

id|name|adde|city
1   a   ad  ca
2   b   bd  bd

Printing the last column of a line in a file

Not the actual issue here, but might help some one: I was doing awk "{print $NF}", note the wrong quotes. Should be awk '{print $NF}', so that the shell doesn't expand $NF.

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

A nice list of Maven Dependencies exists at : Spring Site The major artifacts needed are:

  1. spring-security-core
  2. Spring-security-web
  3. spring-security-config

Hashmap with Streams in Java 8 Streams to collect value of Map

If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst :

Optional<List> o = id1.entrySet()
                      .stream()
                      .filter( e -> e.getKey() == 1)
                      .map(Map.Entry::getValue)
                      .findFirst();

In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :

List<List> list = id1.entrySet()
                     .stream()
                     .filter(.. some predicate...)
                     .map(Map.Entry::getValue)
                     .collect(Collectors.toList());

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

I know this is a very old question, but this worked for me:

UPDATE TABLE SET FIELD1 =
CASE 
WHEN FIELD1 = Condition1 THEN 'Result1'
WHEN FIELD1 = Condition2 THEN 'Result2'
WHEN FIELD1 = Condition3 THEN 'Result3'
END;

Regards

Is there a way to make text unselectable on an HTML page?

If it looks bad you can use CSS to change the appearance of selected sections.

Auto refresh code in HTML using meta tags

It looks like you probably pasted this (or used a word processor like MS Word) using a kind of double-quotes that are not recognized by the browser. Please check that your code uses actual double-quotes like this one ", which is different from the following character:

Replace the meta tag with this one and try again:

<meta http-equiv="refresh" content="5" >

Collapse all methods in Visual Studio Code

Use Ctrl + K + 0 to fold all and Ctrl + K + J to unfold all.

Add 10 seconds to a Date

  1. you can use setSeconds method by getting seconds from today and just adding 10 seconds in it

    var today = new Date();
    today.setSeconds(today.getSeconds() + 10);
    
  2. You can add 10 *1000 milliseconds to the new date:

    var today = new Date(); 
    today = new Date(today.getTime() + 1000*10);
    
  3. You can use setTime:

    today.setTime(now.getTime() + 10000)
    

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

How to run vi on docker container?

If you actually want a small editor for simple housekeeping in a docker, use this in your Dockerfile:

RUN apt-get install -y busybox && ln -s /bin/busybox /bin/vi

I used it on an Ubuntu 18 based docker. (Of course you might need an RUN apt-get update before it but if you are making your own Docker file you probably already have that.)

LINQ to read XML

Or, if you want a more general approach - i.e. for nesting up to "levelN":

void Main()
{
    XElement rootElement = XElement.Load(@"c:\events\test.xml");

    Console.WriteLine(GetOutline(0, rootElement));  
}

private string GetOutline(int indentLevel, XElement element)
{
    StringBuilder result = new StringBuilder();

    if (element.Attribute("name") != null)
    {
        result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
    }

    foreach (XElement childElement in element.Elements())
    {
        result.Append(GetOutline(indentLevel + 1, childElement));
    }

    return result.ToString();
}

Execute a SQL Stored Procedure and process the results

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet

Try
   adapter = New System.Data.SqlClient.SqlDataAdapter
   adapter.SelectCommand = cmd
   adapter.Fill(dsdetailwk, "delivery")
   Catch Err As System.Exception
End Try

sqlConnection1.Close()

datagridview1.DataSource = dsdetailwk.Tables(0)

How to remove a build from itunes connect?

Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing

  1. I set release to "manual" and saved
  2. I tried to create and app release
  3. got an error message something like "you can only have one release at a time"
  4. where the save button was there was not an option to cancel release
  5. the version of the app is not marked "developer rejected" with a red dot

To replace the bad build I did the following

  1. if you click on the "+ version or platform" to create a new version you will not be be able to create a new iOS version
  2. you need to upload a new build
  3. in your rejected app, select the new build
  4. save
  5. submit for review

Java: Reading a file into an array

import java.io.File;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import java.util.List;

// ...

Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();        
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

How to clear memory to prevent "out of memory error" in excel vba?

The best way to help memory to be freed is to nullify large objects:

Sub Whatever()
    Dim someLargeObject as SomeObject

    'expensive computation

    Set someLargeObject = Nothing
End Sub

Also note that global variables remain allocated from one call to another, so if you don't need persistence you should either not use global variables or nullify them when you don't need them any longer.

However this won't help if:

  • you need the object after the procedure (obviously)
  • your object does not fit in memory

Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).

What does "export" do in shell programming?

Well, it generally depends on the shell. For bash, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.

Non-exported variables are only visible from the current process (the shell).

From the bash man page:

export [-fn] [name[=word]] ...
export -p

The supplied names are marked for automatic export to the environment of subsequently executed commands.

If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed.

The -n option causes the export property to be removed from each name.

If a variable name is followed by =word, the value of the variable is set to word.

export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.

You can also set variables as exportable with the typeset command and automatically mark all future variable creations or modifications as such, with set -a.

Python conditional assignment operator

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

d = {}
d.setdefault('key', 1)
d['key'] == 1

d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2

Convert PEM to PPK file format

PuTTYgen for Ubuntu/Linux and PEM to PPK

sudo apt install putty-tools
puttygen -t rsa -b 2048 -C "user@host" -o keyfile.ppk

Differences between ConstraintLayout and RelativeLayout

The real question to ask is, is there any reason to use any layout other than a constraint layout? I believe the answer might be no.

To those insisting they are aimed at novice programmers or the like, they should provide some reason for them to be inferior to any other layout.

Constraints layouts are better in every way (They do cost like 150k in APK size.). They are faster, they are easier, they are more flexible, they react better to changes, they fix the problems when items go away, they conform better to radically different screen types and they don't use a bunch of nested loop with that long drawn out tree structure for everything. You can put anything anywhere, with respect to anything, anywhere.

They were a bit screwy back in mid 2016, where the visual layout editor just wasn't good enough, but they are to the point that if you are having a layout at all, you might want to seriously consider using a constraint layout, even when it does the same thing as a RelativeLayout, or even a simple LinearLayout. FrameLayouts clearly still have their purpose. But, I can't see building anything else at this point. If they started with this they wouldn't have added anything else.

How can I find the number of days between two Date objects in Ruby?

This worked for me:

(endDate - beginDate).to_i

VBA Public Array : how to?

You are using the wrong type. The Array(...) function returns a Variant, not a String.

Thus, in the Declaration section of your module (it does not need to be a different module!), you define

Public colHeader As Variant

and somewhere at the beginning of your program code (for example, in the Workbook_Open event) you initialize it with

colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Another (simple) alternative would be to create a function that returns the array, e.g. something like

Public Function GetHeaders() As Variant
    GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function

This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Invalid self signed SSL cert - "Subject Alternative Name Missing"

Following solution worked for me on chrome 65 (ref) -

Create an OpenSSL config file (example: req.cnf)

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = VA
L = SomeCity
O = MyCompany
OU = MyDivision
CN = www.company.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.company.com
DNS.2 = company.com
DNS.3 = company.net

Create the certificate referencing this config file

openssl req -x509 -nodes -days 730 -newkey rsa:2048 \
 -keyout cert.key -out cert.pem -config req.cnf -sha256

How to find index of all occurrences of element in array?

You can write a simple readable solution to this by using both map and filter:

const nanoIndexes = Cars
  .map((car, i) => car === 'Nano' ? i : -1)
  .filter(index => index !== -1);

EDIT: If you don't need to support IE/Edge (or are transpiling your code), ES2019 gave us flatMap, which lets you do this in a simple one-liner:

const nanoIndexes = Cars.flatMap((car, i) => car === 'Nano' ? i : []);

Chrome extension: accessing localStorage in content script

Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

One downside is that it is asynchronous.

https://developer.chrome.com/extensions/storage.html

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

Get current clipboard content?

window.clipboardData.getData('Text') will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.

Installing Numpy on 64bit Windows 7 with Python 2.7.3

It is not improbable, that programmers looking for python on windows, also use the Python Tools for Visual Studio. In this case it is easy to install additional packages, by taking advantage of the included "Python Environment" Window. "Overview" is selected within the window as default. You can select "Pip" there.

Then you can install numpy without additional work by entering numpy into the seach window. The coresponding "install numpy" instruction is already suggested.

Nevertheless I had 2 easy to solve Problems in the beginning:

  • "error: Unable to find vcvarsall.bat": This problem has been solved here. Although I did not find it at that time and instead installed the C++ Compiler for Python.
  • Then the installation continued but failed because of an additional inner exception. Installing .NET 3.5 solved this.

Finally the installation was done. It took some time (5 minutes), so don't cancel the process to early.

Using BigDecimal to work with currencies

Primitive numeric types are useful for storing single values in memory. But when dealing with calculation using double and float types, there is a problems with the rounding.It happens because memory representation doesn't map exactly to the value. For example, a double value is supposed to take 64 bits but Java doesn't use all 64 bits.It only stores what it thinks the important parts of the number. So you can arrive to the wrong values when you adding values together of the float or double type.

Please see a short clip https://youtu.be/EXxUSz9x7BM

Passing parameter using onclick or a click binding with KnockoutJS

Use a binding, like in this example:

<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')">
  Search Manager
</a>
var ViewModelStructure = function () {
    var self = this;
    this.SearchManager = function (search) {
        console.log(search);
    };
}();

Using an attribute of the current class instance as a default value for method's parameter

There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self.

Here is an example. It is counterintuitive, but actually makes perfect sense:

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

This will print 1 2 1 1 3.

Because it works the same way as

default_s=[]
def add(item, s=default_s):
    s.append(item)

Obviously, if you modify default_s, it retains these modifications.

There are various workarounds, including

def add(item, s=None):
    if not s: s = []
    s.append(item)

or you could do this:

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

Then the method makeDefaultS will have access to self.

Another variation:

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

here the default value of s is a factory function.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

convert month from name to number

Maybe use a combination with strtotime() and date()?

Creating PHP class instance with a string

have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php

$className = 'Foo';
$instance = new $className(); // Foo()

Clicking a button within a form causes page refresh

You can keep <button type="submit">, but must remove the attribute action="" of <form>.

Find if variable is divisible by 2

var x = 2;
x % 2 ? oddFunction() : evenFunction();

Make the console wait for a user input to close

You can just use nextLine(); as pause

import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);

void Read()
{
     System.out.print("Press any key to continue . . . ");
     scan.nextLine();
}

However any button you press except Enter means you will have to press Enter after that but I found it better than scan.next();

How can I insert data into a MySQL database?

This way worked for me when adding random data to MySql table using a python script.
First install the following packages using the below commands

pip install mysql-connector-python<br>
pip install random
import mysql.connector
import random

from datetime import date


start_dt = date.today().replace(day=1, month=1).toordinal()
end_dt = date.today().toordinal()

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root",
    database="your_db_name"
)

mycursor = mydb.cursor()

sql_insertion = "INSERT INTO customer (name,email,address,dateJoined) VALUES (%s, %s,%s, %s)"
#insert 10 records(rows)
for x in range(1,11):
    #generate a random date
    random_day = date.fromordinal(random.randint(start_dt, end_dt))
    value = ("customer" + str(x),"customer_email" + str(x),"customer_address" + str(x),random_day)
    mycursor.execute(sql_insertion , value)

mydb.commit()

print("customer records inserted!")


Following is a sample output of the insertion

cid       |  name      |  email           |    address        |  dateJoined  |

1         | customer1  |  customer_email1 | customer_address1 |  2020-11-15  |
2         | customer2  |  customer_email2 | customer_address2 |  2020-10-11  |
3         | customer3  |  customer_email3 | customer_address3 |  2020-11-17  |
4         | customer4  |  customer_email4 | customer_address4 |  2020-09-20  |
5         | customer5  |  customer_email5 | customer_address5 |  2020-02-18  |
6         | customer6  |  customer_email6 | customer_address6 |  2020-01-11  |
7         | customer7  |  customer_email7 | customer_address7 |  2020-05-30  |
8         | customer8  |  customer_email8 | customer_address8 |  2020-04-22  |
9         | customer9  |  customer_email9 | customer_address9 |  2020-01-05  |
10        | customer10 |  customer_email10| customer_address10|  2020-11-12  |



How to modify PATH for Homebrew?

open bash profile in textEdit

open -e .bash_profile

Edit file or paste in front of PATH export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin:~/bin

save & close the file

*To open .bash_profile directly open textEdit > file > recent

Log4net does not write the log in the log file

Do you call

log4net.Config.XmlConfigurator.Configure();

somewhere to make log4net read your configuration? E.g. in Global.asax:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

    // Initialize log4net.
    log4net.Config.XmlConfigurator.Configure();
}

Displaying Windows command prompt output and redirecting it to a file

Here's a sample of what I've used based on one of the other answers

@echo off
REM SOME CODE
set __ERROR_LOG=c:\errors.txt
REM set __IPADDRESS=x.x.x.x

REM Test a variable
if not defined __IPADDRESS (
     REM Call function with some data and terminate
     call :TEE %DATE%,%TIME%,IP ADDRESS IS NOT DEFINED
     goto :EOF
)

REM If test happens to be successful, TEE out a message and end script.
call :TEE Script Ended Successful
goto :EOF


REM THE TEE FUNCTION
:TEE
for /f "tokens=*" %%Z in ("%*") do (
     >  CON ECHO.%%Z
     >> "%__ERROR_LOG%" ECHO.%%Z
     goto :EOF
)

Unit test naming best practices

I should add that the keeping your tests in the same package but in a parallel directory to the source being tested eliminates the bloat of the code once your ready to deploy it without having to do a bunch of exclude patterns.

I personally like the best practices described in "JUnit Pocket Guide" ... it's hard to beat a book written by the co-author of JUnit!

Failed to authenticate on SMTP server error using gmail

I had the same issue, but when I ran the following command, it was ok:

php artisan config:cache

Trim specific character from a string

If I understood well, you want to remove a specific character only if it is at the beginning or at the end of the string (ex: ||fo||oo|||| should become foo||oo). You can create an ad hoc function as follows:

function trimChar(string, charToRemove) {
    while(string.charAt(0)==charToRemove) {
        string = string.substring(1);
    }

    while(string.charAt(string.length-1)==charToRemove) {
        string = string.substring(0,string.length-1);
    }

    return string;
}

I tested this function with the code below:

var str = "|f|oo||";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "Trimmed: '" + trimChar(str, "|") + "'" );

When should you use a class vs a struct in C++?

They are pretty much the same thing. Thanks to the magic of C++, a struct can hold functions, use inheritance, created using "new" and so on just like a class

The only functional difference is that a class begins with private access rights, while a struct begins with public. This is the maintain backwards compatibility with C.

In practice, I've always used structs as data holders and classes as objects.

Download file inside WebView

Have you tried?

mWebView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype,
                long contentLength) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }
});

Example Link: Webview File Download - Thanks @c49

Pass values of checkBox to controller action in asp.net mvc4

If you want your value to be read by MVT controller when you submit the form and you don't what to deal with hidden inputs. What you can do is add value attribute to your checkbox and set it to true or false.

MVT will not recognize viewModel property myCheckbox as true here

<input type="checkbox" name="myCheckbox" checked="checked" />

but will if you add

<input type="checkbox" name="myCheckbox" checked="checked" value="true" />

Script that does it:

$(document).on("click", "[type='checkbox']", function(e) {
        if (this.checked) {
            $(this).attr("value", "true");
        } else {
            $(this).attr("value","false");}
    });

PHP compare two arrays and get the matched values not the difference

Simple, use array_intersect() instead:

$result = array_intersect($array1, $array2);

How to loop through a plain JavaScript object with the objects as members?

I know it's waaay late, but it did take me 2 minutes to write this optimized and improved version of AgileJon's answer:

var key, obj, prop, owns = Object.prototype.hasOwnProperty;

for (key in validation_messages ) {

    if (owns.call(validation_messages, key)) {

        obj = validation_messages[key];

        for (prop in obj ) {

            // using obj.hasOwnProperty might cause you headache if there is
            // obj.hasOwnProperty = function(){return false;}
            // but owns will always work 
            if (owns.call(obj, prop)) {
                console.log(prop, "=", obj[prop]);
            }

        }

    }

}

Find Number of CPUs and Cores per CPU using Command Prompt

If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS% shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd:

@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f

And then execute like this:

GetNumberOfCores.cmd

echo %NumberOfCores%

The script will set a environment variable named %NumberOfCores% and it will contain the number of processors.

What are all the differences between src and data-src attributes?

If you want the image to load and display a particular image, then use .src to load that image URL.

If you want a piece of meta data (on any tag) that can contain a URL, then use data-src or any data-xxx that you want to select.

MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset

Example of src on an image tag where the image loads the JPEG for you and displays it:

<img id="myImage" src="http://mydomain.com/foo.jpg">

<script>
    var imageUrl = document.getElementById("myImage").src;
</script>

Example of 'data-src' on a non-image tag where the image is not loaded yet - it's just a piece of meta data on the div tag:

<div id="myDiv" data-src="http://mydomain.com/foo.jpg">

<script>
    // in all browsers
    var imageUrl = document.getElementById("myDiv").getAttribute("data-src");

    // or in modern browsers
    var imageUrl = document.getElementById("myDiv").dataset.src;
</script>

Example of data-src on an image tag used as a place to store the URL of an alternate image:

<img id="myImage" src="http://mydomain.com/foo.jpg" data-src="http://mydomain.com/foo.jpg">

<script>
    var item = document.getElementById("myImage");
    // switch the image to the URL specified in data-src
    item.src = item.dataset.src;
</script>

How to remove new line characters from a string?

You can use Trim if you want to remove from start and end.

string stringWithoutNewLine = "\n\nHello\n\n".Trim();

scp from Linux to Windows

To send a file from windows to linux system

scp path-to-file user@ipaddress:/path-to-destination

Example:

scp C:/Users/adarsh/Desktop/Document.txt [email protected]:/tmp

keep in mind that there need to use forward slash(/) inplace of backward slash(\) in for the file in windows path else it will show an error

C:UsersadarshDesktopDocument.txt: No such file or directory

. After executing scp command you will ask for password of root user in linux machine. There you GO...

To send a file from linux to windows system

scp -r user@ipaddress:/path-to-file path-to-destination

Example:

scp -r [email protected]:/tmp/Document.txt C:/Users/adarsh/Desktop/

and provide your linux password. only one you have to add in this command is -r. Thanks.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

After encountering the same issue in a Web API 2 project (and being unable to use the standard CORS packages for reasons not worth going into here), I was able to resolve this by implementing a custom DelagatingHandler:

public class AllowOptionsHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        if (request.Method == HttpMethod.Options &&
            response.StatusCode == HttpStatusCode.MethodNotAllowed)
        {
            response = new HttpResponseMessage(HttpStatusCode.OK);
        }

        return response;
    }
}

For the Web API configuration:

config.MessageHandlers.Add(new AllowOptionsHandler());

Note that I also have the CORS headers enabled in Web.config, similar to some of the other answers posted here:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule" />
  </modules>

  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="accept, cache-control, content-type, authorization" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>

  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

Note that my project does not include MVC, only Web API 2.

Escape regex special characters in a Python string

Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end.

>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\

Or maybe you just want to escape a phrase to paste into your program? If so, do this:

>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'

Handling Dialogs in WPF with MVVM

I was pondering a similar problem when asking how the view model for a task or dialog should look like.

My current solution looks like this:

public class SelectionTaskModel<TChoosable> : ViewModel
    where TChoosable : ViewModel
{
    public SelectionTaskModel(ICollection<TChoosable> choices);
    public ReadOnlyCollection<TChoosable> Choices { get; }
    public void Choose(TChoosable choosen);
    public void Abort();
}

When the view model decides that user input is required, it pulls up a instance of SelectionTaskModel with the possible choices for the user. The infrastructure takes care of bringing up the corresponding view, which in proper time will call the Choose() function with the user's choice.

IntelliJ IDEA JDK configuration on Mac OS

On Mac IntelliJ Idea 12 has it's preferences/keymaps placed here: ./Users/viliuskraujutis/Library/Preferences/IdeaIC12/keymaps/

How do I rename the android package name?

In Android Studio 1.1, the simplest way is to open your project manifest file, then point to each part of the package name that you want to change it and press SHIFT + F6 , then choose rename package and write the new name in the dialog box. That's all.

turn typescript object into json string

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');

fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

Set type for function parameters?

TypeScript is one of the best solution for now

TypeScript extends JavaScript by adding types to the language.

https://www.typescriptlang.org/

How to access JSON decoded array in PHP

As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:

$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..

If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:

echo $myArray[0]->id;

php implode (101) with quotes

$array = array('lastname', 'email', 'phone');


echo "'" . implode("','", $array) . "'";

How to escape a single quote inside awk

For small scripts an optional way to make it readable is to use a variable like this:

awk -v fmt="'%s'\n" '{printf fmt, $1}'

I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.

Java String new line

If you simply want to print a newline in the console you can use ´\n´ for newlines.

If you want to break text in swing components you can use html:

String s = "<html>first line<br />second line</html>";

How to get the background color code of an element in hex?

This Solution utilizes part of what @Newred and @Radu Di?a said. But will work in less standard cases.

 $(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');

The issue both of them have is that neither check for a space between background-color: and the color.

All of these will match with the above code.

 background-color: #ffffff
 background-color:      #fffff;
 background-color:#fffff;

Get Context in a Service

As Service is already a Context itself

you can even get it through:

Context mContext = this;

OR

Context mContext = [class name].this;  //[] only specify the class name
// mContext = JobServiceSchedule.this; 

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Checking if jquery is loaded using Javascript

A quick way is to run a jQuery command in the developer console. On any browser hit F12 and try to access any of the element .

 $("#sideTab2").css("background-color", "yellow");

enter image description here

Get the Selected value from the Drop down box in PHP

You need to set a name on the <select> tag like so:

<select name="select_catalog" id="select_catalog">

You can get it in php with this:

$_POST['select_catalog'];

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I was able to get around this loading the headers before the HTML with php, and it worked very well.

<?php 
header( 'X-UA-Compatible: IE=edge,chrome=1' );
header( 'content: width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' );
include('ix.html');
?> 

ix.html is the content I wanted to load after sending the headers.

Select the values of one property on all objects of an array in PowerShell

I think you might be able to use the ExpandProperty parameter of Select-Object.

For example, to get the list of the current directory and just have the Name property displayed, one would do the following:

ls | select -Property Name

This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm).

ls | select -Property Name | gm

So, to expand the object to be that of the type of property you're looking at, you can do the following:

ls | select -ExpandProperty Name

In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:

$objects = ls | select -ExpandProperty Name

How to hide Soft Keyboard when activity starts

Use SOFT_INPUT_STATE_ALWAYS_HIDDEN instead of SOFT_INPUT_STATE_HIDDEN

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

PHP string "contains"

You can use these string functions,

strstr — Find the first occurrence of a string

stristr — Case-insensitive strstr()

strrchr — Find the last occurrence of a character in a string

strpos — Find the position of the first occurrence of a substring in a string

strpbrk — Search a string for any of a set of characters

If that doesn't help then you should use preg regular expression

preg_match — Perform a regular expression match

React: how to update state.item[1] in state using setState?

Following piece of code went easy on my dull brain. Removing the object and replacing with the updated one

    var udpateditem = this.state.items.find(function(item) { 
                   return item.name == "field_1" });
    udpateditem.name= "New updated name"                       
    this.setState(prevState => ({                                   
    items:prevState.dl_name_template.filter(function(item) { 
                                    return item.name !== "field_1"}).concat(udpateditem)
    }));

How does @synchronized lock/unlock in Objective-C?

In Objective-C, a @synchronized block handles locking and unlocking (as well as possible exceptions) automatically for you. The runtime dynamically essentially generates an NSRecursiveLock that is associated with the object you're synchronizing on. This Apple documentation explains it in more detail. This is why you're not seeing the log messages from your NSLock subclass — the object you synchronize on can be anything, not just an NSLock.

Basically, @synchronized (...) is a convenience construct that streamlines your code. Like most simplifying abstractions, it has associated overhead (think of it as a hidden cost), and it's good to be aware of that, but raw performance is probably not the supreme goal when using such constructs anyway.

Removing multiple keys from a dictionary safely

I'm late to this discussion but for anyone else. A solution may be to create a list of keys as such.

k = ['a','b','c','d']

Then use pop() in a list comprehension, or for loop, to iterate over the keys and pop one at a time as such.

new_dictionary = [dictionary.pop(x, 'n/a') for x in k]

The 'n/a' is in case the key does not exist, a default value needs to be returned.

Setting Environment Variables for Node to retrieve

Like ctrlplusb said, I recommend you to use the package dotenv, but another way to do this is creating a js file and requiring it on the first line of your app server.

env.js:

process.env.VAR1="Some value"
process.env.VAR2="Another Value"

app.js:

require('env')
console.log(process.env.VAR1) // Some value

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.

You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/

Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.

This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.

Pipe output and capture exit status in Bash

It may sometimes be simpler and clearer to use an external command, rather than digging into the details of bash. pipeline, from the minimal process scripting language execline, exits with the return code of the second command*, just like a sh pipeline does, but unlike sh, it allows reversing the direction of the pipe, so that we can capture the return code of the producer process (the below is all on the sh command line, but with execline installed):

$ # using the full execline grammar with the execlineb parser:
$ execlineb -c 'pipeline { echo "hello world" } tee out.txt'
hello world
$ cat out.txt
hello world

$ # for these simple examples, one can forego the parser and just use "" as a separator
$ # traditional order
$ pipeline echo "hello world" "" tee out.txt 
hello world

$ # "write" order (second command writes rather than reads)
$ pipeline -w tee out.txt "" echo "hello world"
hello world

$ # pipeline execs into the second command, so that's the RC we get
$ pipeline -w tee out.txt "" false; echo $?
1

$ pipeline -w tee out.txt "" true; echo $?
0

$ # output and exit status
$ pipeline -w tee out.txt "" sh -c "echo 'hello world'; exit 42"; echo "RC: $?"
hello world
RC: 42
$ cat out.txt
hello world

Using pipeline has the same differences to native bash pipelines as the bash process substitution used in answer #43972501.

* Actually pipeline doesn't exit at all unless there is an error. It executes into the second command, so it's the second command that does the returning.

How do I find the length of an array?

Avoid using the type together with sizeof, as sizeof(array)/sizeof(char), suddenly gets corrupt if you change the type of the array.

In visual studio, you have the equivivalent if sizeof(array)/sizeof(*array). You can simply type _countof(array)

How to center buttons in Twitter Bootstrap 3?

or you can give specific offsets to make button position where you want simply with bootstrap grid system,

<div class="col-md-offset-4 col-md-2 col-md-offset-5">
<input type="submit" class="btn btn-block" value="submit"/>

this way, also let you specify button size if you set btn-block. sure, this will only work md size range, if you want to set other sizes too, use xs,sm,lg.

How to convert int to string on Arduino?

You can simply do:

Serial.println(n);

which will convert n to an ASCII string automatically. See the documentation for Serial.println().

Add views below toolbar in CoordinatorLayout

To use collapsing top ToolBar or using ScrollFlags of your own choice we can do this way:From Material Design get rid of FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleGravity="top"
            app:layout_scrollFlags="scroll|enterAlways">


        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/ic_back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_arrow_back" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"
                android:textSize="16sp"
                android:textStyle="bold" />

        </androidx.appcompat.widget.Toolbar>


        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/post_details_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

How to add empty spaces into MD markdown readme on GitHub?

As a workaround, you can use a code block to render the code literally. Just surround your text with triple backticks ```. It will look like this:

2018-07-20 Wrote this answer Can format it without &nbsp; Also don't need <br /> for new line

Note that using <pre> and <code> you get slightly different behaviour: &nbsp and <br /> will be parsed rather than inserted literally.

<pre>:

2018-07-20 Wrote this answer
           Can format it without  
    Also don't need 
for new line

<code>: 2018-07-20 Wrote this answer Can format it without   Also don't need
for new line

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Getting an option text/value with JavaScript

In jquery you could try this $("#select_id>option:selected").text()

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

Best practice for storing and protecting private API keys in applications

One possible solution is to encode the data in your app and use decoding at runtime (when you want to use that data). I also recommend to use progaurd to make it hard to read and understand the decompiled source code of your app . for example I put a encoded key in the app and then used a decode method in my app to decode my secret keys at runtime:

// "the real string is: "mypassword" "; 
//encoded 2 times with an algorithm or you can encode with other algorithms too
public String getClientSecret() {
    return Utils.decode(Utils
            .decode("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}

Decompiled source code of a proguarded app is this:

 public String c()
 {
    return com.myrpoject.mypackage.g.h.a(com.myrpoject.mypackage.g.h.a("Ylhsd1lYTnpkMjl5WkE9PQ=="));
  }

At least it's complicated enough for me. this is the way I do when I have no choice but store a value in my application. Of course we all know It's not the best way but it works for me.

/**
 * @param input
 * @return decoded string
 */
public static String decode(String input) {
    // Receiving side
    String text = "";
    try {
        byte[] data = Decoder.decode(input);
        text = new String(data, "UTF-8");
        return text;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return "Error";
}

Decompiled version:

 public static String a(String paramString)
  {
    try
    {
      str = new String(a.a(paramString), "UTF-8");
      return str;
    }
    catch (UnsupportedEncodingException localUnsupportedEncodingException)
    {
      while (true)
      {
        localUnsupportedEncodingException.printStackTrace();
        String str = "Error";
      }
    }
  }

and you can find so many encryptor classes with a little search in google.

How to convert a HTMLElement to a string

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

<div id="new-element-1">Hello world.</div>

<script type="text/javascript"><!--

var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>

--></script>

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

  1. outerHTML - Javascript Property
  2. Javascript Reference - Elements

symbol(s) not found for architecture i386

I had used a CLGeocoder without adding a Core.Location Framework. Basically this error can mean multiple things. I hope this helps someone else.

Compile to stand alone exe for C# app in Visual Studio 2010

You can get single file EXE after build the console application

your Application folder - > bin folder -> there will have lot of files there is need 2 files must and other referenced dlls

1. IMG_PDF_CONVERSION [this is my application name, take your application name]
2. IMG_PDF_CONVERSION.exe [this is supporting configure file]
3. your refered dll's

then you can move that 3(exe, configure file, refered dll's) dll to any folder that's it

if you click on 1st IMG_PDF_CONVERSION it will execute the application cool way

any calcification please ask your queries.

Python group by

result = []
# Make a set of your "types":
input_set = set([tpl[1] for tpl in input])
>>> set(['ETH', 'KAT', 'NOT'])
# Iterate over the input_set
for type_ in input_set:
    # a dict to gather things:
    D = {}
    # filter all tuples from your input with the same type as type_
    tuples = filter(lambda tpl: tpl[1] == type_, input)
    # write them in the D:
    D["type"] = type_
    D["itmes"] = [tpl[0] for tpl in tuples]
    # append D to results:
    result.append(D)

result
>>> [{'itmes': ['9085267', '11788544'], 'type': 'NOT'}, {'itmes': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'itmes': ['11013331', '9843236'], 'type': 'KAT'}]

Typescript export vs. default export

Default Export (export default)

// MyClass.ts -- using default export
export default class MyClass { /* ... */ }

The main difference is that you can only have one default export per file and you import it like so:

import MyClass from "./MyClass";

You can give it any name you like. For example this works fine:

import MyClassAlias from "./MyClass";

Named Export (export)

// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }

When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:

import { MyClass } from "./MyClass";

Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.

Or say your file exported multiple classes, then you could import both like so:

import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass

Or you could give either of them a different name in this file:

import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias

Or you could import everything that's exported by using * as:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here

Which to use?

In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.

It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.

Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.

That said, find what you prefer! You could use one, the other, or both at the same time.

Additional Points

A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:

import { default as MyClass } from "./MyClass";

And take note these other ways to import exist: 

import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports

Defining a variable with or without export

To illustrate what the other answers are saying:

$ foo="Hello, World"
$ echo $foo
Hello, World
$ bar="Goodbye"
$ export foo
$ bash
bash-3.2$ echo $foo
Hello, World
bash-3.2$ echo $bar

bash-3.2$ 

Handling data in a PHP JSON Object

Just use it like it was an object you defined. i.e.

$trends = $json_output->trends;

Can't run Curl command inside my Docker Container

curl: command not found

is a big hint, you have to install it with :

apt-get update; apt-get install curl

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

This works for me

  1. Open the file in BBEdit or TextWrangler*.
  2. Set the file as Unicode (UTF-16 Little-Endian) (Line Endings can be Unix or Windows). Save!
  3. In Excel: Data > Get External Data > Import Text File...

Now the key point, choose MacIntosh as File Origin (it should be the first choice).

This is using Excel 2011 (version 14.4.2)

*There's a little dropdown at the bottom of the window

Permission is only granted to system app

Path In Android Studio in mac:

Android Studio -> Preferences -> Editor -> Inspections

Expand Android -> Expand Lint -> Expand Correctness

Uncheck the checkbox for Using system app permission

Click on "APPLY" -> "OK"

Installing Apple's Network Link Conditioner Tool

It's in an additional download. Use this menu item:

Xcode > Open Developer Tool > More Developer Tools...

and get "Hardware IO Tools for Xcode".

For Xcode 8+, get "Additional Tools for Xcode [version]".

Double-click on a .prefPane file to install. If you already have an older .prefPane installed, you'll need to remove it from /Library/PreferencePanes.

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

Set Option  Value
textsize    2147483647
language    us_english
dateformat  mdy
datefirst   7
lock_timeout    -1
quoted_identifier   SET
arithabort  SET
ansi_null_dflt_on   SET
ansi_warnings   SET
ansi_padding    SET
ansi_nulls  SET
concat_null_yields_null SET
isolation level read committed

How to delete mysql database through shell command

[root@host]# mysqladmin -u root -p drop [DB]

Enter password:******

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

How to list the tables in a SQLite database file that was opened with ATTACH?

The easiest way to do this is to open the database directly and use the .dump command, rather than attaching it after invoking the SQLite 3 shell tool.

So... (assume your OS command line prompt is $) instead of $sqlite3:

sqlite3> ATTACH database.sqlite as "attached"

From your OS command line, open the database directly:

$sqlite3 database.sqlite
sqlite3> .dump

JavaScript: Create and save file

You cannot do this purely in Javascript. Javascript running on browsers does not have enough permission yet (there have been proposals) due to security reasons.

Instead, I would recommend using Downloadify:

A tiny javascript + Flash library that enables the creation and download of text files without server interaction.

You can see a simple demo here where you supply the content and can test out saving/cancelling/error handling functionality.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

If your class extends Serializable, you can write and read objects through a ByteArrayOutputStream, that's what I usually do.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm

Have a look and check the differences. specially the even_id in :

<set name="attendees" cascade="all">
    <key column="event_id"/>
    <one-to-many class="Attendee"/>
</set> 

SQL: Group by minimum value in one field while selecting distinct rows

select 
    department, 
    min_salary, 
    (select s1.last_name from staff s1 where s1.salary=s3.min_salary ) lastname 
from 
    (select department, min (salary) min_salary from staff s2 group by s2.department) s3

Dropdown select with images

If you think about it the concept behind a dropdown select it's pretty simple. For what you're trying to accomplish, a simple <ul> will do.

<ul id="menu">
    <li>
        <a href="#"><img src="" alt=""/></a> <!-- Selected -->
        <ul>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
        </ul>
    </li>
</ul>

You style it with css and then some simple jQuery will do. I haven't tried this tho:

$('#menu ul li').click(function(){
    var $a = $(this).find('a');
    $(this).parents('#menu').children('li a').replaceWith($a).
});

javascript - replace dash (hyphen) with a space

replace() returns an new string, and the original string is not modified. You need to do

str = str.replace(/-/g, ' ');

How to push to History in React Router v4?

step one wrap your app in Router

import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));

Now my entire App will have access to BrowserRouter. Step two I import Route and then pass down those props. Probably in one of your main files.

import { Route } from "react-router-dom";

//lots of code here

//somewhere in my render function

    <Route
      exact
      path="/" //put what your file path is here
      render={props => (
      <div>
        <NameOfComponent
          {...props} //this will pass down your match, history, location objects
        />
      </div>
      )}
    />

Now if I run console.log(this.props) in my component js file that I should get something that looks like this

{match: {…}, location: {…}, history: {…}, //other stuff }

Step 2 I can access the history object to change my location

//lots of code here relating to my whatever request I just ran delete, put so on

this.props.history.push("/") // then put in whatever url you want to go to

Also I'm just a coding bootcamp student, so I'm no expert, but I know you can also you use

window.location = "/" //wherever you want to go

Correct me if I'm wrong, but when I tested that out it reloaded the entire page which I thought defeated the entire point of using React.

Disable scrolling in all mobile devices

For future generations:

To prevent scrolling but keep the contextmenu, try

document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });

It still prevents way more than some might like, but for most browsers the only default behaviour prevented should be scrolling.

For a more sophisticated solution that allows for scrollable elements within the nonscrollable body and prevents rubberband, have a look at my answer over here:

https://stackoverflow.com/a/20250111/1431156

How to send redirect to JSP page in Servlet

Look at the HttpServletResponse#sendRedirect(String location) method.

Use it as:

response.sendRedirect(request.getContextPath() + "/welcome.jsp")

Alternatively, look at HttpServletResponse#setHeader(String name, String value) method.

The redirection is set by adding the location header:

response.setHeader("Location", request.getContextPath() + "/welcome.jsp");

Check If only numeric values were entered in input. (jQuery)

I used this to check if all the text boxes had numeric values:

if(!$.isNumeric($('input:text').val())) {
        alert("All the text boxes must have numeric values!");
        return false;
    }

or for one:

$.isNumeric($("txtBox").val());

Available with jQuery 1.7.

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

Find if current time falls in a time range

Using Linq we can simplify this by this

 Enumerable.Range(0, (int)(to - from).TotalHours + 1)
            .Select(i => from.AddHours(i)).Where(date => date.TimeOfDay >= new TimeSpan(8, 0, 0) && date.TimeOfDay <= new TimeSpan(18, 0, 0))

Deleting multiple elements from a list

As a function:

def multi_delete(list_, *args):
    indexes = sorted(list(args), reverse=True)
    for index in indexes:
        del list_[index]
    return list_

Runs in n log(n) time, which should make it the fastest correct solution yet.

Create pandas Dataframe by appending one row at a time

We often see the construct df.loc[subscript] = … to assign to one DataFrame row. Mikhail_Sam posted benchmarks containing, among others, this construct as well as the method using dict and create DataFrame in the end. He found the latter to be the fastest by far. But if we replace the df3.loc[i] = … (with preallocated DataFrame) in his code with df3.values[i] = …, the outcome changes significantly, in that that method performs similar to the one using dict. So we should more often take the use of df.values[subscript] = … into consideration. However note that .values takes a zero-based subscript, which may be different from the DataFrame.index.

Get current URL path in PHP

it should be :

$_SERVER['REQUEST_URI'];

Take a look at : Get the full URL in PHP

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

Calculate the execution time of a method

Following this Microsoft Doc:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

Output: RunTime 00:00:09.94

better way to drop nan rows in pandas

bool_series=pd.notnull(dat["x"])
dat=dat[bool_series]

YouTube iframe embed - full screen

we can get the code below the video. In the share option, we will have an option embed. If we click on the embed we will get the code snippet for that video.

which will be similar to the below code

<iframe width="560" height="315" src="https://www.youtube.com/embed/GZh_Kj1rS74" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

The above code will help you to get the full-screen option.

Animate background image change with jQuery

The simplest solution would be to wrap the element with a div. That wrapping div would have the hidden background image that would appear as the inner element fades.

Here's some example javascript:

$('#wrapper').hover(function(event){
    $('#inner').fadeOut(300);
}, function(event){
    $('#inner').fadeIn(300);
});

and here's the html to go along with it:

<div id="wrapper"><div id="inner">Your inner text</div></div>

Select SQL Server database size

Also compare the results with the following query's result

EXEC sp_helpdb @dbname= 'MSDB'

It produces result similar to the following

enter image description here

There is a good article - Different ways to determine free space for SQL Server databases and database files

Oracle: how to UPSERT (update or insert into a table?)

I'd like Grommit answer, except it require dupe values. I found solution where it may appear once: http://forums.devshed.com/showpost.php?p=1182653&postcount=2

MERGE INTO KBS.NUFUS_MUHTARLIK B
USING (
    SELECT '028-01' CILT, '25' SAYFA, '6' KUTUK, '46603404838' MERNIS_NO
    FROM DUAL
) E
ON (B.MERNIS_NO = E.MERNIS_NO)
WHEN MATCHED THEN
    UPDATE SET B.CILT = E.CILT, B.SAYFA = E.SAYFA, B.KUTUK = E.KUTUK
WHEN NOT MATCHED THEN
    INSERT (  CILT,   SAYFA,   KUTUK,   MERNIS_NO)
    VALUES (E.CILT, E.SAYFA, E.KUTUK, E.MERNIS_NO); 

Page redirect after certain time PHP

You can try this:

header('Refresh: 10; URL=http://yoursite.com/page.php');

Where 10 is in seconds.

"Could not find a part of the path" error message

File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);

This line has the error because what the code expected is the directory name + file name, not the file name.

This is the correct one

File.Copy(source_dir + file_name, destination_dir + file_name.Substring(source_dir.Length), true);

Optimal way to DELETE specified rows from Oracle

First, disabling the index during the deletion would be helpful.

Try with a MERGE INTO statement :
1) create a temp table with IDs and an additional column from TABLE1 and test with the following

MERGE INTO table1 src
USING (SELECT id,col1
         FROM test_merge_delete) tgt
ON (src.id = tgt.id)
WHEN MATCHED THEN
  UPDATE
     SET src.col1 = tgt.col1
  DELETE
   WHERE src.id = tgt.id

How can I see the request headers made by curl when sending a request to the server?

dump the headers in one file and the payload of the response in a different file

curl -k -v -u user:pass  "url" --trace-ascii headers.txt >> response.txt

Create an instance of a class from a string

I know I'm late to the game... but the solution you're looking for might be the combination of the above, and using an interface to define your objects publicly accessible aspects.

Then, if all of your classes that would be generated this way implement that interface, you can just cast as the interface type and work with the resulting object.

How to determine if a number is odd in JavaScript

Use the bitwise AND operator.

_x000D_
_x000D_
function oddOrEven(x) {_x000D_
  return ( x & 1 ) ? "odd" : "even";_x000D_
}_x000D_
_x000D_
function checkNumber(argNumber) {_x000D_
  document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);_x000D_
}_x000D_
 _x000D_
checkNumber(17);
_x000D_
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>
_x000D_
_x000D_
_x000D_

If you don't want a string return value, but rather a boolean one, use this:

var isOdd = function(x) { return x & 1; };
var isEven  = function(x) { return !( x & 1 ); };

Checking if a string is empty or null in Java

import com.google.common.base

if(!Strings.isNullOrEmpty(String str)) {
   // Do your stuff here 
}

How to get URI from an asset File?

The correct url is:

file:///android_asset/RELATIVEPATH

where RELATIVEPATH is the path to your resource relative to the assets folder.

Note the 3 /'s in the scheme. Web view would not load any of my assets without the 3. I tried 2 as (previously) commented by CommonsWare and it wouldn't work. Then I looked at CommonsWare's source on github and noticed the extra forward slash.

This testing though was only done on the 1.6 Android emulator but I doubt its different on a real device or higher version.

EDIT: CommonsWare updated his answer to reflect this tiny change. So I've edited this so it still makes sense with his current answer.

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

Using Anaconda + Spyder (Python 3.7)

[code]

import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
print(soma)
sess = tf.compat.v1.Session()
with sess:
    print(sess.run(soma))

[console]

import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
Tensor("Const_8:0", shape=(), dtype=int32)
Out[18]: tensorflow.python.framework.ops.Tensor

print(soma)
Tensor("add_4:0", shape=(), dtype=int32)

sess = tf.compat.v1.Session()

with sess:
    print(sess.run(soma))
5

Define an <img>'s src attribute in CSS

just this as img tag is a content element

img {
    content:url(http://example.com/image.png);
}

laravel Unable to prepare route ... for serialization. Uses Closure

the solustion when we use routes like this:

Route::get('/', function () {
    return view('welcome');
});

laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize

How can I convert JSON to CSV?

This code should work for you, assuming that your JSON data is in a file called data.json.

import json
import csv

with open("data.json") as file:
    data = json.load(file)

with open("data.csv", "w") as file:
    csv_file = csv.writer(file)
    for item in data:
        fields = list(item['fields'].values())
        csv_file.writerow([item['pk'], item['model']] + fields)

Can I replace groups in Java regex?

replace the password fields from the input:

{"_csrf":["9d90c85f-ac73-4b15-ad08-ebaa3fa4a005"],"originPassword":["uaas"],"newPassword":["uaas"],"confirmPassword":["uaas"]}



  private static final Pattern PATTERN = Pattern.compile(".*?password.*?\":\\[\"(.*?)\"\\](,\"|}$)", Pattern.CASE_INSENSITIVE);

  private static String replacePassword(String input, String replacement) {
    Matcher m = PATTERN.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      Matcher m2 = PATTERN.matcher(m.group(0));
      if (m2.find()) {
        StringBuilder stringBuilder = new StringBuilder(m2.group(0));
        String result = stringBuilder.replace(m2.start(1), m2.end(1), replacement).toString();
        m.appendReplacement(sb, result);
      }
    }
    m.appendTail(sb);
    return sb.toString();
  }

  @Test
  public void test1() {
    String input = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"123\"],\"newPassword\":[\"456\"],\"confirmPassword\":[\"456\"]}";
    String expected = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"**\"],\"newPassword\":[\"**\"],\"confirmPassword\":[\"**\"]}";
    Assert.assertEquals(expected, replacePassword(input, "**"));
  }

Databound drop down list - initial value

I know this is old, but a combination of these ideas leads to a very elegant solution:

Keep all the default property settings for the DropDownList (AppendDataBoundItems=false, Items empty). Then handle the DataBound event like this:

protected void dropdown_DataBound(object sender, EventArgs e)
{
    DropDownList list = sender as DropDownList;
    if (list != null)
        list.Items.Insert(0, "--Select One--");
}

The icing on the cake is that this one handler can be shared by any number of DropDownList objects, or even put into a general-purpose utility library for all your projects.