Programs & Examples On #Clientscript

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Calling Javascript function from server side

This works for me. Hope it will work for you too.

ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);

I have edited the html page which you have provided. The updated page is as below

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>My Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function Test() {
                alert("Hello Test!!!!");
                $('#ButtonRow').css("display", "block");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
                        BorderStyle="Solid">
                        <asp:ListItem>Merchant</asp:ListItem>
                        <asp:ListItem>Store</asp:ListItem>
                        <asp:ListItem>Terminal</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr id="ButtonRow" style="display: none">
                <td>
                    <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>

    <script type="text/javascript">

        $("#<%=SearchCategory.ClientID%> input").change(function () {
            alert("hi");
            $("#ButtonRow").show();
        });
    </script>

How to Check byte array empty or not?

.Net V 4.6 OR C # 6.0

Try This

 if (Attachment?.Length > 0)

How to open a page in a new window or tab from code-behind

Use:

Target= "_blank" property of anchor tag

Insert line after first match using sed

A POSIX compliant one using the s command:

sed '/CLIENTSCRIPT="foo"/s/.*/&\
CLIENTSCRIPT2="hello"/' file

window.open with target "_blank" in Chrome

As Dennis says, you can't control how the browser chooses to handle target=_blank.

If you're wondering about the inconsistent behavior, probably it's pop-up blocking. Many browsers will forbid new windows from being opened apropos of nothing, but will allow new windows to be spawned as the eventual result of a mouse-click event.

How to open new browser window on button click event?

Or write to the response stream:

Response.Write("<script>");
Response.Write("window.open('page.html','_blank')");
Response.Write("</script>");

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Is Button1 visible? I mean, from the server side. Make sure Button1.Visible is true.

Controls that aren't Visible won't be rendered in HTML, so although they are assigned a ClientID, they don't actually exist on the client side.

asp.net: Invalid postback or callback argument

If you look at the first lines of text you can glean what your error is.

this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them

You're dynamically editing the lstProblems dropdown, so when you post back ASP.NET says "Warning! Invalid entries in the dropdown!" and freaks out throwing that error. You have to determine if turning off event validation is an OK solution, but I would research it before doing it, since the idea behind it is to make your site more secure for free.

Here's another stackoverflow answer that does a much better job explaining what to do than me: Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

How to find Control in TemplateField of GridView?

string textboxID;
string da;
textboxID = "ctl00$MainContent$grd$ctl" + (grd.Columns.Count + j).ToString() + "$txtDyna" + (k).ToString();
textboxID= ctl00$MainContent$grd$ctl12$ctl00;
da = Request.Form(textboxID);

JavaScript: Alert.Show(message) From ASP.NET Code-behind

I use this and it works, as long as the page is not redirect afterwards. Would be nice to have it show, and wait until the user clicks OK, regardless of redirects.

/// <summary>
/// A JavaScript alert class
/// </summary>
public static class webMessageBox
{

/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
    public static void Show(string message)
    {
       // Cleans the message to allow single quotation marks
       string cleanMessage = message.Replace("'", "\\'");
       string wsScript = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

       // Gets the executing web page
       Page page = HttpContext.Current.CurrentHandler as Page;

       // Checks if the handler is a Page and that the script isn't allready on the Page
       if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
       {
           //ClientScript.RegisterStartupScript(this.GetType(), "MessageBox", wsScript, true);
           page.ClientScript.RegisterClientScriptBlock(typeof(webMessageBox), "alert", wsScript, false);
       }
    }    
}

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

How to scroll to top of a div using jQuery?

Here is what you can do using jquery:

$('#A_ID').click(function (e) { //#A_ID is an example. Use the id of your Anchor
    $('html, body').animate({
        scrollTop: $('#DIV_ID').offset().top - 20 //#DIV_ID is an example. Use the id of your destination on the page
    }, 'slow');
});

ClientScript.RegisterClientScriptBlock?

Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

Show hide div using codebehind

There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

Rendering and Visibility

There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

<div id="myDiv" runat="server"></div>

The decision to render the div or not can now be done in the code behind class like so:

myDiv.Visible = someConditionalBool;

If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

Client Side Hiding

Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

Hiding in the Code Behind Class

To hide an element that you want rendered to the page but hidden is another simple single line of code:

myDiv.Style["display"] = "none";

If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

// then to show again
myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

// ... and to show 
myDiv.show();

ASP.NET Custom Validator Client side & Server Side validation not firing

Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via

 Page.Validate({Insert validation group name here});

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

This was the reason why I was getting it:

I had an ASP:ListBox. Initially it was hidden. At client side I would populate it via AJAX with options. The user chose one option. Then when clicking the Submit button, the Server would get all funny about the ListBox, since it did not remember it having any options.

So what I did is to make sure I clear all the list options before submitting the form back to the server. That way the server did not complain since the list went to the client empty and it came back empty.

Sorted!!!

Get an image extension from an uploaded file in Laravel

Do something like this:

if($request->hasFile('video')){

    $video=$request->file('video');
    $filename=str_random(20).".".$video->extension(); 
    $path = Storage::putFileAs(
            '/', $video, $filename
     );
    $data['video']=$filename;
 }

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where d.id in (
    select a.id from docs_documents a
    left join docx_document b on b.id = a.document_id
    where b.id is null
        and floor(sysdate - a.create_date) > 120
 );

How to squash all git commits into one?

echo "message" | git commit-tree HEAD^{tree}

This will create an orphaned commit with the tree of HEAD, and output its name (SHA-1) on stdout. Then just reset your branch there.

git reset SHA-1

To do the above in a single step:

git reset $(git commit-tree HEAD^{tree} -m "commit message")

How to create a hidden <img> in JavaScript?

I'm not sure I understand your question. But there are two approaches to making the image invisible...

Pure HTML

<img src="a.gif" style="display: none;" />

Or...

HTML + Javascript

<script type="text/javascript">
document.getElementById("myImage").style.display = "none";
</script>

<img id="myImage" src="a.gif" />

Press Enter to move to next control

In a KeyPress event, if the user pressed Enter, call

SendKeys.Send("{TAB}")

Nicest way to implement automatically selecting the text on receiving focus is to create a subclass of TextBox in your project with the following override:

Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
    SelectionStart = 0
    SelectionLength = Text.Length
    MyBase.OnGotFocus(e)
End Sub

Then use this custom TextBox in place of the WinForms standard TextBox on all your Forms.

Sending an HTTP POST request on iOS

The following code describes a simple example using POST method.(How one can pass data by POST method)

Here, I describe how one can use of POST method.

1. Set post string with actual username and password.

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 

2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

You need to send the actual length of your data. Calculate the length of the post string.

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 

3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

Set the Url for which your going to send the data to that request.

[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]]; 

Now, set HTTP method (POST or GET). Write this lines as it is in your code.

[request setHTTPMethod:@"POST"]; 

Set HTTP header field with length of the post data.

[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

Also set the Encoded value for HTTP header Field.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

Set the HTTPBody of the urlrequest with postData.

[request setHTTPBody:postData];

4. Now, create URLConnection object. Initialize it with the URLRequest.

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

if(conn) {
    NSLog(@"Connection Successful");
} else {
    NSLog(@"Connection could not be made");
}

5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.

// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data

// This method receives the error report in case of connection is not made to server. 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 

// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

Also Refer This and This documentation for POST method.

And here is best example with source code of HTTPPost Method.

How to find an object in an ArrayList by property

For finding objects which are meaningfully equal, you need to override equals and hashcode methods for the class. You can find a good tutorial here.

http://www.thejavageek.com/2013/06/28/significance-of-equals-and-hashcode/

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

Restricting JTextField input to Integers

I can't believe I haven't found this simple solution anywhere on stack overflow yet, it is by far the most useful. Changing the Document or DocumentFilter does not work for JFormattedTextField. Peter Tseng's answer comes very close.

NumberFormat longFormat = NumberFormat.getIntegerInstance();

NumberFormatter numberFormatter = new NumberFormatter(longFormat);
numberFormatter.setValueClass(Long.class); //optional, ensures you will always get a long value
numberFormatter.setAllowsInvalid(false); //this is the key!!
numberFormatter.setMinimum(0l); //Optional

JFormattedTextField field = new JFormattedTextField(numberFormatter);

Find the version of an installed npm package

To see all the installed packages locally or globally, use these commands:

  1. npm list for local packages or npm list -g for globally installed packages.
  2. npm list --depth=0
  3. npm list | sls <package name>
  4. node -v

Loop through each row of a range in Excel

Dim a As Range, b As Range

Set a = Selection

For Each b In a.Rows
    MsgBox b.Address
Next

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

Download large file in python with requests

Your chunk size could be too large, have you tried dropping that - maybe 1024 bytes at a time? (also, you could use with to tidy up the syntax)

def DownloadFile(url):
    local_filename = url.split('/')[-1]
    r = requests.get(url)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
    return 

Incidentally, how are you deducing that the response has been loaded into memory?

It sounds as if python isn't flushing the data to file, from other SO questions you could try f.flush() and os.fsync() to force the file write and free memory;

    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
                os.fsync(f.fileno())

Vector of Vectors to create matrix

try this. m = row, n = col

vector<vector<int>> matrix(m, vector<int>(n));

for(i = 0;i < m; i++)
{
   for(j = 0; j < n; j++)
   {
      cin >> matrix[i][j];
   }
   cout << endl;
}
cout << "::matrix::" << endl;
for(i = 0; i < m; i++)
{
    for(j = 0; j < n; j++)
    {
        cout << matrix[i][j] << " ";
    }
    cout << endl;
}

how to get the cookies from a php curl into a variable

If you use CURLOPT_COOKIE_FILE and CURLOPT_COOKIE_JAR curl will read/write the cookies from/to a file. You can, after curl is done with it, read and/or modify it however you want.

How to drop column with constraint?

First you should drop the problematic DEFAULT constraint, after that you can drop the column

alter table tbloffers drop constraint [ConstraintName]
go

alter table tbloffers drop column checkin

But the error may appear from other reasons - for example the user defined function or view with SCHEMABINDING option set for them.

UPD: Completely automated dropping of constraints script:

DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
    SELECT TOP 1 @sql = N'alter table tbloffers drop constraint ['+dc.NAME+N']'
    from sys.default_constraints dc
    JOIN sys.columns c
        ON c.default_object_id = dc.object_id
    WHERE 
        dc.parent_object_id = OBJECT_ID('tbloffers')
    AND c.name = N'checkin'
    IF @@ROWCOUNT = 0 BREAK
    EXEC (@sql)
END

PHP 5.4 Call-time pass-by-reference - Easy fix available?

For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.

The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)

Using this regex:

^(?!.*function).*(\&\$)

it is possible to search project-wide for the occurrence of &$ only in lines that are not a function definition.

This still turns up a lot of false positives, but it does make the job easier.

VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.

Unix tail equivalent command in Windows Powershell

Just some additions to previous answers. There are aliases defined for Get-Content, for example if you are used to UNIX you might like cat, and there are also type and gc. So instead of

Get-Content -Path <Path> -Wait -Tail 10

you can write

# Print whole file and wait for appended lines and print them
cat <Path> -Wait
# Print last 10 lines and wait for appended lines and print them
cat <Path> -Tail 10 -Wait

How to add image in Flutter

  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

    flutter:
    
      uses-material-design: true
    
      # add this
      assets:
        - images/profile.jpg
    
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using

    Image.asset("images/profile.jpg")
    

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

How to pad a string to a fixed length with spaces in Python?

You can use the ljust method on strings.

>>> name = 'John'
>>> name.ljust(15)
'John           '

Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:

>>> name.ljust(15)[:15]

What's "P=NP?", and why is it such a famous question?

There is not much I can add to the what and why of the P=?NP part of the question, but in regards to the proof. Not only would a proof be worth some extra credit, but it would solve one of the Millennium Problems. An interesting poll was recently conducted and the published results (PDF) are definitely worth reading in regards to the subject of a proof.

Batch file to map a drive when the folder name contains spaces

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes 

does not work?

In Python, what does dict.pop(a,b) mean?

def func(*args): 
    pass

When you define a function this way, *args will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it.

You do this with keyword arguments too, using **kwargs:

def func2(**kwargs): 
    pass

See: Arbitrary argument lists


