Programs & Examples On #Screwturn

ScrewTurn Wiki is an open source (GPLv2) Wiki software that runs on the ASP.NET platform.

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

Warning as error - How to get rid of these

In the Properties,

Go to Configuration Properties. In that go to C/C++ (or something like that). ,Then click General ,In that remove the check in the "Treat Warning As Errors" Check Box

What does a bitwise shift (left or right) do and what is it used for?

Some examples:

  • Bit operations for example converting to and from Base64 (which is 6 bits instead of 8)
  • doing power of 2 operations (1 << 4 equal to 2^4 i.e. 16)
  • Writing more readable code when working with bits. For example, defining constants using 1 << 4 or 1 << 5 is more readable.

Whats the CSS to make something go to the next line in the page?

Have the element display as a block:

display: block;

Sql Server equivalent of a COUNTIF aggregate function

You could use a SUM (not COUNT!) combined with a CASE statement, like this:

SELECT SUM(CASE WHEN myColumn=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView

Note: in my own test NULLs were not an issue, though this can be environment dependent. You could handle nulls such as:

SELECT SUM(CASE WHEN ISNULL(myColumn,0)=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView

Replace single quotes in SQL Server

Try escaping the single quote with a single quote:

Replace(@strip, '''', '')

Read line with Scanner

This code reads the file line by line.

public static void readFileByLine(String fileName) {
  try {
   File file = new File(fileName);
   Scanner scanner = new Scanner(file);
   while (scanner.hasNext()) {
    System.out.println(scanner.next());
   }
   scanner.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } 
 }

You can also set a delimiter as a line separator and then perform the same.

 scanner.useDelimiter(System.getProperty("line.separator"));

You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place

UPDATED ANSWER for your comment:

I just tried to create an input file with the content as below

a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait

tried to read it with the below code.it just worked fine.

 File file = new File("/home/keerthivasan/Desktop/input.txt");
     Scanner scr = null;
         try {
            scr = new Scanner(file);
            while(scr.hasNext()){
                System.out.println("line : "+scr.next());
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
        }

Output:

line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait

so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably

 scr = new Scanner(file);
 scr.useDelimiter("\r\n");

and then do your looping to read lines. Hope this helps!

MySQL "NOT IN" query

The subquery option has already been answered, but note that in many cases a LEFT JOIN can be a faster way to do this:

SELECT table1.*
FROM table1 LEFT JOIN table2 ON table2.principal=table1.principal
WHERE table2.principal IS NULL

If you want to check multiple tables to make sure it's not present in any of the tables (like in SRKR's comment), you can use this:

SELECT table1.*
FROM table1
LEFT JOIN table2 ON table2.name=table1.name
LEFT JOIN table3 ON table3.name=table1.name
WHERE table2.name IS NULL AND table3.name IS NULL

What datatype should be used for storing phone numbers in SQL Server 2005?

Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.

how to stop a for loop

There are several ways to do it:

The simple Way: a sentinel variable

n = L[0][0]
m = len(A)
found = False
for i in range(m):
   if found:
      break
   for j in range(m):
     if L[i][j] != n: 
       found = True
       break

Pros: easy to understand Cons: additional conditional statement for every loop

The hacky Way: raising an exception

n = L[0][0]
m = len(A)

try:
  for x in range(3):
    for z in range(3):
     if L[i][j] != n: 
       raise StopIteration
except StopIteration:
   pass

Pros: very straightforward Cons: you use Exception outside of their semantic

The clean Way: make a function

def is_different_value(l, elem, size):
  for x in range(size):
    for z in range(size):
     if l[i][j] != elem: 
       return True
  return False

if is_different_value(L, L[0][0], len(A)):
  print "Doh"

pros: much cleaner and still efficient cons: yet feels like C

The pythonic way: use iteration as it should be

def is_different_value(iterable):
  first = iterable[0][0]
  for l in iterable:
    for elem in l:
       if elem != first: 
          return True
  return False

if is_different_value(L):
  print "Doh"

pros: still clean and efficient cons: you reinvdent the wheel

The guru way: use any():

def is_different_value(iterable):
  first = iterable[0][0]
  return  any(any((cell != first for cell in col)) for elem in iterable)):

if is_different_value(L):
  print "Doh"

pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

json_encode(): Invalid UTF-8 sequence in argument

The symbol you posted is the placeholder symbol for a broken byte sequence. Basically, it's not a real symbol but an error in your string.

What is the exact byte value of the symbol? Blindly applying utf8_encode is not a good idea, it's better to find out first where the byte(s) came from and what they mean.

How to open a file / browse dialog using javascript?

Create input element.

Missing from these answers is how to get a file dialog without a input element on the page.

The function to show the input file dialog.

function openFileDialog (accept, callback) {  // this function must be called from  a user
                                              // activation event (ie an onclick event)
    
    // Create an input element
    var inputElement = document.createElement("input");

    // Set its type to file
    inputElement.type = "file";

    // Set accept to the file types you want the user to select. 
    // Include both the file extension and the mime type
    inputElement.accept = accept;

    // set onchange event to call callback when user has selected file
    inputElement.addEventListener("change", callback)
    
    // dispatch a click event to open the file dialog
    inputElement.dispatchEvent(new MouseEvent("click")); 
}

NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.

NOTE input.accept is not used in Edge

Example.

Calling above function when user clicks an anchor element.

_x000D_
_x000D_
// wait for window to load
window.addEventListener("load", windowLoad);

// open a dialog function
function openFileDialog (accept, multy = false, callback) { 
    var inputElement = document.createElement("input");
    inputElement.type = "file";
    inputElement.accept = accept; // Note Edge does not support this attribute
    if (multy) {
        inputElement.multiple = multy;
    }
    if (typeof callback === "function") {
         inputElement.addEventListener("change", callback);
    }
    inputElement.dispatchEvent(new MouseEvent("click")); 
}

// onload event
function windowLoad () {
    // add user click event to userbutton
    userButton.addEventListener("click", openDialogClick);
}

// userButton click event
function openDialogClick () {
    // open file dialog for text files
    openFileDialog(".txt,text/plain", true, fileDialogChanged);
}

// file dialog onchange event handler
function fileDialogChanged (event) {
    [...this.files].forEach(file => {
        var div = document.createElement("div");
        div.className = "fileList common";
        div.textContent = file.name;
        userSelectedFiles.appendChild(div);
    });
}
_x000D_
.common {
    font-family: sans-serif;
    padding: 2px;
    margin : 2px;
    border-radius: 4px;
 }
.fileList {
    background: #229;
    color: white;
}
#userButton {
    background: #999;
    color: #000;
    width: 8em;
    text-align: center;
    cursor: pointer;
}

#userButton:hover {
   background : #4A4;
   color : white;
}
_x000D_
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>
_x000D_
_x000D_
_x000D_

Warning the above snippet is written in ES6.

How do you dismiss the keyboard when editing a UITextField

Programmatically set the delegate of the UITextField in swift 3

Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )

 lazy var firstNameTF: UITextField = {

    let firstname = UITextField()
    firstname.placeholder = "FirstName"
    firstname.frame = CGRect(x:38, y: 100, width: 244, height: 30)
    firstname.textAlignment = .center
    firstname.borderStyle = UITextBorderStyle.roundedRect
    firstname.keyboardType = UIKeyboardType.default
    firstname.delegate = self
    return firstname
}()

lazy var lastNameTF: UITextField = {

    let lastname = UITextField()
    lastname.placeholder = "LastName"
    lastname.frame = CGRect(x:38, y: 150, width: 244, height: 30)
    lastname.textAlignment = .center
    lastname.borderStyle = UITextBorderStyle.roundedRect
    lastname.keyboardType = UIKeyboardType.default
    lastname.delegate = self
    return lastname
}()

lazy var emailIdTF: UITextField = {

    let emailid = UITextField()
    emailid.placeholder = "EmailId"
    emailid.frame = CGRect(x:38, y: 200, width: 244, height: 30)
    emailid.textAlignment = .center
    emailid.borderStyle = UITextBorderStyle.roundedRect
    emailid.keyboardType = UIKeyboardType.default
    emailid.delegate = self
    return emailid
}()

// Mark:- handling delegate textField..

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField == firstNameTF {

        lastNameTF.becomeFirstResponder()
    }

    else if textField == lastNameTF {

        emailIdTF.becomeFirstResponder()
    }
    else {
        view.emailIdTF(true)
    }
    return true
}

Overlaying histograms with ggplot2 in R

Your current code:

ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)

is telling ggplot to construct one histogram using all the values in f0 and then color the bars of this single histogram according to the variable utt.

What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram, where each one gets it's own data frame and fill:

ggplot(histogram, aes(f0)) + 
    geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
    geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
    geom_histogram(data = highf0, fill = "green", alpha = 0.2) +

Here's a concrete example with some output:

dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))

ggplot(dat,aes(x=xx)) + 
    geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)

which produces something like this:

enter image description here

Edited to fix typos; you wanted fill, not colour.

Remove All Event Listeners of Specific Type

If your only goal by removing the listeners is to stop them from running, you can add an event listener to the window capturing and canceling all events of the given type:

window.addEventListener(type, function (event) {
    event.stopPropagation();
}, true);

Passing in true for the third parameter causes the event to be captured on the way down. Stopping propagation means that the event never reaches the listeners that are listening for it.

Keep in mind though that this has very limited use as you can't add new listeners for the given type (they will all be blocked). There are ways to get around this somewhat, e.g., by firing a new kind of event that only your listeners would know to listen for. Here is how you can do that:

window.addEventListener('click', function (event) {
    // (note: not cross-browser)
    var event2 = new CustomEvent('click2', {detail: {original: event}});
    event.target.dispatchEvent(event2);
    event.stopPropagation();
}, true);

element.addEventListener('click2', function(event) {
    event = event.detail && event.detail.original ?
        event.detail.original :
        event;
    // ... do something with event ...
});

However, note that this may not work as well for fast events like mousemove, given that the re-dispatching of the event introduces a delay.

Better would be to just keep track of the listeners added in the first place, as outlined in Martin Wantke's answer, if you need to do this.

c# open a new form then close the current form?

                     this.Visible = false;
                        //or                         // will make LOgin Form invisivble
                        //this.Enabled = false;
                         //  or
                       // this.Hide(); 



                        Form1 form1 = new Form1();
                        form1.ShowDialog();

                        this.Dispose();

Close a div by clicking outside

I'd suggest using the stopPropagation() method as shown in the modified fiddle:

Fiddle

$('body').click(function() {
    $(".popup").hide();
});

$('.popup').click(function(e) {
    e.stopPropagation();
});

That way you can hide the popup when you click on the body, without having to add an extra if, and when you click on the popup, the event doesn't bubble up to the body by going through the popup.

Fullscreen Activity in Android?

Here is an example code. You can turn on/off flags to hide/show specific parts.

enter image description here

public static void hideSystemUI(Activity activity) {
    View decorView = activity.getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    //| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    //| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE);
}

Then, you reset to the default state:

enter image description here

public static void showSystemUI(Activity activity) {
    View decorView = activity.getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

You can call the above functions from your onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.course_activity);
    UiUtils.hideSystemUI(this);
}

iOS: Compare two dates

After searching stackoverflow and the web a lot, I've got to conclution that the best way of doing it is like this:

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
    NSDate* enddate = checkEndDate;
    NSDate* currentdate = [NSDate date];
    NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
    double secondsInMinute = 60;
    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

    if (secondsBetweenDates == 0)
        return YES;
    else if (secondsBetweenDates < 0)
        return YES;
    else
        return NO;
}

You can change it to difference between hours also.

Enjoy!


Edit 1

If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date]; && NSTimeInterval distance

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];

How to break out of a loop from inside a switch?

You could put your switch into a separate function like this:

bool myswitchfunction()
{
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        return false; // **HERE, I want to break out of the loop itself**
    }
    return true;
}

while(myswitchfunction())
    ;

RESTful Authentication via Spring

We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:

Set up the security context like so:

<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
    <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url pattern="/authenticate" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>

<bean id="CustomAuthenticationEntryPoint"
    class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />

<bean id="authenticationTokenProcessingFilter"
    class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
    <constructor-arg ref="authenticationManager" />
</bean>

As you can see, we've created a custom AuthenticationEntryPoint, which basically just returns a 401 Unauthorized if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.

CustomAuthenticationEntryPoint:

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
    }
}

AuthenticationTokenProcessingFilter:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired UserService userService;
    @Autowired TokenUtils tokenUtils;
    AuthenticationManager authManager;

    public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if(parms.containsKey("token")) {
            String token = parms.get("token")[0]; // grab the first "token" parameter

            // validate the token
            if (tokenUtils.validate(token)) {
                // determine the user based on the (already validated) token
                UserDetails userDetails = tokenUtils.getUserFromToken(token);
                // build an Authentication object with the user's info
                UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                // set the authentication into the SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));         
            }
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

Obviously, TokenUtils contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:

public interface TokenUtils {
    String getToken(UserDetails userDetails);
    String getToken(UserDetails userDetails, Long expiration);
    boolean validate(String token);
    UserDetails getUserFromToken(String token);
}

That ought to get you off to a good start. Happy coding. :)

How do I remove the file suffix and path portion from a path string in Bash?

The basename and dirname functions are what you're after:

mystring=/foo/fizzbuzz.bar
echo basename: $(basename "${mystring}")
echo basename + remove .bar: $(basename "${mystring}" .bar)
echo dirname: $(dirname "${mystring}")

Has output:

basename: fizzbuzz.bar
basename + remove .bar: fizzbuzz
dirname: /foo

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

How to show a GUI message box from a bash script in linux?

I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package.

Normalization in DOM parsing with java - how does it work?

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

Convert Python program to C/C++ code?

I know this is an older thread but I wanted to give what I think to be helpful information.

I personally use PyPy which is really easy to install using pip. I interchangeably use Python/PyPy interpreter, you don't need to change your code at all and I've found it to be roughly 40x faster than the standard python interpreter (Either Python 2x or 3x). I use pyCharm Community Edition to manage my code and I love it.

I like writing code in python as I think it lets you focus more on the task than the language, which is a huge plus for me. And if you need it to be even faster, you can always compile to a binary for Windows, Linux, or Mac (not straight forward but possible with other tools). From my experience, I get about 3.5x speedup over PyPy when compiling, meaning 140x faster than python. PyPy is available for Python 3x and 2x code and again if you use an IDE like PyCharm you can interchange between say PyPy, Cython, and Python very easily (takes a little of initial learning and setup though).

Some people may argue with me on this one, but I find PyPy to be faster than Cython. But they're both great choices though.

Edit: I'd like to make another quick note about compiling: when you compile, the resulting binary is much bigger than your python script as it builds all dependencies into it, etc. But then you get a few distinct benefits: speed!, now the app will work on any machine (depending on which OS you compiled for, if not all. lol) without Python or libraries, it also obfuscates your code and is technically 'production' ready (to a degree). Some compilers also generate C code, which I haven't really looked at or seen if it's useful or just gibberish. Good luck.

Hope that helps.

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

The docs give a fair indicator of what's required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3


If you're on ubuntu, you may run into trouble installing pyopenssl, you'll need these dependencies:

$ apt-get install libffi-dev libssl-dev

Map a 2D array onto a 1D array

You should be able to access the 2d array with a simple pointer in place. The array[x][y] will be arranged in the pointer as p[0x * width + 0y][0x * width + 1y]...[0x * width + n-1y][1x * width + 0y] etc.

SyntaxError: expected expression, got '<'

I had this same error when I migrated a Wordpress site to another server. The URL in the header for my js scripts was still pointing to the old server and domain name.

Once I updated the domain name, the error went away.

Calculating Time Difference

You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try

import time
time.time()

which gives you the seconds since the start of the epoch.

You can then get the intermediate time with something like

timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)

What's the maximum value for an int in PHP?

Ah I found it: 232 - 1 (2147483647)

http://au2.php.net/int

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

<?php
$large_number =  2147483647;
var_dump($large_number);
// output: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648)

Best way to call a JSON WebService from a .NET Console

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
{
    return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}

How to close a Java Swing application from the code

I think, the idea is here the WindowListener - you can add any code there that you'd like to run before the thing shuts down

ProgressDialog in AsyncTask

AsyncTask is very helpful!

class QueryBibleDetail extends AsyncTask<Integer, Integer, String>{
        private Activity activity;
        private ProgressDialog dialog;
        private Context context;

        public QueryBibleDetail(Activity activity){
            this.activity = activity;
            this.context = activity;
            this.dialog = new ProgressDialog(activity);
            this.dialog.setTitle("????");
            this.dialog.setMessage("????:"+tome+chapterID+":"+sectionFromID+"-"+sectionToID);
            if(!this.dialog.isShowing()){
                this.dialog.show();
            }
        }

        @Override
        protected String doInBackground(Integer... params) {
            Log.d(TAG,"??doInBackground");
            publishProgress(params[0]);

            if(sectionFromID > sectionToID){
                return "";
            }

            String queryBible = "action=query_bible&article="+chapterID+"&id="+tomeID+"&verse_start="+sectionFromID+"&verse_stop="+sectionToID+"";
            try{
                String bible = (Json.getRequest(HOST+queryBible)).trim();
                bible = android.text.Html.fromHtml(bible).toString();
                return bible;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String bible){
            Log.d(TAG,"??onPostExecute");
            TextView bibleBox = (TextView) findViewById(R.id.bibleBox);
            bibleBox.setText(bible);
            this.dialog.dismiss();
        }
    }

How to return PDF to browser in MVC?

I got it working with this code.

using iTextSharp.text;
using iTextSharp.text.pdf;

public FileStreamResult pdf()
{
    MemoryStream workStream = new MemoryStream();
    Document document = new Document();
    PdfWriter.GetInstance(document, workStream).CloseStream = false;

    document.Open();
    document.Add(new Paragraph("Hello World"));
    document.Add(new Paragraph(DateTime.Now.ToString()));
    document.Close();

    byte[] byteInfo = workStream.ToArray();
    workStream.Write(byteInfo, 0, byteInfo.Length);
    workStream.Position = 0;

    return new FileStreamResult(workStream, "application/pdf");    
}

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:

Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.

Addition for BigDecimal

//you can do in this way...as BigDecimal is immutable so cant set values except in constructor

BigDecimal test = BigDecimal.ZERO;
BigDecimal result = test.add(new BigDecimal(30));
System.out.println(result);

result would be 30

What does "select count(1) from table_name" on any database tables mean?

SELECT COUNT(1) from <table name>

should do the exact same thing as

SELECT COUNT(*)  from <table name>

There may have been or still be some reasons why it would perform better than SELECT COUNT(*)on some database, but I would consider that a bug in the DB.

SELECT COUNT(col_name) from <table name>

however has a different meaning, as it counts only the rows with a non-null value for the given column.

What does "make oldconfig" do exactly in the Linux kernel makefile?

Before you run make oldconfig, you need to copy a kernel configuration file from an older kernel into the root directory of the new kernel.

You can find a copy of the old kernel configuration file on a running system at /boot/config-3.11.0. Alternatively, kernel source code has configs in linux-3.11.0/arch/x86/configs/{i386_defconfig / x86_64_defconfig}

If your kernel source is located at /usr/src/linux:

cd /usr/src/linux
cp /boot/config-3.9.6-gentoo .config
make oldconfig

How to define a variable in a Dockerfile?

If the variable is re-used within the same RUN instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Instead of casting the model in the RenderPartial call, and since you're using razor, you can modify the first line in your view from

@model dynamic

to

@model YourNamespace.YourModelType

This has the advantage of working on every @Html.Partial call you have in the view, and also gives you intellisense for the properties.

How to call getResources() from a class which has no context?

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 block1 = new Droid(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic), 100, 10);
 //OR
 builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic));
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

no pg_hba.conf entry for host

also check the PGHOST variable:

ECHO $PGHOST

to see if it matches the local machine name

Stopword removal with NLTK

@alvas's answer does the job but it can be done way faster. Assuming that you have documents: a list of strings.

from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation 

for doc in documents:
    list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2 times faster, which is significant if you need to operate through many documents.

For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.

P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()

and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] inside of a loop.

How to explicitly obtain post data in Spring MVC?

Another answer to the OP's exact question is to set the consumes content type to "text/plain" and then declare a @RequestBody String input parameter. This will pass the text of the POST data in as the declared String variable (postPayload in the following example).

Of course, this presumes your POST payload is text data (as the OP stated was the case).

Example:

    @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
    public ModelAndView someMethod(@RequestBody String postPayload) {    
        // ...    
    }

How can I see CakePHP's SQL dump in the controller?

In CakePHP 1.2 ..

$db =& ConnectionManager::getDataSource('default');
$db->showLog();

jQuery `.is(":visible")` not working in Chrome

I need to use visibility:hidden insted of display:none because visibility takes events, while display does not.

So I do .attr('visibility') === "visible"

Using an HTTP PROXY - Python

You can do it even without the HTTP_PROXY environment variable. Try this sample:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()
print html

In your case it really seems that the proxy server is refusing the connection.


Something more to try:

import urllib2

#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html

Edit 2014: This seems to be a popular question / answer. However today I would use third party requests module instead.

For one request just do:

import requests

r = requests.get("http://www.google.com", 
                 proxies={"http": "http://61.233.25.166:80"})
print(r.text)

For multiple requests use Session object so you do not have to add proxies parameter in all your requests:

import requests

s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")
print(r.text)

Weird PHP error: 'Can't use function return value in write context'

This also happens when using empty on a function return:

!empty(trim($someText)) and doSomething()

because empty is not a function but a language construct (not sure), and it only takes variables:

Right:

empty($someVar)

Wrong:

empty(someFunc())

Since PHP 5.5, it supports more than variables. But if you need it before 5.5, use trim($name) == false. From empty documentation.

c# search string in txt file

You have to use while since foreach does not know about index. Below is an example code.

int counter = 0;
string line;

Console.Write("Input your search text: ");
var text = Console.ReadLine();

System.IO.StreamReader file =
    new System.IO.StreamReader("SampleInput1.txt");

while ((line = file.ReadLine()) != null)
{
    if (line.Contains(text))
    {
        break;
    }

    counter++;
}

Console.WriteLine("Line number: {0}", counter);

file.Close();

Console.ReadLine();

Background color for Tk in Python

I know this is kinda an old question but:

root["bg"] = "black"

will also do what you want and it involves less typing.

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

This is happening because github is not currently in your known hosts.

You should be prompted to add github to your known hosts. If this hasn't happened, you can run ssh -T [email protected] to receive the prompt again.

How to do a PUT request with curl?

Quick Answer:

In a single line, the curl command would be:

a) If sending form data:

curl -X PUT -H "Content-Type: multipart/form-data;" -F "key1=val1" "YOUR_URI"

b) If sending raw data as json:

curl -X PUT -H "Content-Type: application/json" -d '{"key1":"value"}' "YOUR_URI"

c) If sending a file with a POST request:

curl -X POST "YOUR_URI" -F 'file=@/file-path.csv'

Alternative solution:

You can use the POSTMAN app from Chrome Store to get the equivalent cURL request. This is especially useful when writing more complicated requests.

For the request with other formats or for different clients like java, PHP, you can check out POSTMAN/comment below.

POSTMAN to get the request code

How to redirect to an external URL in Angular2?

If you've been using the OnDestry lifecycle hook, you might be interested in using something like this before calling window.location.href=...

    this.router.ngOnDestroy();
    window.location.href = 'http://www.cnn.com/';

that will trigger the OnDestry callback in your component that you might like.

Ohh, and also:

import { Router } from '@angular/router';

is where you find the router.

---EDIT--- Sadly, I might have been wrong in the example above. At least it's not working as exepected in my production code right now - so, until I have time to investigate further, I solve it like this (since my app really need the hook when possible)

this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});

Basically routing to any (dummy) route to force the hook, and then navigate as requested.

How can I change NULL to 0 when getting a single value from a SQL function?

ORACLE/PLSQL:

NVL FUNCTION

SELECT NVL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

This SQL statement would return 0 if the SUM(Price) returned a null value. Otherwise, it would return the SUM(Price) value.

How to vertically center <div> inside the parent element with CSS?

simplest way to center your div element is to use this class with following properties.

.light {
    margin: auto;
    width: 50%;
    border: 3px solid green;
    padding: 10px;
}

When to catch java.lang.Error?

Very, very rarely.

I did it only for one very very specific known cases. For example, java.lang.UnsatisfiedLinkError could be throw if two independence ClassLoader load same DLL. (I agree that I should move the JAR to a shared classloader)

But most common case is that you needed logging in order to know what happened when user come to complain. You want a message or a popup to user, rather then silently dead.

Even programmer in C/C++, they pop an error and tell something people don't understand before it exit (e.g. memory failure).

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

What does T&& (double ampersand) mean in C++11?

It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.

In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);

In C++0x, this is not the case.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);

Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr cannot be copied but can be moved, which means that std::unique_ptr can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr cannot.

Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.

std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template

Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.

(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&

Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.

template<typename A, typename B> auto min(A&& aref, B&& bref) {
    // for example, if you pass a const std::string& as first argument,
    // then A becomes const std::string& and by extension, aref becomes
    // const std::string&, completely maintaining it's type information.
    if (std::forward<A>(aref) < std::forward<B>(bref))
        return std::forward<A>(aref);
    else
        return std::forward<B>(bref);
}

I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.

CRC32 C or C++ implementation

using zlib.h (http://refspecs.linuxbase.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/zlib-crc32-1.html):

#include <zlib.h>
unsigned long  crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const unsigned char*)data_address, data_len);

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try this instead:

select xmltype(t.xml).extract('//fax/text()').getStringVal() from mytab t

TypeError: sequence item 0: expected string, int found

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

Java Refuses to Start - Could not reserve enough space for object heap

Given that none of the other suggestions have worked (including many things I'd have suggested myself), to help troubleshoot further, could you try running:

sysctl -a

On both the SuSE and RedHat machines to see if there are any differences? I'm guessing the default configurations are different between these two distributions that's causing this.

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How to add an action to a UIAlertView button using Swift iOS

Swift 3.0 Version of Jake's Answer

// Create the alert controller

let alertController = UIAlertController(title: "Alert!", message: "There is no items for the current user", preferredStyle: .alert)

            // Create the actions
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
                UIAlertAction in
                NSLog("OK Pressed")
            }
            let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
                UIAlertAction in
                NSLog("Cancel Pressed")
            }

            // Add the actions
            alertController.addAction(okAction)
            alertController.addAction(cancelAction)

            // Present the controller
            self.present(alertController, animated: true, completion: nil)

How to control the line spacing in UILabel

The solutions stated here didn't work for me. I found a slightly different way to do it with the iOS 6 NSAttributeString:

myLabel.numberOfLines = 0; 
NSString* string = @"String with line one. \n Line two. \n Line three.";
NSMutableParagraphStyle *style  = [[NSMutableParagraphStyle alloc] init];
style.minimumLineHeight = 30.f;
style.maximumLineHeight = 30.f;
NSDictionary *attributtes = @{NSParagraphStyleAttributeName : style,};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:string
                                                         attributes:attributtes];   
[myLabel sizeToFit];

"message failed to fetch from registry" while trying to install any module

I had this issue with npm v1.1.4 (and node v0.6.12), which are the Ubuntu 12.04 repository versions.

It looks like that version of npm isn't supported any more, updating node (and npm with it) resolved the issue.

First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).

sudo apt-get purge nodejs npm

Then enable nodesource's repo and install:

curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs

Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:

From: here

Replacing backslashes with forward slashes with str_replace() in php

you have to place double-backslash

$str = str_replace('\\', '/', $str);

How to pass an object from one activity to another on Android

Create your own class Customer as following:

import import java.io.Serializable;
public class Customer implements Serializable
{
    private String name;
    private String city;

    public Customer()
    {

    }
    public Customer(String name, String city)
    {
        this.name= name;
        this.city=city;
    }
    public String getName() 
    {
        return name;
    }
    public void setName(String name) 
    {
        this.name = name;
    }
    public String getCity() 
    {
        return city;
    }
    public void setCity(String city) 
    {
        this.city= city;
    }

}

In your onCreate() method

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_top);

    Customer cust=new Customer();
    cust.setName("abc");
    cust.setCity("xyz");

    Intent intent=new Intent(abc.this,xyz.class);
    intent.putExtra("bundle",cust);
    startActivity(intent); 
}

In xyz activity class you need to use the following code:

Intent intent=getIntent();
Customer cust=(Customer)intent.getSerializableExtra("bundle");
textViewName.setText(cust.getName());
textViewCity.setText(cust.getCity());

Cannot serve WCF services in IIS on Windows 8

This is really the same solution as faester's solution and Bill Moon's, but here's how you do it with PowerShell:

Import-Module Servermanager
Add-WindowsFeature AS-HTTP-Activation

Of course, there's nothing stopping you from calling DISM from PowerShell either.

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

Get the last inserted row ID (with SQL statement)

Assuming a simple table:

CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);

We can capture IDENTITY values in a table variable for further consumption.

DECLARE @IDs TABLE(ID INT);

-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name) 
  OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';

SELECT ID FROM @IDs;

The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

Need to ZIP an entire directory using Node.js

I have found this small library that encapsulates what you need.

npm install zip-a-folder

const zip-a-folder = require('zip-a-folder');
await zip-a-folder.zip('/path/to/the/folder', '/path/to/archive.zip');

https://www.npmjs.com/package/zip-a-folder

datatable jquery - table header width not aligned with body width

I was using Bootstrap 4, and had added the class table-sm to my table. That messed up the formatting. Removing that class fixed the problem.


If you can't remove that class, I would suspect that adding it via javascript to the headers table would work. Datatables uses two tables to display a table when scrollX is enabled -- one for the header, and one for the body.

Running Selenium Webdriver with a proxy in Python

How about something like this

PROXY = "149.215.113.110:70"

webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "class":"org.openqa.selenium.Proxy",
    "autodetect":False
}

# you have to use remote, otherwise you'll have to code it yourself in python to 
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX)

You can read more about it here.

Create a tar.xz in one command

If you like the pipe mode, this is the most clean solution:

tar c some-dir | xz > some-dir.tar.xz

It's not necessary to put the f option in order to deal with files and then to use - to specify that the file is the standard input. It's also not necessary to specify the -z option for xz, because it's default.

It works with gzip and bzip2 too:

tar c some-dir | gzip > some-dir.tar.gz

or

tar c some-dir | bzip2 > some-dir.tar.bz2

Decompressing is also quite straightforward:

xzcat tarball.tar.xz | tar x
bzcat tarball.tar.bz2 | tar x
zcat tarball.tar.gz | tar x

If you have only tar archive, you can use cat:

cat archive.tar | tar x

If you need to list the files only, use tar t.

Including a groovy script in another groovy

For late-comers, it appears that groovy now support the :load file-path command which simply redirects input from the given file, so it is now trivial to include library scripts.

It works as input to the groovysh & as a line in a loaded file:
groovy:000> :load file1.groovy

file1.groovy can contain:
:load path/to/another/file invoke_fn_from_file();

creating batch script to unzip a file without additional zip tools

Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.

How to programmatically add controls to a form in VB.NET

Dim numberOfButtons As Integer
Dim buttons() as Button

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Redim buttons(numberOfbuttons)
    for counter as integer = 0 to numberOfbuttons
        With buttons(counter)
           .Size = (10, 10)
           .Visible = False
           .Location = (55, 33 + counter*13)
           .Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
           'any other property
        End With
        '
    next
End Sub

If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.

If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:

AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked 

then create

Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
     'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub

when you call: objectYouCall.numberOfButtons = initial_value_from_main_program

response_yes_or_no_or_other = objectYouCall.ShowDialog()

For radio buttons, textboxes, same story, different ending.

Capturing standard out and error with Start-Process

In the code given in the question, I think that reading the ExitCode property of the initiation variable should work.

$process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru -Wait
$process.ExitCode

Note that (as in your example) you need to add the -PassThru and -Wait parameters (this caught me out for a while).

javascript regex for special characters

var regex = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g

Should work

Also may want to have a minimum length i.e. 6 characters

var regex = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]{6,}$/g

Why should the static field be accessed in a static way?

There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.

Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:

public class A {
    public static String VALUE = "Aaa";
}

public class B extends A {
    public static String VALUE = "Bbb";
}

Direct access to the static variable:

A.VALUE (="Aaa")
B.VALUE (="Bbb")

Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):

new B().VALUE (="Bbb")

So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.

Now to the point where it gets tricky: Interfaces can also have static variables.

public interface C {
    public static String VALUE = "Ccc";
}

public interface D {
    public static String VALUE = "Ddd";
}

Let's remove the static variable from B, and observe following situations:

  • B implements C, D
  • B extends A implements C
  • B extends A implements C, D
  • B extends A implements C where A implements D
  • B extends A implements C where C extends D
  • ...

The statement new B().VALUE is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:

error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match

And that's exactly the reason why static variables should be accessed in a static way.

PowerShell equivalent to grep -f

I'm not familiar with grep but with Select-String you can do:

Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>

You can also do that with Get-Content:

(Get-Content filename.txt) -match 'pattern'

How to run console application from Windows Service?

Services are required to connect to the Service Control Manager and provide feedback at start up (ie. tell SCM 'I'm alive!'). That's why C# application have a different project template for services. You have two alternatives:

  • wrapp your exe on srvany.exe, as described in KB How To Create a User-Defined Service
  • have your C# app detect when is launched as a service (eg. command line param) and switch control to a class that inherits from ServiceBase and properly implements a service.

CSS Layout - Dynamic width DIV

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>

Can I force a page break in HTML printing?

Just wanted to put an update. page-break-after is a legacy property now.

Official page states

This property has been replaced by the break-after property.

Change select box option background color

Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

Defining a percentage width for a LinearLayout?

Hope this can help

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="horizontal">

    <LinearLayout android:layout_width="0dip"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:id="@+id/linearLayout_dummy1" android:layout_weight=".15">
    </LinearLayout>


    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout1" android:orientation="vertical"
        android:layout_width="0dip" android:layout_weight=".7">
        <Button android:text="Button" android:id="@+id/button1"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_gravity="center">
        </Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button2"
            android:layout_height="wrap_content" android:text="Button"
            android:layout_gravity="center"></Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button3"
            android:layout_height="wrap_content" android:text="Button"
            android:layout_gravity="center"></Button>
    </LinearLayout>

    <LinearLayout android:layout_width="0dip"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:id="@+id/linearLayout_dummy2" android:layout_weight=".15">
    </LinearLayout>

</LinearLayout>

(1) Set layout_width to "0dip" (2) Set the layout_height to .xx (% you want)

throwing exceptions out of a destructor

Throwing out of a destructor can result in a crash, because this destructor might be called as part of "Stack unwinding". Stack unwinding is a procedure which takes place when an exception is thrown. In this procedure, all the objects that were pushed into the stack since the "try" and until the exception was thrown, will be terminated -> their destructors will be called. And during this procedure, another exception throw is not allowed, because it's not possible to handle two exceptions at a time, thus, this will provoke a call to abort(), the program will crash and the control will return to the OS.

How to add item to the beginning of List<T>?

Use List<T>.Insert

While not relevant to your specific example, if performance is important also consider using LinkedList<T> because inserting an item to the start of a List<T> requires all items to be moved over. See When should I use a List vs a LinkedList.

JQuery Redirect to URL after specified time

You could use the setTimeout() function:

// Your delay in milliseconds
var delay = 1000; 
setTimeout(function(){ window.location = URL; }, delay);

Angular2: custom pipe could not be found

If you are declaring your pipe in another module, make sure to add it to that module Declarations and Exports array, then import that module in whatever module is consuming that pipe.

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

How to delete columns in numpy.array

Removing Matrix columns that contain NaN. This is a lengthy answer, but hopefully easy to follow.

def column_to_vector(matrix, i):
    return [row[i] for row in matrix]
import numpy
def remove_NaN_columns(matrix):
    import scipy
    import math
    from numpy import column_stack, vstack

    columns = A.shape[1]
    #print("columns", columns)
    result = []
    skip_column = True
    for column in range(0, columns):
        vector = column_to_vector(A, column)
        skip_column = False
        for value in vector:
            # print(column, vector, value, math.isnan(value) )
            if math.isnan(value):
                skip_column = True
        if skip_column == False:
            result.append(vector)
    return column_stack(result)

### test it
A = vstack(([ float('NaN'), 2., 3., float('NaN')], [ 1., 2., 3., 9]))
print("A shape", A.shape, "\n", A)
B = remove_NaN_columns(A)
print("B shape", B.shape, "\n", B)

A shape (2, 4) 
 [[ nan   2.   3.  nan]
 [  1.   2.   3.   9.]]
B shape (2, 2) 
 [[ 2.  3.]
 [ 2.  3.]]

Running an Excel macro via Python?

Hmm i was having some trouble with that part (yes still xD):

xl.Application.Run("excelsheet.xlsm!macroname.macroname")

cos im not using excel often (same with vb or macros, but i need it to use femap with python) so i finaly resolved it checking macro list: Developer -> Macros: there i saw that: this macroname.macroname should be sheet_name.macroname like in "Macros" list.

(i spend something like 30min-1h trying to solve it, so it may be helpful for noobs like me in excel) xD

Why do package names often begin with "com"

It's the domain name spelt out in reverse.

For example, one of my domains is hedgee.com. So, I use com.hedgee as the base name of all my packages.

How can I add the sqlite3 module to Python?

if you have error in Sqlite built in python you can use Conda to solve this conflict

conda install sqlite

How to convert Observable<any> to array[]

This should work:

GetCountries():Observable<CountryData[]>  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json());
}

For this to work you will need to import the following:

import 'rxjs/add/operator/map'

How to trigger an event in input text after I stop typing/writing?

I've been searching for a simple HTML/JS code and I did not found any. Then, I wrote the code below using onkeyup="DelayedSubmission()".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
    var date = new Date();
    initial_time = date.getTime();
    if (typeof setInverval_Variable == 'undefined') {
            setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
    } 
}
function DelayedSubmission_Check() {
    var date = new Date();
    check_time = date.getTime();
    var limit_ms=check_time-initial_time;
    if (limit_ms > 800) { //Change value in milliseconds
        alert("insert your function"); //Insert your function
        clearInterval(setInverval_Variable);
        delete setInverval_Variable;
    }
}

</script>
</head>
<body>

<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />

</body>
</html>

Ant if else condition?

The if attribute does not exist for <copy>. It should be applied to the <target>.

Below is an example of how you can use the depends attribute of a target and the if and unless attributes to control execution of dependent targets. Only one of the two should execute.

<target name="prepare-copy" description="copy file based on condition"
    depends="prepare-copy-true, prepare-copy-false">
</target>

<target name="prepare-copy-true" description="copy file based on condition"
    if="copy-condition">
    <echo>Get file based on condition being true</echo>
    <copy file="${some.dir}/true" todir="." />
</target>

<target name="prepare-copy-false" description="copy file based on false condition" 
    unless="copy-condition">
    <echo>Get file based on condition being false</echo>
    <copy file="${some.dir}/false" todir="." />
</target>

If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}" instead of if="copy-condition".

In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.

How to change the port number for Asp.Net core app?

In visual studio 2017 we can change the port number from LaunchSetting.json

In Properties-> LaunchSettings.json.

Open LaunchSettings.json and change the Port Number.

Launch

Change the port Number in json file

enter image description here

Windows service on Local Computer started and then stopped error

In our case, nothing was added in the Windows Event Logs except logs that the problematic service has been started and then stopped.

It turns out that the service's CONFIG file was invalid. Correcting the invalid CONFIG file fixed the issue.

Suppress command line output

Use this script instead:

@taskkill/f /im test.exe >nul 2>&1
@pause

What the 2>&1 part actually does, is that it redirects the stderr output to stdout. I will explain it better below:

@taskkill/f /im test.exe >nul 2>&1

Kill the task "test.exe". Redirect stderr to stdout. Then, redirect stdout to nul.

@pause

Show the pause message Press any key to continue . . . until someone presses a key.

NOTE: The @ symbol is hiding the prompt for each command. You can save up to 8 bytes this way.

The shortest version of your script could be:
@taskkill/f /im test.exe >nul 2>&1&pause
The & character is used for redirection the first time, and for separating the commands the second time.
An @ character is not needed twice in a line. This code is just 40 bytes, despite the one you've posted being 49 bytes! I actually saved 9 bytes. For a cleaner code look above.

How to convert an ArrayList containing Integers to primitive int array?

Next lines you can find convertion from int[] -> List -> int[]

   private static int[] convert(int[] arr) {
        List<Integer> myList=new ArrayList<Integer>();
        for(int number:arr){
               myList.add(number);
            }
        }
        int[] myArray=new int[myList.size()];
        for(int i=0;i<myList.size();i++){
           myArray[i]=myList.get(i);
        }
        return myArray;
    }

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Instead, you could git CtrlZ and retry the commit but this time add " -m " with a message in quotes after it, then it will commit without prompting you with that page.

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

jQuery datepicker to prevent past date

Try setting startDate to the current date. For example:

$('.date-pick').datePicker({startDate:'01/01/1996'});

Make docker use IPv4 for port binding

By default, docker uses AF_INET6 sockets which can be used for both IPv4 and IPv6 connections. This causes netstat to report an IPv6 address for the listening address.

From RedHat https://access.redhat.com/solutions/3114021

Sum values in foreach loop php

$total=0;
foreach($group as $key=>$value)
{
   echo $key. " = " .$value. "<br>"; 
   $total+= $value;
}
echo $total;

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

jQuery counter to count up to a target number

I ended up creating my own plugin. Here it is in case this helps anyone:

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});
        
        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;
        
        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);
            
            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));
                
                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }
                
                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;
                    
                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };
    
    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

Here's some sample code of how to use it:

<script type="text/javascript"><!--
    jQuery(function($) {
        $('.timer').countTo({
            from: 50,
            to: 2500,
            speed: 1000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });
//--></script>

<span class="timer"></span>

View the demo on JSFiddle: http://jsfiddle.net/YWn9t/

How to get random value out of an array?

Derived from Laravel Collection::random():

function array_random($array, $amount = 1)
{
    $keys = array_rand($array, $amount);

    if ($amount == 1) {
        return $array[$keys];
    }

    $results = [];
    foreach ($keys as $key) {
        $results[] = $array[$key];
    }

    return $results;
}

Usage:

$items = ['foo', 'bar', 'baz', 'lorem'=>'ipsum'];

array_random($items); // 'bar'
array_random($items, 2); // ['foo', 'ipsum']

A few notes:

  • $amount has to be less than or equal to count($array).
  • array_rand() doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Use shuffle() afterwards if needed.


Documentation: array_rand(), shuffle()


edit: The Laravel function has noticeably grown since then, see Laravel 5.4's Arr::random(). Here is something more elaborate, derived from the grown-up Laravel function:

function array_random($array, $number = null)
{
    $requested = ($number === null) ? 1 : $number;
    $count = count($array);

    if ($requested > $count) {
        throw new \RangeException(
            "You requested {$requested} items, but there are only {$count} items available."
        );
    }

    if ($number === null) {
        return $array[array_rand($array)];
    }

    if ((int) $number === 0) {
        return [];
    }

    $keys = (array) array_rand($array, $number);

    $results = [];
    foreach ($keys as $key) {
        $results[] = $array[$key];
    }

    return $results;
}

A few highlights:

  • Throw exception if there are not enough items available
  • array_random($array, 1) returns an array of one item (#19826)
  • Support value "0" for the number of items (#20439)

Question mark characters displaying within text, why is this?

I usually curse MS word and then run the following Wscript.

// replace with path to a file that needs cleaning
PATH = "test.html"

var go=WScript.CreateObject("Scripting.FileSystemObject");
var content=go.GetFile(PATH).OpenAsTextStream().ReadAll();
var out=go.CreateTextFile("clean-"+PATH, true);

// symbols
content=content.replace(/“/g,'"');
content=content.replace(/”/g,'"');
content=content.replace(/’/g,"'");
content=content.replace(/–/g,"-");
content=content.replace(/©/g,"&copy;");
content=content.replace(/®/g,"&reg;");
content=content.replace(/°/g,"&deg;");
content=content.replace(/¶/g,"<p>");
content=content.replace(/¿/g,"&iquest;");
content=content.replace(/¡/g,'&iexcl;');
content=content.replace(/¢/g,'&cent;');
content=content.replace(/£/g,'&pound;');
content=content.replace(/¥/g,'&yen;');

out.Write(content);

How to convert Calendar to java.sql.Date in Java?

Did you try cal.getTime()? This gets the date representation.

You might also want to look at the javadoc.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

I guess this can be due to many things. In my case it was having "WHERE id IN" condition in my query and I was setting IDs separated by dash as a string using setString method on PreparedStatement.

Not sure if there is better way to do this but I just added placeholder in my statement and replaced it by values on my own.

Postgres: clear entire database before re-creating / re-populating from bash script

I've used:

pg_restore -c -d database_name filename.dump

CSS/Javascript to force html table row on a single line

If you don't want the text to wrap and you don't want the size of the column to get bigger then set a width and height on the column and set "overflow: hidden" in your stylesheet.

To do this on only one column you will want to add a class to that column on each row. Otherwise you can set it on all columns, that is up to you.

Html:

<table width="300px">
<tr>
    <td>Column 1</td><td>Column 2</td>
</tr>
<tr>
   <td class="column-1">this is the text in column one which wraps</td>
   <td>this is the column two test</td>
</tr>
</table>

stylsheet:

.column-1
{
  overflow: hidden;
  width: 150px;
  height: 1.2ex; 
}

An ex unit is the relative font size for height, if you are using pixels to set the font size you may wish to use that instead.

How to pass optional parameters while omitting some other optional parameters?

you can use optional variable by ? or if you have multiple optional variable by ..., example:

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

In the above:

  • name is required
  • country is required and has a default value
  • address is optional
  • hobbies is an array of optional params

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

I had the same problem. For me the reason was that I was using the same bridging-header for both my App and my Today Extension. My Today Extension does not include Parse, but because it was defined in the bridging-header it was trying to look for it. I created a new bridging-header for my Today Extension and the error dissapeared.

Make Vim show ALL white spaces as a character

I use this

/\s
:set hlsearch

to highlight white spaces. It searches for all white spaces, and then enables the highlight to make them pop out. However, it does not print a special character.

How to add an extra row to a pandas dataframe

Try this:

df.loc[len(df)]=['8/19/2014','Jun','Fly','98765'] 

Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.

Separating class code into a header and cpp file

Basically a modified syntax of function declaration/definitions:

a2dd.h

class A2DD
{
private:
  int gx;
  int gy;

public:
  A2DD(int x,int y);

  int getSum();
};

a2dd.cpp

A2DD::A2DD(int x,int y)
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}

Detecting which UIButton was pressed in a UITableView

create an nsmutable array and put all button in that array usint[array addObject:yourButton];

in the button press method

-

 (void)buttonPressedAction:(id)sender
{
    UIButton *button = (UIButton *)sender;

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

if([buton isEqual:[yourArray objectAtIndex:i]]){

//here write wat u need to do

}
}

How to create a generic array?

Here is the implementation of LinkedList<T>#toArray(T[]):

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                            a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;

    if (a.length > size)
        a[size] = null;

    return a;
}

In short, you could only create generic arrays through Array.newInstance(Class, int) where int is the size of the array.

How to check the presence of php and apache on ubuntu server through ssh

Another way to find out if a program is installed is by using the which command. It will show the path of the program you're searching for. For example if when your searching for apache you can use the following command:

$ which apache2ctl
/usr/sbin/apache2ctl

And if you searching for PHP try this:

$ which php
/usr/bin/php

If the which command doesn't give any result it means the software is not installed (or is not in the current $PATH):

$ which php
$

How to keep a VMWare VM's clock in sync?

In my case we are running VMWare Server 2.02 on Windows Server 2003 R2 Standard. The Host is also Windows Server 2003 R2 Standard. I had the VMware Tools installed and set to sync the time. I did everything imaginable that I found on various internet sites. We still had horrendous drift, although it had shrunk from 15 minutes or more down to the 3 or 4 minute range.

Finally in the vmware.log I found this entry (resides in the folder as the .vmx file): "Your host system does not guarantee synchronized TSCs across different CPUs, so please set the /usepmtimer option in your Windows Boot.ini file to ensure that timekeeping is reliable. See Microsoft KB http://support.microsoft.com/kb... for details and Microsoft KB http://support.microsoft.com/kb... for additional information."

Cause: This problem occurs when the computer has the AMD Cool'n'Quiet technology (AMD dual cores) enabled in the BIOS or some Intel multi core processors. Multi core or multiprocessor systems may encounter Time Stamp Counter (TSC) drift when the time between different cores is not synchronized. The operating systems which use TSC as a timekeeping resource may experience the issue. Newer operating systems typically do not use the TSC by default if other timers are available in the system which can be used as a timekeeping source. Other available timers include the PM_Timer and the High Precision Event Timer (HPET). Resolution: To resolve this problem check with the hardware vendor to see if a new driver/firmware update is available to fix the issue.

Note The driver installation may add the /usepmtimer switch in the Boot.ini file.

Once this (/usepmtimer switch) was done the clock was dead on time.

How to completely uninstall python 2.7.13 on Ubuntu 16.04

caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.

To completely uninstall Python2.x.x and everything depends on it. use this command:

sudo apt purge python2.x-minimal

As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.

Thanks, I hope it will be helpful for you.

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

How can I install Visual Studio Code extensions offline?

If you are looking for a scripted solution:

  1. Get binary download URL: you can use an API, but be warned that there is no documentation for it. This API can return an URL to download .vsix files (see example below)
  2. Download the binary
  3. Carefully unzip the binary into ~/.vscode/extensions/: you need to modify unzipped directory name, remove one file and move/rename another one.

For API start by looking at following example, and for hints how to modify request head to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/extensionManagement/common/extensionGalleryService.ts.

POST https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=5.1-preview HTTP/1.1
content-type: application/json

{
    "filters": [
        {
        "criteria": [
            {
                "filterType": 8,
                "value": "Microsoft.VisualStudio.Code",
            },
            {
                "filterType": 7,
                "value": "ms-python.python",
            }
        ],
        "pageNumber": 1,
        "pageSize": 10,
        "sortBy": 0,
        "sortOrder": 0,
        }
    ],
    "assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"],
    "flags": 514,
}

Explanations to the above example:

  • "filterType": 8 - FilterType.Target more FilterTypes
  • "filterType": 7 - FilterType.ExtensionName more FilterTypes
  • "flags": 514 - 0x2 | 0x200 - Flags.IncludeFiles | Flags.IncludeLatestVersionOnly - more Flags
    • to get flag decimal value you can run python -c "print(0x2|0x200)"
  • "assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"] - to get only link to .vsix file more AssetTypes

OS X: equivalent of Linux's wget

Here's the Mac OS X equivalent of Linux's wget.

For Linux, for instance Ubuntu on an AWS instance, use:

wget http://example.com/textfile.txt

On a Mac, i.e. for local development, use this:

curl http://example.com/textfile.txt -o textfile.txt

The -o parameter is required on a Mac for output into a file instead of on screen. Specify a different target name for renaming the downloaded file.

Use capital -O for renaming with wget. Lowercase -o will specify output file for transfer log.

Is there a php echo/print equivalent in javascript

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).

LEFT JOIN only first row

I want to give a more generalized answer. One that will handle any case when you want to select only the first item in a LEFT JOIN.

You can use a subquery that GROUP_CONCATS what you want (sorted, too!), then just split the GROUP_CONCAT'd result and take only its first item, like so...

LEFT JOIN Person ON Person.id = (
    SELECT SUBSTRING_INDEX(
        GROUP_CONCAT(FirstName ORDER BY FirstName DESC SEPARATOR "_" ), '_', 1)
    ) FROM Person
);

Since we have DESC as our ORDER BY option, this will return a Person id for someone like "Zack". If we wanted someone with the name like "Andy", we would change ORDER BY FirstName DESC to ORDER BY FirstName ASC.

This is nimble, as this places the power of ordering totally within your hands. But, after much testing, it will not scale well in a situation with lots of users and lots of data.

It is, however, useful in running data-intensive reports for admin.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

I hit this problem because I had: project A (a desktop .exe) refer to project B (a portable .dll). A & B had different versions of JSON.Net, and so there was a loader conflict. Once I made all the versions of JSON.net the same, it worked. (This is in effect what some of the solutions above are doing - I'm just calling out why it works)

Adb over wireless without usb cable at all for not rooted phones

type in Windows cmd.exe

    cd %userprofile%\.android
    dir
    copy adbkey.pub adb_keys
    dir

copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.

from: How to solve ADB device unauthorized in Android ADB host device?

now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.

from: How can I connect to Android with ADB over TCP?

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

Most of the times, the issue is with the paths you have mentioned for 'java home' and 'javac' tags in settings.xml which is present in your .m2 repository and the issue is not with your path variable or Java_Home variable. If you check and correct the same, you should be able to execute your commands successfully. - Jaihind

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

You should probably stop using launch images in iOS 8 and use a storyboard or nib/xib.

  • In Xcode 6, open the File menu and choose New ? File... ? iOS ? User Interface ? Launch Screen.

  • Then open the settings for your project by clicking on it.

  • In the General tab, in the section called App Icons and Launch Images, set the Launch Screen File to the files you just created (this will set UILaunchStoryboardName in info.plist).

Note that for the time being the simulator will only show a black screen, so you need to test on a real device.

Adding a Launch Screen xib file to your project:

Adding a new Launch Screen xib file

Configuring your project to use the Launch Screen xib file instead of the Asset Catalog:

Configure project to use Launch Screen xob

Creating JSON on the fly with JObject

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

How to insert the current timestamp into MySQL database using a PHP insert query

Forgot to put the variable in the sql statement without quotations.

 $update_query = 
      "UPDATE db.tablename SET insert_time=NOW() WHERE username='" .$somename."'";

How to distinguish between left and right mouse click with jQuery

there is also a way, to do it without JQuery!

check out this:

document.addEventListener("mousedown", function(evt) {
    switch(evt.buttons) {
      case 1: // left mouse
      case 2: // right mouse
      case 3: // middle mouse <- I didn't tested that, I just got a touchpad
    }
});

How to update record using Entity Framework 6?

This if for Entity Framework 6.2.0.

If you have a specific DbSet and an item that needs to be either updated or created:

var name = getNameFromService();

var current = _dbContext.Names.Find(name.BusinessSystemId, name.NameNo);
if (current == null)
{
    _dbContext.Names.Add(name);
}
else
{
    _dbContext.Entry(current).CurrentValues.SetValues(name);
}
_dbContext.SaveChanges();

However this can also be used for a generic DbSet with a single primary key or a composite primary key.

var allNames = NameApiService.GetAllNames();
GenericAddOrUpdate(allNames, "BusinessSystemId", "NameNo");

public virtual void GenericAddOrUpdate<T>(IEnumerable<T> values, params string[] keyValues) where T : class
{
    foreach (var value in values)
    {
        try
        {
            var keyList = new List<object>();

            //Get key values from T entity based on keyValues property
            foreach (var keyValue in keyValues)
            {
                var propertyInfo = value.GetType().GetProperty(keyValue);
                var propertyValue = propertyInfo.GetValue(value);
                keyList.Add(propertyValue);
            }

            GenericAddOrUpdateDbSet(keyList, value);
            //Only use this when debugging to catch save exceptions
            //_dbContext.SaveChanges();
        }
        catch
        {
            throw;
        }
    }
    _dbContext.SaveChanges();
}

public virtual void GenericAddOrUpdateDbSet<T>(List<object> keyList, T value) where T : class
{
    //Get a DbSet of T type
    var someDbSet = Set(typeof(T));

    //Check if any value exists with the key values
    var current = someDbSet.Find(keyList.ToArray());
    if (current == null)
    {
        someDbSet.Add(value);
    }
    else
    {
        Entry(current).CurrentValues.SetValues(value);
    }
}

Catch an exception thrown by an async void method

This blog explains your problem neatly Async Best Practices.

The gist of it being you shouldn't use void as return for an async method, unless it's an async event handler, this is bad practice because it doesn't allow exceptions to be caught ;-).

Best practice would be to change the return type to Task. Also, try to code async all the way trough, make every async method call and be called from async methods. Except for a Main method in a console, which can't be async (before C# 7.1).

You will run into deadlocks with GUI and ASP.NET applications if you ignore this best practice. The deadlock occurs because these applications runs on a context that allows only one thread and won't relinquish it to the async thread. This means the GUI waits synchronously for a return, while the async method waits for the context: deadlock.

This behaviour won't happen in a console application, because it runs on context with a thread pool. The async method will return on another thread which will be scheduled. This is why a test console app will work, but the same calls will deadlock in other applications...

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Another reason this error might occur is: there is no index.html in .../YourApp/www/ !

I just followed the ionic guide, and one of the steps is:

$ rm www/index.html

On iOS this is no problem as during the build the compiler takes some default HTML instead. However, when building for android, NO example index.html is used. Took me sometime to find out ("WHY does it work on iOS, but not on android...?)

Easy solution: create a index.html, save it under .../YourApp/www, rebuild ...et voila!

How can I use Google's Roboto font on a website?

Use /fonts/ or /font/ before font type name in your CSS stylesheet. I face this error but after that its working fine.

@font-face {
    font-family: 'robotoregular';
    src: url('../fonts/Roboto-Regular-webfont.eot');
    src: url('../fonts/Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'),
         url('../fonts/Roboto-Regular-webfont.woff') format('woff'),
         url('../fonts/Roboto-Regular-webfont.ttf') format('truetype'),
         url('../fonts/Roboto-Regular-webfont.svg#robotoregular') format('svg');
    font-weight: normal;
    font-style: normal;

}

Javascript - Regex to validate date format

You could use a character class ([./-]) so that the seperators can be any of the defined characters

var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/

Or better still, match the character class for the first seperator, then capture that as a group ([./-]) and use a reference to the captured group \1 to match the second seperator, which will ensure that both seperators are the same:

var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/

"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches

How do I configure git to ignore some files locally?

From the relevant Git documentation:

Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the $GIT_DIR/info/exclude file.

The .git/info/exclude file has the same format as any .gitignore file. Another option is to set core.excludesFile to the name of a file containing global patterns.

Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:

git update-index --assume-unchanged <file-list>

Note on $GIT_DIR: This is a notation used all over the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.


Edit: Another way is to use:

git update-index --skip-worktree <file-list>

Reverse it by:

git update-index --no-skip-worktree <file-list>

Image style height and width not taken in outlook mails

The px needs to be left off, for some odd reason.

Removing Java 8 JDK from Mac

Use /usr/libexec/java_home ; I found these alias and function to be pretty useful in my ~/.profile:

alias java_ls='/usr/libexec/java_home -V 2>&1 | cut -s -d , -f 1 | cut -c 5-'
function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    java -version
}

How to get the first column of a pandas DataFrame as a Series?

From v0.11+, ... use df.iloc.

In [7]: df.iloc[:,0]
Out[7]: 
0    1
1    2
2    3
3    4
Name: x, dtype: int64

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

I finally solved this issue by disabling IPv6 on the network configuration

Screenshot of my network configuration

Note that I use a VPN connection. If you do too, you must restart it. I'm pretty sure that it will work even if you don't use a VPN.

How do I grep for all non-ASCII characters?

The following code works:

find /tmp | perl -ne 'print if /[^[:ascii:]]/'

Replace /tmp with the name of the directory you want to search through.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

In my case this was being issued by wp cli, and the problem was that I didn't have php7.3-curl installed. Fixed with: apt-get install -y --quiet php7.3-curl

sqlite database default time value 'now'

If you want millisecond precision, try this:

CREATE TABLE my_table (
    timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);

This will save the timestamp as text, though.

Importing a GitHub project into Eclipse

As mentioned in Alain Beauvois's answer, and now (Q4 2013) better explained in

Copy the URL from GitHub and select in Eclipse from the menu the

File ? Import ? Git ? Projects from Git

http://wiki.eclipse.org/images/5/5a/Egit-0.9-import-projects-select-repository.png


If the Git repo isn't cloned yet:

In> order to checkout a remote project, you will have to clone its repository first.
Open the Eclipse Import wizard (e.g. File => Import), select Git => Projects from Git and click Next.
Select “URI” and click Next.
Now you will have to enter the repository’s location and connection data. Entering the URI will automatically fill some fields. Complete any other required fields and hit Next. If you use GitHub, you can copy the URI from the web page.

Select all branches you wish to clone and hit Next again.

Hit the Clone… button to open another wizard for cloning Git repositories.

http://eclipsesource.com/blogs/wp-content/uploads/2012/12/14-282x300.png


Original answer (July 2011)

First, if your "Working Directory" is C:\Users, that is odd, since it would mean you have cloned the GitHub repo directly within C:\Users (i.e. you have a .git directory in C:\Users)

Usually, you would clone a GitHub repo in "any directory of your choice\theGitHubRepoName".

As described in the EGit user Manual page:

In any case (unless you create a "bare" Repository, but that's not discussed here), the new Repository is essentially a folder on the local hard disk which contains the "working directory" and the metadata folder.
The metadata folder is a dedicated child folder named ".git" and often referred to as ".git-folder". It contains the actual repository (i.e. the Commits, the References, the logs and such).

The metadata folder is totally transparent to the Git client, while the working directory is used to expose the currently checked out Repository content as files for tools and editors.

Typically, if these files are to be used in Eclipse, they must be imported into the Eclipse workspace in one way or another. In order to do so, the easiest way would be to check in .project files from which the "Import Existing Projects" wizard can create the projects easily. Thus in most cases, the structure of a Repository containing Eclipse projects would look similar to something like this:

See also the Using EGit with Github section.


My working directory is now c:\users\projectname\.git

You should have the content of that repo checked out in c:\users\projectname (in other words, you should have more than just the .git).

So then I try to import the project using the eclipse "import" option.
When I try to import selecting the option "Use the new projects wizard", the source code is not imported.

That is normal.

If I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project.

Again normal.

When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?

No, that would only create an empty project.
If that project is created in c:\users\projectname, you can then declare the eisting source directory in that project.
Since it is defined in the same working directory than the Git repo, that project should then appear as "versioned".

You could also use the "Import existing project" option, if your GitHub repo had versioned the .project and .classpath file, but that may not be the case here.

Unable to create Android Virtual Device

Had to restart the Eclipse after completing the installation of ARM EABI v7a system image.

Configure DataSource programmatically in Spring Boot

All you need to do is annotate a method that returns a DataSource with @Bean. A complete working example follows.

@Bean
public DataSource dataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(dbUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();   
}

CSS text-align: center; is not centering things

I assume you want all the items next to each other, and the whole thing to be centered horizontally.

li elements are display: block by default, taking up all the horizontal space.

Add

div#footer ul li { display: inline }

once you've done that, you probably want to get rid of the list's bullets:

div#footer ul { list-style-type: none; padding: 0px; margin: 0px }

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

Can't access Tomcat using IP address

You need allow ip based access for tomcat in server.xml, by default its disabled. Open server.xml search for "

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           URIEncoding="UTF-8"
           redirectPort="8443" />

Here add a new attribute useIPVHosts="true" so it looks like this,

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           URIEncoding="UTF-8"
           redirectPort="8443"
           useIPVHosts="true" />

Now restart tomcat, it should work

DataGridView changing cell background color

dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.LightGreen;

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If you use .NET as your middle tier, check the route attribute clearly, for example,

I had issue when it was like this,

[Route("something/{somethingLong: long}")] //Space.

Fixed it by this,

[Route("something/{somethingLong:long}")] //No space

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Append an int to a std::string

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

TypeScript - Append HTML to container element in Angular 2

There is a better solution to this answer that is more Angular based.

  1. Save your string in a variable in the .ts file

    MyStrings = ["one","two","three"]

  2. In the html file use *ngFor.

    <div class="one" *ngFor="let string of MyStrings; let i = index"> <div class="two">{{string}}</div> </div>

  3. if you want to dynamically insert the div element, just push more strings into the MyStrings array

    myFunction(nextString){ this.MyString.push(nextString) }

this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.

HTML form with two submit buttons and two "target" attributes

In this example, taken from

http://www.webdeveloper.com/forum/showthread.php?t=75170

You can see the way to change the target on the button OnClick event.

function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}

<FORM name="myform" method="post" action="" target="" >

<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">

Why number 9 in kill -9 command in unix?

See the wikipedia article on Unix signals for the list of other signals. SIGKILL just happened to get the number 9.

You can as well use the mnemonics, as the numbers:

kill -SIGKILL pid

How do I check whether an array contains a string in TypeScript?

You can use the some method:

console.log(channelArray.some(x => x === "three")); // true

You can use the find method:

console.log(channelArray.find(x => x === "three")); // three

Or you can use the indexOf method:

console.log(channelArray.indexOf("three")); // 2

Javascript Append Child AFTER Element

You could also do

function insertAfter(node1, node2) {
    node1.outerHTML += node2.outerHTML;
}

or

function insertAfter2(node1, node2) {
    var wrap = document.createElement("div");
    wrap.appendChild(node2.cloneNode(true));
    var node2Html = wrap.innerHTML;
    node1.insertAdjacentHTML('afterend', node2Html);
}

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)

LINQ extension methods - Any() vs. Where() vs. Exists()

Any() returns true if any of the elements in a collection meet your predicate's criteria.

Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.

Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.

How to animate the change of image in an UIImageView?

Code:

var fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");

fadeAnim.fromValue = firstImage;
fadeAnim.toValue   = secondImage;
fadeAnim.duration  = 0.8;         //smoothest value

imageView.layer.addAnimation(fadeAnim, forKey: "contents");

imageView.image = secondImage;

Example:

UIImageView Example from code

Fun, More Verbose Solution: (Toggling on a tap)

    let fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");

    switch imageView.image {
        case firstImage?:
            fadeAnim.fromValue = firstImage;
            fadeAnim.toValue   = secondImage;
            imageView.image    = secondImage;
        default:
            fadeAnim.fromValue = secondImage;
            fadeAnim.toValue   = firstImage;
            imageView.image    = firstImage;
    }

    fadeAnim.duration = 0.8;

    imageView.layer.addAnimation(fadeAnim, forKey: "contents");

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

calling a function from class in python - different way

class MathsOperations:
    def __init__ (self, x, y):
        self.a = x
        self.b = y
    def testAddition (self):
        return (self.a + self.b)

    def testMultiplication (self):
        return (self.a * self.b)

then

temp = MathsOperations()
print(temp.testAddition())

How can I make the computer beep in C#?

Try this

Console.WriteLine("\a")

Default optional parameter in Swift function

It is little tricky when you try to combine optional parameter and default value for that parameter. Like this,

func test(param: Int? = nil)

These two are completely opposite ideas. When you have an optional type parameter but you also provide default value to it, it is no more an optional type now since it has a default value. Even if the default is nil, swift simply removes the optional binding without checking what the default value is.

So it is always better not to use nil as default value.

How to change app default theme to a different app theme?

If you are trying to reference an android style, you need to put "android:" in there

android:theme="@android:style/Theme.Black"

If that doesn't solve it, you may need to edit your question with the full manifest file, so we can see more details

Python string to unicode

Unicode escapes only work in unicode strings, so this

 a="\u2026"

is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.

To make unicode out of this, use decode('unicode-escape'):

a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

How do you round UP a number in Python?

Interesting Python 2.x issue to keep in mind:

>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0

The problem is that dividing two ints in python produces another int and that's truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.

In javascript, the exact same code produces a different result:

console.log(Math.ceil(4500/1000));
5

How to draw a path on a map using kml file?

There is now a beta available of Google Maps KML Importing Utility.

It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams

KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());

or local resources

KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());

After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.

layer.addLayerToMap();

Why do we check up to the square root of a prime number to determine if it is prime?

It's all really just basic uses of Factorization and Square Roots.

It may appear to be abstract, but in reality it simply lies with the fact that a non-prime-number's maximum possible factorial would have to be its square root because:

sqrroot(n) * sqrroot(n) = n.

Given that, if any whole number above 1 and below or up to sqrroot(n) divides evenly into n, then n cannot be a prime number.

Pseudo-code example:

i = 2;

is_prime = true;

while loop (i <= sqrroot(n))
{
  if (n % i == 0)
  {
    is_prime = false;
    exit while;
  }
  ++i;
}

How can I hide a TD tag using inline JavaScript or CSS?

.hide{

visibility: hidden

}

<td class="hide"/>

Edit- Just for you

The difference between display and visibility is this.

"display": has many properties or values, but the ones you're focused on are "none" and "block". "none" is like a hide value, and "block" is like show. If you use the "none" value you will totally hide what ever html tag you have applied this css style. If you use "block" you will see the html tag and it's content. very simple.

"visibility": has many values, but we want to know more about the "hidden" and "visible" values. "hidden" will work in the same way as the "block" value for display, but this will hide tag and it's content, but it will not hide the phisical space of that tag. For example, if you have a couple of text lines, then and image (picture) and then a table with three columns and two rows with icons and text. Now if you apply the visibility css with the hidden value to the image, the image will disappear but the space the image was using will remaing in it's place, in other words, you will end with a big space (hole) between the text and the table. Now if you use the "visible" value your target tag and it's elements will be visible again.

Array slices in C#

In C# 7.2, you can use Span<T>. The benefit of the new System.Memory system is that it doesn't need copying around data.

The method you need is Slice:

Span<byte> slice = foo.Slice(0, 40);

A lot of methods now support Span and IReadOnlySpan, so it will be very straightforward to use this new type.

Note that at the time of writing the Span<T> type is not defined in the the most recent version of .NET yet (4.7.1) so to use it you need to install the System.Memory package from NuGet.

Make a VStack fill the width of the screen in SwiftUI

A good solution and without "contraptions" is the forgotten ZStack

ZStack(alignment: .top){
    Color.red
    VStack{
        Text("Hello World").font(.title)
        Text("Another").font(.body)
    }
}

Result:

enter image description here

Rename multiple files based on pattern in Unix

Using find, xargs and sed:

find . -name "fgh*" -type f -print0 | xargs -0 -I {} sh -c 'mv "{}" "$(dirname "{}")/`echo $(basename "{}") | sed 's/^fgh/jkl/g'`"'

It's more complex than @nik's solution but it allows to rename files recursively. For instance, the structure,

.
+-- fghdir
¦   +-- fdhfilea
¦   +-- fghfilea
+-- fghfile\ e
+-- fghfilea
+-- fghfileb
+-- fghfilec
+-- other
    +-- fghfile\ e
    +-- fghfilea
    +-- fghfileb
    +-- fghfilec

would be transformed to this,

.
+-- fghdir
¦   +-- fdhfilea
¦   +-- jklfilea
+-- jklfile\ e
+-- jklfilea
+-- jklfileb
+-- jklfilec
+-- other
    +-- jklfile\ e
    +-- jklfilea
    +-- jklfileb
    +-- jklfilec

The key to make it work with xargs is to invoke the shell from xargs.

django no such table:

One way to sync your database to your django models is to delete your database file and run makemigrations and migrate commands again. This will reflect your django models structure to your database from scratch. Although, make sure to backup your database file before deleting in case you need your records.

This solution worked for me since I wasn't much bothered about the data and just wanted my db and models structure to sync up.

ASP.NET MVC 3 Razor - Adding class to EditorFor

No need to create custom template for MVC 4. Use TextBox instead of EditFor here special html attributes are not supported, it is only supported from MVC 5. TextBox is should support for MVC 4, I don't know about other version.

@Html.TextBox("test", "", new { @id = "signupform", @class = "form-control", @role = "form",@placeholder="Name" })

How to update values using pymongo?

With my pymongo version: 3.2.2 I had do the following

from bson.objectid import ObjectId
import pymongo

client = pymongo.MongoClient("localhost", 27017)
db = client.mydbname

db.ProductData.update_one({
  '_id': ObjectId(p['_id']['$oid'])
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

How do I test a single file using Jest?

You have two options:

  • Option 1: Command line. You can run the following command

    node '/Users/complete-path-to-you-project/your-project/node_modules/.bin/jest' '/Users/complete-path-to-you-project/your-project/path-to-your-file-within-the-project/your-file.spec.ts'
    

    This avoids you to install Jest globally. You use the jest used by your project.

  • Option 2: If you are using Visual Studio Code you have a great plugin to do this: Jest Runner. It allows you not only to run tests file by file, but even specific suites and specs just by a right click on the tests you want to run.

Trying to mock datetime.date.today(), but not working

We can use pytest-mock (https://pypi.org/project/pytest-mock/) mocker object to mock datetime behaviour in a particular module

Let's say you want to mock date time in the following file

# File path - source_dir/x/a.py
import datetime

def name_function():
     name = datetime.now()
     return f"name_{name}"

In the test function, mocker will be added to the function when test runs

def test_name_function(mocker):
     mocker.patch('x.a.datetime')
     x.a.datetime.now.return_value = datetime(2019, 1, 1)

     actual = name_function()

     assert actual == "name_2019-01-01"

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

Session state can only be used when enableSessionState is set to true either in a configuration

For SharePoint Can find the web config file in C:\inetpub\wwwroot\wss\VirtualDirectories\Sitecollection port number - and Make changes

 <system.web>
  <pages enableSessionState="true" /> 
 </system.web>

and using SharePoint Management Shell Run below Command

   Enable-SPSessionStateService -DefaultProvision