Programs & Examples On #Ghostscriptsharp

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Concat strings by & and + in VB.Net

From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

    Dim s1 As String
    Dim i As Integer
    s1 = "Hello"
    i = 1
    String.Format("{0} {1}", s1, i)

It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I am having OpenCV version 3.4.3 on MacOS. I was getting the same error as above.

I changed my code from

frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)   

to

frame = cv2.resize(frame, None, fx=0.5, fy=0.5)    

Now its working fine for me.

How to access the GET parameters after "?" in Express?

So, after checking out the express reference, I found that req.query.color would return me the value I'm looking for.

req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'

Example:

GET /something?color1=red&color2=blue

Then in express, the handler:

app.get('/something', (req, res) => {
    req.query.color1 === 'red'  // true
    req.query.color2 === 'blue' // true
})

using mailto to send email with an attachment

If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:.

To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:

var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle);    //not really necessary
mapi.Send(subject, body, true);

Datepicker: How to popup datepicker when click on edittext

    EditText text = (EditText) findViewById(R.id.editText);

    text.setOnClickListener(new OnClickListener(){
       @RequiresApi(api = Build.VERSION_CODES.N)
       @Override
       public void onClick(View view) {

             DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
               @Override
               public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                   String date = i2 + "/" + (++i1) + "/" + i;
                   text.setText(date);
                }
        },year,month,date);
       }
    });  

    datePickerDialog.show();

you can also set the Minimum date and max date by these statements.

   datepickerDialoge.getDatepicker().setMinDate(long Date);

   datepickerDialoge.getDatepicker().setMaxDate(long Date);

Note:add these line before datepickerDialog.show(); statement you will get date by like this=12/2/2017.

I Hope my answer will help.

How can I turn a JSONArray into a JSONObject?

Can't you originally get the data as a JSONObject?

Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?

I'm not sure that it is possible to convert a JsonArray into a JsonObject.

I presume you are using the following from json.org

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

Convert generic List/Enumerable to DataTable?

If you are using VB.NET then this class does the job.