In your case, you've defined a class which is acting like a dictionary. The dict.pop method is defined as pop(key[, default]).

Your method doesn't use the default parameter. But, by defining your method with *args and passing *args to dict.pop(), you are allowing the caller to use the default parameter.

In other words, you should be able to use your class's pop method like dict.pop:

my_a = a()
value1 = my_a.pop('key1')       # throw an exception if key1 isn't in the dict
value2 = my_a.pop('key2', None) # return None if key2 isn't in the dict

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

No, there is not really any other way : if you have many locations and want to display them on a map, the best solution is to :

  • fetch the latitude+longitude, using the geocoder, when a location is created
  • store those in your database, alongside the address
  • and use those stored latitude+longitude when you want to display the map.

This is, of course, considering that you have a lot less creation/modification of locations than you have consultations of locations.


Yes, it means you'll have to do a bit more work when saving the locations -- but it also means :

  • You'll be able to search by geographical coordinates
    • i.e. "I want a list of points that are near where I'm now"
  • Displaying the map will be a lot faster
    • Even with more than 20 locations on it
  • Oh, and, also (last but not least) : this will work ;-)
    • You will less likely hit the limit of X geocoder calls in N seconds.
    • And you will less likely hit the limit of Y geocoder calls per day.

Getting number of days in a month

You want DateTime.DaysInMonth:

int days = DateTime.DaysInMonth(year, month);

Obviously it varies by year, as sometimes February has 28 days and sometimes 29. You could always pick a particular year (leap or not) if you want to "fix" it to one value or other.

Cannot install signed apk to device manually, got error "App not installed"

File > Project Structure > Build Variants > Select release > Make sure 'Signing Config' is not empty > if it is select from the drop window the $signingConfigs.release

I did this with Android Studio 3.1.4 and it allowed me to create a release apk after following all the steps above of creating the release apk and release key and adding the info to the app gradle. Cheers!

Where do I call the BatchNormalization function in Keras?

It is another type of layer, so you should add it as a layer in an appropriate place of your model

model.add(keras.layers.normalization.BatchNormalization())

See an example here: https://github.com/fchollet/keras/blob/master/examples/kaggle_otto_nn.py

Convert a Pandas DataFrame to a dictionary

If you don't mind the dictionary values being tuples, you can use itertuples:

>>> {x[0]: x[1:] for x in df.itertuples(index=False)}
{'p': (1, 3, 2), 'q': (4, 3, 2), 'r': (4, 0, 9)}

Plotting images side by side using matplotlib

As per matplotlib's suggestion for image grids:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, image_data):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()

What is the point of "final class" in Java?

TO ADDRESS THE FINAL CLASS PROBLEM:

There are two ways to make a class final. The first is to use the keyword final in the class declaration:

public final class SomeClass {
  //  . . . Class contents
}

The second way to make a class final is to declare all of its constructors as private:

public class SomeClass {
  public final static SOME_INSTANCE = new SomeClass(5);
  private SomeClass(final int value) {
  }

Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.

public class Test{
  private Test(Class beanClass, Class stopClass, int flags)
    throws Exception{
    //  . . . snip . . . 
  }
}

Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The Test class is a good example of how implicit final classes can cause problems.

So you should mark it final when you implicitly make a class final by making it's constructor private.

Null or empty check for a string variable

Yes, it works. Check the below example. Assuming @value is not int

WITH CTE 
AS
(
    SELECT NULL AS test
    UNION
    SELECT '' AS test
    UNION
    SELECT '123' AS test
)

SELECT 
    CASE WHEN isnull(test,'')='' THEN 'empty' ELSE test END AS IS_EMPTY 
FROM CTE

Result :

IS_EMPTY
--------
empty
empty
123

Error 1046 No database Selected, how to resolve?

first select database : USE db_name

then creat table:CREATE TABLE tb_name ( id int, name varchar(255), salary int, city varchar(255) );

this for mysql 5.5 version syntax

How to add a new audio (not mixing) into a video using ffmpeg?

None of these solutions quite worked for me. My original audio was being overwritten, or I was getting an error like "failed to map memory" with the more complex 'amerge' example. It seems I needed -filter_complex amix.

ffmpeg -i videowithaudioyouwanttokeep.mp4 -i audiotooverlay.mp3 -vcodec copy -filter_complex amix -map 0:v -map 0:a -map 1:a -shortest -b:a 144k out.mkv

Get week number (in the year) from a date PHP

I have tried to solve this question for years now, I thought I found a shorter solution but had to come back again to the long story. This function gives back the right ISO week notation:

/**
 * calcweek("2018-12-31") => 1901
 * This function calculates the production weeknumber according to the start on 
 * monday and with at least 4 days in the new year. Given that the $date has
 * the following format Y-m-d then the outcome is and integer.
 *
 * @author M.S.B. Bachus
 *
 * @param date-notation PHP "Y-m-d" showing the data as yyyy-mm-dd
 * @return integer
 **/
function calcweek($date) {
  // 1. Convert input to $year, $month, $day
  $dateset      = strtotime($date);
  $year         = date("Y", $dateset);
  $month        = date("m", $dateset);
  $day          = date("d", $dateset);

  $referenceday = getdate(mktime(0,0,0, $month, $day, $year));
  $jan1day      = getdate(mktime(0,0,0,1,1,$referenceday[year]));

  // 2. check if $year is a  leapyear
  if ( ($year%4==0 && $year%100!=0) || $year%400==0) {
    $leapyear = true;
  } else {
    $leapyear = false;
  }

  // 3. check if $year-1 is a  leapyear
  if ( (($year-1)%4==0 && ($year-1)%100!=0) || ($year-1)%400==0 ) {
    $leapyearprev = true;
  } else {
    $leapyearprev = false;
  }

  // 4. find the dayofyearnumber for y m d
  $mnth = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
  $dayofyearnumber = $day + $mnth[$month-1];
  if ( $leapyear && $month > 2 ) { $dayofyearnumber++; }

  // 5. find the jan1weekday for y (monday=1, sunday=7)
  $yy = ($year-1)%100;
  $c  = ($year-1) - $yy;
  $g  = $yy + intval($yy/4);
  $jan1weekday = 1+((((intval($c/100)%4)*5)+$g)%7);

  // 6. find the weekday for y m d
  $h = $dayofyearnumber + ($jan1weekday-1);
  $weekday = 1+(($h-1)%7);

  // 7. find if y m d falls in yearnumber y-1, weeknumber 52 or 53
  $foundweeknum = false;
  if ( $dayofyearnumber <= (8-$jan1weekday) && $jan1weekday > 4 ) {
    $yearnumber = $year - 1;
    if ( $jan1weekday = 5 || ( $jan1weekday = 6 && $leapyearprev )) {
      $weeknumber = 53;
    } else {
      $weeknumber = 52;
    }
    $foundweeknum = true;
  } else {
    $yearnumber = $year;
  }

  // 8. find if y m d falls in yearnumber y+1, weeknumber 1
  if ( $yearnumber == $year && !$foundweeknum) {
    if ( $leapyear ) {
      $i = 366;
    } else {
      $i = 365;
    }
    if ( ($i - $dayofyearnumber) < (4 - $weekday) ) {
      $yearnumber = $year + 1;
      $weeknumber = 1;
      $foundweeknum = true;
    }
  }

  // 9. find if y m d falls in yearnumber y, weeknumber 1 through 53
  if ( $yearnumber == $year && !$foundweeknum ) {
    $j = $dayofyearnumber + (7 - $weekday) + ($jan1weekday - 1);
    $weeknumber = intval( $j/7 );
    if ( $jan1weekday > 4 ) { $weeknumber--; }
  }

  // 10. output iso week number (YYWW)
  return ($yearnumber-2000)*100+$weeknumber;
}

I found out that my short solution missed the 2018-12-31 as it gave back 1801 instead of 1901. So I had to put in this long version which is correct.

Java's L number (long) specification

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix).

How to create a .NET DateTime from ISO 8601 format

Although MSDN says that "s" and "o" formats reflect the standard, they seem to be able to parse only a limited subset of it. Especially it is a problem if the string contains time zone specification. (Neither it does for basic ISO8601 formats, or reduced precision formats - however this is not exactly your case.) That is why I make use of custom format strings when it comes to parsing ISO8601. Currently my preferred snippet is:

static readonly string[] formats = { 
    // Basic formats
    "yyyyMMddTHHmmsszzz",
    "yyyyMMddTHHmmsszz",
    "yyyyMMddTHHmmssZ",
    // Extended formats
    "yyyy-MM-ddTHH:mm:sszzz",
    "yyyy-MM-ddTHH:mm:sszz",
    "yyyy-MM-ddTHH:mm:ssZ",
    // All of the above with reduced accuracy
    "yyyyMMddTHHmmzzz",
    "yyyyMMddTHHmmzz",
    "yyyyMMddTHHmmZ",
    "yyyy-MM-ddTHH:mmzzz",
    "yyyy-MM-ddTHH:mmzz",
    "yyyy-MM-ddTHH:mmZ",
    // Accuracy reduced to hours
    "yyyyMMddTHHzzz",
    "yyyyMMddTHHzz",
    "yyyyMMddTHHZ",
    "yyyy-MM-ddTHHzzz",
    "yyyy-MM-ddTHHzz",
    "yyyy-MM-ddTHHZ"
    };

public static DateTime ParseISO8601String ( string str )
{
    return DateTime.ParseExact ( str, formats, 
        CultureInfo.InvariantCulture, DateTimeStyles.None );
}

If you don't mind parsing TZ-less strings (I do), you can add an "s" line to greatly extend the number of covered format alterations.

Force decimal point instead of comma in HTML5 number input (client-side)

Use lang attribut on the input. Locale on my web app fr_FR, lang="en_EN" on the input number and i can use indifferently a comma or a dot. Firefox always display a dot, Chrome display a comma. But both separtor are valid.

Laravel migration table field's type change

The standard solution didn't work for me, when changing the type from TEXT to LONGTEXT.

I had to it like this:

public function up()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn  LONGTEXT;');
}

public function down()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn TEXT;');
}

This could be a Doctrine issue. More information here.

Another way to do it is to use the string() method, and set the value to the text type max length:

    Schema::table('mytable', function ($table) {
        // Will set the type to LONGTEXT.
        $table->string('mycolumn', 4294967295)->change();
    });

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib

How to convert DateTime to a number with a precision greater than days in T-SQL?

You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.

DECLARE @Date DATETIME = Getdate()
DECLARE @DateInt INT = CONVERT(VARCHAR(30), @Date, 112)
DECLARE @TimeInt INT = REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
DECLARE @DateTimeInt BIGINT = CONVERT(VARCHAR(30), @Date, 112) + REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
SELECT @Date as Date, @DateInt DateInt, @TimeInt TimeInt, @DateTimeInt DateTimeInt

Date                    DateInt     TimeInt     DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107    150821      20130107150821

How to access the php.ini file in godaddy shared hosting linux

Not php.ini file, but a way around it. Go to GoDaddy's

Files > Backup > Restore a MySQL Database Backup

Choose your file and click Upload. No timeouts. Rename the DB if needed, and assign a user in

Databases > MySQL Databases

What does "Error: object '<myvariable>' not found" mean?

Let's discuss why an "object not found" error can be thrown in R in addition to explaining what it means. What it means (to many) is obvious: the variable in question, at least according to the R interpreter, has not yet been defined, but if you see your object in your code there can be multiple reasons for why this is happening:

  1. check syntax of your declarations. If you mis-typed even one letter or used upper case instead of lower case in a later calling statement, then it won't match your original declaration and this error will occur.

  2. Are you getting this error in a notebook or markdown document? You may simply need to re-run an earlier cell that has your declarations before running the current cell where you are calling the variable.

  3. Are you trying to knit your R document and the variable works find when you run the cells but not when you knit the cells? If so - then you want to examine the snippet I am providing below for a possible side effect that triggers this error:

    {r sourceDataProb1, echo=F, eval=F} # some code here

The above snippet is from the beginning of an R markdown cell. If eval and echo are both set to False this can trigger an error when you try to knit the document. To clarify. I had a use case where I had left these flags as False because I thought i did not want my code echoed or its results to show in the markdown HTML I was generating. But since the variable was then used in later cells, this caused an error during knitting. Simple trial and error with T/F TRUE/FALSE flags can establish if this is the source of your error when it occurs in knitting an R markdown document from RStudio.

Lastly: did you remove the variable or clear it from memory after declaring it?

  • rm() removes the variable
  • hitting the broom icon in the evironment window of RStudio clearls everything in the current working environment
  • ls() can help you see what is active right now to look for a missing declaration.
  • exists("x") - as mentioned by another poster, can help you test a specific value in an environment with a very lengthy list of active variables

Is Secure.ANDROID_ID unique for each device?

Just list an alternaitve solution here, the Advertising ID:

https://support.google.com/googleplay/android-developer/answer/6048248?hl=en

Copied from the link above:

The advertising ID is a unique, user-resettable ID for advertising, provided by Google Play services. It gives users better controls and provides developers with a simple, standard system to continue to monetize their apps. It enables users to reset their identifier or opt out of personalized ads (formerly known as interest-based ads) within Google Play apps.

The limitations are:

  1. Google Play enabled devices only.
  2. Privacy Policy: https://support.google.com/googleplay/android-developer/answer/113469?hl=en&rd=1#privacy

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Count all values in a matrix greater than a value

There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask array is the easiest one (and iirc a much faster one):

>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[  123, 24123, 32432],
       [  234,    24,    23]])
>>> b = y > 200
>>> b
array([[False,  True,  True],
       [ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432,   234])
>>> len(y[b])
3
>>>> y[b].sum()
56789

Update:

As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:

>>>> (y>200).sum()
3

which is a simpler solution.


Speed comparison with filter:

### use boolean/mask array ###

b = y > 200

%timeit y[b]
100000 loops, best of 3: 3.31 us per loop

%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop

### use filter ###

x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop

%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop

%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop

%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop

*** use numpy.where ***

nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop

%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop

List supported SSL/TLS versions for a specific OpenSSL build

When you run OPENSSL command using s_client this is the output. See the Cipher, if the cipher NULL it means that version of TLS is not supported.

TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : ECDHE-RSA-AES256
    Session-ID: A84600002D4945DE6
    Session-ID-ctx:
    Master-Key:  
    Start Time: 15852343333860
    Timeout   : 2343 (sec)
    Verify return code: 0 (ok)

Find all storage devices attached to a Linux machine

/proc/partitions will list all the block devices and partitions that the system recognizes. You can then try using file -s <device> to determine what kind of filesystem is present on the partition, if any.

document.getElementByID is not a function

It worked like this for me:

document.getElementById("theElementID").setAttribute("src", source);
document.getElementById("task-text").innerHTML = "";

Change the

getElementById("theElementID")

for your element locator (name, css, xpath...)

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

The key is to set match processor settings for the project which are at two places.

enter image description here

And also make sure the architecture settings is same in Test menu >> Test Settings >> Default Processor Architecture >> as show below.

enter image description here

This is for VS2013 but maybe same for other versions too.

Update - For VS2019:

enter image description here

Datatype for storing ip address in SQL Server

I'm using varchar(15) so far everything is working for me. Insert, Update, Select. I have just started an app that has IP Addresses, though I have not done much dev work yet.

Here is the select statement:

select * From dbo.Server 
where  [IP] = ('132.46.151.181')
Go

ReSharper "Cannot resolve symbol" even when project builds

I ended up needing to request Resharper to clear its cache along with doing it manually through Windows File Explorer. This finally resolved the issue for me.

  1. (As reported in many of the solutions here) RESHARPER > Options... > Environment > General > Clear Caches.
  2. Close Visual Studio.
  3. Go to this path in File Explorer for Resharper 10 in Visual Studio 2015: %localappdata%\JetBrains\Transient\ReSharperPlatformVs14
  4. Delete all subfolders and their contents within that folder.
  5. Restart Visual Studio, reload your Solution and wait for Resharper to initialize itself for the Solution.

Cannot run the macro... the macro may not be available in this workbook

In my case the error happened when I placed my macro (public sub) into a ThisWorkbook section of the file expecting it will make it visible for Application.Run function. This was not the case and I got that error you mentioned.

I moved my macro into a separate Module and it resolved the problem.

Aligning two divs side-by-side

This Can be Done by Style Property.

<!DOCTYPE html>
<html>
<head>
<style> 
#main {

  display: flex;
}

#main div {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 40px;
}
</style>
</head>
<body>

<div id="main">
  <div style="background-color:coral;">Red DIV</div>
  <div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>

</body>
</html>

Its Result will be :

enter image description here

Enjoy... Please Note: This works in Higher version of CSS (>3.0).

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

I got the solution for the Android Studio installation after trying everything that I could find on the Internet. If you're using Android Studio and getting this error:

Find [Path_to_Android_SDK]\sdk\tools\android.bat. In my case, it was in C:\Users\Nathan\AppData\Local\Android\android-studio\sdk\tools\android.bat.

Right-click it, hit Edit, and scroll all the way down to the bottom.

Find where it says: call %java_exe% %REMOTE_DEBUG% ...

Replace that with call %java_exe% -Djava.net.preferIPv4Stack=true %REMOTE_DEBUG% ...

Restart Android Studio/SDK and everything works. This fixed many issues for me, including being unable to fetch XML files or create new projects.

C#: Printing all properties of an object

Any other solution/library is in the end going to use reflection to introspect the type...

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

your Apple developer certificate might have expired or else ur system date is greater than your account expiry date

How can I make a button redirect my page to another page?

you could do so:

<button onclick="location.href='page'">

you could change the action attribute of the form on click the button:

<button class="float-left submit-button" onclick='myFun()'>Home</button>

<script>
myFun(){
$('form').attr('action','new path');
}
</script>

Add Whatsapp function to website, like sms, tel

Use:

https://wa.me/YOURNUMBER

where YOURNUMBER is without the two leading 00.

For instance for +37061204312 you write:

https://wa.me/37061204312

This link seems to work on mobiles and on desktop computers.

To prefill the message with text you can use:

https://wa.me/YOURNUMBER/?text=urlencodedtext

More in the Whatsapp FAQ: https://faq.whatsapp.com/en/android/26000030/

What is the difference between String.slice and String.substring?

slice() works like substring() with a few different behaviors.

Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);

What they have in common:

  1. If start equals stop: returns an empty string
  2. If stop is omitted: extracts characters to the end of the string
  3. If either argument is greater than the string's length, the string's length will be used instead.

Distinctions of substring():

  1. If start > stop, then substring will swap those 2 arguments.
  2. If either argument is negative or is NaN, it is treated as if it were 0.

Distinctions of slice():

  1. If start > stop, slice() will return the empty string. ("")
  2. If start is negative: sets char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
  3. If stop is negative: sets stop to: string.length – Math.abs(stop) (original value), except bounded at 0 (thus, Math.max(0, string.length + stop)) as covered in the ECMA specification.

Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()

Notepad++ add to every line

To append different text to the end of each line, you can use the plugin ConyEdit to do this.
With ConyEdit running in the background, follow these steps.

  1. use the command line cc.gl a to get lines and store in an array named a.
  2. use the command line cc.aal //$a to append after each line, using the contents of array a.

Example
enter image description here

Disable eslint rules for folder

YAML version :

overrides:
  - files: *-tests.js
    rules:
      no-param-reassign: 0

Example of specific rules for mocha tests :

You can also set a specific env for a folder, like this :