Imports System.Reflection
''' <summary>
''' Convert any List(Of T) to a DataTable with correct column types and converts Nullable Type values to DBNull
''' </summary>

Public Class ConvertListToDataset

    Public Function ListToDataset(Of T)(ByVal list As IList(Of T)) As DataTable

        Dim dt As New DataTable()
        '/* Create the DataTable columns */
        For Each pi As PropertyInfo In GetType(T).GetProperties()
            If pi.PropertyType.IsValueType Then
                Debug.Print(pi.Name)
            End If
            If IsNothing(Nullable.GetUnderlyingType(pi.PropertyType)) Then
                dt.Columns.Add(pi.Name, pi.PropertyType)
            Else
                dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(pi.PropertyType))
            End If
        Next

        '/* Populate the DataTable with the values in the Items in List */
        For Each item As T In list
            Dim dr As DataRow = dt.NewRow()
            For Each pi As PropertyInfo In GetType(T).GetProperties()
                dr(pi.Name) = IIf(IsNothing(pi.GetValue(item)), DBNull.Value, pi.GetValue(item))
            Next
            dt.Rows.Add(dr)
        Next
        Return dt

    End Function

End Class

How exactly does <script defer="defer"> work?

The real answer is: Because you cannot trust defer.

In concept, defer and async differ as follows:

async allows the script to be downloaded in the background without blocking. Then, the moment it finishes downloading, rendering is blocked and that script executes. Render resumes when the script has executed.

defer does the same thing, except claims to guarantee that scripts execute in the order they were specified on the page, and that they will be executed after the document has finished parsing. So, some scripts may finish downloading then sit and wait for scripts that downloaded later but appeared before them.

Unfortunately, due to what is really a standards cat fight, defer's definition varies spec to spec, and even in the most recent specs doesn't offer a useful guarantee. As answers here and this issue demonstrate, browsers implement defer differently:

  • In certain situations some browsers have a bug that causes defer scripts to run out of order.
  • Some browsers delay the DOMContentLoaded event until after the defer scripts have loaded, and some don't.
  • Some browsers obey defer on <script> elements with inline code and without a src attribute, and some ignore it.

Fortunately the spec does at least specify that async overrides defer. So you can treat all scripts as async and get a wide swath of browser support like so:

<script defer async src="..."></script>

98% of browsers in use worldwide and 99% in the US will avoid blocking with this approach.

(If you need to wait until the document has finished parsing, listen to the event DOMContentLoaded event or use jQuery's handy .ready() function. You'd want to do this anyway to fall back gracefully on browsers that don't implement defer at all.)

CSS :not(:last-child):after selector

For me it work fine

&:not(:last-child){
            text-transform: uppercase;
        }

How to check if cursor exists (open status)

You can use the CURSOR_STATUS function to determine its state.

IF CURSOR_STATUS('global','myCursor')>=-1
BEGIN
 DEALLOCATE myCursor
END

How to raise a ValueError?

raise ValueError('could not find %c in %s' % (ch,str))

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

How can I make a button have a rounded border in Swift?

You can subclass UIButton and add @IBInspectable variables to it so you can configure the custom button parameters via the StoryBoard "Attribute Inspector". Below I write down that code.

@IBDesignable
class BHButton: UIButton {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    @IBInspectable lazy var isRoundRectButton : Bool = false

    @IBInspectable public var cornerRadius : CGFloat = 0.0 {
        didSet{
            setUpView()
        }
    }

    @IBInspectable public var borderColor : UIColor = UIColor.clear {
        didSet {
            self.layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable public var borderWidth : CGFloat = 0.0 {
        didSet {
            self.layer.borderWidth = borderWidth
        }
    }

    //  MARK:   Awake From Nib

    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        if isRoundRectButton {
            self.layer.cornerRadius = self.bounds.height/2;
            self.clipsToBounds = true
        }
        else{
            self.layer.cornerRadius = self.cornerRadius;
            self.clipsToBounds = true
        }
    }

}

Tomcat won't stop or restart

Make sure Tomcat is not currently running and the PID file is removed. Them you should start Tomcat successfully.

If you start fresh then:

  1. Create setenv.sh file in <CATALINA_HOME>/bin.
  2. In it I set CATALINA_PID=/tmp/tomcat.pid (or other directory of your choice) so you have more control over the Tomcat process.

Then to start Tomcat find catalina.sh in <CATALINA_HOME>/bin and execute:

./catalina.sh start

and to stop it run:

./catalina.sh stop 10 -force

From catalina.sh script's doc:

./catalina.sh

Usage: catalina.sh ( commands ... )
commands:

start             Start Catalina in a separate window
stop              Stop Catalina, waiting up to 5 seconds for the process to end
stop n            Stop Catalina, waiting up to n seconds for the process to end
stop -force       Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
stop n -force     Stop Catalina, wait up to n seconds and then use kill -KILL if still running

Note: If you want to use -force flag then setting CATALINA_PID is mandatory.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     
     $key_value =   $response['key_name'];//access key

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

How to make canvas responsive

The object-fit CSS property sets how the content of a replaced element, such as an img or video, should be resized to fit its container.

Magically, object fit also works on a canvas element. No JavaScript needed, and the canvas doesn't stretch, automatically fills to proportion.

canvas {
    width: 100%;
    object-fit: contain;
}

How do I use a PriorityQueue?

Just to answer the add() vs offer() question (since the other one is perfectly answered imo, and this might not be):

According to JavaDoc on interface Queue, "The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues."

That means if you can add the element (which should always be the case in a PriorityQueue), they work exactly the same. But if you can't add the element, offer() will give you a nice and pretty false return, while add() throws a nasty unchecked exception that you don't want in your code. If failure to add means code is working as intended and/or it is something you'll check normally, use offer(). If failure to add means something is broken, use add() and handle the resulting exception thrown according to the Collection interface's specifications.

They are both implemented this way to fullfill the contract on the Queue interface that specifies offer() fails by returning a false (method preferred in capacity-restricted queues) and also maintain the contract on the Collection interface that specifies add() always fails by throwing an exception.

Anyway, hope that clarifies at least that part of the question.

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

How to add click event to a iframe with JQuery

You could simulate a focus/click event by having something like the following. (adapted from $(window).blur event affecting Iframe)

_x000D_
_x000D_
$(window).blur(function () {_x000D_
  // check focus_x000D_
  if ($('iframe').is(':focus')) {_x000D_
    console.log("iframe focused");_x000D_
    $(document.activeElement).trigger("focus");// Could trigger click event instead_x000D_
  }_x000D_
  else {_x000D_
    console.log("iframe unfocused");_x000D_
  }                _x000D_
});_x000D_
_x000D_
//Test_x000D_
$('#iframe_id').on('focus', function(e){_x000D_
  console.log(e);_x000D_
  console.log("hello im focused");_x000D_
})
_x000D_
_x000D_
_x000D_

Create a new line in Java's FileWriter

Since 1.8, I thought this might be an additional solution worth adding to the responses:

Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException

StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());

If appending to the same file, perhaps use an Append flag with Files.write()

Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);

Populate nested array in mongoose

Mongoose 5.4 supports this

Project.find(query)
.populate({
  path: 'pages.page.components',
  model: 'Component'
})

Call to a member function on a non-object

Either $objPage is not an instance variable OR your are overwriting $objPage with something that is not an instance of class PageAttributes.

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

Eclipse DDMS error "Can't bind to local 8600 for debugger"

I had a similar problem on OSX. It just so happens I had opened two instances of Eclipse so I could refer to some code in another workspace. Eventually I realized the two instances might be interfering with each other so I closed one. After that, I'm no longer seeing the "Can't bind..." error.

Which is the correct C# infinite loop, for (;;) or while (true)?

Gasp, use:

while (!false)
{

}

OR as jsight pointed out, you may want to be doubly sure:

while (!false && true)
{
}

Before people yell at me, it's all the same CIL code, I checked :)

Send attachments with PHP Mail()?

To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:

<?php 
//define the receiver of the email 
$to = '[email protected]'; 
//define the subject of the email 
$subject = 'Test email with attachment'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: [email protected]\r\nReply-To: [email protected]"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); 
//define the body of the message. 
ob_start(); //Turn on output buffering 
?> 
--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>-- 

--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: application/zip; name="attachment.zip"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment  

<?php echo $attachment; ?> 
--PHP-mixed-<?php echo $random_hash; ?>-- 

<?php 
//copy current buffer contents into $message variable and delete current output buffer 
$message = ob_get_clean(); 
//send the email 
$mail_sent = @mail( $to, $subject, $message, $headers ); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 
?>

As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

Taken from here.

Meaning of delta or epsilon argument of assertEquals for double values

Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!

From the JUnit javadoc:

delta - the maximum delta between expected and actual for which both numbers are still considered equal.

It's probably overkill, but I typically use a really small number, e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertEquals(123.456, 123.456, DELTA);
}

If you're using hamcrest assertions, you can just use the standard equalTo() with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo() (see javadoc), e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertThat(123.456, equalTo(123.456));
    assertThat(123.456, closeTo(123.456, DELTA));
}

FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals() with two doubles. The implementation (if you're interested) is:

private static boolean doublesAreEqual(double value1, double value2) {
    return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}

How to Apply Corner Radius to LinearLayout

You can create an XML file in the drawable folder. Call it, for example, shape.xml

In shape.xml:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"   >

    <solid
        android:color="#888888" >
    </solid>

    <stroke
        android:width="2dp"
        android:color="#C4CDE0" >
    </stroke>

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"    >
    </padding>

    <corners
        android:radius="11dp"   >
    </corners>

</shape>

The <corner> tag is for your specific question.

Make changes as required.

And in your whatever_layout_name.xml:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="5dp"
    android:background="@drawable/shape"    >
</LinearLayout>

This is what I usually do in my apps. Hope this helps....

How to pass variable number of arguments to printf/sprintf

Simple example below. Note you should pass in a larger buffer, and test to see if the buffer was large enough or not

void Log(LPCWSTR pFormat, ...) 
{
    va_list pArg;
    va_start(pArg, pFormat);
    char buf[1000];
    int len = _vsntprintf(buf, 1000, pFormat, pArg);
    va_end(pArg);
    //do something with buf
}

How can I see the current value of my $PATH variable on OS X?

You need to use the command echo $PATH to display the PATH variable or you can just execute set or env to display all of your environment variables.

By typing $PATH you tried to run your PATH variable contents as a command name.

Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:

/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin

To me this list appears to be complete.

Custom CSS for <audio> tag?

There is not currently any way to style HTML5 <audio> players using CSS. Instead, you can leave off the control attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.

XmlSerializer giving FileNotFoundException at constructor

A custom class to serialise:

[Serializable]
public class TestClass
{
    int x = 2;
    int y = 4;
    public TestClass(){}
    public TestClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public int TestFunction()
    {
        return x + y;
    }
}

I have attached the code snippet. Maybe this can help you out.

static void Main(string[] args)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(TestClass));

    MemoryStream memoryStream = new MemoryStream();
    XmlTextWriter xmlWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

    TestClass domain = new TestClass(10, 3);
    xmlSerializer.Serialize(xmlWriter, domain);
    memoryStream = (MemoryStream)xmlWriter.BaseStream;
    string xmlSerializedString = ConvertByteArray2Str(memoryStream.ToArray());

    TestClass xmlDomain = (TestClass)DeserializeObject(xmlSerializedString);

    Console.WriteLine(xmlDomain.TestFunction().ToString());
    Console.ReadLine();
}

What is the main difference between Collection and Collections in Java?

Collection is a interface and Collections is class in Java.util package

Do I really need to encode '&' as '&amp;'?

If you're really talking about the static text

<title>Foo & Bar</title>

stored in some file on the hard disk and served directly by a server, then yes: it probably doesn't need to be escaped.

However, since there is very little HTML content nowadays that's completely static, I'll add the following disclaimer that assumes that the HTML content is generated from some other source (database content, user input, web service call result, legacy API result, ...):

If you don't escape a simple &, then chances are you also don't escape a &amp; or a &nbsp; or <b> or <script src="http://attacker.com/evil.js"> or any other invalid text. That would mean that you are at best displaying your content wrongly and more likely are suspectible to XSS attacks.

In other words: when you're already checking and escaping the other more problematic cases, then there's almost no reason to leave the not-totally-broken-but-still-somewhat-fishy standalone-& unescaped.

Matlab: Running an m-file from command-line

Thanks to malat. Your comment helped me. But I want to add my try-catch block, as I found the MExeption method getReport() that returns the whole error message and prints it to the matlab console.

Additionally I printed the filename as this compilation is part of a batch script that calls matlab.

try
    some_code
    ...
catch message
    display(['ERROR in file: ' message.stack.file])
    display(['ERROR: ' getReport(message)])
end;

For a false model name passed to legacy code generation method, the output would look like:

ERROR in file: C:\..\..\..
ERROR: Undefined function or variable 'modelname'.

Error in sub-m-file (line 63)
legacy_code( 'slblock_generate', specs, modelname);

Error in m-file (line 11)
sub-m-file

Error in run (line 63)
evalin('caller', [script ';']);

Finally, to display the output at the windows command prompt window, just log the matlab console to a file with -logfile logfile.txt (use additionally -wait) and call the batch command type logfile.txt

Doctrine2: Best way to handle many-to-many with extra columns in reference table

You may be able to achieve what you want with Class Table Inheritance where you change AlbumTrackReference to AlbumTrack:

class AlbumTrack extends Track { /* ... */ }

And getTrackList() would contain AlbumTrack objects which you could then use like you want:

foreach($album->getTrackList() as $albumTrack)
{
    echo sprintf("\t#%d - %-20s (%s) %s\n", 
        $albumTrack->getPosition(),
        $albumTrack->getTitle(),
        $albumTrack->getDuration()->format('H:i:s'),
        $albumTrack->isPromoted() ? ' - PROMOTED!' : ''
    );
}

You will need to examine this throughly to ensure you don't suffer performance-wise.

Your current set-up is simple, efficient, and easy to understand even if some of the semantics don't quite sit right with you.

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

Click a button programmatically

Let say button 1 has an event called

Button1_Click(Sender, eventarg)

If you want to call it in Button2 then call this function directly.

Button1_Click(Nothing, Nothing)

Only mkdir if it does not exist

Use mkdir's -p option, but note that it has another effect as well.

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

Json.NET serialize object with root name

Writing a custom JsonConverter is another approach mentioned in similar questions. However, due to nature of how JsonConverter is designed, using that approach for this question is tricky, as you need to be careful with the WriteJson implementation to avoid getting into infinite recursion: JSON.Net throws StackOverflowException when using [JsonConvert()].

One possible implementation:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    //JToken t = JToken.FromObject(value); // do not use this! leads to stack overflow
    JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(value.GetType());

    writer.WriteStartObject();
    writer.WritePropertyName(value.GetType().Name);
    writer.WriteStartObject();
    foreach (var property in contract.Properties)
    {
        // this removes any property with null value
        var propertyValue = property.ValueProvider.GetValue(value);
        if (propertyValue == null) continue;

        writer.WritePropertyName(property.PropertyName);
        serializer.Serialize(writer, propertyValue);
        //writer.WriteValue(JsonConvert.SerializeObject(property.ValueProvider.GetValue(value))); // this adds escaped quotes
    }
    writer.WriteEndObject();
    writer.WriteEndObject();
}

How do I get the opposite (negation) of a Boolean in Python?

You can just compare the boolean array. For example

X = [True, False, True]

then

Y = X == False

would give you

Y = [False, True, False]

How do I know which version of Javascript I'm using?

In chrome you can find easily not only your JS version but also a flash version. All you need is to type chrome://version/ in a command line and you will get something like this:

enter image description here

Why do we always prefer using parameters in SQL statements?

Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface such as a desktop program or web site.

In your example, a user can directly run SQL code on your database by crafting statements in txtSalary.

For example, if they were to write 0 OR 1=1, the executed SQL would be

 SELECT empSalary from employee where salary = 0 or 1=1

whereby all empSalaries would be returned.

Further, a user could perform far worse commands against your database, including deleting it If they wrote 0; Drop Table employee:

SELECT empSalary from employee where salary = 0; Drop Table employee

The table employee would then be deleted.


In your case, it looks like you're using .NET. Using parameters is as easy as:

    string sql = "SELECT empSalary from employee where salary = @salary";

    using (SqlConnection connection = new SqlConnection(/* connection info */))
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        var salaryParam = new SqlParameter("salary", SqlDbType.Money);
        salaryParam.Value = txtMoney.Text;
    
        command.Parameters.Add(salaryParam);
        var results = command.ExecuteReader();
    }

    Dim sql As String = "SELECT empSalary from employee where salary = @salary"
    Using connection As New SqlConnection("connectionString")
        Using command As New SqlCommand(sql, connection)
            Dim salaryParam = New SqlParameter("salary", SqlDbType.Money)
            salaryParam.Value = txtMoney.Text
    
            command.Parameters.Add(salaryParam)

            Dim results = command.ExecuteReader()
        End Using
    End Using

Edit 2016-4-25:

As per George Stocker's comment, I changed the sample code to not use AddWithValue. Also, it is generally recommended that you wrap IDisposables in using statements.

How to document Python code using Doxygen

Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.

For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.

Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help() function available in the interactive interpreter.

ASP.NET DateTime Picker

The answer to your question is that Yes there are good free/open source time picker controls that go well with ASP.NET Calendar controls.

ASP.NET calendar controls just write an HTML table.

If you are using HTML5 and .NET Framework 4.5, you can instead use an ASP.NET TextBox control and set the TextMode property to "Date", "Month", "Week", "Time", or "DateTimeLocal" -- or if you your browser doesn't support this, you can set this property to "DateTime". You can then read the Text property to get the date, or time, or month, or week as a string from the TextBox.

If you are using .NET Framework 4.0 or an older version, then you can use HTML5's <input type="[month, week, etc.]">; if your browser doesn't support this, use <input type="datetime">.

If you need the server-side code (written in either C# or Visual Basic) for the information that the user inputs in the date field, then you can try to run the element on the server by writing runat="server" inside the input tag. As with all things ASP, make sure to give this element an ID so you can access it on the server side. Now you can read the Value property to get the input date, time, month, or week as a string.

If you cannot run this element on the server, then you will need a hidden field in addition to the <input type="[date/time/month/week/etc.]". In the submit function (written in JavaScript), set the value of the hidden field to the value of the input type="date", or "time", or "month", or "week" -- then on the server-side code, read the Value property of that hidden field as string too.

Make sure that the hidden field element of the HTML can run on the server.

Convert and format a Date in JSP

Date td = new Date();
String b = new String("");
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
b = format.format(td);
out.println(b);           

App.Config change value

AppSettings.Set does not persist the changes to your configuration file. It just changes it in memory. If you put a breakpoint on System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);, and add a watch for System.Configuration.ConfigurationManager.AppSettings[0] you will see it change from "English" to "Russian" when that line of code runs.

The following code (used in a console application) will persist the change.

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}

From this post: http://vbcity.com/forums/t/152772.aspx

One major point to note with the above is that if you are running this from the debugger (within Visual Studio) then the app.config file will be overwritten each time you build. The best way to test this is to build your application and then navigate to the output directory and launch your executable from there. Within the output directory you will also find a file named YourApplicationName.exe.config which is your configuration file. Open this in Notepad to see that the changes have in fact been saved.

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

Use this. Works fine

input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

EDIT

kotlin version

fun EditText.onlyNumbers() {
    inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or
        InputType.TYPE_NUMBER_FLAG_SIGNED
    keyListener = DigitsKeyListener.getInstance("0123456789")
}

C++ class forward declaration

In order for new T to compile, T must be a complete type. In your case, when you say new tile_tree_apple inside the definition of tile_tree::tick, tile_tree_apple is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.

Something like:

class A
{
    void f1();
    void f2();
};
class B
{
   void f3();
   void f4();
};

inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}

When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!

How to throw an exception in C?

C doesn't have exceptions.

There are various hacky implementations that try to do it (one example at: http://adomas.org/excc/).

Why can't I have abstract static methods in C#?

The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).

Express-js wildcard routing to cover everything under and including a path

For those who are learning node/express (just like me): do not use wildcard routing if possible!

I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.

More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

It looks like you are calling a non static member (a property or method, specifically setTextboxText) from a static method (specifically SumData). You will need to either:

  1. Make the called member static also:

    static void setTextboxText(int result)
    {
        // Write static logic for setTextboxText.  
        // This may require a static singleton instance of Form1.
    }
    
  2. Create an instance of Form1 within the calling method:

    private static void SumData(object state)
    {
        int result = 0;
        //int[] icount = (int[])state;
        int icount = (int)state;
    
        for (int i = icount; i > 0; i--)
        {
            result += i;
            System.Threading.Thread.Sleep(1000);
        }
        Form1 frm1 = new Form1();
        frm1.setTextboxText(result);
    }
    

    Passing in an instance of Form1 would be an option also.

  3. Make the calling method a non-static instance method (of Form1):

    private void SumData(object state)
    {
        int result = 0;
        //int[] icount = (int[])state;
        int icount = (int)state;
    
        for (int i = icount; i > 0; i--)
        {
            result += i;
            System.Threading.Thread.Sleep(1000);
        }
        setTextboxText(result);
    }
    

More info about this error can be found on MSDN.

Colspan all columns

Below is a concise es6 solution (similar to Rainbabba's answer but without the jQuery).

_x000D_
_x000D_
Array.from(document.querySelectorAll('[data-colspan-max]')).forEach(td => {_x000D_
    let table = td;_x000D_
    while (table && table.nodeName !== 'TABLE') table = table.parentNode;_x000D_
    td.colSpan = Array.from(table.querySelector('tr').children).reduce((acc, child) => acc + child.colSpan, 0);_x000D_
});
_x000D_
html {_x000D_
  font-family: Verdana;_x000D_
}_x000D_
tr > * {_x000D_
  padding: 1rem;_x000D_
  box-shadow: 0 0 8px gray inset;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
  <tr>_x000D_
    <th>Header 1</th>_x000D_
    <th>Header 2</th>_x000D_
    <th>Header 3</th>_x000D_
    <th>Header 4</th>_x000D_
    <th>Header 5</th>_x000D_
    <th>Header 6</th>_x000D_
  </tr>_x000D_
</thead>_x000D_
<tbod><tr>_x000D_
  <td data-colspan-max>td will be set to full width</td>_x000D_
</tr></tbod>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Difference between require, include, require_once and include_once?

one thing I noticed, when using include I can only access the included files functions from the file that included it. With require_once, I can run that function in a second required_once file.

also: I recommend adding

if(file_exists($RequiredFile)){
    require_once($RequiredFile);
}else{
  die('Error: File Does Not Exist');
}

Because when require_once kills the page, it can sometimes echo the directory of your website files

Here's a custom function I made to require files:

function addFile($file, $type = 'php', $important=false){
    //site-content is a directory where I store all the files that I plan to require_once
    //the site-content directory has "deny from all" in its .htaccess file to block direct connections
    if($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){
        //!is_dir checks that the file is not a folder
        require_once('site-content/'.$file.'.'.$type);
        return 'site-content/'.$file.'.'.$type;
    }else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){
        //if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)
        require_once('site-content/'.$file);
        return 'site-content/'.$file;
    }else if($important){
        //if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)
        die('Server Error: Files Missing');
        return false;
    }else{
        //the function returns false if the file does not exist, so you can check if your functions were successfully added
        return false;
    }
}

usage example:

$success = addFile('functions/common');

if($success){
    commonFunction();
}else{
    fallbackFunction();
}

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

I'm not sure about HQL, but in JPA you just call the query's setParameter with the parameter and collection.

Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);

where names is the collection of names you're searching for

Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");

Reading file input from a multipart/form-data POST

How about some Regex?

I wrote this for a text a file, but I believe this could work for you

(In case your text file contains line starting exactly with the "matched" ones below - simply adapt your Regex)

    private static List<string> fileUploadRequestParser(Stream stream)
    {
        //-----------------------------111111111111111
        //Content-Disposition: form-data; name="file"; filename="data.txt"
        //Content-Type: text/plain
        //...
        //...
        //-----------------------------111111111111111
        //Content-Disposition: form-data; name="submit"
        //Submit
        //-----------------------------111111111111111--

        List<String> lstLines = new List<string>();
        TextReader textReader = new StreamReader(stream);
        string sLine = textReader.ReadLine();
        Regex regex = new Regex("(^-+)|(^content-)|(^$)|(^submit)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);

        while (sLine != null)
        {
            if (!regex.Match(sLine).Success)
            {
                lstLines.Add(sLine);
            }
            sLine = textReader.ReadLine();
        }

        return lstLines;
    }

How to get the list of properties of a class?

You can use Reflection to do this: (from my library - this gets the names and values)

public static Dictionary<string, object> DictionaryFromType(object atype)
{
    if (atype == null) return new Dictionary<string, object>();
    Type t = atype.GetType();
    PropertyInfo[] props = t.GetProperties();
    Dictionary<string, object> dict = new Dictionary<string, object>();
    foreach (PropertyInfo prp in props)
    {
        object value = prp.GetValue(atype, new object[]{});
        dict.Add(prp.Name, value);
    }
    return dict;
}

This thing will not work for properties with an index - for that (it's getting unwieldy):

public static Dictionary<string, object> DictionaryFromType(object atype, 
     Dictionary<string, object[]> indexers)
{
    /* replace GetValue() call above with: */
    object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
}

Also, to get only public properties: (see MSDN on BindingFlags enum)

/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)

This works on anonymous types, too!
To just get the names:

public static string[] PropertiesFromType(object atype)
{
    if (atype == null) return new string[] {};
    Type t = atype.GetType();
    PropertyInfo[] props = t.GetProperties();
    List<string> propNames = new List<string>();
    foreach (PropertyInfo prp in props)
    {
        propNames.Add(prp.Name);
    }
    return propNames.ToArray();
}

And it's just about the same for just the values, or you can use:

GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values

But that's a bit slower, I would imagine.

Apache Name Virtual Host with SSL

You may be able to replace the:

VirtualHost ipaddress:443

with

VirtualHost *:443

You probably need todo this on all of your virt hosts.

It will probably clear up that message. Let the ServerName directive worry about routing the message request.

Again, you may not be able to do this if you have multiple ip's aliases to the same machine.

html select option separator

The disabled option approach seems to look the best and be the best supported. I've also included an example of using the optgroup.

optgroup (this way kinda sucks):

_x000D_
_x000D_
<select>_x000D_
    <optgroup>_x000D_
        <option>First</option>_x000D_
    </optgroup>_x000D_
    <optgroup label="_________">_x000D_
        <option>Second</option>_x000D_
        <option>Third</option>_x000D_
    </optgroup>_x000D_
</select>
_x000D_
_x000D_
_x000D_

disabled option (a bit better):

_x000D_
_x000D_
<select>_x000D_
    <option>First</option>_x000D_
    <option disabled>_________</option>_x000D_
    <option>Second</option>_x000D_
    <option>Third</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

And if you want to be really fancy, use the horizontal unicode box drawing character.
(BEST OPTION!)

_x000D_
_x000D_
<select>_x000D_
    <option>First</option>_x000D_
    <option disabled>----------</option>_x000D_
    <option>Second</option>_x000D_
    <option>Third</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/JFDgH/2/

How to remove last n characters from a string in Bash?

In this case you could use basename assuming you have the same suffix on the files you want to remove.

Example:

basename -s .rtf "some string.rtf"

This will return "some string"

If you don't know the suffix, and want it to remove everything after and including the last dot:

f=file.whateverthisis
basename "${f%.*}"

outputs "file"

% means chop, . is what you are chopping, * is wildcard

What are enums and why are they useful?

Besides the already mentioned use-cases, I often find enums useful for implementing the strategy pattern, following some basic OOP guidelines:

  1. Having the code where the data is (that is, within the enum itself -- or often within the enum constants, which may override methods).
  2. Implementing an interface (or more) in order to not bind the client code to the enum (which should only provide a set of default implementations).

The simplest example would be a set of Comparator implementations:

enum StringComparator implements Comparator<String> {
    NATURAL {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareTo(s2);
        }
    },
    REVERSE {
        @Override
        public int compare(String s1, String s2) {
            return NATURAL.compare(s2, s1);
        }
    },
    LENGTH {
        @Override
        public int compare(String s1, String s2) {
            return new Integer(s1.length()).compareTo(s2.length());
        }
    };
}

This "pattern" can be used in far more complex scenarios, making extensive use of all the goodies that come with the enum: iterating over the instances, relying on their implicit order, retrieving an instance by its name, static methods providing the right instance for specific contexts etc. And still you have this all hidden behind the interface so your code will work with custom implementations without modification in case you want something that's not available among the "default options".

I've seen this successfully applied for modeling the concept of time granularity (daily, weekly, etc.) where all the logic was encapsulated in an enum (choosing the right granularity for a given time range, specific behavior bound to each granularity as constant methods etc.). And still, the Granularity as seen by the service layer was simply an interface.

Disabled UIButton not faded or grey

You can use following code:

sendButton.enabled = YES;
sendButton.alpha = 1.0;

or

sendButton.enabled = NO;
sendButton.alpha = 0.5;

Replacing instances of a character in a string

You can do this:

string = "this; is a; sample; ; python code;!;" #your desire string
result = ""
for i in range(len(string)):
    s = string[i]
    if (s == ";" and i in [4, 18, 20]): #insert your desire list
        s = ":"
    result = result + s
print(result)

SQL Server: Make all UPPER case to Proper Case/Title Case

Just learned about InitCap().

Here is some sample code:

SELECT ID
      ,InitCap(LastName ||', '|| FirstName ||' '|| Nvl(MiddleName,'')) AS RecipientName
FROM SomeTable

Add leading zeroes/0's to existing Excel values to certain length

I am not sure if this is new in Excel 2013, but if you right-click on the column and say "Special" there is actually a pre-defined option for ZIP Code and ZIP Code + 4. Magic.

enter image description here

How can I get a list of all open named pipes in Windows?

I stumbled across a feature in Chrome that will list out all open named pipes by navigating to "file://.//pipe//"

Since I can't seem to find any reference to this and it has been very helpful to me, I thought I might share.

How to set border on jPanel?

JPanel jPanel = new JPanel();

jPanel.setBorder(BorderFactory.createLineBorder(Color.black));

Here not only jPanel, you can add border to any Jcomponent

Converting Symbols, Accent Letters to English Alphabet

Since the encoding that turns "the Family" into "t?? T???ly" is effectively random and not following any algorithm that can be explained by the information of the Unicode codepoints involved, there's no general way to solve this algorithmically.

You will need to build the mapping of Unicode characters into latin characters which they resemble. You could probably do this with some smart machine learning on the actual glyphs representing the Unicode codepoints. But I think the effort for this would be greater than manually building that mapping. Especially if you have a good amount of examples from which you can build your mapping.

To clarify: a few of the substitutions can actually be solved via the Unicode data (as the other answers demonstrate), but some letters simply have no reasonable association with the latin characters which they resemble.

Examples:

  • "?" (U+0452 CYRILLIC SMALL LETTER DJE) is more related to "d" than to "h", but is used to represent "h".
  • "T" (U+0166 LATIN CAPITAL LETTER T WITH STROKE) is somewhat related to "T" (as the name suggests) but is used to represent "F".
  • "?" (U+0E04 THAI CHARACTER KHO KHWAI) is not related to any latin character at all and in your example is used to represent "a"

What's the difference between unit tests and integration tests?

A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.

When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test

What's the difference between a word and byte?

It seems all the answers assume high level languages and mainly C/C++.

But the question is tagged "assembly" and in all assemblers I know (for 8bit, 16bit, 32bit and 64bit CPUs), the definitions are much more clear:

byte  = 8 bits 
word  = 2 bytes
dword = 4 bytes = 2Words (dword means "double word")
qword = 8 bytes = 2Dwords = 4Words ("quadruple word")

How to detect a mobile device with JavaScript?

A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is

@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px)  {
    #hoofdcollumn {margin: 10px 5%; width:90%}
}

Hope this helps!

Browse files and subfolders in Python

You can use os.walk() to recursively iterate through a directory and all its subdirectories:

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".html", ".htm")):
            # whatever

To build a list of these names, you can use a list comprehension:

htmlfiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(path)
             for name in files
             if name.endswith((".html", ".htm"))]

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

If you are looking for a JavaScript solution, here's my gist:

https://gist.github.com/sillicon/4abcd9079a7d29cbb53ebee547b55fba

The basic idea is the same, take the screen shot first, then crop it. However, my solution will not require other libraries, just pure WebDriver API code. However, the side effect is that it may increase the load of your testing browser.

How can I detect browser type using jQuery?

The best solution is probably: use Modernizr.

However, if you necessarily want to use $.browser property, you can do it using jQuery Migrate plugin (for JQuery >= 1.9 - in earlier versions you can just use it) and then do something like:

if($.browser.chrome) {
   alert(1);
} else if ($.browser.mozilla) {
   alert(2);
} else if ($.browser.msie) {
   alert(3);
}

And if you need for some reason to use navigator.userAgent, then it would be:

$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase()); 
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase()); 

Angular - Set headers for every request

This is how I did for setting token with every request.

import { RequestOptions, BaseRequestOptions, RequestOptionsArgs } from '@angular/http';

export class CustomRequestOptions extends BaseRequestOptions {

    constructor() {
        super();
        this.headers.set('Content-Type', 'application/json');
    }
    merge(options?: RequestOptionsArgs): RequestOptions {
        const token = localStorage.getItem('token');
        const newOptions = super.merge(options);
        if (token) {
            newOptions.headers.set('Authorization', `Bearer ${token}`);
        }

        return newOptions;
    }
}

And register in app.module.ts

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Store a closure as a variable in Swift

For me following was working:

var completionHandler:((Float)->Void)!

get list of pandas dataframe columns based on data type

I came up with this three liner.

Essentially, here's what it does:

  1. Fetch the column names and their respective data types.
  2. I am optionally outputting it to a csv.

inp = pd.read_csv('filename.csv') # read input. Add read_csv arguments as needed
columns = pd.DataFrame({'column_names': inp.columns, 'datatypes': inp.dtypes})
columns.to_csv(inp+'columns_list.csv', encoding='utf-8') # encoding is optional

This made my life much easier in trying to generate schemas on the fly. Hope this helps

Shorten string without cutting words in JavaScript

shorten(str, maxLen, appendix, separator = ' ') {
if (str.length <= maxLen) return str;
let strNope = str.substr(0, str.lastIndexOf(separator, maxLen));
return (strNope += appendix);

}

var s= "this is a long string and I cant explain all"; shorten(s, 10, '...')

/* "this is .." */

How to save all console output to file in R?

Run R in emacs with ESS (Emacs Speaks Statistics) r-mode. I have one window open with my script and R code. Another has R running. Code is sent from the syntax window and evaluated. Commands, output, errors, and warnings all appear in the running R window session. At the end of some work period, I save all the output to a file. My own naming system is *.R for scripts and *.Rout for save output files. Here's a screenshot with an example.Screenshot writing and evaluating R with Emacs/ESS.

Returning JSON response from Servlet to Javascript/JSP page

I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

R: Plotting a 3D surface from x, y, z

You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.

The variables "b" and "s" could be x or y.

require(lattice)

# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape


wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
    light.source = c(10,10,10), main = "Study 1",
    scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
    screen = list(z = 40, x = -75, y = 0))

Partly cherry-picking a commit with Git

The core thing you're going to want here is git add -p (-p is a synonym for --patch). This provides an interactive way to check in content, letting you decide whether each hunk should go in, and even letting you manually edit the patch if necessary.

To use it in combination with cherry-pick:

git cherry-pick -n <commit> # get your patch, but don't commit (-n = --no-commit)
git reset                   # unstage the changes from the cherry-picked commit
git add -p                  # make all your choices (add the changes you do want)
git commit                  # make the commit!

(Thanks to Tim Henigan for reminding me that git-cherry-pick has a --no-commit option, and thanks to Felix Rabe for pointing out that you need to reset! If you only want to leave a few things out of the commit, you could use git reset <path>... to unstage just those files.)

You can of course provide specific paths to add -p if necessary. If you're starting with a patch you could replace the cherry-pick with apply.


If you really want a git cherry-pick -p <commit> (that option does not exist), your can use

git checkout -p <commit>

That will diff the current commit against the commit you specify, and allow you to apply hunks from that diff individually. This option may be more useful if the commit you're pulling in has merge conflicts in part of the commit you're not interested in. (Note, however, that checkout differs from cherry-pick: checkout tries to apply <commit>'s contents entirely, cherry-pick applies the diff of the specified commit from it's parent. This means that checkout can apply more than just that commit, which might be more than you want.)

How to show soft-keyboard when edittext is focused

I had a similar problem using view animations. So I've put an animation listener to make sure I'd wait for the animation to end before trying to request a keyboard access on the shown edittext.

    bottomUp.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (textToFocus != null) {
                // Position cursor at the end of the text
                textToFocus.setSelection(textToFocus.getText().length());
                // Show keyboard
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(textToFocus, InputMethodManager.SHOW_IMPLICIT);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });

How to change the color of text in javafx TextField?

The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.

.text-input {
    -fx-text-fill: -fx-text-inner-color;
    -fx-highlight-fill: derive(-fx-control-inner-background,-20%);
    -fx-highlight-text-fill: -fx-text-inner-color;
    -fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
    -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: 0, 1;
    -fx-background-radius: 3, 2;
    -fx-cursor: text;
    -fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
    -fx-highlight-fill: -fx-accent;
    -fx-highlight-text-fill: white;
    -fx-background-color: 
        -fx-focus-color,
        -fx-control-inner-background,
        -fx-faint-focus-color,
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: -0.2, 1, -1.4, 3;
    -fx-background-radius: 3, 2, 4, 0;
    -fx-prompt-text-fill: transparent;
}

Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:

textField.setStyle("-fx-text-inner-color: red;");

How to construct a set out of list items in python?

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

Using awk to print all columns from the nth to the last

awk '{ for(i=3; i<=NF; ++i) printf $i""FS; print "" }'

lauhub proposed this correct, simple and fast solution here

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

Insert php variable in a href

Try using printf function or the concatination operator

http://php.net/manual/en/function.printf.php

Get the generated SQL statement from a SqlCommand object?

Profiler is hands-down your best option.

You might need to copy a set of statements from profiler due to the prepare + execute steps involved.

Oracle pl-sql escape character (for a " ' ")

you can use ESCAPE like given example below

The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL.

SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/';

The same works inside PL/SQL:

 if( id like '%/_%' ESCAPE '/' )

This applies only to like patterns, for example in an insert there is no need to escape _ or %, they are used as plain characters anyhow. In arbitrary strings only ' needs to be escaped by ''.

Day Name from Date in JS

Try using this code:

var event = new Date();
var options = { weekday: 'long' };
console.log(event.toLocaleDateString('en-US', options));

this will give you the day name in string format.

How can I use Ruby to colorize the text output to a terminal?

Colorize is my favorite gem! :-)

Check it out:

https://github.com/fazibear/colorize

Installation:

gem install colorize

Usage:

require 'colorize'

puts "I am now red".red
puts "I am now blue".blue
puts "Testing".yellow

Animate visibility modes, GONE and VISIBLE

Well there is a very easy way, but just setting android:animateLayoutChanges="true" will not work. You need to enableTransitionType in you activity. Check this link for more info: http://www.thecodecity.com/2018/03/android-animation-on-view-visibility.html

How to add font-awesome to Angular 2 + CLI project

For fontawesome 5.x+ the most simplest way would be the following,

install using npm package: npm install --save @fortawesome/fontawesome-free

In your styles.scss file include:

$fa-font-path: "~@fortawesome/fontawesome-free/webfonts";
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/regular';

Note: if you have _variables.scss file then it's more appropriate to include the $fa-font-path inside it and not in styles.scss file.

Error: "setFile(null,false) call failed" when using log4j

Please changes your log file location to another drive. it will work.

this happen's the permission of creating log file.

Select distinct rows from datatable in Linq

Check this link

get distinct rows from datatable using Linq (distinct with mulitiple columns)

Or try this

var distinctRows = (from DataRow dRow in dTable.Rows
                    select new  {  col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();

EDIT: Placed the missing first curly brace.

VBA test if cell is in a range

If the two ranges to be tested (your given cell and your given range) are not in the same Worksheet, then Application.Intersect throws an error. Thus, a way to avoid it is with something like

Sub test_inters(rng1 As Range, rng2 As Range)
    If (rng1.Parent.Name = rng2.Parent.Name) Then
        Dim ints As Range
        Set ints = Application.Intersect(rng1, rng2)
        If (Not (ints Is Nothing)) Then
            ' Do your job
        End If
    End If
End Sub

How do I REALLY reset the Visual Studio window layout?

Have you tried this? In Visual Studio go to Tools > Import and Export Settings > Reset all settings

Be sure you back up your settings before you do this. I made the mistake of trying this to fix an issue and didn't realize it would undo all my appearance settings and toolbars as well. Took a lot of time to get back to the way I like things.

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

How to colorize diff on the command line?

Coloured, word-level diff ouput

Here's what you can do with the the below script and diff-highlight:

Coloured diff screenshot

#!/bin/sh -eu

# Use diff-highlight to show word-level differences

diff -U3 --minimal "$@" |
  sed 's/^-/\x1b[1;31m-/;s/^+/\x1b[1;32m+/;s/^@/\x1b[1;34m@/;s/$/\x1b[0m/' |
  diff-highlight

(Credit to @retracile's answer for the sed highlighting)

Multiple HttpPost method in Web API controller

Put Route Prefix [RoutePrefix("api/Profiles")] at the controller level and put a route at action method [Route("LikeProfile")]. Don't need to change anything in global.asax file

namespace KhandalVipra.Controllers
{
    [RoutePrefix("api/Profiles")]
    public class ProfilesController : ApiController
    {
        // POST: api/Profiles/LikeProfile
        [Authorize]
        [HttpPost]
        [Route("LikeProfile")]
        [ResponseType(typeof(List<Like>))]
        public async Task<IHttpActionResult> LikeProfile()
        {
        }
    }
}

Saving results with headers in Sql Server Management Studio

In SQL Server 2014 Management Studio the setting is at:

Tools > Options > Query Results > SQL Server > Results to Text > Include column headers in the result set.

PIG how to count a number of rows in alias

Be careful, with COUNT your first item in the bag must not be null. Else you can use the function COUNT_STAR to count all rows.

Return row of Data Frame based on value in a column - R

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ]

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                 Amount = c(150, 120, 175, 160, 120))

df[which.min(df$Amount), ]
#   Name Amount
# 2    B    120

df[which(df$Amount == min(df$Amount)), ]
#   Name Amount
# 2    B    120
# 5    E    120

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

Reading a cell value in Excel vba and write in another Cell

surely you can do this with worksheet formulas, avoiding VBA entirely:

so for this value in say, column AV S:1 P:0 K:1 Q:1

you put this formula in column BC:

=MID(AV:AV,FIND("S",AV:AV)+2,1)

then these formulas in columns BD, BE...

=MID(AV:AV,FIND("P",AV:AV)+2,1)
=MID(AV:AV,FIND("K",AV:AV)+2,1)
=MID(AV:AV,FIND("Q",AV:AV)+2,1)

so these formulas look for the values S:1, P:1 etc in column AV. If the FIND function returns an error, then 0 is returned by the formula, else 1 (like an IF, THEN, ELSE

Then you would just copy down the formulas for all the rows in column AV.

HTH Philip

Tool to convert java to c# code

Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.

Environment variables in Eclipse

The .bashrc file is used for setting variables used by interactive login shells. If you want those environment variables available in Eclipse you need to put them in /etc/environment.

AngularJS toggle class using ng-class

I made this work in this way:

<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>

in your controller:

$scope.toggleClass = function (event) {
    $(event.target).toggleClass('active');
}

.m2 , settings.xml in Ubuntu

Quoted from http://maven.apache.org/settings.html:

There are two locations where a settings.xml file may live:

The Maven install: $M2_HOME/conf/settings.xml

A user's install: ${user.home}/.m2/settings.xml

So, usually for a specific user you edit

/home/*username*/.m2/settings.xml

To set environment for all local users, you might think about changing the first path.

Create a 3D matrix

If you want to define a 3D matrix containing all zeros, you write

A = zeros(8,4,20);

All ones uses ones, all NaN's uses NaN, all false uses false instead of zeros.

If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.

For example

B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array

How to read the output from git diff?

The default output format (which originally comes from a program known as diff if you want to look for more info) is known as a “unified diff”. It contains essentially 4 different types of lines:

  • context lines, which start with a single space,
  • insertion lines that show a line that has been inserted, which start with a +,
  • deletion lines, which start with a -, and
  • metadata lines which describe higher level things like which file this is talking about, what options were used to generate the diff, whether the file changed its permissions, etc.

I advise that you practice reading diffs between two versions of a file where you know exactly what you changed. Like that you'll recognize just what is going on when you see it.

Show space, tab, CRLF characters in editor of Visual Studio

For those who are looking for a button toggle:

The name of this command is View white space in GUI menu (Edit -> Advanced -> View white space).

Menu toggle

The name of this command in the Add command popup is Toggle Visual Space.

Button toggle.

Where is SQL Server Management Studio 2012?

After going back into the installer & checking off "Management Tools", ssms.exe was available under "C:\Program Files\Microsoft SQL Server\110\Tools\Binn\ManagementStudio" (thanks to everyone for pointing out where to find it).

sql server setup

What is an opaque response, and what purpose does it serve?

javascript is a bit tricky getting the answer, I fixed it by getting the api from the backend and then calling it to the frontend.

public function get_typechange () {

    $ url = "https://........";
    $ json = file_get_contents ($url);
    $ data = json_decode ($ json, true);
    $ resp = json_encode ($data);
    $ error = json_last_error_msg ();
    return $ resp;

}

When should use Readonly and Get only properties

A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).

C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).

private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;

public string Name{ // This is a readonly property.
  get {
    return _name;  
  }
}

public bool Enabled{ // This is a read- and writeable property.
  get{
    return _enabled;
  }
  set{
    _enabled = value;
  }
} 

Problems with entering Git commit message with Vim

You can change the comment character to something besides # like this:

git config --global core.commentchar "@"

Git pull after forced update

Pull with rebase

A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull command:

git pull --rebase

$(document).on("click"... not working?

This works:

<div id="start-element">Click Me</div>

$(document).on("click","#test-element",function() {
    alert("click");
});

$(document).on("click","#start-element",function() {
    $(this).attr("id", "test-element");
});

Here is the Fiddle

What is fastest children() or find() in jQuery?

None of the other answers dealt with the case of using .children() or .find(">") to only search for immediate children of a parent element. So, I created a jsPerf test to find out, using three different ways to distinguish children.

As it happens, even when using the extra ">" selector, .find() is still a lot faster than .children(); on my system, 10x so.

So, from my perspective, there does not appear to be much reason to use the filtering mechanism of .children() at all.

.NET Global exception handler in console application

No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:

using System;

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.

Retrieve last 100 lines logs

Look, the sed script that prints the 100 last lines you can find in the documentation for sed (https://www.gnu.org/software/sed/manual/sed.html#tail):

$ cat sed.cmd
1! {; H; g; }
1,100 !s/[^\n]*\n//
$p

$ sed -nf sed.cmd logfilename

For me it is way more difficult than your script so

tail -n 100 logfilename

is much much simpler. And it is quite efficient, it will not read all file if it is not necessary. See my answer with strace report for tail ./huge-file: https://unix.stackexchange.com/questions/102905/does-tail-read-the-whole-file/102910#102910

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

How to view the SQL queries issued by JPA?

There's a file called persistence.xml Press Ctrl+Shift+R and find it, then, there's a place written something like showSQL.

Just put it as true

I'm not sure if the server must be started as Debug mode. Check the SQLs created on console.

How to cast from List<Double> to double[] in Java?

High performance - every Double object wraps a single double value. If you want to store all these values into a double[] array, then you have to iterate over the collection of Double instances. A O(1) mapping is not possible, this should be the fastest you can get:

 double[] target = new double[doubles.size()];
 for (int i = 0; i < target.length; i++) {
    target[i] = doubles.get(i).doubleValue();  // java 1.4 style
    // or:
    target[i] = doubles.get(i);                // java 1.5+ style (outboxing)
 }

Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive method:

public static double[] toPrimitive(Double[] array) {
  if (array == null) {
    return null;
  } else if (array.length == 0) {
    return EMPTY_DOUBLE_ARRAY;
  }
  final double[] result = new double[array.length];
  for (int i = 0; i < array.length; i++) {
    result[i] = array[i].doubleValue();
  }
  return result;
}

(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )

By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[] from the list, then to unwrap the double values.

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

Regular expressions in C: examples?

While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.

I made an answer for this already, but I think it can help here too..

Regex In C To Search For Credit Card Numbers

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}

Install PCRE using:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig

Compile using :

gcc foo.c -lpcre2-8 -o foo

Check my answer for more details.

List of standard lengths for database fields

These might be useful to someone;

youtube max channel length = 20
facebook max name length   = 50
twitter max handle length  = 15
email max length           = 255 

http://www.interoadvisory.com/2015/08/6-areas-inside-of-linkedin-with-character-limits/

HTML img scaling

Adding max-width: 100%; to the img tag works for me.

How to set border's thickness in percentages?

You can also use

border-left: 9vw solid #F5E5D6;
border-right: 9vw solid #F5E5D6;     

OR

border: 9vw solid #F5E5D6;

Clearing coverage highlighting in Eclipse

I have used the Open Clover Tool for the code coverage, I have also been searching this for a long time. Its pretty straightforward, in the Coverage Explorer tab, you can find three square buttons which says the code lines you wanted to display, click on hide the coverage square box and its gone. Last button in the image below: enter image description here

Inserting a value into all possible locations in a list

Use insert() to insert an element before a given position.

For instance, with

arr = ['A','B','C']
arr.insert(0,'D')

arr becomes ['D','A','B','C'] because D is inserted before the element at index 0.

Now, for

arr = ['A','B','C']
arr.insert(4,'D')

arr becomes ['A','B','C','D'] because D is inserted before the element at index 4 (which is 1 beyond the end of the array).

However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.

Here's some example code:

import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
    print perm

will print out

('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')

How to set an "Accept:" header on Spring RestTemplate request?

If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...

private HttpHeaders createHttpHeaders(String user, String password)
{
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Basic " + encodedAuth);
    return headers;
}

private void doYourThing() 
{
    String theUrl = "http://blah.blah.com:8080/rest/api/blah";
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders("fred","1234");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}

How to count certain elements in array?

Depending on how you want to run it:

const reduced = (array, val) => { // self explanatory
    return array.filter((element) => element === val).length;
}

console.log(reduced([1, 2, 3, 5, 2, 8, 9, 2], 2));

// 3

const reducer = (array) => { // array to set > set.forEach > map.set
    const count = new Map();
    const values = new Set(array);
    values.forEach((element)=> {
        count.set(element, array.filter((arrayElement) => arrayElement === element).length);
    });
    return count;
}
console.log(reducer([1, 2, 3, 5, 2, 8, 9, 2]));

// Map(6) {1 => 1, 2 => 3, 3 => 1, 5 => 1, 8 => 1, …}

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Note that these solutions use the Code Igniter Active Records Class

This method uses sub queries like you wish but you should sanitize $countryId yourself!

$this->db->select('username')
         ->from('user')
         ->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
         ->get();

Or this method would do it using joins and will sanitize the data for you (recommended)!

$this->db->select('username')
         ->from('users')
         ->join('locations', 'users.locationid = locations.locationid', 'inner')
         ->where('countryid', $countryId)
         ->get();

How do I validate a date string format in python?

>>> import datetime
>>> def validate(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD")


>>> validate('2003-12-23')
>>> validate('2003-12-32')

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    validate('2003-12-32')
  File "<pyshell#18>", line 5, in validate
    raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

OK, found solution.

In the file database.php, by default, it comes the "mysql" part:

 'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

all you need to do is change the values :

'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),

by your database name (you must create one if you dont have any) and by that database username

like this

'database' => env('DB_DATABASE', 'MyDatabase'),
'username' => env('DB_USERNAME', 'MyUsername'),

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give name and values to those submit buttons like:

    <td>
    <input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
    </td>
    <td>
    <input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
    </td>

and then in your php script you could check

if($_POST['mybutton'] == 'save')
{
  ///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
  ///do publish processing here
}

Function pointer as parameter

Replace void *disconnectFunc; with void (*disconnectFunc)(); to declare function pointer type variable. Or even better use a typedef:

typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
    fptr = func;
}

void D::disconnected()
{
    fptr();
    connected = false;
}

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

batch script - read line by line

The "call" solution has some problems.

It fails with many different contents, as the parameters of a CALL are parsed twice by the parser.
These lines will produce more or less strange problems

one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty

the end

Therefore you shouldn't use the value of %%a with a call, better move it to a variable and then call a function with only the name of the variable.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
    set "myVar=%%a"
    call :processLine myVar
)
goto :eof

:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

Simple 3x3 matrix inverse code (C++)

I would also recommend Ilmbase, which is part of OpenEXR. It's a good set of templated 2,3,4-vector and matrix routines.

Bootstrap 3 Align Text To Bottom of Div

Here's another solution: http://jsfiddle.net/6WvUY/7/.

HTML:

<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <img src="//placehold.it/600x300" alt="Logo" class="img-responsive"/>
        </div>
        <div class="col-sm-6">
            <h3>Some Text</h3>
        </div>
    </div>
</div>

CSS:

.row {
    display: table;
}

.row > div {
    float: none;
    display: table-cell;
}

Removing Conda environment

First you have to deactivate your environment before removing it. You can remove conda environment by using the following command

Suppose your environment name is "sample_env" , you can remove this environment by using

source deactivate    
conda remove -n sample_env --all

'--all' will be used to remove all the dependencies

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

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
 );

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

How to catch curl errors in PHP

Since you are interested in catching network related errors and HTTP errors, the following provides a better approach:

function curl_error_test($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $responseBody = curl_exec($ch);
    /*
     * if curl_exec failed then
     * $responseBody is false
     * curl_errno() returns non-zero number
     * curl_error() returns non-empty string
     * which one to use is up too you
     */
    if ($responseBody === false) {
        return "CURL Error: " . curl_error($ch);
    }

    $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    /*
     * 4xx status codes are client errors
     * 5xx status codes are server errors
     */
    if ($responseCode >= 400) {
        return "HTTP Error: " . $responseCode;
    }

    return "No CURL or HTTP Error";
}

Tests:

curl_error_test("http://expamle.com");          // CURL Error: Could not resolve host: expamle.com
curl_error_test("http://example.com/whatever"); // HTTP Error: 404
curl_error_test("http://example.com");          // No CURL or HTTP Error

Add list to set?

Use set.update() or |=

>>> a = set('abc')
>>> l = ['d', 'e']
>>> a.update(l)
>>> a
{'e', 'b', 'c', 'd', 'a'}

>>> l = ['f', 'g']
>>> a |= set(l)
>>> a
{'e', 'b', 'f', 'c', 'd', 'g', 'a'}

edit: If you want to add the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable.

Convert row to column header for Pandas DataFrame,

This works (pandas v'0.19.2'):

df.rename(columns=df.iloc[0])

Separators for Navigation

Put it in as a background on the list element:

<ul id="nav">
    <li><a><img /></a></li>
    ...
    <li><a><img /></a></li>
</ul>

#nav li{background: url(/images/separator.gif) no-repeat left; padding-left:20px;} 
/* left padding creates a gap between links */

Next, I recommend a different markup for accessibility:
Rather than embedding the images inline, put text in as text, surround each with a span, apply the image as a background the the , and then hide the text with display:none -- this gives much more styling flexibilty, and allows you to use tiling with a 1px wide bg image, saves bandwidth, and you can embed it in a CSS sprite, which saves HTTP calls:

HTML:

<ul id="nav">
    <li><a><span>link text</span></a></li>
    ...
    <li><a><span>link text</span></a></li>
</ul

CSS:

#nav li{background: url(/images/separator.gif) no-repeat left; padding-left:20px;} 
#nav a{background: url(/images/nav-bg.gif) repeat-x;}
#nav a span{display:none;}

UPDATE OK, I see others got similar answer in before me -- and I note that John also includes a means for keeping the separator from appearing before the first element, by using the li + li selector -- which means any li coming after another li.

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}

Exploring Docker container's file system

If you are using the AUFS storage driver, you can use my docker-layer script to find any container's filesystem root (mnt) and readwrite layer :

# docker-layer musing_wiles
rw layer : /var/lib/docker/aufs/diff/c83338693ff190945b2374dea210974b7213bc0916163cc30e16f6ccf1e4b03f
mnt      : /var/lib/docker/aufs/mnt/c83338693ff190945b2374dea210974b7213bc0916163cc30e16f6ccf1e4b03f

Edit 2018-03-28 :
docker-layer has been replaced by docker-backup

How to validate a url in Python? (Malformed or not)

Use the validators package:

>>> import validators
>>> validators.url("http://google.com")
True
>>> validators.url("http://google")
ValidationFailure(func=url, args={'value': 'http://google', 'require_tld': True})
>>> if not validators.url("http://google"):
...     print "not valid"
... 
not valid
>>>

Install it from PyPI with pip (pip install validators).

Setting Icon for wpf application (VS 08)

@742's answer works pretty well, but as outlined in the comments when running from the VS debugger the generic icon is still shown.

If you want to have your icon even when you're pressing F5, you can add in the Main Window:

<Window x:Class="myClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon="./Resources/Icon/myIcon.png">

where you indicate the path to your icon (the icon can be *.png, *.ico.)

(Note you will still need to set the Application Icon or it'll still be the default in Explorer).

What's the proper way to compare a String to an enum value?

public class Main {

    enum Vehical{
        Car,
        Bus,
        Van
    }

    public static void main(String[] args){

      String vehicalType = "CAR";

        if(vehicalType.equals(Vehical.Car.name())){
            System.out.println("The provider is Car");
        }

     String vehical_Type = "BUS";

       if(vehical_Type.equals(Vehical.Bus.toString())){
            System.out.println("The provider is Bus");
        }


    }
}

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

Are there inline functions in java?

In Java, the optimizations are usually done at the JVM level. At runtime, the JVM perform some "complicated" analysis to determine which methods to inline. It can be aggressive in inlining, and the Hotspot JVM actually can inline non-final methods.

The java compilers almost never inline any method call (the JVM does all of that at runtime). They do inline compile time constants (e.g. final static primitive values). But not methods.

For more resources:

  1. Article: The Java HotSpot Performance Engine: Method Inlining Example

  2. Wiki: Inlining in OpenJDK, not fully populated but contains links to useful discussions.

Override and reset CSS style: auto or none don't work

I ended up using Javascript to perfect everything.

My JS fiddle: https://jsfiddle.net/QEpJH/612/

HTML:

<div class="container">
    <img src="http://placekitten.com/240/300">
</div>

<h3 style="clear: both;">Full Size Image - For Reference</h3>
<img src="http://placekitten.com/240/300">

CSS:

.container {
    background-color:#000;
    width:100px;
    height:200px;

    display:flex;
    justify-content:center;
    align-items:center;
    overflow:hidden;

}

JS:

$(".container").each(function(){
    var divH = $(this).height()
    var divW = $(this).width()
    var imgH = $(this).children("img").height();
    var imgW = $(this).children("img").width();

    if ( (imgW/imgH) < (divW/divH)) { 
        $(this).addClass("1");
        var newW = $(this).width();
        var newH = (newW/imgW) * imgH;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    } else {
        $(this).addClass("2");
        var newH = $(this).height();
        var newW = (newH/imgH) * imgW;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    }
})

How can I use iptables on centos 7?

If you do so, and you're using fail2ban, you will need to enable the proper filters/actions:

Put the following lines in /etc/fail2ban/jail.d/sshd.local

[ssh-iptables]
enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
logpath  = /var/log/secure
maxretry = 5
bantime = 86400

Enable and start fail2ban:

systemctl enable fail2ban
systemctl start fail2ban

Reference: http://blog.iopsl.com/fail2ban-on-centos-7-to-protect-ssh-part-ii/

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

I just went through all 4 pages of this so far, and I was rather surprised that I didn't see this way to shorten a check for InvokeRequired:

using System;
using System.Windows.Forms;

/// <summary>
/// Extension methods acting on Control objects.
/// </summary>
internal static class ControlExtensionMethods
{
    /// <summary>
    /// Invokes the given action on the given control's UI thread, if invocation is needed.
    /// </summary>
    /// <param name="control">Control on whose UI thread to possibly invoke.</param>
    /// <param name="action">Action to be invoked on the given control.</param>
    public static void MaybeInvoke(this Control control, Action action)
    {
        if (control != null && control.InvokeRequired)
        {
            control.Invoke(action);
        }
        else
        {
            action();
        }
    }

    /// <summary>
    /// Maybe Invoke a Func that returns a value.
    /// </summary>
    /// <typeparam name="T">Return type of func.</typeparam>
    /// <param name="control">Control on which to maybe invoke.</param>
    /// <param name="func">Function returning a value, to invoke.</param>
    /// <returns>The result of the call to func.</returns>
    public static T MaybeInvoke<T>(this Control control, Func<T> func)
    {
        if (control != null && control.InvokeRequired)
        {
            return (T)(control.Invoke(func));
        }
        else
        {
            return func();
        }
    }
}

Usage:

myForm.MaybeInvoke(() => this.Text = "Hello world");

// Sometimes the control might be null, but that's okay.
var dialogResult = this.Parent.MaybeInvoke(() => MessageBox.Show(this, "Yes or no?", "Choice", MessageBoxButtons.YesNo));

Django Cookies, how can I set them?

Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.

Here is an example with a Django view ...

def homepage(request):

    request.session.setdefault('how_many_visits', 0)
    request.session['how_many_visits'] += 1

    print(request.session['how_many_visits'])

    return render(request, 'home.html', {})

If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.

Could not find module "@angular-devkit/build-angular"

I just did below and it worked.

npm install --save-dev

How to get MAC address of client using PHP?

//Simple & effective way to get client mac address
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');

// Capture the output into a variable

    $mycom=ob_get_contents();

// Clean (erase) the output buffer

    ob_clean();

$findme = "Physical";
//Search the "Physical" | Find the position of Physical text
$pmac = strpos($mycom, $findme);

// Get Physical Address
$mac=substr($mycom,($pmac+36),17);
//Display Mac Address
echo $mac;

Celery Received unregistered task of type (run example)

The solution for me to add this line to /etc/default/celeryd

CELERYD_OPTS="-A tasks"

Because when I run these commands:

celery worker --loglevel=INFO
celery worker -A tasks --loglevel=INFO

Only the latter command was showing task names at all.

I have also tried adding CELERY_APP line /etc/default/celeryd but that didn't worked either.

CELERY_APP="tasks"

scp via java

Like some here, I ended up writing a wrapper around the JSch library.

It's called way-secshell and it is hosted on GitHub:

https://github.com/objectos/way-secshell

// scp myfile.txt localhost:/tmp
File file = new File("myfile.txt");
Scp res = WaySSH.scp()
  .file(file)
  .toHost("localhost")
  .at("/tmp")
  .send();

SQL Server procedure declare a list

I've always found it easier to invert the test against the list in situations like this. For instance...

SELECT 
    field0, field1, field2 
FROM 
    my_table 
WHERE 
    ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%' 

This means that there is no complicated mish-mash required for the values that you are looking for.

As an example, if our list was ('1,2,3'), then we add a comma to the start and end of our list like so: ',' + @mysearchlist + ','.

We also do the same for the field value we're looking for and add wildcards: '%,' + CAST(field3 AS VARCHAR) + ',%' (notice the % and the , characters).

Finally we test the two using the LIKE operator: ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'.

CSS smooth bounce animation

The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration to suit your needs.

_x000D_
_x000D_
.animated {_x000D_
  -webkit-animation-duration: .5s;_x000D_
  animation-duration: .5s;_x000D_
  -webkit-animation-fill-mode: both;_x000D_
  animation-fill-mode: both;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  0%, 100% {_x000D_
    -webkit-transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    -webkit-transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
@keyframes bounce {_x000D_
  0%, 100% {_x000D_
    transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
.bounce {_x000D_
  -webkit-animation-name: bounce;_x000D_
  animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  background-color: red;_x000D_
  position: relative;_x000D_
  top: 100px;_x000D_
  left: 100px;_x000D_
  border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
  position: relative;_x000D_
  top: 92px;_x000D_
  left: -300px;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
_x000D_
_x000D_


Here is how your original keyframe settings would be interpreted by the browser:

  • At 0% (that is, at 0s or start of animation) - translate by 0px in Y axis.
  • At 20% (that is, at 0.5s of animation) - translate by 0px in Y axis.
  • At 40% (that is, at 1s of animation) - translate by 0px in Y axis.
  • At 50% (that is, at 1.25s of animation) - translate by 5px in Y axis. This results in a gradual upward movement.
  • At 60% (that is, at 1.5s of animation) - translate by 0px in Y axis. This results in a gradual downward movement.
  • At 80% (that is, at 2s of animation) - translate by 0px in Y axis.
  • At 100% (that is, at 2.5s or end of animation) - translate by 0px in Y axis.

Extract the first word of a string in a SQL Server query

Try This:

Select race_id, race_description
, Case patIndex ('%[ /-]%', LTrim (race_description))
    When 0 Then LTrim (race_description)
    Else substring (LTrim (race_description), 1, patIndex ('%[ /-]%', LTrim (race_description)) - 1)
End race_abbreviation

from tbl_races

Aborting a stash pop in Git

I solved this in a somewhat different way. Here's what happened.

First, I popped on the wrong branch and got conflicts. The stash remained intact but the index was in conflict resolution, blocking many commands.

A simple git reset HEAD aborted the conflict resolution and left the uncommitted (and UNWANTED) changes.

Several git co <filename> reverted the index to the initial state. Finally, I switched branch with git co <branch-name> and run a new git stash pop, which resolved without conflicts.

Why is my Spring @Autowired field null?

Another solution would be putting call: SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
To MileageFeeCalculator constructor like this:

@Service
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService; // <--- will be autowired when constructor is called

    public MileageFeeCalculator() {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
    }

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); 
    }
}

Insert ellipsis (...) into HTML tag if content too wide

DO THE ELLIPSIS USING ONLY CSS

<html>
<head>
<style type="text/css">
#ellipsisdiv {
    width:200px;
    white-space: nowrap;  
    overflow: hidden;  
    text-overflow: ellipsis;  
}  
</style>
</head>
<body>
<div id="ellipsisdiv">
This content is more than 200px and see how the the ellipsis comes at the end when the content width exceeds the div width.
</div>
</body>
</html>

*This code works on most current browsers. If you experience any problem with Opera and IE (which probably you won't), add these in the style:

-o-text-overflow: ellipsis;  
-ms-text-overflow: ellipsis;

* This feature is part of CSS3. Its complete syntax is:

text-overflow: clip|ellipsis|string;

Check if a key is down?

I know this is very old question, however there is a very lightweight (~.5Kb) JavaScript library that effectively "patches" the inconsistent firing of keyboard event handlers when using the DOM API.

The library is Keydrown.

Here's the operative code sample that has worked well for my purposes by just changing the key on which to set the listener:

kd.P.down(function () {
  console.log('The "P" key is being held down!');
});

kd.P.up(function () {
  console.clear();
});

// This update loop is the heartbeat of Keydrown
kd.run(function () {
  kd.tick();
});

I've incorporated Keydrown into my client-side JavaScript for a proper pause animation in a Red Light Green Light game I'm writing. You can view the entire game here. (Note: If you're reading this in the future, the game should be code complete and playable :-D!)

I hope this helps.

Git error: "Host Key Verification Failed" when connecting to remote repository

I had the similar issue, unfortunately I used the GitExtensions HMI and forgot that I wrote a passphrase. With HMI.... forget it ! Do not enter passphrase when you generate your key !

What is the --save option for npm install?

Update as of npm 5:

As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.


Original answer:

It won't do anything if you don't have a package.json file. Start by running npm init to create one. Then calls to npm install --save or npm install --save-dev or npm install --save-optional will update the package.json to list your dependencies.

Can I run a 64-bit VMware image on a 32-bit machine?

If you have 32-bit hardware, no, you cannot run a 64-bit guest OS. "VMware software does not emulate an instruction set for different hardware not physically present".

However, QEMU can emulate a 64-bit processor, so you could convert the VMWare machine and run it with this

From this 2008-era blog post (mirrored by archive.org):

$ cd /path/to/vmware/guestos
$ for i in \`ls *[0-9].vmdk\`; do qemu-img convert -f vmdk $i -O raw {i/vmdk/raw};done
$ cat *.raw >> guestos.img

To run it,

qemu -m 256 -hda guestos.img

The downside? Most of us runs VMware without preallocation space for the virtual disk. So, when we make a conversion from VMware to QEMU, the raw file will be the total space WITH preallocation. I am still testing with -f qcow format will it solve the problem or not. Such as:

for i in `ls *[0-9].vmdk`; do qemu-img convert -f vmdk $i -O qcow ${i/vmdk/qcow}; done && cat *.qcow >> debian.img

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Change

from urllib.request import urlopen

to

from urllib import urlopen

I was able to solve this problem by changing like this. For Python2.7 in macOS10.14

Fatal error: "No Target Architecture" in Visual Studio

If you are using Resharper make sure it does not add the wrong header for you, very common cases with ReSharper are:

  • #include <consoleapi2.h
  • #include <apiquery2.h>
  • #include <fileapi.h>

UPDATE:
Another suggestion is to check if you are including a "partial Windows.h", what I mean is that if you include for example winbase.h or minwindef.h you may end up with that error, add "the big" Windows.h instead. There are also some less obvious cases that I went through, the most notable was when I only included synchapi.h, the docs clearly state that is the header to be included for some functions like AcquireSRWLockShared but it triggered the No target architecture, the fix was to remove the synchapi.h and include "the big" Windows.h.

The Windows.h is huge, it defines macros(many of them remove the No target arch error) and includes many other headers. In summary, always check if you are including some header that could be replaced by Windows.h because it is not unusual to include a header that relies on some constants that are defined by Windows.h, so if you fail to include this header your compilation may fail.

How to change the name of a Django app?

In case you are using PyCharm and project stops working after rename:

  1. Edit Run/Debug configuration and change environment variable DJANGO_SETTINGS_MODULE, since it includes your project name.
  2. Go to Settings / Languages & Frameworks / Django and update the settings file location.

jQuery fade out then fade in

With async functions and promises, it now can work as simply as this:

async function foobar() {
  await $("#example").fadeOut().promise();
  doSomethingElse();
  await $("#example").fadeIn().promise();
}

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

OpenCV in Android Studio

Integrating OpenCV v3.1.0 into Android Studio v1.4.1, instructions with additional detail and this-is-what-you-should-get type screenshots.

Most of the credit goes to Kiran, Kool, 1", and SteveLiles over at opencv.org for their explanations. I'm adding this answer because I believe that Android Studio's interface is now stable enough to work with on this type of integration stuff. Also I have to write these instructions anyway for our project.

Experienced A.S. developers will find some of this pedantic. This answer is targeted at people with limited experience in Android Studio.

  1. Create a new Android Studio project using the project wizard (Menu:/File/New Project):

    • Call it "cvtest1"
    • Form factor: API 19, Android 4.4 (KitKat)
    • Blank Activity named MainActivity

      You should have a cvtest1 directory where this project is stored. (the title bar of Android studio shows you where cvtest1 is when you open the project)

  2. Verify that your app runs correctly. Try changing something like the "Hello World" text to confirm that the build/test cycle is OK for you. (I'm testing with an emulator of an API 19 device).

  3. Download the OpenCV package for Android v3.1.0 and unzip it in some temporary directory somewhere. (Make sure it is the package specifically for Android and not just the OpenCV for Java package.) I'll call this directory "unzip-dir" Below unzip-dir you should have a sdk/native/libs directory with subdirectories that start with things like arm..., mips... and x86... (one for each type of "architecture" Android runs on)

  4. From Android Studio import OpenCV into your project as a module: Menu:/File/New/Import_Module:

    • Source-directory: {unzip-dir}/sdk/java
    • Module name: Android studio automatically fills in this field with openCVLibrary310 (the exact name probably doesn't matter but we'll go with this).
    • Click on next. You get a screen with three checkboxes and questions about jars, libraries and import options. All three should be checked. Click on Finish.

      Android Studio starts to import the module and you are shown an import-summary.txt file that has a list of what was not imported (mostly javadoc files) and other pieces of information. enter image description here

      But you also get an error message saying failed to find target with hash string 'android-14'.... This happens because the build.gradle file in the OpenCV zip file you downloaded says to compile using android API version 14, which by default you don't have with Android Studio v1.4.1. enter image description here

  5. Open the project structure dialogue (Menu:/File/Project_Structure). Select the "app" module, click on the Dependencies tab and add :openCVLibrary310 as a Module Dependency. When you select Add/Module_Dependency it should appear in the list of modules you can add. It will now show up as a dependency but you will get a few more cannot-find-android-14 errors in the event log.

  6. Look in the build.gradle file for your app module. There are multiple build.gradle files in an Android project. The one you want is in the cvtest1/app directory and from the project view it looks like build.gradle (Module: app). Note the values of these four fields:

    • compileSDKVersion (mine says 23)
    • buildToolsVersion (mine says 23.0.2)
    • minSdkVersion (mine says 19)
    • targetSdkVersion (mine says 23)
  7. Your project now has a cvtest1/OpenCVLibrary310 directory but it is not visible from the project view:

enter image description here

Use some other tool, such as any file manager, and go to this directory. You can also switch the project view from Android to Project Files and you can find this directory as shown in this screenshot: enter image description here

Inside there is another build.gradle file (it's highlighted in the above screenshot). Update this file with the four values from step 6.

  1. Resynch your project and then clean/rebuild it. (Menu:/Build/Clean_Project) It should clean and build without errors and you should see many references to :openCVLibrary310 in the 0:Messages screen.

    enter image description here

    At this point the module should appear in the project hierarchy as openCVLibrary310, just like app. (Note that in that little drop-down menu I switched back from Project View to Android View ). You should also see an additional build.gradle file under "Gradle Scripts" but I find the Android Studio interface a little bit glitchy and sometimes it does not do this right away. So try resynching, cleaning, even restarting Android Studio.

    You should see the openCVLibrary310 module with all the OpenCV functions under java like in this screenshot:

    enter image description here

  2. Copy the {unzip-dir}/sdk/native/libs directory (and everything under it) to your Android project, to cvtest1/OpenCVLibrary310/src/main/, and then rename your copy from libs to jniLibs. You should now have a cvtest1/OpenCVLibrary310/src/main/jniLibs directory. Resynch your project and this directory should now appear in the project view under openCVLibrary310.

    enter image description here

  3. Go to the onCreate method of MainActivity.java and append this code:

    if (!OpenCVLoader.initDebug()) {
        Log.e(this.getClass().getSimpleName(), "  OpenCVLoader.initDebug(), not working.");
    } else {
        Log.d(this.getClass().getSimpleName(), "  OpenCVLoader.initDebug(), working.");
    }
    

    Then run your application. You should see lines like this in the Android Monitor: enter image description here (I don't know why that line with the error message is there)

  4. Now try to actually use some openCV code. In the example below I copied a .jpg file to the cache directory of the cvtest1 application on the android emulator. The code below loads this image, runs the canny edge detection algorithm and then writes the results back to a .png file in the same directory.

    Put this code just below the code from the previous step and alter it to match your own files/directories.

    String inputFileName="simm_01";
    String inputExtension = "jpg";
    String inputDir = getCacheDir().getAbsolutePath();  // use the cache directory for i/o
    String outputDir = getCacheDir().getAbsolutePath();
    String outputExtension = "png";
    String inputFilePath = inputDir + File.separator + inputFileName + "." + inputExtension;
    
    
    Log.d (this.getClass().getSimpleName(), "loading " + inputFilePath + "...");
    Mat image = Imgcodecs.imread(inputFilePath);  
    Log.d (this.getClass().getSimpleName(), "width of " + inputFileName + ": " + image.width());
    // if width is 0 then it did not read your image.
    
    
    // for the canny edge detection algorithm, play with these to see different results
    int threshold1 = 70;
    int threshold2 = 100;
    
    Mat im_canny = new Mat();  // you have to initialize output image before giving it to the Canny method
    Imgproc.Canny(image, im_canny, threshold1, threshold2);
    String cannyFilename = outputDir + File.separator + inputFileName + "_canny-" + threshold1 + "-" + threshold2 + "." + outputExtension;
    Log.d (this.getClass().getSimpleName(), "Writing " + cannyFilename);
    Imgcodecs.imwrite(cannyFilename, im_canny);
    
  5. Run your application. Your emulator should create a black and white "edge" image. You can use the Android Device Monitor to retrieve the output or write an activity to show it.

The Gotchas:

  • If you lower your target platform below KitKat some of the OpenCV libraries will no longer function, specifically the classes related to org.opencv.android.Camera2Renderer and other related classes. You can probably get around this by simply removing the apprpriate OpenCV .java files.
  • If you raise your target platform to Lollipop or above my example of loading a file might not work because use of absolute file paths is frowned upon. So you might have to change the example to load a file from the gallery or somewhere else. There are numerous examples floating around.

Compute a confidence interval from sample data

import numpy as np
import scipy.stats


def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

you can calculate like this way.

How to play ringtone/alarm sound in Android

You can push a MP3 file in your /sdcard folder using DDMS, restart the emulator, then open the Media application, browse to your MP3 file, long press on it and select "Use as phone ringtone".

Error is gone!

Edit: same trouble with notification sounds (e.g. for SMS) solved using Ringdroid application

How to check version of python modules?

Building on Jakub Kukul's answer I found a more reliable way to solve this problem.

The main problem of that approach is that requires the packages to be installed "conventionally" (and that does not include using pip install --user), or be in the system PATH at Python initialisation.

To get around that you can use pkg_resources.find_distributions(path_to_search). This basically searches for distributions that would be importable if path_to_search was in the system PATH.

We can iterate through this generator like this:

avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
    avail_modules[d.key] = d.version

This will return a dictionary having modules as keys and their version as value. This approach can be extended to a lot more than version number.

Thanks to Jakub Kukul for pointing to the right direction

What is the syntax to insert one list into another list in python?

If we just do x.append(y), y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:

x = [1,2,3] y = [4,5,6] x.append(y[:])

Replace missing values with column mean

Go simply with Zoo, it will simply replace all NA values with mean of the column values:

library(zoo)
na.aggregate(data)