overrides:
  - files: test/*-tests.js
    env:
      mocha: true

This configuration will fix error message about describe and it not defined, only for your test folder:

/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef

What is the difference between Serializable and Externalizable in Java?

To add to the other answers, by implementating java.io.Serializable, you get "automatic" serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.

In earlier version of Java, reflection was very slow, and so serializaing large object graphs (e.g. in client-server RMI applications) was a bit of a performance problem. To handle this situation, the java.io.Externalizable interface was provided, which is like java.io.Serializable but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement readExternal and writeExternal methods on your class). This gives you the means to get around the reflection performance bottleneck.

In recent versions of Java (1.3 onwards, certainly) the performance of reflection is vastly better than it used to be, and so this is much less of a problem. I suspect you'd be hard-pressed to get a meaningful benefit from Externalizable with a modern JVM.

Also, the built-in Java serialization mechanism isn't the only one, you can get third-party replacements, such as JBoss Serialization, which is considerably quicker, and is a drop-in replacement for the default.

A big downside of Externalizable is that you have to maintain this logic yourself - if you add, remove or change a field in your class, you have to change your writeExternal/readExternal methods to account for it.

In summary, Externalizable is a relic of the Java 1.1 days. There's really no need for it any more.

Scrolling to an Anchor using Transition/CSS3

While some of the answers were very useful and informative, I thought I would write down the answer I came up with. The answer from Alex was very good, it is however limited in the sense that the height of the div needs to be hard coded in the CSS.

So the solution I came up with uses JS (no jQuery) and is actually a stripped down version (almost to the minimum) of over solutions to solve similar problems I found on Statckoverflow:

HTML

<div class="header">
    <p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
    <p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
    <p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
    <p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
    <div id="S1" class="curtain">
    blabla
    </div>
    <div id="S2" class="curtain">
    blabla
    </div>
    <div id="S3" class="curtain">
    blabla
    </div>
    <div id="S4" class="curtain">
    blabla
    </div>
 </div>

NOTE THE "RETURN FALSE;" in the on click call. This is important if you want to avoid having your browser jumping to the link itself (and let the effect being managed by your JS).

JS code:

<script>
function scrollTo(to, duration) {
    if (document.body.scrollTop == to) return;
    var diff = to - document.body.scrollTop;
    var scrollStep = Math.PI / (duration / 10);
    var count = 0, currPos;
    start = element.scrollTop;
    scrollInterval = setInterval(function(){
        if (document.body.scrollTop != to) {
            count = count + 1;
            currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
            document.body.scrollTop = currPos;
        }
        else { clearInterval(scrollInterval); }
    },10);
}

function test(elID)
{
    var dest = document.getElementById(elID);
    scrollTo(dest.offsetTop, 500);
}
</script>

It's incredibly simple. It finds the vertical position of the div in the document using its unique ID (in the function test). Then it calls the scrollTo function passing the starting position (document.body.scrollTop) and the destination position (dest.offsetTop). It performs the transition using some sort of ease-inout curve.

Thanks everyone for your help.

Knowing a bit of coding can help you avoiding (sometimes heavy) libraries, and giving you (the programmer) more control.

Android Studio is slow (how to speed up)?

try deleting c:\users\.AndroidStudioX.X folder. it will also remove your android studio settings and customization

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

For those who still have this problem, and none of the above solutions worked for you:
Update your versions of java and Eclipse.
In my case, I updated from java 7 to java 9, and Eclipse Mars to Eclipse Oxygen, and this problem was solved !!!

Storing sex (gender) in database

I would go with Option 3 but multiple NON NULLABLE bit columns instead of one. IsMale (1=Yes / 0=No) IsFemale (1=Yes / 0=No)

if requried: IsUnknownGender (1=Yes / 0=No) and so on...

This makes for easy reading of the definitions, easy extensibility, easy programmability, no possibility of using values outside the domain and no requirement of a second lookup table+FK or CHECK constraints to lock down the values.

EDIT: Correction, you do need at least one constraint to ensure the set flags are valid.

Multiple IF statements between number ranges

standalone one cell solution based on VLOOKUP

US syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A),
        IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
 {{(TRANSPOSE({{{0;   "Less than 500"},
               {500;  "Between 500 and 1000"}},
              {{1000; "Between 1000 and 1500"},
               {1500; "Between 1500 and 2000"}}}))}}, 2)),)), )

EU syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A);
        IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
 {{(TRANSPOSE({{{0;   "Less than 500"}\
               {500;  "Between 500 and 1000"}}\
              {{1000; "Between 1000 and 1500"}\
               {1500; "Between 1500 and 2000"}}}))}}; 2));)); )

alternatives: https://webapps.stackexchange.com/questions/123729/

iOS Remote Debugging

I haven't tried it, but iOS WebKit debug proxy (ios_webkit_debug_proxy / iwdp) supposedly lets you remotely debug UIWebView. From the README.md

The ios_webkit_debug_proxy (aka iwdp) allows developers to inspect MobileSafari and UIWebViews on real and simulated iOS devices via the Chrome DevTools UI and Chrome Remote Debugging Protocol. DevTools requests are translated into Apple's Remote Web Inspector service calls.

How to make a input field readonly with JavaScript?

The above answers did not work for me. The below does: document.getElementById("input_field_id").setAttribute("readonly", true);

And to remove the readonly attribute: document.getElementById("input_field_id").removeAttribute("readonly");

And for running when the page is loaded, it is worth referring to here.

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Java 1.7 makes our lives much easier thanks to the try-with-resources statement.

try (Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement()) {
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do stuff with the result set.
    }
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do more stuff with the second result set.
    }
}

This syntax is quite brief and elegant. And connection will indeed be closed even when the statement couldn't be created.

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

This should work.

SELECT a.[CUSTOMER ID], a.[NAME], SUM(b.[AMOUNT]) AS [TOTAL AMOUNT]
FROM RES_DATA a INNER JOIN INV_DATA b
ON a.[CUSTOMER ID]=b.[CUSTOMER ID]
GROUP BY a.[CUSTOMER ID], a.[NAME]

I tested it with SQL Fiddle against SQL Server 2008: http://sqlfiddle.com/#!3/1cad5/1

Basically what's happening here is that, because of the join, you are getting the same row on the "left" (i.e. from the RES_DATA table) for every row on the "right" (i.e. the INV_DATA table) that has the same [CUSTOMER ID] value. When you group by just the columns on the left side, and then do a sum of just the [AMOUNT] column from the right side, it keeps the one row intact from the left side, and sums up the matching values from the right side.

Add up a column of numbers at the Unix shell

Pipe to gawk:

 cat files.txt | xargs ls -l | cut -c 23-30 | gawk 'BEGIN { sum = 0 } // { sum = sum + $0 } END { print sum }'

Table with fixed header and fixed column on pure css

Something like this may work for you... It will probably require you to have set column widths for your header row.

thead { 
    position: fixed;
}

http://jsfiddle.net/vkhNC/

Update:

I am not convinced that the example you gave is possible with just CSS. I would love for someone to prove me wrong. Here is what I have so far. It is not the finished product but it could be a start for you. I hope this points you in a helpful direction, wherever that may be.

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

How to escape "&" in XML?

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

MySQL Event Scheduler on a specific time everyday

My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:

CREATE EVENT applog_clean_event
ON SCHEDULE 
    EVERY 1 DAY
    STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO 

How to detect when cancel is clicked on file input?

The new File System Access API will make our life easy again :)

try {
    const [fileHandle] = await window.showOpenFilePicker();
    const file = await fileHandle.getFile();
    // ...
}
catch (e) {
    console.log('Cancelled, no file selected');
}

Browser support is very limited (Jan, 2021). The example code works well in Chrome Desktop 86.

Generate list of all possible permutations of a string

def permutation(str)
  posibilities = []
  str.split('').each do |char|
    if posibilities.size == 0
      posibilities[0] = char.downcase
      posibilities[1] = char.upcase
    else
      posibilities_count = posibilities.length
      posibilities = posibilities + posibilities
      posibilities_count.times do |i|
        posibilities[i] += char.downcase
        posibilities[i+posibilities_count] += char.upcase
      end
    end
  end
  posibilities
end

Here is my take on a non recursive version

What is in your .vimrc?

My 242-line .vimrc is not that interesting, but since nobody mentioned it, I felt like I must share the two most important mappings that have enhanced my workflow besides the default mappings:

map <C-j> :bprev<CR>
map <C-k> :bnext<CR>
set hidden " this will go along

Seriously, switching buffers is the thing to do very often. Windows, sure, but everything doesn't fit the screen so nicely.

Similar set of maps for quick browsing of errors (see quickfix) and grep results:

map <C-n> :cn<CR>
map <C-m> :cp<CR>

Simple, effortless and efficient.

How to extract table as text from the PDF using Python?

This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.

Here are the steps I found to work.

  1. Use pdfimages from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.

  2. Use Tesseract to detect rotation and ImageMagick mogrify to fix it.

  3. Use OpenCV to find and extract tables.

  4. Use OpenCV to find and extract each cell from the table.

  5. Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.

  6. Use Tesseract to OCR each cell.

  7. Combine the extracted text of each cell into the format you need.

I wrote a python package with modules that can help with those steps.

Repo: https://github.com/eihli/image-table-ocr

Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html

Some of the steps don't require code, they take advantage of external tools like pdfimages and tesseract. I'll provide some brief examples for a couple of the steps that do require code.

  1. Finding tables:

This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/

import cv2

def find_tables(image):
    BLUR_KERNEL_SIZE = (17, 17)
    STD_DEV_X_DIRECTION = 0
    STD_DEV_Y_DIRECTION = 0
    blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
    MAX_COLOR_VAL = 255
    BLOCK_SIZE = 15
    SUBTRACT_FROM_MEAN = -2

    img_bin = cv2.adaptiveThreshold(
        ~blurred,
        MAX_COLOR_VAL,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        BLOCK_SIZE,
        SUBTRACT_FROM_MEAN,
    )
    vertical = horizontal = img_bin.copy()
    SCALE = 5
    image_width, image_height = horizontal.shape
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
    horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
    vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)

    horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
    vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))

    mask = horizontally_dilated + vertically_dilated
    contours, hierarchy = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
    )

    MIN_TABLE_AREA = 1e5
    contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
    perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
    epsilons = [0.1 * p for p in perimeter_lengths]
    approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
    bounding_rects = [cv2.boundingRect(a) for a in approx_polys]

    # The link where a lot of this code was borrowed from recommends an
    # additional step to check the number of "joints" inside this bounding rectangle.
    # A table should have a lot of intersections. We might have a rectangular image
    # here though which would only have 4 intersections, 1 at each corner.
    # Leaving that step as a future TODO if it is ever necessary.
    images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
    return images
  1. Extract cells from table.

This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.

We want to identify the cells from left-to-right, top-to-bottom.

We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.

def cell_in_same_row(c1, c2):
    c1_center = c1[1] + c1[3] - c1[3] / 2
    c2_bottom = c2[1] + c2[3]
    c2_top = c2[1]
    return c2_top < c1_center < c2_bottom

orig_cells = [c for c in cells]
rows = []
while cells:
    first = cells[0]
    rest = cells[1:]
    cells_in_same_row = sorted(
        [
            c for c in rest
            if cell_in_same_row(c, first)
        ],
        key=lambda c: c[0]
    )

    row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
    rows.append(row_cells)
    cells = [
        c for c in rest
        if not cell_in_same_row(c, first)
    ]

# Sort rows by average height of their center.
def avg_height_of_center(row):
    centers = [y + h - h / 2 for x, y, w, h in row]
    return sum(centers) / len(centers)

rows.sort(key=avg_height_of_center)

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

How do I concatenate two text files in PowerShell?

I used:

Get-Content c:\FileToAppend_*.log | Out-File -FilePath C:\DestinationFile.log 
-Encoding ASCII -Append

This appended fine. I added the ASCII encoding to remove the nul characters Notepad++ was showing without the explicit encoding.

Is it a good practice to place C++ definitions in header files?

As Tuomas said, your header should be minimal. To be complete I will expand a bit.

I personally use 4 types of files in my C++ projects:

  • Public:
  • Forwarding header: in case of templates etc, this file get the forwarding declarations that will appear in the header.
  • Header: this file includes the forwarding header, if any, and declare everything that I wish to be public (and defines the classes...)
  • Private:
  • Private header: this file is a header reserved for implementation, it includes the header and declares the helper functions / structures (for Pimpl for example or predicates). Skip if unnecessary.
  • Source file: it includes the private header (or header if no private header) and defines everything (non-template...)

Furthermore, I couple this with another rule: Do not define what you can forward declare. Though of course I am reasonable there (using Pimpl everywhere is quite a hassle).

It means that I prefer a forward declaration over an #include directive in my headers whenever I can get away with them.

Finally, I also use a visibility rule: I limit the scopes of my symbols as much as possible so that they do not pollute the outer scopes.

Putting it altogether:

// example_fwd.hpp
// Here necessary to forward declare the template class,
// you don't want people to declare them in case you wish to add
// another template symbol (with a default) later on
class MyClass;
template <class T> class MyClassT;

// example.hpp
#include "project/example_fwd.hpp"

// Those can't really be skipped
#include <string>
#include <vector>

#include "project/pimpl.hpp"

// Those can be forward declared easily
#include "project/foo_fwd.hpp"

namespace project { class Bar; }

namespace project
{
  class MyClass
  {
  public:
    struct Color // Limiting scope of enum
    {
      enum type { Red, Orange, Green };
    };
    typedef Color::type Color_t;

  public:
    MyClass(); // because of pimpl, I need to define the constructor

  private:
    struct Impl;
    pimpl<Impl> mImpl; // I won't describe pimpl here :p
  };

  template <class T> class MyClassT: public MyClass {};
} // namespace project

// example_impl.hpp (not visible to clients)
#include "project/example.hpp"
#include "project/bar.hpp"

template <class T> void check(MyClass<T> const& c) { }

// example.cpp
#include "example_impl.hpp"

// MyClass definition

The lifesaver here is that most of the times the forward header is useless: only necessary in case of typedef or template and so is the implementation header ;)

Check if a varchar is a number (TSQL)

Do not forget to exclude carriage returns from your data !!!

as in:

SELECT 
  Myotherval
  , CASE WHEN TRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '%[^0-9]%' and RTRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '.' and isnumeric(REPLACE([MyVal], char(13) + char(10), '')) = 1 THEN 'my number: ' +  [MyVal]
             ELSE ISNULL(Cast([MyVal] AS VARCHAR(8000)), '')
        END AS 'MyVal'
FROM MyTable

Python wildcard search in string

Same idea as Yuushi in using regular expressions, but this uses the findall method within the re library instead of a list comprehension:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)

How to serve an image using nodejs

2016 Update

Examples with Express and without Express that actually work

This question is over 5 years old but every answer has some problems.

TL;DR

Scroll down for examples to serve an image with:

  1. express.static
  2. express
  3. connect
  4. http
  5. net

All of the examples are also on GitHub: https://github.com/rsp/node-static-http-servers

Test results are available on Travis: https://travis-ci.org/rsp/node-static-http-servers

Introduction

After over 5 years since this question was asked there is only one correct answer by generalhenry but even though that answer has no problems with the code, it seems to have some problems with reception. It was commented that it "doesn't explain much other than how to rely on someone else to get the job done" and the fact how many people have voted this comment up clearly shows that a lot of things need clarification.

First of all, a good answer to "How to serve images using Node.js" is not implementing a static file server from scratch and doing it badly. A good answer is using a module like Express that does the job correctly.

Answering comments that say that using Express "doesn't explain much other than how to rely on someone else to get the job done" it should be noted, that using the http module already relies on someone else to get the job done. If someone doesn't want to rely on anyone to get the job done then at least raw TCP sockets should be used instead - which I do in one of my examples below.

A more serious problem is that all of the answers here that use the http module are broken. They introduce race conditions, insecure path resolution that will lead to path traversal vulnerability, blocking I/O that will completely fail to serve any concurrent requests at all and other subtle problems - they are completely broken as examples of what the question asks about, and yet they already use the abstraction that is provided by the http module instead of using TCP sockets so they don't even do everything from scratch as they claim.

If the question was "How to implement static file server from scratch, as a learning exercise" then by all means answers how to do that should be posted - but even then we should expect them to at least be correct. Also, it is not unreasonable to assume that someone who wants to serve an image might want to serve more images in the future so one could argue that writing a specific custom static file server that can serve only one single file with hard-coded path is somewhat shortsighted. It seems hard to imagine that anyone who searches for an answer on how to serve an image would be content with a solution that serves just a single image instead of a general solution to serve any image.

In short, the question is how to serve an image and an answer to that is to use an appropriate module to do that in a secure, preformant and reliable way that is readable, maintainable and future-proof while using the best practice of professional Node development. But I agree that a great addition to such an answer would be showing a way to implement the same functionality manually but sadly every attempt to do that has failed so far. And that is why I wrote some new examples.

After this short introduction, here are my five examples doing the job on 5 different levels of abstraction.

Minimum functionality

Every example serves files from the public directory and supports the minumum functionality of:

  • MIME types for most common files
  • serves HTML, JS, CSS, plain text and images
  • serves index.html as a default directory index
  • responds with error codes for missing files
  • no path traversal vulnerabilities
  • no race conditions while reading files

I tested every version on Node versions 4, 5, 6 and 7.

express.static

This version uses the express.static built-in middleware of the express module.

This example has the most functionality and the least amount of code.

var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

express

This version uses the express module but without the express.static middleware. Serving static files is implemented as a single route handler using streams.

This example has simple path traversal countermeasures and supports a limited set of most common MIME types.

var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.get('*', function (req, res) {
    var file = path.join(dir, req.path.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        return res.status(403).end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.set('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.set('Content-Type', 'text/plain');
        res.status(404).end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

connect

This version uses the connect module which is a one level of abstraction lower than express.

This example has similar functionality to the express version but using slightly lower-lever APIs.

var path = require('path');
var connect = require('connect');
var app = connect();
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

app.use(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

http

This version uses the http module which is the lowest-level API for HTTP in Node.

This example has similar functionality to the connect version but using even more lower-level APIs.

var path = require('path');
var http = require('http');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = http.createServer(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

net

This version uses the net module which is the lowest-level API for TCP sockets in Node.

This example has some of the functionality of the http version but the minimal and incomplete HTTP protocol has been implemented from scratch. Since it doesn't support chunked encoding it loads the files into memory before serving them to know the size before sending a response because statting the files and then loading would introduce a race condition.

var path = require('path');
var net = require('net');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = net.createServer(function (con) {
    var input = '';
    con.on('data', function (data) {
        input += data;
        if (input.match(/\n\r?\n\r?/)) {
            var line = input.split(/\n/)[0].split(' ');
            var method = line[0], url = line[1], pro = line[2];
            var reqpath = url.toString().split('?')[0];
            if (method !== 'GET') {
                var body = 'Method not implemented';
                con.write('HTTP/1.1 501 Not Implemented\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
            if (file.indexOf(dir + path.sep) !== 0) {
                var body = 'Forbidden';
                con.write('HTTP/1.1 403 Forbidden\n');
                con.write('Content-Type: text/plain\n');
                con.write('Content-Length: '+body.length+'\n\n');
                con.write(body);
                con.destroy();
                return;
            }
            var type = mime[path.extname(file).slice(1)] || 'text/plain';
            var s = fs.readFile(file, function (err, data) {
                if (err) {
                    var body = 'Not Found';
                    con.write('HTTP/1.1 404 Not Found\n');
                    con.write('Content-Type: text/plain\n');
                    con.write('Content-Length: '+body.length+'\n\n');
                    con.write(body);
                    con.destroy();
                } else {
                    con.write('HTTP/1.1 200 OK\n');
                    con.write('Content-Type: '+type+'\n');
                    con.write('Content-Length: '+data.byteLength+'\n\n');
                    con.write(data);
                    con.destroy();
                }
            });
        }
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});

Download examples

I posted all of the examples on GitHub with more explanation.

Examples with express.static, express, connect, http and net:

Other project using only express.static:

Tests

Test results are available on Travis:

Everything is tested on Node versions 4, 5, 6, and 7.

See also

Other related answers:

Questions every good .NET developer should be able to answer?

I'd not ask those "know something from the textbook" questions, but rather ask some tinkering stuff like:

  • What does the foreach loop do in plain C#? (Expecting him to write a iterator loop.)
  • What's a singleton?
  • Let him/her parse a String to Datetime (expecting him/her to use TryParse instead of try/catch)
  • Implement the singleton, strategy and command patterns
  • Let him/her Refactor a piece of code for testing. Expecting him/her to abstract the external services away from the Unit under Test and implement his own Test-double of the service (providing no mocking framework)

These are not 100% sure, depending on the person I may ask them:

  • let him/her guard a method from null input (expecting him/her to use multiple returns to reduce nesting)
  • how does a object initializer work (Expecting him/her to write the thread-safe assignment)

Also I'd ask him how he/she learned his/her stuff and what he/she is reading (what blogs, books).

How do I make XAML DataGridColumns fill the entire DataGrid?

Set the columns Width property to be a proportional width such as *

How to send POST in angularjs with multiple params?

  var headers = {'SourceFrom':'web'};
  restUtil.post(url, params, headers).then(function(response){

You can also send (POST) multiple params within {} and add it.

How to get rid of the "No bootable medium found!" error in Virtual Box?

It's Never late. This error shows that you have After Installation of OS in Virtual Box you Remove the ISO file from Virtual Box Setting or you change your OS ISO file location. Thus you can Solve your Problem bY following given steps or you can watch video at Link

  1. Open Virtual Box and Select you OS from List in Left side.
  2. Then Select Setting. (setting Windows will open)
  3. The Select on "Storage" From Left side Panel.
  4. Then select on "empty" disk Icon on Right side panel.
  5. Under "Attribute" Section you can See another Disk icon. select o it.
  6. Then Select on "Choose Virtual Optical Disk file" and Select your OS ISO file.
  7. Restart VirtualBox and Start you OS.

To watch Video click on Below link: Link

How to create and use resources in .NET

The above method works good.

Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.

To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).

To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name]).

how to display full stored procedure code?

Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.

Are you trying to do this... without a management app?

Insert current date into a date column using T-SQL?

Couple of ways. Firstly, if you're adding a row each time a [de]activation occurs, you can set the column default to GETDATE() and not set the value in the insert. Otherwise,

UPDATE TableName SET [ColumnName] = GETDATE() WHERE UserId = @userId

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

How to disable the resize grabber of <textarea>?

example of textarea for disable the resize option

<textarea CLASS="foo"></textarea>

<style>
textarea.foo
{
resize:none;
}

</style>

PostgreSQL delete all content

The content of the table/tables in PostgreSQL database can be deleted in several ways.

Deleting table content using sql:

Deleting content of one table:

TRUNCATE table_name;
DELETE FROM table_name;

Deleting content of all named tables:

TRUNCATE table_a, table_b, …, table_z;

Deleting content of named tables and tables that reference to them (I will explain it in more details later in this answer):

TRUNCATE table_a, table_b CASCADE;

Deleting table content using pgAdmin:

Deleting content of one table:

Right click on the table -> Truncate

Deleting content of table and tables that reference to it:

Right click on the table -> Truncate Cascaded

Difference between delete and truncate:

From the documentation:

DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html

TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html

Working with table that is referenced from other table:

When you have database that has more than one table the tables have probably relationship. As an example there are three tables:

create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);

create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

And some prepared data for these tables:

insert into customers values (1, 'John', 'Smith');

insert into orders values 
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);        

insert into loyalty_cards values (100, 'A123456789', 1);

Table orders references table customers and table loyalty_cards references table customers. When you try to TRUNCATE / DELETE FROM the table that is referenced by other table/s (the other table/s has foreign key constraint to the named table) you get an error. To delete content from all three tables you have to name all these tables (the order is not important)

TRUNCATE customers, loyalty_cards, orders;

or just the table that is referenced with CASCADE key word (you can name more tables than just one)

TRUNCATE customers CASCADE;

The same applies for pgAdmin. Right click on customers table and choose Truncate Cascaded.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Add multiDexEnabled in gradle (app level) like this:

defaultConfig {
        ...
        ...
        multiDexEnabled true
    }

Do you get charged for a 'stopped' instance on EC2?

When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.

HTTP POST with URL query parameters -- good idea or not?

The REST camp have some guiding principles that we can use to standardize the way we use HTTP verbs. This is helpful when building RESTful API's as you are doing.

In a nutshell: GET should be Read Only i.e. have no effect on server state. POST is used to create a resource on the server. PUT is used to update or create a resource. DELETE is used to delete a resource.

In other words, if your API action changes the server state, REST advises us to use POST/PUT/DELETE, but not GET.

User agents usually understand that doing multiple POSTs is bad and will warn against it, because the intent of POST is to alter server state (eg. pay for goods at checkout), and you probably don't want to do that twice!

Compare to a GET which you can do an often as you like (idempotent).

Find if variable is divisible by 2

if (x & 1)
 itIsOddNumber();
else
 itIsEvenNumber();

Differences between key, superkey, minimal superkey, candidate key and primary key

I have always found it difficult to remember all the keys; so I keep the below notes handy, hope they help someone! Let me know if it can be improved.

  • Key: An attribute or combination of attributes that uniquely identify an entity/record in a relational table.

  • PK: A single key that is unique and not-null. It is one of the candidate keys.

  • Foreign Key: FK is a key in one table (child) that uniquely identifies a row of another table (parent). A FK is not-unique in the child table. It is a candidate key in the parent table. Referential integrity is maintained as the value in FK is present as a value in PK in parent table else it is NULL.

  • Unique Key: A unique key that may or may not be NULL

  • Natural key: PK in OLTP. It may be a PK in OLAP.

  • Surrogate Key: It is the Surrogate PK in OLAP acting as the substitute of the PK in OLTP. Artificial key generated internally in OLAP.

  • Composite Key: PK made up of multiple attributes

  • SuperKey: A key that can be uniquely used to identify a database record, that may contain extra attributes that are not necessary to uniquely identify records.

  • Candidate Key: A candidate key can be uniquely used to identify a database record without any extraneous data. They are Not Null and unique. It is a minimal super-key.

  • Alternate Key: A candidate key that is not the primary key is called an alternate key.

  • Candidate Key/s with Extraneous data: Consider that can be used to identify a record in the Employee table but candidate key alone is sufficient for this task. So becomes the extraneous data.

Note that the PK, Foreign Key, Unique Key, Natural key, Surrogate Key, Composite Key are defined as Database objects; where the Natural key is a PK in the OLTP and could be a PK in the target OLAP. For the rest of the keys, it's up to the DB designer/architect to decide whether unique/not-null/referential integrity constraints need to enforced or not.

Below I have tried to use set theory to simplify the representation of the membership of the keys w.r.t. each other.

key = { All of the below keys   }
PK  = { PK  }
Foreign Key = { Key with Not Null constraint    }
Unique Key  = { {Candidate Key/s}, {attributes containing NULL} }
Natural key = { PK  }
Surrogate Key   = { PK  }
Composite Key   = { PK  }
Super Key   = { {Candidate Key/s}, {Candidate Key/s with Extraneous data}   }
Candidate Key   = { PK, {Alternate Key/s}   }
Alternate Key   = { {Candidate Keys} - PK   }
Candidate Key/s with Extraneous data    = {     }

I have summarized it below:

Database Keys

Notes: an-overview-of-the-database-keys-primary-key-composite-key-surrogate-key-et-al

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

Returning data from Axios API

IMO extremely important rule of thumb for your client side js code is to keep separated the data handling and ui building logic into different funcs, which is also valid for axios data fetching ... in this way your control flow and error handlings will be much more simple and easier to manage, as it could be seen from this ok fetch

and this NOK fetch

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

       function getUrlParams (){
          var url_params = new URLSearchParams();
          if( window.location.toString().indexOf("?") != -1) {
             var href_part = window.location.search.split('?')[1]
             href_part.replace(/([^=&]+)=([^&]*)/g,
                function(m, key, value) {
                   var attr = decodeURIComponent(key)
                   var val = decodeURIComponent(value)
                   url_params.append(attr,val);
             });
          }
          // for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
          return url_params ;
       }


      function getServerData (url, urlParams ){
          if ( typeof url_params == "undefined" ) { urlParams = getUrlParams()  }
          return axios.get(url , { params: urlParams } )
          .then(response => {
             return response ;
          })
          .catch(function(error) {
             console.error ( error )
             return error.response;
          })
       }

    // Action !!!
    getServerData(url , url_params)
        .then( response => {
           if ( response.status === 204 ) {
              var warningMsg = response.statusText
              console.warn ( warningMsg )
              return
           } else if ( response.status === 404 || response.status === 400) {
              var errorMsg = response.statusText // + ": "  + response.data.msg // this is my api
              console.error( errorMsg )
              return ;
           } else {
              var data = response.data
              var dataType = (typeof data)
              if ( dataType === 'undefined' ) {
                 var msg = 'unexpected error occurred while fetching data !!!'
                 // pass here to the ui change method the msg aka
                 // showMyMsg ( msg , "error")
              } else {
                 var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
                 // call here the ui building method
                 // BuildList ( items )
              }
              return
           }

        })




    </script>

Bootstrap 3.0 Popovers and tooltips

Working with BOOTSTRAP 3 : Short and Simple

Check - JS Fiddle

HTML

<div id="myDiv">
<button class="btn btn-large btn-danger" data-toggle="tooltip" data-placement="top" title="" data-original-title="Tooltip on top">Tooltip on top</button>    
</div>

Javascript

$(function () { 
    $("[data-toggle='tooltip']").tooltip(); 
});

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

I have problems with set password too. And find answer at official site

SET PASSWORD FOR 'root'@'localhost' = 'your_password';

Unable to launch the IIS Express Web server

@roblll had it right. But for those of you who didn't want to dig for the answer, here it is:

  1. Close Visual Studio (might not be necessary, but it won't hurt).
  2. Navigate to your Documents folder. This is where my IISExpress configuration directory was.
  3. In the config folder, there is a file called the application host. Open that.
  4. Search for the name of your project. It should have been added in there by Visual Studio when it bombed in your previous attempts.
  5. Note that there's a binding for HTTP with the port you intend to use for https.

    //Change this:
    <binding protocol="http" bindingInformation="*:44300:localhost" />
    
    //to this:
    <binding protocol="https" bindingInformation="*:44300:localhost" />
    

Keep in mind, Visual Studio might have supplied different ports than you expected. Just make sure that the ports in the binding correspond to what's in the Web tab of your project's properties.

http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx

Hashing a file in Python

For the correct and efficient computation of the hash value of a file (in Python 3):

  • Open the file in binary mode (i.e. add 'b' to the filemode) to avoid character encoding and line-ending conversion issues.
  • Don't read the complete file into memory, since that is a waste of memory. Instead, sequentially read it block by block and update the hash for each block.
  • Eliminate double buffering, i.e. don't use buffered IO, because we already use an optimal block size.
  • Use readinto() to avoid buffer churning.

Example:

import hashlib

def sha256sum(filename):
    h  = hashlib.sha256()
    b  = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

Python Progress Bar

This is my simple solution:

import time

def progress(_cur, _max):
    p = round(100*_cur/_max)
    b = f"Progress: {p}% - ["+"."*int(p/5)+" "*(20-int(p/5))+"]"
    print(b, end="\r")

# USAGE:
for i in range(0,101):
    time.sleep(0.1) 
    progress(i,100)

print("..."*5, end="\r")
print("Done")

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

[SOLVED] Neos/swiftmailer: Address in mailbox given [] does not comply with RFC 2822, 3.6.2

Exception in line 261 of /var/www/html/vendor/Packages/Libraries/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

private function _assertValidAddress($address)
{
    if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D',
        $address)) {
        throw new Swift_RfcComplianceException(
            'Address in mailbox given ['.$address.
            '] does not comply with RFC 2822, 3.6.2.'
            );
    }
}

https://discuss.neos.io/t/solved-neos-swiftmailer-address-in-mailbox-given-does-not-comply-with-rfc-2822-3-6-2/3012

Given final block not properly padded

This can also be a issue when you enter wrong password for your sign key.

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

Using LINQ to group a list of objects

The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID

 var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                                  .Select(group => new { GroupID = group.Key, Customers = group.ToList() })
                                                  .ToList();

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.

if (isset($_GET['something']) == true) {
    thing = isset($_GET['something']);
} else {
    thing = "";
}

How to darken an image on mouseover?

Create black png with lets say 50% transparency. Overlay this on mouseover.

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

SQLite in Android How to update a specific row

public long fillDataTempo(String table){
    String[] table = new String[1];
    tabela[0] = table; 
    ContentValues args = new ContentValues();
    args.put(DBOpenHelper.DATA_HORA, new Date().toString());
    args.put(DBOpenHelper.NOME_TABELA, nome_tabela);
    return db.update(DATABASE_TABLE, args, STRING + " LIKE ?" ,tabela);
}

In Angular, I need to search objects in an array

I know if that can help you a bit.

Here is something I tried to simulate for you.

Checkout the jsFiddle ;)

http://jsfiddle.net/migontech/gbW8Z/5/

Created a filter that you also can use in 'ng-repeat'

app.filter('getById', function() {
  return function(input, id) {
    var i=0, len=input.length;
    for (; i<len; i++) {
      if (+input[i].id == +id) {
        return input[i];
      }
    }
    return null;
  }
});

Usage in controller:

app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
     $scope.fish = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}]

     $scope.showdetails = function(fish_id){
         var found = $filter('getById')($scope.fish, fish_id);
         console.log(found);
         $scope.selected = JSON.stringify(found);
     }
}]);

If there are any questions just let me know.

Twitter Bootstrap modal on mobile devices

We use this code to center the Bootstrap modal dialogs when they open. I haven't had any issue with them on iOS while using this but I'm not sure if it will work for Android.

$('.modal').on('show', function(e) {
    var modal = $(this);
    modal.css('margin-top', (modal.outerHeight() / 2) * -1)
         .css('margin-left', (modal.outerWidth() / 2) * -1);
    return this;
});

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

Write HTML string in JSON

One way is to replace the double quotes in the HTML with single quotes but using double quotes has become the standard convention for attribute values in HTML.

The better option is to escape the double quotes in json and other characters that need to be escaped.

You can get some more details about escaping here: Where can I find a list of escape characters required for my JSON ajax return type?

Error while sending QUERY packet

You guessed right MySQL have limitation for size of data, you need to break your query in small group of records or you can Change your max_allowed_packet by using SET GLOBAL max_allowed_packet=524288000;

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.

How can I check if an InputStream is empty without reading from it?

public void run() {
    byte[] buffer = new byte[256];  
    int bytes;                      

    while (true) {
        try {
            bytes = mmInStream.read(buffer);
            mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

Split string into individual words Java

String[] str = s.split("[^a-zA-Z]+");

CSS Change List Item Background Color with Class

1) You can use the !important rule, like this:

.selected
{
  background-color:red !important;
}

See http://www.w3.org/TR/CSS2/cascade.html#important-rules for more info.

2) In your example you can also get the red background by using ul.nav li.selected instead of just .selected. This makes the selector more specific.

See http://www.w3.org/TR/CSS2/cascade.html#specificity for more info.

How to count number of files in each directory?

Slightly modified version of Sebastian's answer using find instead of du (to exclude file-size-related overhead that du has to perform and that is never used):

 find ./ -mindepth 2 -type f | cut -d/ -f2 | sort | uniq -c | sort -nr

-mindepth 2 parameter is used to exclude files in current directory. If you remove it, you'll see a bunch of lines like the following:

  234 dir1
  123 dir2
    1 file1
    1 file2
    1 file3
      ...
    1 fileN

(much like the du-based variant does)

If you do need to count the files in current directory as well, use this enhanced version:

{ find ./ -mindepth 2 -type f | cut -d/ -f2 | sort && find ./ -maxdepth 1 -type f | cut -d/ -f1; } | uniq -c | sort -nr

The output will be like the following:

  234 dir1
  123 dir2
   42 .

How can I have Github on my own server?

If you must have GitHub, there is the enterprise version as already mentioned.

If you want to look for alternatives for running a central git server for your company, you can try Gitolite.

https://github.com/sitaramc/gitolite
https://github.com/sitaramc/gitolite/wiki/

How to generate access token using refresh token through google drive API?

Using Post call, worked for me.

RestClient restClient = new RestClient();
RestRequest request = new RestRequest();

request.AddQueryParameter("client_id", "value");
request.AddQueryParameter("client_secret", "value");
request.AddQueryParameter("grant_type", "refresh_token");
request.AddQueryParameter("refresh_token", "value");

restClient.BaseUrl = new System.Uri("https://oauth2.googleapis.com/token");
restClient.Post(request);

https://youtu.be/aHs3edo0-mU

jQuery see if any or no checkboxes are selected

Without using 'length' you can do it like this:

if ($('input[type=checkbox]').is(":checked")) {
      //any one is checked
}
else {
//none is checked
}

AngularJS ui-router login authentication

I think you need a service that handle the authentication process (and its storage).

In this service you'll need some basic methods :

  • isAuthenticated()
  • login()
  • logout()
  • etc ...

This service should be injected in your controllers of each module :

  • In your dashboard section, use this service to check if user is authenticated (service.isAuthenticated() method) . if not, redirect to /login
  • In your login section, just use the form data to authenticate the user through your service.login() method

A good and robust example for this behavior is the project angular-app and specifically its security module which is based over the awesome HTTP Auth Interceptor Module

Hope this helps

Parsing a JSON string in Ruby

This is a bit late but I ran into something interesting that seems important to contribute.

I accidentally wrote this code, and it seems to work:

require 'yaml'
CONFIG_FILE = ENV['CONFIG_FILE'] # path to a JSON config file 
configs = YAML.load_file("#{CONFIG_FILE}")
puts configs['desc']['someKey']

I was surprised to see it works since I am using the YAML library, but it works.

The reason why it is important is that yaml comes built-in with Ruby so there's no gem install.

I am using versions 1.8.x and 1.9.x - so the json library is not built in, but it is in version 2.x.

So technically - this is the easiest way to extract the data in version lower than 2.0.

C# : Passing a Generic Object

try

public void PrintGeneric<T>(T test) where T: ITest
{
    Console.WriteLine("Generic : " + test.@var);
}

as @Ash Burlaczenko has said you cant name a variable after a keyword, if you reallllly want this prefix with @ symbol to escape the keyword

WebAPI to Return XML

You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

Accept: application/xml

You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

EDIT: based on your edited question with code:

Simple return list of string, instead of converting it to XML. try it using Fiddler.

public List<string> Get(int tenantID, string dataType, string ActionName)
    {
       List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
       return SQLResult;
     }

For example if your list is like:

List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;

and you specify Accept: application/xml the output will be:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Test1</string>
  <string>Test2</string>
  <string>Test3</string>
</ArrayOfstring>

and if you specify 'Accept: application/json' in the request then the output will be:

[
  "Test1",
  "Test2",
  "Test3"
]

So let the client request the content type, instead of you sending the customized xml.

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

How can I make a clickable link in an NSAttributedString?

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],   
                                 NSUnderlineColorAttributeName: [UIColor blueColor],
                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;

KEY POINTS:

  • Make sure that you enable "Selectable" behavior of the UITextView in XIB.
  • Make sure that you disable "Editable" behavior of the UITextView in XIB.

Can I do Model->where('id', ARRAY) multiple where conditions?

WHERE AND SELECT Condition In Array Format Laravel

use DB;

$conditions = array(
    array('email', '=', '[email protected]')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

If you like to add support to IOS7 IOS8 you can apply this code into your project .

-(void) Subscribe {
    NSLog(@"Registering for push notifications...");

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }
}

-(void)application:(UIApplication *)application 
    didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {

    if (notificationSettings.types) {
        NSLog(@"user allowed notifications");
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        NSLog(@"user did not allow notifications");
        UIAlertView *alert =[[UIAlertView alloc] 
            initWithTitle:@"Please turn on Notification"
            message:@"Go to Settings > Notifications > App.\n Switch on Sound, Badge & Alert"
            delegate:self
            cancelButtonTitle:@"Ok"
            otherButtonTitles: nil];
        [alert show];
        // show alert here
    }
}

Python sum() function with list parameter

In the last answer, you don't need to make a list from numbers; it is already a list:

numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Note: If you are using Bootstrap + AngularJS + UI Bootstrap, .left .right and .next classes are never added. Using the example at the following link and the CSS from Robert McKee answer works. I wanted to comment because it took 3 days to find a full solution. Hope this helps others!

https://angular-ui.github.io/bootstrap/#/carousel

Code snip from UI Bootstrap Demo at the above link.

angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
  $scope.myInterval = 5000;
  var slides = $scope.slides = [];
  $scope.addSlide = function() {
    var newWidth = 600 + slides.length + 1;
    slides.push({
      image: 'http://placekitten.com/' + newWidth + '/300',
      text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
        ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
    });
  };
  for (var i=0; i<4; i++) {
    $scope.addSlide();
  }
});

Html From UI Bootstrap, Notice I added the .fade class to the example.

<div ng-controller="CarouselDemoCtrl">
    <div style="height: 305px">
        <carousel class="fade" interval="myInterval">
          <slide ng-repeat="slide in slides" active="slide.active">
            <img ng-src="{{slide.image}}" style="margin:auto;">
            <div class="carousel-caption">
              <h4>Slide {{$index}}</h4>
              <p>{{slide.text}}</p>
            </div>
          </slide>
        </carousel>
    </div>
</div>

CSS from Robert McKee's answer above

.carousel.fade {
opacity: 1;
}
.carousel.fade .item {
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
left: 0 !important;
opacity: 0;
top:0;
position:absolute;
width: 100%;
display:block !important;
z-index:1;
}
.carousel.fade .item:first-child {
top:auto;
position:relative;
}
.carousel.fade .item.active {
opacity: 1;
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
z-index:2;
}
/*
Added z-index to raise the left right controls to the top
*/
.carousel-control {
z-index:3;
}

How do I use CSS with a ruby on rails application?

Use the rails style sheet tag to link your main.css like this

<%= stylesheet_link_tag "main" %>

Go to

config/initializers/assets.rb

Once inside the assets.rb add the following code snippet just below the Rails.application.config.assets.version = '1.0'

Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( main.css )

Restart your server.

How to pick an image from gallery (SD Card) for my app?

#initialize in main activity 
    path = Environment.getExternalStorageDirectory()
            + "/images/make_machine_example.jpg"; #
     ImageView image=(ImageView)findViewById(R.id.image);
 //--------------------------------------------------||

 public void FromCamera(View) {

    Log.i("camera", "startCameraActivity()");
    File file = new File(path);
    Uri outputFileUri = Uri.fromFile(file);
    Intent intent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(intent, 1);

}

public void FromCard() {
    Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, 2);
}

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 2 && resultCode == RESULT_OK
            && null != data) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        bitmap = BitmapFactory.decodeFile(picturePath);
        image.setImageBitmap(bitmap);

        if (bitmap != null) {
            ImageView rotate = (ImageView) findViewById(R.id.rotate);

        }

    } else {

        Log.i("SonaSys", "resultCode: " + resultCode);
        switch (resultCode) {
        case 0:
            Log.i("SonaSys", "User cancelled");
            break;
        case -1:
            onPhotoTaken();
            break;

        }

    }

}

protected void onPhotoTaken() {
    // Log message
    Log.i("SonaSys", "onPhotoTaken");
    taken = true;
    imgCapFlag = true;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
    bitmap = BitmapFactory.decodeFile(path, options);
    image.setImageBitmap(bitmap);


}

Select method of Range class failed via VBA

This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range use Activesheet.range("range").select

What's the proper way to "go get" a private repository?

For people using private GitLabs, here's a snippet that may help: https://gist.github.com/MicahParks/1ba2b19c39d1e5fccc3e892837b10e21

Also pasted below:

Problem

The go command line tool needs to be able to fetch dependencies from your private GitLab, but authenticaiton is required.

This assumes your private GitLab is hosted at privategitlab.company.com.

Environment variables

The following environment variables are recommended:

export GO111MODULE=on
export GOPRIVATE=privategitlab.company.com

The above lines might fit best in your shell startup, like a ~/.bashrc.

Explanation

GO111MODULE=on tells Golang command line tools you are using modules. I have not tested this with projects not using Golang modules on a private GitLab.

GOPRIVATE=privategitlab.company.com tells Golang command line tools to not use public internet resources for the hostnames listed (like the public module proxy).

Get a personal access token from your private GitLab

To future proof these instructions, please follow this guide from the GitLab docs. I know that the read_api scope is required for Golang command line tools to work, and I may suspect read_repository as well, but have not confirmed this.

Set up the ~/.netrc

In order for the Golang command line tools to authenticate to GitLab, a ~/.netrc file is best to use.

To create the file if it does not exist, run the following commands:

touch ~/.netrc
chmod 600 ~/.netrc

Now edit the contents of the file to match the following:

machine privategitlab.company.com login USERNAME_HERE password TOKEN_HERE

Where USERNAME_HERE is replaced with your GitLab username and TOKEN_HERE is replaced with the access token aquired in the previous section.

Common mistakes

Do not set up a global git configuration with something along the lines of this:

git config --global url."[email protected]:".insteadOf "https://privategitlab.company.com"

I beleive at the time of writing this, the SSH git is not fully supported by Golang command line tools and this may cause conflicts with the ~/.netrc.

Bonus: SSH config file

For regular use of the git tool, not the Golang command line tools, it's convient to have a ~/.ssh/config file set up. In order to do this, run the following commands:

mkdir ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/config
chmod 600 ~/.ssh/config

Please note the permissions on the files and directory above are essentail for SSH to work in it's default configuration on most Linux systems.

Then, edit the ~/.ssh/config file to match the following:

Host privategitlab.company.com
  Hostname privategitlab.company.com
  User USERNAME_HERE
  IdentityFile ~/.ssh/id_rsa

Please note the spacing in the above file matters and will invalidate the file if it is incorrect.

Where USERNAME_HERE is your GitLab username and ~/.ssh/id_rsa is the path to your SSH private key in your file system. You've already uploaded its public key to GitLab. Here are some instructions.

How can I check whether a radio button is selected with JavaScript?

http://www.somacon.com/p143.php/

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

What is the difference between a candidate key and a primary key?

Think of a table of vehicles with an integer Primary Key.

The registration number would be a candidate key.

In the real world registration numbers are subject change so it depends somewhat on the circumstances what might qualify as a candidate key.

Setting background color for a JFrame

You can use this code block for JFrame background color.

    JFrame frame = new JFrame("Frame BG color");
    frame.setLayout(null);
    
    frame.setSize(1000, 650);
    frame.getContentPane().setBackground(new Color(5, 65, 90));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);

Convert from lowercase to uppercase all values in all character variables in dataframe

Alternatively, if you just want to convert one particular row to uppercase, use the code below:

df[[1]] <- toupper(df[[1]])

Cannot find JavaScriptSerializer in .Net 4.0

This is how to get JavaScriptSerializer available in your application, targetting .NET 4.0 (full)

using System.Web.Script.Serialization;

This should allow you to create a new JavaScriptSerializer object!

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

following Donald's comment:

This variable applies when binary logging is enabled.

All I had to do was:

  1. disabled log_bin in my.cnf (#log_bin)
  2. restart mysql
  3. import DB
  4. enable log_bin
  5. restart mysql

That step out that import problem.

(Then I'll review the programmer's code to suggest an improvement)

Append values to a set in Python

For me, in Python 3, it's working simply in this way:

keep = keep.union((0,1,2,3,4,5,6,7,8,9,10))

I don't know if it may be correct...

How do I remove version tracking from a project cloned from git?

The easiest way to solve this problem is to use a command line. Type this command

rm -R .git/

OR

rm -rf .git/

Converting JSON String to Dictionary Not List

I am working with a Python code for a REST API, so this is for those who are working on similar projects.

I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:

datapoint_1 = json1_data['datapoints']['datapoint_1']

where datapoint_1 is inside the datapoints dictionary.

How to remove all files from directory without removing directory in Node.js

graph-fs


Install

npm i graph-fs

Use

const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");

directory.clear(); // <--

How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

Save Javascript objects in sessionStorage

Could you not 'stringify' your object...then use sessionStorage.setItem() to store that string representation of your object...then when you need it sessionStorage.getItem() and then use $.parseJSON() to get it back out?

Working example http://jsfiddle.net/pKXMa/

Selenium 2.53 not working on Firefox 47

As of September 2016

Firefox 48.0 and selenium==2.53.6 work fine without any errors

To upgrade firefox on Ubuntu 14.04 only

sudo apt-get update
sudo apt-get upgrade firefox

Can't load IA 32-bit .dll on a AMD 64-bit platform

Short answer to first question: yes.

Longer answer: maybe; it depends on whether the build process for SVMLight behaves itself on 64-bit windows.

Final note: that call to System.loadLibrary is silly. Either call System.load with a full pathname or let it search java.library.path.

Get variable from PHP to JavaScript

<?php 
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>

This is the easiest way of passing a php variable to javascript without Ajax.

You can also use something like this:

var i = "<?php echo json_encode($j); ?>";

This said to be safer or more secure. i think

relative path in require_once doesn't work

I just came across this same problem, where it was all working fine, up until the point I had an includes within another includes.

require_once '../script/pdocrud.php';  //This worked fine up until I had an includes within another includes, then I got this error:
Fatal error: require_once() [function.require]: Failed opening required '../script/pdocrud.php' (include_path='.:/opt/php52/lib/php')

Solution 1. (undesired hardcoding of my public html folder name, but it works):

require_once $_SERVER["DOCUMENT_ROOT"] . '/orders.simplystyles.com/script/pdocrud.php';

Solution 2. (undesired comment above about DIR only working since php 5.3, but it works):

require_once __DIR__. '/../script/pdocrud.php';

Solution 3. (I can't see any downsides, and it works perfectly in my php 5.3):

require_once dirname(__FILE__). '/../script/pdocrud.php';

How to retry after exception?

Here's my idea on how to fix this:

j = 19
def calc(y):
    global j
    try:
        j = j + 8 - y
        x = int(y/j)   # this will eventually raise DIV/0 when j=0
        print("i = ", str(y), " j = ", str(j), " x = ", str(x))
    except:
        j = j + 1   # when the exception happens, increment "j" and retry
        calc(y)
for i in range(50):
    calc(i)

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

Why docker container exits immediately

If you check Dockerfile from containers, for example fballiano/magento2-apache-php

you'll see that at the end of his file he adds the following command: while true; do sleep 1; done

Now, what I recommend, is that you do this

docker container ls --all | grep 127

Then, you will see if your docker image had an error, if it exits with 0, then it probably needs one of these commands that will sleep forever.

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Converting a Date object to a calendar object

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

Position last flex item at the end of container

This flexbox principle also works horizontally

During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Setting an automatic left margin for the Last Item will do the work.

.last-item {
  margin-left: auto;
}

Code Example:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 400px;_x000D_
  outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  margin: 5px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p class="last-item"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen Snippet

This can be very useful for Desktop Footers.

As Envato did here with the company logo.

Codepen Snippet

How to position a table at the center of div horizontally & vertically

To position horizontally center you can say width: 50%; margin: auto;. As far as I know, that's cross browser. For vertical alignment you can try vertical-align:middle;, but it may only work in relation to text. It's worth a try though.

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

I run into a similar problem while running a Unit Test. Console.WriteLine() did not write anything into the VS Output Window.

Using System.Diagnostics.Debug.WriteLine() solved the problem.

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

I removed old AppleWWDRCA, downloaded and installed AppleWWDRCA, but problem remained. I also, checked my distribution and development certificates from Keychain Access, and see below error;

"This certificate has an invalid issuer."

Then,

  1. I revoked both development and distribution certificates on member center.
  2. Re-created CSR file and add development and distribution certificates from zero, downloaded them, and installed.

This fixed certificate problem.

Since old certificates revoked, existing provisioning profiles become invalid. To fix this;

  1. On member center, opened provisioning profiles.
  2. Opened profile detail by clicking "Edit", checked certificate from the list, and clicked "Generate" button.
  3. Downloaded and installed both development and distribution profiles.

I hope this helps.

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

Here is one case that worked for me if we need to convert .cer to .crt, though both of them are contextually same

openssl pkcs12 -in identity.p12 -nokeys -out mycertificate.crt

where we should have a valid private key (identity.p12) PKCS 12 format, this one i generated from keystore (.jks file) provided by CA (Certification Authority) who created my certificate.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

How to read a file and write into a text file?

It far easier to use the scripting runtime which is installed by default on Windows

Just go project Reference and check Microsoft Scripting Runtime and click OK.

Then you can use this code which is way better than the default file commands

Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    Final = Final & TempS & vbCrLf
Loop
TS.Close

Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
    TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing

As for what is wrong with your original code here you are reading each line of the text file.

Input #iFileNo, sFileText

Then here you write it out

Write #iFileNo, sFileText

sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.

So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.

Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo

iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo

Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).

If you need to process the incoming data then you need to do something like this.

Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection

iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
  C.Add sFileText
Loop
Close #iFileNo

For Each vTemp in C
     Process vTemp
Next sTemp

iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
   Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo

Contain an image within a div?

Since you don't want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.

#container img {
    max-height: 250px;
    max-width: 250px;
} 

See my example with an image that isn't a square, it doesn't stretch

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

You can use org.modeshape.common.text.Inflector.

Specifically:

String camelCase(String lowerCaseAndUnderscoredWord,
    boolean uppercaseFirstLetter, char... delimiterChars) 

By default, this method converts strings to UpperCamelCase.

Maven artifact is: org.modeshape:modeshape-common:2.3.0.Final

on JBoss repository: https://repository.jboss.org/nexus/content/repositories/releases

Here's the JAR file: https://repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar

How to get Real IP from Visitor?

This is my function.

benefits :

  • Work if $_SERVER was not available.
  • Filter private and/or reserved IPs;
  • Process all forwarded IPs in X_FORWARDED_FOR
  • Compatible with CloudFlare
  • Can set a default if no valid IP found!
  • Short & Simple !

/**
 * Get real user ip
 *
 * Usage sample:
 * GetRealUserIp();
 * GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
 * 
 * @param string $default default return value if no valid ip found
 * @param int    $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
 *
 * @return string real user ip
 */

function GetRealUserIp($default = NULL, $filter_options = 12582912) {
    $HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
    $HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
    $HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
    $REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');

    $all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
    foreach ($all_ips as $ip) {
        if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
            break;
    }
    return $ip?$ip:$default;
}

Base64 encoding and decoding in client-side Javascript

In Node.js we can do it in simple way

var base64 = 'SGVsbG8gV29ybGQ='
var base64_decode = new Buffer(base64, 'base64').toString('ascii');

console.log(base64_decode); // "Hello World"

Select SQL Server database size

You can check how this query works following this link.

    IF OBJECT_ID('tempdb..#spacetable') IS NOT NULL 
    DROP TABLE tempdb..#spacetable 
    create table #spacetable
    (
    database_name varchar(50) ,
    total_size_data int,
    space_util_data int,
    space_data_left int,
    percent_fill_data float,
    total_size_data_log int,
    space_util_log int,
    space_log_left int,
    percent_fill_log char(50),
    [total db size] int,
    [total size used] int,
    [total size left] int
    )
    insert into  #spacetable
    EXECUTE master.sys.sp_MSforeachdb 'USE [?];
    select x.[DATABASE NAME],x.[total size data],x.[space util],x.[total size data]-x.[space util] [space left data],
    x.[percent fill],y.[total size log],y.[space util],
    y.[total size log]-y.[space util] [space left log],y.[percent fill],
    y.[total size log]+x.[total size data] ''total db size''
    ,x.[space util]+y.[space util] ''total size used'',
    (y.[total size log]+x.[total size data])-(y.[space util]+x.[space util]) ''total size left''
     from (select DB_NAME() ''DATABASE NAME'',
    sum(size*8/1024) ''total size data'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
    ,case when sum(size*8/1024)=0 then ''divide by zero'' else
    substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
    from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=0
    group by type_desc  ) as x ,
    (select 
    sum(size*8/1024) ''total size log'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
    ,case when sum(size*8/1024)=0 then ''divide by zero'' else
    substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
    from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=1
    group by type_desc  )y'
    select * from #spacetable 
    order by database_name
    drop table #spacetable

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

I did what @gbero said, and I changed the Android version number that Studio uses from 22 to 17 and it works.

I am using the backwards compatibility to build for Android ver 22 but to target 17 (idk if that's correctly said, I am still trying to figure this app stuff out) so that triggered the backwards compatibility, which afaik is what the android.support.v7.* is. This is probably a bug with their rendering code. Not sure if clearing the cache as suggested above was needed as rendering didn't work just after invalidating the cache, it started working after I changed the version to render. If I change back to version 22, the rendering breaks, if I switch back to 17, it works again.

my fix

Hidden features of Windows batch files

Search and replace when setting environment variables:

> @set fname=%date:/=%

...removes the "/" from a date for use in timestamped file names.

and substrings too...

> @set dayofweek=%fname:~0,3%

Remove border radius from Select tag in bootstrap 3

You can use -webkit-border-radius: 0;. Like this:-

-webkit-border-radius: 0;
border: 0;
outline: 1px solid grey;
outline-offset: -1px;

This will give square corners as well as dropdown arrows. Using -webkit-appearance: none; is not recommended as it will turn off all the styling done by Chrome.

Setting HttpContext.Current.Session in a unit test

You can try FakeHttpContext:

using (new FakeHttpContext())
{
   HttpContext.Current.Session["CustomerId"] = "customer1";       
}

PHP: date function to get month of the current date

As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.

<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";

// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);

// Output it month is various formats according to http://php.net/date

echo date('M',$dateAsUnixTimestamp);
// Will output Apr

echo date('n',$dateAsUnixTimestamp);
// Will output 4

echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>

CSS rotation cross browser with jquery.animate()

Thanks yckart! Great contribution. I fleshed out your plugin a bit more. Added startAngle for full control and cross-browser css.

$.fn.animateRotate = function(startAngle, endAngle, duration, easing, complete){
    return this.each(function(){
        var elem = $(this);

        $({deg: startAngle}).animate({deg: endAngle}, {
            duration: duration,
            easing: easing,
            step: function(now){
                elem.css({
                  '-moz-transform':'rotate('+now+'deg)',
                  '-webkit-transform':'rotate('+now+'deg)',
                  '-o-transform':'rotate('+now+'deg)',
                  '-ms-transform':'rotate('+now+'deg)',
                  'transform':'rotate('+now+'deg)'
                });
            },
            complete: complete || $.noop
        });
    });
};

What is the proper way to re-throw an exception in C#?

It depends. In a debug build, I want to see the original stack trace with as little effort as possible. In that case, "throw;" fits the bill. In a release build, however, (a) I want to log the error with the original stack trace included, and once that's done, (b) refashion the error handling to make more sense to the user. Here "Throw Exception" makes sense. It's true that rethrowing the error discards the original stack trace, but a non-developer gets nothing out of seeing stack trace information so it's okay to rethrow the error.

        void TrySuspectMethod()
        {
            try
            {
                SuspectMethod();
            }
#if DEBUG
            catch
            {
                //Don't log error, let developer see 
                //original stack trace easily
                throw;
#else
            catch (Exception ex)
            {
                //Log error for developers and then 
                //throw a error with a user-oriented message
                throw new Exception(String.Format
                    ("Dear user, sorry but: {0}", ex.Message));
#endif
            }
        }

The way the question is worded, pitting "Throw:" vs. "Throw ex;" makes it a bit of a red-herring. The real choice is between "Throw;" and "Throw Exception," where "Throw ex;" is an unlikely special case of "Throw Exception."

ionic build Android | error: No installed build tools found. Please install the Android build tools

I fix this by downloading sdk package called platform-tools and buid-tools using sdkmanager. You can use sdkmanager.exe or if you are using SDK CLI, go to ~\AppData\Local\Android\sdk\tools\bin and run this command:

sdkmanager "platform-tools" "platforms;android-26"

or

sdkmanager "build-tools;27.0.3"

or both

After that you should be able to run ionic cordova run android or ionic build android.

Note: globalize sdkmanager command by adding ~\AppData\Local\Android\sdk\tools and ~\AppData\Local\Android\sdk\tools\bin to your environment variable.

Function to convert timestamp to human date in javascript

The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:

var d = new Date(1382086394000);

How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.

Fri Oct 18 2013 18:53:14 GMT+1000 (EST) 

In ES5 there are some other built-in formatting options:

and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:

alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());

* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.

How do I prevent 'git diff' from using a pager?

You can add an alias to diff with its own pager with pager.alias, like so:

[alias]
  dc = diff
  dsc = diff --staged
[pager]
  dc = cat
  dsc = cat

This will keep the color on and use 'cat' as the pager when invoked at 'git dc'.

Also, things not to do:

  • use --no-pager in your alias. Git (1.8.5.2, Apple Git-48) will complain that you are trying to modify the environment.
  • use a shell with !sh or !git. This will bypass the environment error, above, but it will reset your working directory (for the purposes of this command) to the top-level Git directory, so any references to a local file will not work if you are already in a subdirectory of your repository.

How to create a file in Android?

From here: http://www.anddev.org/working_with_files-t115.html

//Writing a file...  



try { 
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */             
       FileOutputStream fOut = openFileOutput("samplefile.txt",
                                                            MODE_PRIVATE);
       OutputStreamWriter osw = new OutputStreamWriter(fOut); 

       // Write the string to the file
       osw.write(TESTSTRING);

       /* ensure that everything is
        * really written out and close */
       osw.flush();
       osw.close();

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file
        isr.read(inputBuffer);

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe) 
      {ioe.printStackTrace();}

How to write specific CSS for mozilla, chrome and IE

Place your css in the following script and paste it into your CSS file.

@media screen and (-webkit-min-device-pixel-ratio:0) { your complete css style }

For example: @media screen and (-webkit-min-device-pixel-ratio:0) { container { margin-top: 120px;} }

Works like a charm.

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

I'm partial to scikits.statsmodels. Here an example:

import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1

results = sm.OLS(Y,sm.add_constant(X)).fit()

print results.summary()

plt.scatter(X,Y)

X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

plt.show()

The only tricky part is sm.add_constant(X) which adds a columns of ones to X in order to get an intercept term.

     Summary of Regression Results
=======================================
| Dependent Variable:            ['y']|
| Model:                           OLS|
| Method:                Least Squares|
| Date:               Sat, 28 Sep 2013|
| Time:                       09:22:59|
| # obs:                         100.0|
| Df residuals:                   98.0|
| Df model:                        1.0|
==============================================================================
|                   coefficient     std. error    t-statistic          prob. |
------------------------------------------------------------------------------
| x1                      1.007       0.008466       118.9032         0.0000 |
| const                 0.05165       0.005138        10.0515         0.0000 |
==============================================================================
|                          Models stats                      Residual stats  |
------------------------------------------------------------------------------
| R-squared:                     0.9931   Durbin-Watson:              1.484  |
| Adjusted R-squared:            0.9930   Omnibus:                    12.16  |
| F-statistic:                1.414e+04   Prob(Omnibus):           0.002294  |
| Prob (F-statistic):        9.137e-108   JB:                        0.6818  |
| Log likelihood:                 223.8   Prob(JB):                  0.7111  |
| AIC criterion:                 -443.7   Skew:                     -0.2064  |
| BIC criterion:                 -438.5   Kurtosis:                   2.048  |
------------------------------------------------------------------------------

example plot

How to use onBlur event on Angular2?

/*for reich text editor */
  public options: Object = {
    charCounterCount: true,
    height: 300,
    inlineMode: false,
    toolbarFixed: false,
    fontFamilySelection: true,
    fontSizeSelection: true,
    paragraphFormatSelection: true,

    events: {
      'froalaEditor.blur': (e, editor) => { this.handleContentChange(editor.html.get()); }}

Javascript form validation with password confirming

 if ($("#Password").val() != $("#ConfirmPassword").val()) {
          alert("Passwords do not match.");
      }

A JQuery approach that will eliminate needless code.

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Random number c++ in some range

int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

git - Server host key not cached

Just ssh'ing to the host is not enough, on Windows at least. That adds the host key to ssh/known_hosts but the error still persists.

You need to close the git bash window and open a new one. Then the registry cache is cleared and the push/pull then works.

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

Reset all changes after last commit in git

How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?

  1. You can undo changes to tracked files with:

    git reset HEAD --hard
    
  2. You can remove untracked files with:

    git clean -f
    
  3. You can remove untracked files and directories with:

    git clean -fd
    

    but you can't undo change to untracked files.

  4. You can remove ignored and untracked files and directories

    git clean -fdx
    

    but you can't undo change to ignored files.

You can also set clean.requireForce to false:

git config --global --add clean.requireForce false

to avoid using -f (--force) when you use git clean.

Read input from console in Ruby?

Are you talking about gets?

puts "Enter A"
a = gets.chomp
puts "Enter B"
b = gets.chomp
c = a.to_i + b.to_i
puts c

Something like that?

Update

Kernel.gets tries to read the params found in ARGV and only asks to console if not ARGV found. To force to read from console even if ARGV is not empty use STDIN.gets