Programs & Examples On #Itemcommand

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

Creating a folder if it does not exists - "Item already exists"

Alternative syntax using the -Not operator and depending on your preference for readability:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Make second argument of Response false as shown below.

Response.Redirect(url,false);

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

why numpy.ndarray is object is not callable in my simple for python loop

Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Thanks for the original answer here. With python 3 the following line of code:

print(json.dumps(result_dict,ensure_ascii=False))

was ok. Consider trying not writing too much text in the code if it's not imperative.

This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2) http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html

basically install he_IL or whatever language locale on ubuntu check it is not installed

locale -a 

install it where XX is your language

sudo apt-get install language-pack-XX

For example:

sudo apt-get install language-pack-he

add the following text to /etc/apache2/envvrs

export LANG='he_IL.UTF-8'
export LC_ALL='he_IL.UTF-8'

Than you would hopefully not get python errors on from apache like:

print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)

Also in apache try to make utf the default encoding as explained here:
How to change the default encoding to UTF-8 for Apache?

Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation

Is it possible to save HTML page as PDF using JavaScript or jquery?

Ya its very easy to do with javascript. Hope this code is useful to you.

You'll need the JSpdf library.

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">Generate PDF</button>

<script>
    var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });

    // This code is collected but useful, click below to jsfiddle link.
</script>

jsfiddle link here

Sorting an array in C?

The best sorting technique of all generally depends upon the size of an array. Merge sort can be the best of all as it manages better space and time complexity according to the Big-O algorithm (This suits better for a large array).

Match two strings in one line with grep

You should have grep like this:

$ grep 'string1' file | grep 'string2'

Is there a “not in” operator in JavaScript for checking object properties?

As already said by Jordão, just negate it:

if (!(id in tutorTimes)) { ... }

Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes returns true because it is defined in Object.prototype.

If you want to test if a property doesn't exist in the current object, use hasOwnProperty:

if (!tutorTimes.hasOwnProperty(id)) { ... }

Or if you might have a key that is hasOwnPropery you can use this:

if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }

Can I change the color of Font Awesome's icon color?

Is there any possible way to change the color of a font-awesome icon to black?

Yes, there is. See the snipped bellow

_x000D_
_x000D_
<!-- Assuming that you don't have, this needs to be in your HTML file (usually the header) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- Here is what you need to use -->
<a href="/users/edit" class="fa fa-cog" style="color:black"> Edit Profile</a>
_x000D_
_x000D_
_x000D_

Font awesome is supposed to be font not image, right?

Yes, it is a font. Therefore, you are able to scale it to any size without losing quality.

Modal width (increase)

Bootstrap 4 includes sizing utilities. You can change the size to 25/50/75/100% of the page width (I wish there were even more increments).

To use these we will replace the modal-lg class. Both the default width and modal-lg use css max-width to control the modal's width, so first add the mw-100 class to effectively disable max-width. Then just add the width class you want, e.g. w-75.

Note that you should place the mw-100 and w-75 classes in the div with the modal-dialog class, not the modal div e.g.,

<div class='modal-dialog mw-100 w-75'>
    ...
</div>

How do I get a div to float to the bottom of its container?

Stu's answer comes the closest to working so far, but it still doesn't take into account the fact that your outer div's height may change, based on the way the text wraps inside of it. So, repositioning the inner div (by changing the height of the "pipe") only once won't be enough. That change has to occur inside of a loop, so you can continually check whether you've achieved the right positioning yet, and readjust if needed.

The CSS from the previous answer is still perfectly valid:

#outer {
    position: relative; 
}

#inner {
    float:right;
    position:absolute;
    bottom:0;
    right:0;
    clear:right
}

.pipe {
    width:0px; 
    float:right

}

However, the Javascript should look more like this:

var innerBottom;
var totalHeight;
var hadToReduce = false;
var i = 0;
jQuery("#inner").css("position","static");
while(true) {

    // Prevent endless loop
    i++;
    if (i > 5000) { break; }

    totalHeight = jQuery('#outer').outerHeight();
    innerBottom = jQuery("#inner").position().top + jQuery("#inner").outerHeight();
    if (innerBottom < totalHeight) {
        if (hadToReduce !== true) { 
            jQuery(".pipe").css('height', '' + (jQuery(".pipe").height() + 1) + 'px');
        } else { break; }
    } else if (innerBottom > totalHeight) {
        jQuery(".pipe").css('height', '' + (jQuery(".pipe").height() - 1) + 'px');
        hadToReduce = true;
    } else { break; }
}

How to find first element of array matching a boolean condition in JavaScript?

I have got inspiration from multiple sources on the internet to derive into the solution below. Wanted to take into account both some default value and to provide a way to compare each entry for a generic approach which this solves.

Usage: (giving value "Second")

var defaultItemValue = { id: -1, name: "Undefined" };
var containers: Container[] = [{ id: 1, name: "First" }, { id: 2, name: "Second" }];
GetContainer(2).name;

Implementation:

class Container {
    id: number;
    name: string;
}

public GetContainer(containerId: number): Container {
  var comparator = (item: Container): boolean => {
      return item.id == containerId;
    };
    return this.Get<Container>(this.containers, comparator, this.defaultItemValue);
  }

private Get<T>(array: T[], comparator: (item: T) => boolean, defaultValue: T): T {
  var found: T = null;
  array.some(function(element, index) {
    if (comparator(element)) {
      found = element;
      return true;
    }
  });

  if (!found) {
    found = defaultValue;
  }

  return found;
}

How To Upload Files on GitHub

To upload files to your repo without using the command-line, simply type this after your repository name in the browser:

https://github.com/yourname/yourrepositoryname/upload/master

and then drag and drop your files.(provided you are on github and the repository has been created beforehand)

Adding a Method to an Existing Object Instance

You can use lambda to bind a method to an instance:

def run(self):
    print self._instanceString

class A(object):
    def __init__(self):
        self._instanceString = "This is instance string"

a = A()
a.run = lambda: run(a)
a.run()

Output:

This is instance string

accessing a variable from another class

Filename=url.java

public class url {

    public static final String BASEURL = "http://192.168.1.122/";

}

if u want to call the variable just use this:

url.BASEURL + "your code here";

Adding two Java 8 streams, or an extra element to a stream

Unfortunately this answer is probably of little or no help whatsoever, but I did a forensics analysis of the Java Lambda Mailing list to see if I could find the cause of this design. This is what I found out.

In the beginning there was an instance method for Stream.concat(Stream)

In the mailing list I can clearly see the method was originally implemented as an instance method, as you can read in this thread by Paul Sandoz, about the concat operation.

In it they discuss the issues that could arise from those cases in which the stream could be infinite and what concatenation would mean in those cases, but I do not think that was the reason for the modification.

You see in this other thread that some early users of the JDK 8 questioned about the behavior of the concat instance method when used with null arguments.

This other thread reveals, though, that the design of the concat method was under discussion.

Refactored to Streams.concat(Stream,Stream)

But without any explanation, suddenly, the methods were changed to static methods, as you can see in this thread about combining streams. This is perhaps the only mail thread that sheds a bit of light about this change, but it was not clear enough for me to determine the reason for the refactoring. But we can see they did a commit in which they suggested to move the concat method out of Stream and into the helper class Streams.

Refactored to Stream.concat(Stream,Stream)

Later, it was moved again from Streams to Stream, but yet again, no explanation for that.

So, bottom line, the reason for the design is not entirely clear for me and I could not find a good explanation. I guess you could still ask the question in the mailing list.

Some Alternatives for Stream Concatenation

This other thread by Michael Hixson discusses/asks about other ways to combine/concat streams

  1. To combine two streams, I should do this:

    Stream.concat(s1, s2)
    

    not this:

    Stream.of(s1, s2).flatMap(x -> x)
    

    ... right?

  2. To combine more than two streams, I should do this:

    Stream.of(s1, s2, s3, ...).flatMap(x -> x)
    

    not this:

    Stream.of(s1, s2, s3, ...).reduce(Stream.empty(), Stream::concat)
    

    ... right?

Controller 'ngModel', required by directive '...', can't be found

One possible solution to this issue is ng-model attribute is required to use that directive.

Hence adding in the 'ng-model' attribute can resolve the issue.

<input submit-required="true" ng-model="user.Name"></input>

What does the term "Tuple" Mean in Relational Databases?

Tuples are known values which is used to relate the table in relational DB.

nvm is not compatible with the npm config "prefix" option:

Let me describe my situation.

First, check the current config

$ nvm use --delete-prefix v10.7.0
$ npm config list

Then, I found the error config in output:

; project config /mnt/c/Users/paul/.npmrc
prefix = "/mnt/c/Users/paul/C:\\Program Files\\nodejs"

So, I deleted the C:\\Program Files\\nodejs in /mnt/c/Users/paul/.npmrc.

Pass a simple string from controller to a view MVC3

If you are trying to simply return a string to a View, try this:

public string Test()
{
     return "test";
}

This will return a view with the word test in it. You can insert some html in the string.

You can also try this:

public ActionResult Index()
{
    return Content("<html><b>test</b></html>");
}

How to find all the dependencies of a table in sql server

You can use free tool called Advanced SQL Server Dependencies http://advancedsqlserverdependencies.codeplex.com/

It supports all database objects (tables, views, etc.) and can find dependencies across multiple databases (in case of synonyms).

C# ASP.NET MVC Return to Previous Page

I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.

You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.

Edit:

Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.

For instance:

public ActionResult Index()
{
    return View();
}

[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
   // load object and return in view
   ViewModel viewModel = Load(id);

   // get the previous url and store it with view model
   viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;

   return View(viewModel);
}

[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
   // Attempt to save the posted object if it works, return index if not return the Edit view again

   bool success = Save(viewModel);
   if (success)
   {
       return Redirect(viewModel.PreviousUrl);
   }
   else
   {
      ModelState.AddModelError("There was an error");
      return View(viewModel);
   }
}

The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:

@model ViewModel

@using (Html.BeginForm())
{
    ...
    <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}

Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.

This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.

Spring Boot - inject map from application.yml

I run into the same problem today, but unfortunately Andy's solution didn't work for me. In Spring Boot 1.2.1.RELEASE it's even easier, but you have to be aware of a few things.

Here is the interesting part from my application.yml:

oauth:
  providers:
    google:
     api: org.scribe.builder.api.Google2Api
     key: api_key
     secret: api_secret
     callback: http://callback.your.host/oauth/google

providers map contains only one map entry, my goal is to provide dynamic configuration for other OAuth providers. I want to inject this map into a service that will initialize services based on the configuration provided in this yaml file. My initial implementation was:

@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {

    private Map<String, Map<String, String>> providers = [:]

    @Override
    void afterPropertiesSet() throws Exception {
       initialize()
    }

    private void initialize() {
       //....
    }
}

After starting the application, providers map in OAuth2ProvidersService was not initialized. I tried the solution suggested by Andy, but it didn't work as well. I use Groovy in that application, so I decided to remove private and let Groovy generates getter and setter. So my code looked like this:

@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {

    Map<String, Map<String, String>> providers = [:]

    @Override
    void afterPropertiesSet() throws Exception {
       initialize()
    }

    private void initialize() {
       //....
    }
}

After that small change everything worked.

Although there is one thing that might be worth mentioning. After I make it working I decided to make this field private and provide setter with straight argument type in the setter method. Unfortunately it wont work that. It causes org.springframework.beans.NotWritablePropertyException with message:

Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Cannot access indexed value in property referenced in indexed property path 'providers[google]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Bean property 'providers[google]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

Keep it in mind if you're using Groovy in your Spring Boot application.

How can I make a menubar fixed on the top while scrolling

 #header {
        top:0;
        width:100%;
        position:fixed;
        background-color:#FFF;
    }

    #content {
        position:static;
        margin-top:100px;
    }

Disabling SSL Certificate Validation in Spring RestTemplate

What you need to add is a custom HostnameVerifier class bypasses certificate verification and returns true

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

This needs to be placed appropriately in your code.

Laravel 5 Eloquent where and or in Clauses

Also, if you have a variable,

CabRes::where('m_Id', 46)
      ->where('t_Id', 2)
      ->where(function($q) use ($variable){
          $q->where('Cab', 2)
            ->orWhere('Cab', $variable);
      })
      ->get();

Compile to a stand-alone executable (.exe) in Visual Studio

I agree with @Marlon. When you compile your C# project with the Release configuration, you will find into the "bin/Release" folder of your project the executable of your application. This SHOULD work for a simple application.

But, if your application have any dependencies on some external dll, I suggest you to create a SetupProject with VisualStudio. Doing so, the project wizard will find all dependencies of your application and add them (the librairies) to the installation folder. Finally, all you will have to do is run the setup on the users computer and install your software.

Memory errors and list limits?

First off, see How Big can a Python Array Get? and Numpy, problem with long arrays

Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:

  1. If you are running on an older OS or one that forces processes to use a limited amount of memory, you may need to increase the amount of memory the Python process has access to.
  2. Break the list apart using chunking. For example, do the first 1000 elements of the list, pickle and save them to disk, and then do the next 1000. To work with them, unpickle one chunk at a time so that you don't run out of memory. This is essentially the same technique that databases use to work with more data than will fit in RAM.

Array to Hash Ruby

All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

Let's look at:

a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]

You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}

All of the methods, including the reduce(&:merge!) result in the same removal.

It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

How to clear input buffer in C?

The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.

The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.

If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.

As for the proposed solutions, see (again from the comp.lang.c FAQ):

which basically state that the only portable approach is to do:

int c;
while ((c = getchar()) != '\n' && c != EOF) { }

Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.

Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, Both are functionally the same thing. But in C++ you should switch to nullptr in the place of NULL;

self.tableView.reloadData() not working in Swift

If your connection is in background thread then you should update UI in main thread like this

self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true)

As I have mentioned here

Swift 4:

self.tblMainTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)

Errors: Data path ".builders['app-shell']" should have required property 'class'

I had the same problem, but I solved it thanks to the comment of Ekta Gandhi:

Finally i found the solution.

1) Firstly eliminate all changes in package.json file by giving simple command git checkout package.json.

2) Then after make change in package.json in @angular-devkit/build-angular- ~0.800.1(Add tail instead of cap)

3) Then run command rm -rf node_modules/

4) Then clean catch by giving command npm clean cache -f

5) And at last run command npm install. This works for me.

.... Along with the modification proposed by Dimuthu

Made it to @angular-devkit/build-angular": "0.13.4" and it worked.

MySQL/SQL: Group by date only on a Datetime column

Cast the datetime to a date, then GROUP BY using this syntax:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can GROUP BY the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference to performance, it is a little clearer.

PHPDoc type hinting for array of objects?

In the PhpStorm IDE from JetBrains, you can use /** @var SomeObj[] */, e.g.:

/**
 * @return SomeObj[]
 */
function getSomeObjects() {...}

The phpdoc documentation recommends this method:

specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.

Example: @return int[]

How to resolve Unneccessary Stubbing exception

Replace

@RunWith(MockitoJUnitRunner.class)

with

@RunWith(MockitoJUnitRunner.Silent.class)

or remove @RunWith(MockitoJUnitRunner.class)

or just comment out the unwanted mocking calls (shown as unauthorised stubbing).

How to extract numbers from a string in Python?

line2 = "hello 12 hi 89"
temp1 = re.findall(r'\d+', line2) # through regular expression
res2 = list(map(int, temp1))
print(res2)

Hi ,

you can search all the integers in the string through digit by using findall expression .

In the second step create a list res2 and add the digits found in string to this list

hope this helps

Regards, Diwakar Sharma

jQuery click event on radio button doesn't get fired

There are a couple of things wrong in this code:

  1. You're using <input> the wrong way. You should use a <label> if you want to make the text behind it clickable.
  2. It's setting the enabled attribute, which does not exist. Use disabled instead.
  3. If it would be an attribute, it's value should not be false, use disabled="disabled" or simply disabled without a value.
  4. If checking for someone clicking on a form event that will CHANGE it's value (like check-boxes and radio-buttons), use .change() instead.

I'm not sure what your code is supposed to do. My guess is that you want to disable the input field with class roomNumber once someone selects "Walk in" (and possibly re-enable when deselected). If so, try this code:

HTML:

<form class="type">
    <p>
        <input type="radio" name="type" checked="checked" id="guest" value="guest" />
        <label for="guest">In House</label>
    </p>
    <p>
        <input type="radio" name="type" id="walk_in" value="walk_in" />
        <label for="walk_in">Walk in</label>
    </p>
    <p>
        <input type="text" name="roomnumber" class="roomNumber" value="12345" />
    </p>
</form>

Javascript:

$("form input:radio").change(function () {
    if ($(this).val() == "walk_in") {
        // Disable your roomnumber element here
        $('.roomNumber').attr('disabled', 'disabled');
    } else {
        // Re-enable here I guess
        $('.roomNumber').removeAttr('disabled');
    }
});

I created a fiddle here: http://jsfiddle.net/k28xd/1/

php var_dump() vs print_r()

var_dump() :-

  1. This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
  2. This function display number of element in a variable.
  3. This function display length of variable.
  4. Can't return the value only print the value.
  5. it is use for debugging purpose.

Example :-

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

output :-

   array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

print_r() :-

  1. Prints human-readable information about a variable.
  2. Not display number of element in a variable as var_dump().
  3. Not display length of variable in a variable as var_dump().
  4. Return the value if we set second parameter to true in printf_r().

Example :-

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

Output:-

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Package doesn't exist error in intelliJ

I tried all appreciated answers and none of them solve my problem!

According to Intellij community, there is a bug with Maven builds in 2020.1 and 2020.1.1 versions: https://youtrack.jetbrains.com/issue/IDEA-237320?_ga=2.235486722.203129946.1591253608-322129264.1584010541

Please try to run on 2019.3.4 version (Its worked for me from the first time)

You can download from here

https://www.jetbrains.com/idea/download/previous.html?_ga=2.190043688.203129946.1591253608-322129264.1584010541

How do I find the install time and date of Windows?

I find the creation date of c:\pagefile.sys can be pretty reliable in most cases. It can easily be obtained using this command (assuming Windows is installed on C:):

dir /as /t:c c:\pagefile.sys

The '/as' specifies 'system files', otherwise it will not be found. The '/t:c' sets the time field to display 'creation'.

How to implement infinity in Java?

The Double and Float types have the POSITIVE_INFINITY constant.

Print string and variable contents on the same line in R

Or using message

message("Current working dir: ", wd)

@agstudy's answer is the more suitable here

Using Linq to group a list of objects into a new grouped list of list of objects

Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:

public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;

groupedCustomerList =
        from User in userList
        group User by User.GroupID into newGroup
        orderby newGroup.Key
        select newGroup;

Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.

python NameError: global name '__file__' is not defined

This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell.

Python Shell doesn't detect current file path in __file__ and it's related to your filepath in which you added this line

So you should write this line os.path.join(os.path.dirname(__file__)) in file.py. and then run python file.py, It works because it takes your filepath.

The infamous java.sql.SQLException: No suitable driver found

I encountered this issue by putting a XML file into the src/main/resources wrongly, I deleted it and then all back to normal.

How can I have two fixed width columns with one flexible column in the center?

Compatibility with older browsers can be a drag, so be adviced.

If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.

Change left and right values to meet your requirement.

Thank you.

Hope this helps.

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
  flex: 1;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
  background: orange;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="column left">this is left</div>_x000D_
  <div class="column center">this is center</div>_x000D_
  <div class="column right">this is right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Differences in boolean operators: & vs && and | vs ||

I think you're talking about the logical meaning of both operators, here you have a table-resume:

boolean a, b;

Operation     Meaning                       Note
---------     -------                       ----
   a && b     logical AND                    short-circuiting
   a || b     logical OR                     short-circuiting
   a &  b     boolean logical AND            not short-circuiting
   a |  b     boolean logical OR             not short-circuiting
   a ^  b     boolean logical exclusive OR
  !a          logical NOT

short-circuiting        (x != 0) && (1/x > 1)   SAFE
not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

Not Safe means the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.

What is mod_php?

mod_php means PHP, as an Apache module.

Basically, when loading mod_php as an Apache module, it allows Apache to interpret PHP files (those are interpreted by mod_php).


EDIT : There are (at least) two ways of running PHP, when working with Apache :

  • Using CGI : a PHP process is launched by Apache, and it is that PHP process that interprets PHP code -- not Apache itself
  • Using PHP as an Apache module (called mod_php) : the PHP interpreter is then kind of "embedded" inside the Apache process : there is no external PHP process -- which means that Apache and PHP can communicate better.


And re-edit, after the comment : using CGI or mod_php is up to you : it's only a matter of configuration of your webserver.

To know which way is currently used on your server, you can check the output of phpinfo() : there should be something indicating whether PHP is running via mod_php (or mod_php5), or via CGI.

You might also want to take a look at the php_sapi_name() function : it returns the type of interface between web server and PHP.


If you check in your Apache's configuration files, when using mod_php, there should be a LoadModule line looking like this :

LoadModule php5_module        modules/libphp5.so

(The file name, on the right, can be different -- on Windows, for example, it should be a .dll)

How to send authorization header with axios

On non-simple http requests your browser will send a "preflight" request (an OPTIONS method request) first in order to determine what the site in question considers safe information to send (see here for the cross-origin policy spec about this). One of the relevant headers that the host can set in a preflight response is Access-Control-Allow-Headers. If any of the headers you want to send were not listed in either the spec's list of whitelisted headers or the server's preflight response, then the browser will refuse to send your request.

In your case, you're trying to send an Authorization header, which is not considered one of the universally safe to send headers. The browser then sends a preflight request to ask the server whether it should send that header. The server is either sending an empty Access-Control-Allow-Headers header (which is considered to mean "don't allow any extra headers") or it's sending a header which doesn't include Authorization in its list of allowed headers. Because of this, the browser is not going to send your request and instead chooses to notify you by throwing an error.

Any Javascript workaround you find that lets you send this request anyways should be considered a bug as it is against the cross origin request policy your browser is trying to enforce for your own safety.

tl;dr - If you'd like to send Authorization headers, your server had better be configured to allow it. Set your server up so it responds to an OPTIONS request at that url with an Access-Control-Allow-Headers: Authorization header.

Local dependency in package.json

This works for me.

Place the following in your package.json file

"scripts": {
    "preinstall": "npm install ../my-own-module/"
}

how do I check in bash whether a file was created more than x time ago?

The find one is good but I think you can use anotherway, especially if you need to now how many seconds is the file old

date -d "now - $( stat -c "%Y" $filename ) seconds" +%s

using GNU date

How to position text over an image in css

This is another method for working with Responsive sizes. It will keep your text centered and maintain its position within its parent. If you don't want it centered then it's even easier, just work with the absolute parameters. Keep in mind the main container is using display: inline-block. There are many others ways to do this, depending on what you're working on.

Based off of Centering the Unknown

Working codepen example here

HTML

<div class="containerBox">
    <div class="text-box">
        <h4>Your Text is responsive and centered</h4>
    </div>
    <img class="img-responsive" src="http://placehold.it/900x100"/>
</div>

CSS

.containerBox {
    position: relative;
    display: inline-block;
}
.text-box {
    position: absolute;    
    height: 100%;
    text-align: center;    
    width: 100%;
}
.text-box:before {
   content: '';
   display: inline-block;
   height: 100%;
   vertical-align: middle;
}
h4 {
   display: inline-block;
   font-size: 20px; /*or whatever you want*/
   color: #FFF;   
}
img {
  display: block;
  max-width: 100%;
  height: auto;
}

jQuery check/uncheck radio button onclick

The solutions I tried from this question did not work for me. Of the answers that worked partially, I still found that I had to click the previously unchecked radio button twice just to get it checked again. I'm currently using jQuery 3+.

After messing around with trying to get this to work using data attributes or other attributes, I finally figured out the solution by using a class instead.

For your checked radio input, give it the class checked e.g.:

<input type="radio" name="likes_cats" value="Meow" class="checked" checked>

Here is the jQuery:

$('input[type="radio"]').click(function() {
    var name = $(this).attr('name');

    if ($(this).hasClass('checked')) {
        $(this).prop('checked', false);
        $(this).removeClass('checked');
    }
    else {
        $('input[name="'+name+'"]').removeClass('checked');
        $(this).addClass('checked');
    }
});

Install msi with msiexec in a Specific Directory

Use INSTALLLOCATION. When you have problems, use the /lv log.txt to dump verbose logs. The logs would tell you if there is a property change that would override your own options. If you already installed the product, then a second run might just update it without changing the install location. You will have to uninstall first (use the /x option).

Status bar and navigation bar appear over my view's bounds in iOS 7

Swift 4.2 - Xcode 10.0 - iOS 12.0:

if #available(iOS 11.0, *) {} else {
  self.edgesForExtendedLayout = []
  self.navigationController?.view.backgroundColor = .white
}

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

This happened to me as well, and the answers given here already were not satisfying, so I did my own research.

Background: Eclipse access restrictions

Eclipse has a mechanism called access restrictions to prevent you from accidentally using classes which Eclipse thinks are not part of the public API. Usually, Eclipse is right about that, in both senses: We usually do not want to use something which is not part of the public API. And Eclipse is usually right about what is and what isn't part of the public API.

Problem

Now, there can be situations, where you want to use public Non-API, like sun.misc (you shouldn't, unless you know what you're doing). And there can be situations, where Eclipse is not really right (that's what happened to me, I just wanted to use javax.smartcardio). In that case, we get this error in Eclipse.

Solution

The solution is to change the access restrictions.

  • Go to the properties of your Java project,
    • i.e. by selecting "Properties" from the context menu of the project in the "Package Explorer".
  • Go to "Java Build Path", tab "Libraries".
  • Expand the library entry
  • select
    • "Access rules",
    • "Edit..." and
    • "Add..." a "Resolution: Accessible" with a corresponding rule pattern. For me that was "javax/smartcardio/**", for you it might instead be "com/apple/eawt/**".

Hadoop "Unable to load native-hadoop library for your platform" warning

export JAVA_HOME=/home/hadoop/software/java/jdk1.7.0_80
export HADOOP_HOME=/usr/local/hadoop
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_COMMON_LIB_NATIVE_DIR"

How to create XML file with specific structure in Java

There is no need for any External libraries, the JRE System libraries provide all you need.

I am infering that you have a org.w3c.dom.Document object you would like to write to a file

To do that, you use a javax.xml.transform.Transformer:

import org.w3c.dom.Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

public class XMLWriter {
    public static void writeDocumentToFile(Document document, File file) {

        // Make a transformer factory to create the Transformer
        TransformerFactory tFactory = TransformerFactory.newInstance();

        // Make the Transformer
        Transformer transformer = tFactory.newTransformer();

        // Mark the document as a DOM (XML) source
        DOMSource source = new DOMSource(document);

        // Say where we want the XML to go
        StreamResult result = new StreamResult(file);

        // Write the XML to file
        transformer.transform(source, result);
    }
}

Source: http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

Clear git local cache

All .idea files that are explicitly ignored are still showing up to commit

you have to remove them from the staging area

git rm --cached .idea

now you have to commit those changes and they will be ignored from this point on.
Once git start to track changes it will not "stop" tracking them even if they were added to the .gitignore file later on.

You must explicitly remove them and then commit your removal manually in order to fully ignore them.


enter image description here

enter image description here

HashSet vs LinkedHashSet

I suggest you to use LinkedHashSet most of the time, because it has better performance overall):

  1. Predictable iteration order LinkedHashSet (Oracle)
  2. LinkedHashSet is more expensive for insertions than HashSet;
  3. In general slightly better performance than HashMap, because the most of the time we use Set structures for iterating.

Performance tests:

------------- TreeSet -------------
 size       add  contains   iterate
   10       746       173        89
  100       501       264        68
 1000       714       410        69
10000      1975       552        69
------------- HashSet -------------
 size       add  contains   iterate
   10       308        91        94
  100       178        75        73
 1000       216       110        72
10000       711       215       100
---------- LinkedHashSet ----------
 size       add  contains   iterate
   10       350        65        83
  100       270        74        55
 1000       303       111        54
10000      1615       256        58

You can see source test page here: The Final Performance Testing Example

Python: URLError: <urlopen error [Errno 10060]

Answer (Basic is advance!):

Error: 10060 Adding a timeout parameter to request solved the issue for me.

Example 1

import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)

Example 2

A similar error also occurred while I was making a GET request. Again, passing a timeout parameter solved the 10060 Error.

response = requests.get(param_url, timeout=20)

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

Create an empty list in python with certain size

Not technically a list but similar to a list in terms of functionality and it's a fixed length

from collections import deque
my_deque_size_10 = deque(maxlen=10)

If it's full, ie got 10 items then adding another item results in item @index 0 being discarded. FIFO..but you can also append in either direction. Used in say

  • a rolling average of stats
  • piping a list through it aka sliding a window over a list until you get a match against another deque object.

If you need a list then when full just use list(deque object)

Could not open input file: artisan

What did the trick for me was to do cd src from my project directoy, and then use the php artisan command, since my artisan file was in the src folder. Here is my project structure:

project
|__ config
|__ src
    |__ app
    |__ ..
    |__ artisan  // hello there!
    |__ ...
|__ ...

'' is not recognized as an internal or external command, operable program or batch file

This is a very common question seen on Stackoverflow.

The important part here is not the command displayed in the error, but what the actual error tells you instead.

a Quick breakdown on why this error is received.

cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.

How do I fix this:

When Actual Command/executable fails

First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.

If you have any executable which you are attempting to run from cmd.exe then you need to tell cmd.exe where this file is located. There are 2 ways of doing this.

  1. specify the full path to the file.

    "C:\My_Files\mycommand.exe"

  2. Add the location of the file to your environment Variables.

Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables

In the System Variables Window, locate path and select edit

Now simply add your path to the end of the string, seperated by a semicolon ; as:

;C:\My_Files\

Save the changes and exit. You need to make sure that ANY cmd.exe windows you had open are then closed and re-opened to allow it to re-import the environment variables. Now you should be able to run mycommand.exe from any path, within cmd.exe as the environment is aware of the path to it.

When C:\Program or Similar fails

This is a very simple error. Each string after a white space is seen as a different command in cmd.exe terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe to see it as a single string, and not separate commands.

So to execute C:\Program Files\My-App\Mobile.exe simply run as:

"C:\Program Files\My-App\Mobile.exe"

I ran into a merge conflict. How can I abort the merge?

If your git version is >= 1.6.1, you can use git reset --merge.

Also, as @Michael Johnson mentions, if your git version is >= 1.7.4, you can also use git merge --abort.

As always, make sure you have no uncommitted changes before you start a merge.

From the git merge man page

git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.

MERGE_HEAD is present when a merge is in progress.

Also, regarding uncommitted changes when starting a merge:

If you have changes you don't want to commit before starting a merge, just git stash them before the merge and git stash pop after finishing the merge or aborting it.

How to detect browser using angularjs?

I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.

angular.module('myModule').service('browserDetectionService', function() {

 return {
isCompatible: function () {

  var browserInfo = navigator.userAgent;
  var browserFlags =  {};

  browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
  browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
  browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
  browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
  browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;

  browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
  browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
  browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
  browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
  browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
  browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
  browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here

  browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
  browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
  browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;

  return !browserFlags.ISOLD;
  }
};

});

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Angular.js programmatically setting a form field to dirty

You can use $setDirty(); method. See documentation https://docs.angularjs.org/api/ng/type/form.FormController

Example:

$scope.myForm.$setDirty();

Lost connection to MySQL server during query?

The easiest solution I found to this problem was to downgrade the MySql from MySQL Workbench to MySQL Version 1.2.17. I had browsed some MySQL Forums, where it was said that the timeout time in MySQL Workbech has been hard coded to 600 and some suggested methods to change it didn't work for me. If someone is facing the same problem with workbench you could try downgrading too.

How to make JavaScript execute after page load?

There is a very good documentation on How to detect if document has loaded using Javascript or Jquery.

Using the native Javascript this can be achieved

if (document.readyState === "complete") {
 init();
 }

This can also be done inside the interval

var interval = setInterval(function() {
    if(document.readyState === 'complete') {
        clearInterval(interval);
        init();
    }    
}, 100);

Eg By Mozilla

switch (document.readyState) {
  case "loading":
    // The document is still loading.
    break;
  case "interactive":
    // The document has finished loading. We can now access the DOM elements.
    var span = document.createElement("span");
    span.textContent = "A <span> element.";
    document.body.appendChild(span);
    break;
  case "complete":
    // The page is fully loaded.
    console.log("Page is loaded completely");
    break;
}

Using Jquery To check only if DOM is ready

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
});

To check if all resources are loaded use window.load

 $( window ).load(function() {
        console.log( "window loaded" );
    });

How to store images in mysql database using php

<!-- 
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])


CREATE TABLE  `images` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `image` longblob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

-->
<!-- this form is user to store images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />

<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>



<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
        mysql_connect("", "", "") OR DIE (mysql_error());
        mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
    header("location:search.php");

}

//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
        $name=$_POST['image_name'];
        $email=$_POST['mail'];
        $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
        }
                // our sql query
                $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
                            mysql_query($sql) or die("Error in Query insert: " . mysql_error());
} 
?>



<?php
//SEARCH.PHP PAGE
    //connect to database.db name = images
         mysql_connect("localhost", "root", "") OR DIE (mysql_error());
        mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database

        $msg="";
        $sql="select * from images";
        if(mysql_query($sql))
        {
            $res=mysql_query($sql);
            while($row=mysql_fetch_array($res))
            {
                    $id=$row['id'];
                    $name=$row['name'];
                    $image=$row['image'];

                  $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " />   </a>';

            }
        }
        else
            $msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

What is a Question Mark "?" and Colon ":" Operator Used for?

Maybe It can be perfect example for Android, For example:

void setWaitScreen(boolean set) {
    findViewById(R.id.screen_main).setVisibility(
            set ? View.GONE : View.VISIBLE);
    findViewById(R.id.screen_wait).setVisibility(
            set ? View.VISIBLE : View.GONE);
}

Passing arguments to angularjs filters

Extending on pkozlowski.opensource's answer and using javascript array's builtin filter method a prettified solution could be this:

.filter('weDontLike', function(){
    return function(items, name){
        return items.filter(function(item) {
            return item.name != name;
        });
    };
});

Here's the jsfiddle link.

More on Array filter here.

html div onclick event

You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway

Test the click on the div and examine the target

Live Demo

$(".expandable-panel-heading").on("click",function (e) {
    if (e.target.id =="ancherComplaint") { // or test the tag
        e.preventDefault(); // or e.stopPropagation()
        markActiveLink(e.target);
    }    
    else alert('123');
});
function markActiveLink(el) {   
    alert(el.id);
} 

How to get the full URL of a Drupal page?

This is what I found to be useful

global $base_root;
$base_root . request_uri();

Returns query strings and it's what's used in core: page_set_cache()

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

Getting the current Fragment instance in the viewpager

Simply get the current item from pager and then ask your adapter to the fragment of that position.

 int currentItem = viewPager.getCurrentItem();
    Fragment item = mPagerAdapter.getItem(currentItem);
    if (null != item && item.isVisible()) {
       //do whatever want to do with fragment after doing type checking
        return;
    }

Select row and element in awk

Since awk and perl are closely related...


Perl equivalents of @Dennis's awk solutions:

To print the second line:
perl -ne 'print if $. == 2' file

To print the second field:
perl -lane 'print $F[1]' file

To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file


Perl equivalent of @Glenn's solution:

Print the j'th field of the i'th line

perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file


Perl equivalents of @Hai's solutions:

if you are looking for second columns that contains abc:

perl -lane 'print if $F[1] =~ /abc/' foo

... and if you want to print only a particular column:

perl -lane 'print $F[2] if $F[1] =~ /abc/' foo

... and for a particular line number:

perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo


-l removes newlines, and adds them back in when printing
-a autosplits the input line into array @F, using whitespace as the delimiter
-n loop over each line of the input file
-e execute the code within quotes
$F[1] is the second element of the array, since Perl starts at 0
$. is the line number

make iframe height dynamic based on content inside- JQUERY/Javascript

There are four different properties you can look at to get the height of the content in an iFrame.

document.documentElement.scrollHeight
document.documentElement.offsetHeight
document.body.scrollHeight
document.body.offsetHeight

Sadly they can all give different answers and these are inconsistant between browsers. If you set the body margin to 0 then the document.body.offsetHeight gives the best answer. To get the correct value try this function; which is taken from the iframe-resizer library that also looks after keeping the iFrame the correct size when the content changes,or the browser is resized.

function getIFrameHeight(){
    function getComputedBodyStyle(prop) {
        function getPixelValue(value) {
            var PIXEL = /^\d+(px)?$/i;

            if (PIXEL.test(value)) {
                return parseInt(value,base);
            }

            var 
                style = el.style.left,
                runtimeStyle = el.runtimeStyle.left;

            el.runtimeStyle.left = el.currentStyle.left;
            el.style.left = value || 0;
            value = el.style.pixelLeft;
            el.style.left = style;
            el.runtimeStyle.left = runtimeStyle;

            return value;
        }

        var 
            el = document.body,
            retVal = 0;

        if (document.defaultView && document.defaultView.getComputedStyle) {
            retVal =  document.defaultView.getComputedStyle(el, null)[prop];
        } else {//IE8 & below
            retVal =  getPixelValue(el.currentStyle[prop]);
        } 

        return parseInt(retVal,10);
    }

    return document.body.offsetHeight +
        getComputedBodyStyle('marginTop') +
        getComputedBodyStyle('marginBottom');
}

How to print / echo environment variables?

The syntax

variable=value command

is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:

a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'

The result will be 5 for the first echo and 3 for the second.

removing table border

Use Firebug to inspect the table in question, and see where does it inherit the border from. (check the right column). Try setting on-the-fly inline style border:none; to see if you get rid of it. Could also be the browsers default stylesheets. In this case, use a CSS reset. http://developer.yahoo.com/yui/reset/

What exactly does += do in python?

It adds the right operand to the left. x += 2 means x = x + 2

It can also add elements to a list -- see this SO thread.

Passing Arrays to Function in C++

The simple answer is that arrays are ALWAYS passed by reference and the int arg[] simply lets the compiler know to expect an array

How do I check for a network connection?

Call this method to check the network Connection.

public static bool IsConnectedToInternet()
        {
            bool returnValue = false;
            try
            {

                int Desc;
                returnValue = Utility.InternetGetConnectedState(out Desc, 0);
            }
            catch
            {
                returnValue = false;
            }
            return returnValue;
        }

Put this below line of code.

[DllImport("wininet.dll")]
        public extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

How to deal with SettingWithCopyWarning in Pandas

Here I answer the question directly. How to deal with it?

Make a .copy(deep=False) after you slice. See pandas.DataFrame.copy.

Wait, doesn't a slice return a copy? After all, this is what the warning message is attempting to say? Read the long answer:

import pandas as pd
df = pd.DataFrame({'x':[1,2,3]})

This gives a warning:

df0 = df[df.x>2]
df0['foo'] = 'bar'

This does not:

df1 = df[df.x>2].copy(deep=False)
df1['foo'] = 'bar'

Both df0 and df1 are DataFrame objects, but something about them is different that enables pandas to print the warning. Let's find out what it is.

import inspect
slice= df[df.x>2]
slice_copy = df[df.x>2].copy(deep=False)
inspect.getmembers(slice)
inspect.getmembers(slice_copy)

Using your diff tool of choice, you will see that beyond a couple of addresses, the only material difference is this:

|          | slice   | slice_copy |
| _is_copy | weakref | None       |

The method that decides whether to warn is DataFrame._check_setitem_copy which checks _is_copy. So here you go. Make a copy so that your DataFrame is not _is_copy.

The warning is suggesting to use .loc, but if you use .loc on a frame that _is_copy, you will still get the same warning. Misleading? Yes. Annoying? You bet. Helpful? Potentially, when chained assignment is used. But it cannot correctly detect chain assignment and prints the warning indiscriminately.

How can I update the current line in a C# Windows Console App?

Here's another one :D

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Working... ");
        int spinIndex = 0;
        while (true)
        {
            // obfuscate FTW! Let's hope overflow is disabled or testers are impatient
            Console.Write("\b" + @"/-\|"[(spinIndex++) & 3]);
        }
    }
}

Get time of specific timezone

The .getTimezoneOffset() method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.

How to force keyboard with numbers in mobile website in Android

IMPORTANT NOTE

I am posting this as an answer, not a comment, as it is rather important info and it will attract more attention in this format.

As other fellows pointed, you can force a device to show you a numeric keyboard with type="number" / type="tel", but I must emphasize that you have to be extremely cautious with this.

If someone expects a number beginning with zeros, such as 000222, then she is likely to have trouble, as some browsers (desktop Chrome, for instance) will send to the server 222, which is not what she wants.

About type="tel" I can't say anything similar but personally I do not use it, as its behavior on different telephones can vary. I have confined myself to the simple pattern="[0-9]*" which do not work in Android

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

How to make Bootstrap 4 cards the same height in card-columns?

Here is how I did it:

CSS:

.my-flex-card > div > div.card {
    height: calc(100% - 15px);
    margin-bottom: 15px;
}

HTML:

<div class="row my-flex-card">
    <div class="col-lg-3 col-sm-6">
        <div class="card">
            <div class="card-block">
                aaaa
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6">
        <div class="card">
            <div class="card-block">
                bbbb
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6">
        <div class="card">
            <div class="card-block">
                cccc
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6">
        <div class="card">
            <div class="card-block">
                dddd
            </div>
        </div>
    </div>
</div>

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

I solved this problem using a different approach. You simply need to serialize the objects before passing through the closure, and de-serialize afterwards. This approach just works, even if your classes aren't Serializable, because it uses Kryo behind the scenes. All you need is some curry. ;)

Here's an example of how I did it:

def genMapper(kryoWrapper: KryoSerializationWrapper[(Foo => Bar)])
               (foo: Foo) : Bar = {
    kryoWrapper.value.apply(foo)
}
val mapper = genMapper(KryoSerializationWrapper(new Blah(abc))) _
rdd.flatMap(mapper).collectAsMap()

object Blah(abc: ABC) extends (Foo => Bar) {
    def apply(foo: Foo) : Bar = { //This is the real function }
}

Feel free to make Blah as complicated as you want, class, companion object, nested classes, references to multiple 3rd party libs.

KryoSerializationWrapper refers to: https://github.com/amplab/shark/blob/master/src/main/scala/shark/execution/serialization/KryoSerializationWrapper.scala

How to delete an SVN project from SVN repository

There's no concept of "project" in svn. So, feel free to delete whatever you think belongs to the project.

How can I put a database under git (version control)?

We used to run a social website, on a standard LAMP configuration. We had a Live server, Test server, and Development server, as well as the local developers machines. All were managed using GIT.

On each machine, we had the PHP files, but also the MySQL service, and a folder with Images that users would upload. The Live server grew to have some 100K (!) recurrent users, the dump was about 2GB (!), the Image folder was some 50GB (!). By the time that I left, our server was reaching the limit of its CPU, Ram, and most of all, the concurrent net connection limits (We even compiled our own version of network card driver to max out the server 'lol'). We could not (nor should you assume with your website) put 2GB of data and 50GB of images in GIT.

To manage all this under GIT easily, we would ignore the binary folders (the folders containing the Images) by inserting these folder paths into .gitignore. We also had a folder called SQL outside the Apache documentroot path. In that SQL folder, we would put our SQL files from the developers in incremental numberings (001.florianm.sql, 001.johns.sql, 002.florianm.sql, etc). These SQL files were managed by GIT as well. The first sql file would indeed contain a large set of DB schema. We don't add user-data in GIT (eg the records of the users table, or the comments table), but data like configs or topology or other site specific data, was maintained in the sql files (and hence by GIT). Mostly its the developers (who know the code best) that determine what and what is not maintained by GIT with regards to SQL schema and data.

When it got to a release, the administrator logs in onto the dev server, merges the live branch with all developers and needed branches on the dev machine to an update branch, and pushed it to the test server. On the test server, he checks if the updating process for the Live server is still valid, and in quick succession, points all traffic in Apache to a placeholder site, creates a DB dump, points the working directory from 'live' to 'update', executes all new sql files into mysql, and repoints the traffic back to the correct site. When all stakeholders agreed after reviewing the test server, the Administrator did the same thing from Test server to Live server. Afterwards, he merges the live branch on the production server, to the master branch accross all servers, and rebased all live branches. The developers were responsible themselves to rebase their branches, but they generally know what they are doing.

If there were problems on the test server, eg. the merges had too many conflicts, then the code was reverted (pointing the working branch back to 'live') and the sql files were never executed. The moment that the sql files were executed, this was considered as a non-reversible action at the time. If the SQL files were not working properly, then the DB was restored using the Dump (and the developers told off, for providing ill-tested SQL files).

Today, we maintain both a sql-up and sql-down folder, with equivalent filenames, where the developers have to test that both the upgrading sql files, can be equally downgraded. This could ultimately be executed with a bash script, but its a good idea if human eyes kept monitoring the upgrade process.

It's not great, but its manageable. Hope this gives an insight into a real-life, practical, relatively high-availability site. Be it a bit outdated, but still followed.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

In c and C++ there is no data type called BOOLEAN Thats why it uses 1 and 0 as true false value. and in JAVA 1 and 0 are count as an INTEGER type so it produces error in java. And java have its own boolean values true and false with boolean data type.

happy programming..

All combinations of a list of lists

Nothing wrong with straight up recursion for this task, and if you need a version that works with strings, this might fit your needs:

combinations = []

def combine(terms, accum):
    last = (len(terms) == 1)
    n = len(terms[0])
    for i in range(n):
        item = accum + terms[0][i]
        if last:
            combinations.append(item)
        else:
            combine(terms[1:], item)


>>> a = [['ab','cd','ef'],['12','34','56']]
>>> combine(a, '')
>>> print(combinations)
['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Email and phone Number Validation in android

For check email and phone number you need to do that

public static boolean isValidMobile(String phone) {
    boolean check = false;
    if (!Pattern.matches("[a-zA-Z]+", phone)) {
        if (phone.length() < 9 || phone.length() > 13) {
            // if(phone.length() != 10) {
            check = false;
            // txtPhone.setError("Not Valid Number");
        } else {
            check = android.util.Patterns.PHONE.matcher(phone).matches();
        }
    } else {
        check = false;
    }
    return check;
}

public static boolean isEmailValid(String email) {
    boolean check;
    Pattern p;
    Matcher m;

    String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    p = Pattern.compile(EMAIL_STRING);

    m = p.matcher(email);
    check = m.matches();

    return check;
}



String enter_mob_or_email="";//1234567890 or [email protected]
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid

}else isEmailValid(enter_mob_or_email){//Email is valid

}else{// Not valid email or phone number

}

Function to convert column number to letter?

LATEST UPDATE: Please ignore the function below, @SurasinTancharoen managed to alert me that it is broken at n = 53.
For those who are interested, here are other broken values just below n = 200:

Certain values of

Please use @brettdj function for all your needs. It even works for Microsoft Excel latest maximum number of columns limit: 16384 should gives XFD

enter image description here

END OF UPDATE


The function below is provided by Microsoft:

Function ConvertToLetter(iCol As Integer) As String
   Dim iAlpha As Integer
   Dim iRemainder As Integer
   iAlpha = Int(iCol / 27)
   iRemainder = iCol - (iAlpha * 26)
   If iAlpha > 0 Then
      ConvertToLetter = Chr(iAlpha + 64)
   End If
   If iRemainder > 0 Then
      ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
   End If
End Function

Source: How to convert Excel column numbers into alphabetical characters

APPLIES TO

  • Microsoft Office Excel 2007
  • Microsoft Excel 2002 Standard Edition
  • Microsoft Excel 2000 Standard Edition
  • Microsoft Excel 97 Standard Edition

How to create a custom attribute in C#

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

how to get list of port which are in use on the server

nmap is a useful tool for this kind of thing

How to easily consume a web service from PHP

I've had great success with wsdl2php. It will automatically create wrapper classes for all objects and methods used in your web service.

How to find rows in one table that have no corresponding row in another table

I can't tell you which of these methods will be best on H2 (or even if all of them will work), but I did write an article detailing all of the (good) methods available in TSQL. You can give them a shot and see if any of them works for you:

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&referringTitle=Home

How to reload current page in ReactJS?

This is my code .This works for me

componentDidMount(){
        axios.get('http://localhost:5000/supplier').then(
            response => {
                console.log(response)
                this.setState({suppliers:response.data.data})
            }
        )
        .catch(error => {
            console.log(error)
        })
        
    }

componentDidUpdate(){
        this.componentDidMount();
}

window.location.reload(); I think this thing is not good for react js

How to delete files recursively from an S3 bucket

In case if you want to remove all objects with "foo/" prefix using Java AWS SDK 2.0

import java.util.ArrayList;
import java.util.Iterator;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;

//...

ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder()
    .bucket(bucketName)
    .prefix("foo/")
    .build()
;
ListObjectsResponse objectsResponse = s3Client.listObjects(listObjectsRequest);

while (true) {
    ArrayList<ObjectIdentifier> objects = new ArrayList<>();

    for (Iterator<?> iterator = objectsResponse.contents().iterator(); iterator.hasNext(); ) {
        S3Object s3Object = (S3Object)iterator.next();
        objects.add(
            ObjectIdentifier.builder()
                .key(s3Object.key())
                .build()
        );
    }

    s3Client.deleteObjects(
        DeleteObjectsRequest.builder()
            .bucket(bucketName)
            .delete(
                Delete.builder()
                    .objects(objects)
                    .build()
            )
            .build()
    );

    if (objectsResponse.isTruncated()) {
        objectsResponse = s3Client.listObjects(listObjectsRequest);
        continue;
    }

    break;
};

Angular HttpClient "Http failure during parsing"

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

Git: How to rebase to a specific commit?

Since rebasing is so fundamental, here's an expansion of Nestor Milyaev's answer. Combining jsz's and Simon South's comments from Adam Dymitruk's answer yields this command which works on the topic branch regardless of whether it branches from the master branch's commit A or C:

git checkout topic
git rebase --onto <commit-B> <pre-rebase-A-or-post-rebase-C-or-base-branch-name>

Note that the last argument is required (otherwise it rewinds your branch to commit B).

Examples:

# if topic branches from master commit A:
git checkout topic
git rebase --onto <commit-B> <commit-A>
# if topic branches from master commit C:
git checkout topic
git rebase --onto <commit-B> <commit-C>
# regardless of whether topic branches from master commit A or C:
git checkout topic
git rebase --onto <commit-B> master

So the last command is the one that I typically use.

Testing the type of a DOM element in JavaScript

Perhaps you'll have to check the nodetype too:

if(element.nodeType == 1){//element of type html-object/tag
  if(element.tagName=="a"){
    //this is an a-element
  }
  if(element.tagName=="div"){
    //this is a div-element
  }
}

Edit: Corrected the nodeType-value

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() returns true for blanks(just whitespaces)and for null String as well. Actually it trims the Char sequences and then performs check.

StringUtils.isEmpty() returns true when there is no charsequence in the String parameter or when String parameter is null. Difference is that isEmpty() returns false if String parameter contains just whiltespaces. It considers whitespaces as a state of being non empty.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

don't forget to

chmod ~/.local/share/applications/postman.desktop +x

otherwise it won't show in the Unity Launcher

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to center a button within a div?

_x000D_
_x000D_
div {
    text-align : center;
}
button {
    width: 50%;
    margin: 1rem auto;
}
_x000D_
<div style="width:100%; height:100%; border: 1px solid">
  <button type="button">hello</button>
</div>
_x000D_
_x000D_
_x000D_

This is what I mostly do.
I think bootstrap also uses this in "mx-auto".

App can't be opened because it is from an unidentified developer

In terminal type the command:

xattr -d com.apple.quarantine [file path here]

Once you click enter it will no longer have that problem. Its annoying that apple adds a quarantine to files automatically. I do not know how to turn this off but there probably is a way...

JQuery addclass to selected div, remove class if another div is selected

**This can be achived easily using two different ways:**

1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery

**1)First Way**

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').removeClass('active class or your class name which you want to    remove').addClass('active class or your class name which you want to add');     
});
});

**2) Second Way**

i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)

<div id="dvId" class="ActiveClassname ">
</div

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').toggleClass('ActiveClassname InActiveClassName');     
});
});


Enjoy.....:)

If you any doubt free to ask any time...

C# Inserting Data from a form into an access Database

This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.

 private void button2_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
    @"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";

     try
       {
           conn.Open();
           String ticketno=textBox1.Text.ToString();                 
           String Purchaseprice=textBox2.Text.ToString();
           String sellprice=textBox3.Text.ToString();
           String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";

            OleDbCommand cmd = new OleDbCommand(my_querry, conn);
            cmd.ExecuteNonQuery();

            MessageBox.Show("Data saved successfuly...!");
          }
         catch (Exception ex)
         {
             MessageBox.Show("Failed due to"+ex.Message);
         }
         finally
         {
             conn.Close();
         }

How can I resize an image dynamically with CSS as the browser width/height changes?

Just use this code. What most are forgeting is to specify max-width as the max-width of the image

img {   
    height: auto;
    width: 100%;
    max-width: 300px;
}

Check this demonstration http://shorturl.at/nBKVY

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

Bower: ENOGIT Git is not installed or not in the PATH

On Windows, you can try to set the path at the command prompt:

set PATH=%PATH%;C:\Program Files\Git\bin;

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

The problem, in my case, was that I was using Amazon's Cloudflare and Cloudfront's Cloudfront in tandem, and Cloudfront did not like the settings that I had provided Cloudflare.

More specifically, in the Crypto settings on Cloudflare, I had set the "Minimum TLS Settings" to 1.2, without enabling the TLS 1.2 communication setting for the distribution in Cloudfront. This was enough to make Cloudfront declare a 502 Bad Gateway error when it tried to connect to the Cloudflare-protected server.

To fix this, I had to disable SSLv3 support in the Origin Settings for that Cloudfront distribution, and enable TLS 1.2 as a supported protocol for that origin server.

To debug this problem, I used command-line versions of curl, to see what Cloudfront was actually returning when you asked for an image from its CDN, and I also used the command-line version of openssl, to determine exactly which protocols Cloudflare was offering (it wasn't offering TLS 1.0).

tl:dr; make sure everything accepts and asks for TLS 1.2, or whatever latest and greatest TLS everyone is using by the time you read this.

What does the "@" symbol do in SQL?

Its a parameter the you need to define. to prevent SQL Injection you should pass all your variables in as parameters.

How to disable sort in DataGridView?

Use LINQ:

Datagridview1.Columns.Cast<DataGridViewColumn>().ToList().ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable);

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

In SQL Server Enterprise Manager, open \Server Objects\Linked Servers\Providers, right click on the OraOLEDB.Oracle provider, select properties and check the "Allow inprocess" option. Recreate your linked server and test again.

You can also execute the following query if you don't have access to SQL Server Management Studio :

EXEC master.dbo.sp_MSset_oledb_prop N'OraOLEDB.Oracle', N'AllowInProcess', 1

How can I get the current user directory?

Try:

System.Environment.GetEnvironmentVariable("USERPROFILE");

Edit:

If the version of .NET you are using is 4 or above, you can use the Environment.SpecialFolder enumeration:

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

Why does flexbox stretch my image rather than retaining aspect ratio?

I faced the same issue with a Foundation menu. align-self: center; didn't work for me.

My solution was to wrap the image with a <div style="display: inline-table;">...</div>

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Assign keyboard shortcut to run procedure

According to Microsoft's documentation

  1. On the Tools menu, point to Macro, and then click Macros.

  2. In the Macro name box, enter the name of the macro you want to assign to a keyboard shortcut key.

  3. Click Options.

  4. If you want to run the macro by pressing a keyboard shortcut key, enter a letter in the Shortcut key box. You can use CTRL+ letter (for lowercase letters) or CTRL+SHIFT+ letter (for uppercase letters), where letter is any letter key on the keyboard. The shortcut key cannot use a number or special character, such as @ or #.

    Note: The shortcut key will override any equivalent default Microsoft Excel shortcut keys while the workbook that contains the macro is open.

  5. If you want to include a description of the macro, type it in the Description box.

  6. Click OK.

  7. Click Cancel.

Input from the keyboard in command line application

Here is simple example of taking input from user on console based application: You can use readLine(). Take input from console for first number then press enter. After that take input for second number as shown in the image below:

func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
    return firstNo + secondNo
}

let num1 = readLine()
let num2 = readLine()

var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)

let sum = solveMefirst(IntNum1!, secondNo: IntNum2!)
print(sum)

Output

Get the value of bootstrap Datetimepicker in JavaScript

I tried all the above methods and I did not get the value properly in the same format, then I found this.

$("#datetimepicker1").find("input")[1].value;

The above code will return the value in the same format as in the datetime picker.

This may help you guys in the future.

Hope this was helpful..

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I just ran into the same kind of error using RSelenium::rsDriver()'s default chromever = "latest" setting which resulted in the failed attempt to combine chromedriver 75.0.3770.8 with latest google-chrome-stable 74.0.3729.157:

session not created: This version of ChromeDriver only supports Chrome version 75

Since this obviously seems to be a recurring and pretty annoying issue, I have come up with the following workaround to always use the latest compatible ChromeDriver version:

rD <- RSelenium::rsDriver(browser = "chrome",
                          chromever =
                                  system2(command = "google-chrome-stable",
                                          args = "--version",
                                          stdout = TRUE,
                                          stderr = TRUE) %>%
                                  stringr::str_extract(pattern = "(?<=Chrome )\\d+\\.\\d+\\.\\d+\\.") %>%
                                  magrittr::extract(!is.na(.)) %>%
                                  stringr::str_replace_all(pattern = "\\.",
                                                           replacement = "\\\\.") %>%
                                  paste0("^",  .) %>%
                                  stringr::str_subset(string =
                                                              binman::list_versions(appname = "chromedriver") %>%
                                                              dplyr::last()) %>%
                                  as.numeric_version() %>%
                                  max() %>%
                                  as.character())

The above code is only tested under Linux and makes use of some tidyverse packages (install them beforehand or rewrite it in base R). For other operating systems you might have to adapt it a bit, particularly replace command = "google-chrome-stable" with the system-specific command to launch Google Chrome:

  • On macOS it should be enough to replace command = "google-chrome-stable" with command = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".

  • On Windows a plattform-specific bug prevents us from calling the Google Chrome binary directly to get its version number. Instead do the following:

    rD <- RSelenium::rsDriver(browser = "chrome",
                              chromever =
                                system2(command = "wmic",
                                        args = 'datafile where name="C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe" get Version /value',
                                        stdout = TRUE,
                                        stderr = TRUE) %>%
                                stringr::str_extract(pattern = "(?<=Version=)\\d+\\.\\d+\\.\\d+\\.") %>%
                                magrittr::extract(!is.na(.)) %>%
                                stringr::str_replace_all(pattern = "\\.",
                                                         replacement = "\\\\.") %>%
                                paste0("^",  .) %>%
                                stringr::str_subset(string =
                                                            binman::list_versions(appname = "chromedriver") %>%
                                                            dplyr::last()) 
                                as.numeric_version() %>%
                                max() %>%
                                as.character())
    

Basically, the code just ensures the latest ChromeDriver version matching the major-minor-patch version number of the system's stable Google Chrome browser is passed as chromever argument. This procedure should adhere to the official ChromeDriver versioning scheme. Quote:

  • ChromeDriver uses the same version number scheme as Chrome (...)
  • Each version of ChromeDriver supports Chrome with matching major, minor, and build version numbers. For example, ChromeDriver 73.0.3683.20 supports all Chrome versions that start with 73.0.3683.

Renew Provisioning Profile

In addition to the other solutions I needed to edit the code signing on the main project and the Target file to get the app building to the device again after an expired provisioning profile.

::Delete the old expired profiles

::Add the new profile with the Organizer

::Clean All Targets

::Get Info -> Code Signing on both the main project and the Target

::Build and Run

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:

easy_install

aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 
BeautifulSoup-3.1.0.1/
BeautifulSoup-3.1.0.1/BeautifulSoup.py
BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff
BeautifulSoup-3.1.0.1/CHANGELOG
BeautifulSoup-3.1.0.1/README
BeautifulSoup-3.1.0.1/setup.py
BeautifulSoup-3.1.0.1/testall.sh
BeautifulSoup-3.1.0.1/to3.sh
BeautifulSoup-3.1.0.1/PKG-INFO
BeautifulSoup-3.1.0.1/BeautifulSoup.pyc
BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc

aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/

aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install
running install
<... snip ...>

'router-outlet' is not a known element

Assuming you are using Angular 6 with angular-cli and you have created a separate routing module which is responsible for routing activities - configure your routes in Routes array.Make sure that you are declaring RouterModule in exports array. Code would look like this:

@NgModule({
      imports: [
      RouterModule,
      RouterModule.forRoot(appRoutes)
     // other imports here
     ],
     exports: [RouterModule]
})
export class AppRoutingModule { }

How to run certain task every day at a particular time using ScheduledExecutorService?

Why to complicate a situation if you can just write like it? (yes -> low cohesion, hardcoded -> but it is a example and unfortunately with imperative way). For additional info read code example at below ;))

package timer.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.*;

public class TestKitTimerWithExecuterService {

    private static final Logger log = LoggerFactory.getLogger(TestKitTimerWithExecuterService.class);

    private static final ScheduledExecutorService executorService 
= Executors.newSingleThreadScheduledExecutor();// equal to => newScheduledThreadPool(1)/ Executor service with one Thread

    private static ScheduledFuture<?> future; // why? because scheduleAtFixedRate will return you it and you can act how you like ;)



    public static void main(String args[]){

        log.info("main thread start");

        Runnable task = () -> log.info("******** Task running ********");

        LocalDateTime now = LocalDateTime.now();

        LocalDateTime whenToStart = LocalDate.now().atTime(20, 11); // hour, minute

        Duration duration = Duration.between(now, whenToStart);

        log.info("WhenToStart : {}, Now : {}, Duration/difference in second : {}",whenToStart, now, duration.getSeconds());

        future = executorService.scheduleAtFixedRate(task
                , duration.getSeconds()    //  difference in second - when to start a job
                ,2                         // period
                , TimeUnit.SECONDS);

        try {
            TimeUnit.MINUTES.sleep(2);  // DanDig imitation of reality
            cancelExecutor();    // after canceling Executor it will never run your job again
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("main thread end");
    }




    public static void cancelExecutor(){

        future.cancel(true);
        executorService.shutdown();

        log.info("Executor service goes to shut down");
    }

}

What is the effect of extern "C" in C++?

Just wanted to add a bit of info, since I haven't seen it posted yet.

You'll very often see code in C headers like so:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.

Although, I have also seen C++ code such as:

extern "C" {
#include "legacy_C_header.h"
}

which I imagine accomplishes much the same thing.

Not sure which way is better, but I have seen both.

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Displaying a flash message after redirect in Codeigniter

In Your Controller set this

<?php

public function change_password(){







if($this->input->post('submit')){
$change = $this->common_register->change_password();

if($change == true){
$messge = array('message' => 'Password chnage successfully','class' => 'alert alert-success fade in');
$this->session->set_flashdata('item', $messge);
}else{
$messge = array('message' => 'Wrong password enter','class' => 'alert alert-danger fade in');
$this->session->set_flashdata('item',$messge );
}
$this->session->keep_flashdata('item',$messge);



redirect('controllername/methodname','refresh');
}

?>

In Your View File Set this
<script type="application/javascript">
/** After windod Load */
$(window).bind("load", function() {
  window.setTimeout(function() {
    $(".alert").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove();
    });
}, 4000);
});
</script>

<?php

if($this->session->flashdata('item')) {
$message = $this->session->flashdata('item');
?>
<div class="<?php echo $message['class'] ?>"><?php echo $message['message']; ?>

</div>
<?php
}

?>

Please check below link for Displaying a flash message after redirect in Codeigniter

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

How to reposition Chrome Developer Tools

The Version 56.0.2924.87 which I am in now, Undocks the DevTools automatically if you are NOT in a desktop. Otherwise Open a NEW new Chrome tab and Inspect to Dock the DevTools back into the window.

Reading in a JSON File Using Swift

Swift 2.1 answer (based on Abhishek's) :

    if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") {
        do {
            let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            do {
                let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                if let people : [NSDictionary] = jsonResult["person"] as? [NSDictionary] {
                    for person: NSDictionary in people {
                        for (name,value) in person {
                            print("\(name) , \(value)")
                        }
                    }
                }
            } catch {}
        } catch {}
    }

ASP.Net MVC Redirect To A Different View

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is:

return RedirectToAction("Index", model);

Then in your Index method, return the view you want.

What are the differences between a superkey and a candidate key?

Superkey :A set of attributes or combination of attributes which uniquely identify the tuple in a given relation . Superkey have two properties uniqueness and reducible set

Candidate key: Minimal set of superkey which have following two properties: uniqueness and irreducible set or attribute

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

First, open a terminal session and run:

cd /usr/local/
git status

to see if Homebrew is clean.

If it's dirty, run:

git reset --hard && git clean -df

then

brew doctor
brew update

If it's still broken, try this in your session:

sudo rm /System/Library/Frameworks/Ruby.framework/Versions/Current
sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/1.8 /System/Library/Frameworks/Ruby.framework/Versions/Current

This will force Homebrew to use Ruby 1.8 from the system's installation.

Value Change Listener to JTextField

If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.

usernameTextField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
    }
});

How can I set the background color of <option> in a <select> element?

_x000D_
_x000D_
select.list1 option.option2
{
    background-color: #007700;
}
_x000D_
<select class="list1">
  <option value="1">Option 1</option>
  <option value="2" class="option2">Option 2</option>
</select>
_x000D_
_x000D_
_x000D_

How to ping an IP address


Just an addition to what others have given, even though they work well but in some cases if internet is slow or some unknown network problem exists, some of the codes won't work (isReachable()). But this code mentioned below creates a process which acts as a command line ping (cmd ping) to windows. It works for me in all cases, tried and tested.

Code :-

public class JavaPingApp {

public static void runSystemCommand(String command) {

    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader inputStream = new BufferedReader(
                new InputStreamReader(p.getInputStream()));

        String s = "";
        // reading output stream of the command
        while ((s = inputStream.readLine()) != null) {
            System.out.println(s);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {

    String ip = "stackoverflow.com"; //Any IP Address on your network / Web
    runSystemCommand("ping " + ip);
}
}

Hope it helps, Cheers!!!

Difference between require, include, require_once and include_once?

Just use require and include.

Because think how to work with include_once or require_once. That is looking for log data which save included or required PHP files. So that is slower than include and require.

if (!defined(php)) {
    include 'php';
    define(php, 1);
}

Just using like this...

What does enctype='multipart/form-data' mean?

enctype='multipart/form-data' means that no characters will be encoded. that is why this type is used while uploading files to server.
So multipart/form-data is used when a form requires binary data, like the contents of a file, to be uploaded

How to log a method's execution time exactly in milliseconds?

Here is another way, in Swift, to do that using the defer keyword

func methodName() {
  let methodStart = Date()
  defer {
    let executionTime = Date().timeIntervalSince(methodStart)
    print("Execution time: \(executionTime)")
  }
  // do your stuff here
}

From Apple's docs: A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

This is similar to a try/finally block with the advantage of having the related code grouped.

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I have the same problem, the difference is I don't have access to the source code. I've fixed my problem by putting correct version of EntityFramework.SqlServer.dll in the bin directory of the application.

Basic calculator in Java

import java.util.Scanner;
public class JavaApplication1 {


    public static void main(String[] args) {

         int x,
         int y;

         Scanner input=new Scanner(System.in);
         System.out.println("Enter Number 1");
         x=input.nextInt();
         System.out.println("Enter Number 2");
         y=input.nextInt();

         System.out.println("Please enter operation + - / or *");
         Scanner op=new Scanner(System.in);
         String operation = op.next();

         if (operation.equals("+")){
             System.out.println("Your Answer: " + (x+y));
         }
         if (operation.equals("-")){
             System.out.println("Your Answer: "+ (x-y));
         }
         if (operation.equals("/")){
             System.out.println("Your Answer: "+ (x/y));
         }
         if (operation.equals("*")){
            System.out.println("Your Answer: "+ (x*y));
         }
    }

}

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

It appears to only be availabe using the mysqlnd driver.
Try replacing it with the integer it represents; 1002, if I am not mistaken.

`&mdash;` or `&#8212;` is there any difference in HTML output?

Could be that using the numeral code is more universal, as it's a direct reference to a character in the html entity table, but I guess they both work everywhere. The first notation is just massively easier to remember for a lot of characters.

Generate MD5 hash string with T-SQL

None of the other answers worked for me. Note that SQL Server will give different results if you pass in a hard-coded string versus feed it from a column in your result set. Below is the magic that worked for me to give a perfect match between SQL Server and MySql

select LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', CONVERT(varchar, EmailAddress)), 2)) from ...

How can I exclude one word with grep?

I've a directory with a bunch of files. I want to find all the files that DO NOT contain the string "speedup" so I successfully used the following command:

grep -iL speedup *

vim - How to delete a large block of text without counting the lines?

There are many better answers here, but for completeness I will mention the method I used to use before reading some of the great answers mentioned above.

Suppose you want to delete from lines 24-39. You can use the ex command

:24,39d

You can also yank lines using

:24,39y

And find and replace just over lines 24-39 using

:24,39s/find/replace/g

How do I recognize "#VALUE!" in Excel spreadsheets?

This will return TRUE for #VALUE! errors (ERROR.TYPE = 3) and FALSE for anything else.

=IF(ISERROR(A1),ERROR.TYPE(A1)=3)

Adding link a href to an element using css

You cannot simply add a link using CSS. CSS is used for styling.

You can style your using CSS.

If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.

You can accomplish that very easily using jQuery.

I have done a sample for you. You can refer that.

URL : http://jsfiddle.net/zyk9w/

$('#link').attr('href','http://www.google.com');

This single line will do the trick.

How to display Base64 images in HTML?

You need to specify correct Content-type, Content-encoding and charset like

 data:image/jpeg;charset=utf-8;base64, 

according to the syntax of the data URI scheme:

 data:[<media type>][;charset=<character set>][;base64],<data>

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

YouTube: How to present embed video with sound muted

Source: https://developers.google.com/youtube/iframe_api_reference

   <div id="player"></div>
    <script>

          var tag = document.createElement('script');
          tag.src = "https://www.youtube.com/iframe_api";
          var firstScriptTag = document.getElementsByTagName('script')[0];
          firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

          var player;
          function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
              height: '720',
              width: '1280',
              videoId: 'M7lc1UVf-VE',
              playerVars :{'autoplay':1,'loop':1,'playlist':'M7lc1UVf-VE','vq':'hd720'},
              events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
              }
            });
          }

          function onPlayerReady(event) {
               event.target.setVolume(0);
           event.target.playVideo();
          }

          var done = false;
          function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING && !done) {
        //      setTimeout(stopVideo, 6000);
                      done = true;
            }
               event.target.setVolume(0);
          }
    </script>

nvarchar(max) still being truncated

I have encountered the same problem today and found that beyond that 4000 character limit, I had to split the dynamic query into two strings and concatenate them when executing the query.

DECLARE @Query NVARCHAR(max);
DECLARE @Query2 NVARCHAR(max);
SET @Query = 'SELECT...' -- some of the query gets set here
SET @Query2 = '...' -- more query gets added on, etc.

EXEC (@Query + @Query2)

Convert a Unicode string to an escaped ASCII string

You need to use the Convert() method in the Encoding class:

  • Create an Encoding object that represents ASCII encoding
  • Create an Encoding object that represents Unicode encoding
  • Call Encoding.Convert() with the source encoding, the destination encoding, and the string to be encoded

There is an example here:

using System;
using System.Text;

namespace ConvertExample
{
   class ConvertExampleClass
   {
      static void Main()
      {
         string unicodeString = "This string contains the unicode character Pi(\u03a0)";

         // Create two different encodings.
         Encoding ascii = Encoding.ASCII;
         Encoding unicode = Encoding.Unicode;

         // Convert the string into a byte[].
         byte[] unicodeBytes = unicode.GetBytes(unicodeString);

         // Perform the conversion from one encoding to the other.
         byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

         // Convert the new byte[] into a char[] and then into a string.
         // This is a slightly different approach to converting to illustrate
         // the use of GetCharCount/GetChars.
         char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
         ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
         string asciiString = new string(asciiChars);

         // Display the strings created before and after the conversion.
         Console.WriteLine("Original string: {0}", unicodeString);
         Console.WriteLine("Ascii converted string: {0}", asciiString);
      }
   }
}

Chrome hangs after certain amount of data transfered - waiting for available socket

Explanation:

This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video> or <audio> tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.

Solution 1:

You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto".

Solution 2:

If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.

Solution 3: Force-open Sockets (Not recommended)

If you must, you can force-open the sockets in your browser (In Chrome only):

  1. Go to the address bar and type chrome://net-internals.
  2. Select Sockets from the menu.
  3. Click on the Flush socket pools button.

This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

If your data file is structured like this

col1, col2, col3
   1,    2,    3
  10,   20,   30
 100,  200,  300

then numpy.genfromtxt can interpret the first line as column headers using the names=True option. With this you can access the data very conveniently by providing the column header:

data = np.genfromtxt('data.txt', delimiter=',', names=True)
print data['col1']    # array([   1.,   10.,  100.])
print data['col2']    # array([   2.,   20.,  200.])
print data['col3']    # array([   3.,   30.,  300.])

Since in your case the data is formed like this

row1,   1,  10, 100
row2,   2,  20, 200
row3,   3,  30, 300

you can achieve something similar using the following code snippet:

labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
data = {label: row for label, row in zip(labels, raw_data)}

The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt creates using the names=True option:

print data['row1']    # array([   1.,   10.,  100.])
print data['row2']    # array([   2.,   20.,  200.])
print data['row3']    # array([   3.,   30.,  300.])

How can I make the browser wait to display the page until it's fully loaded?

You could start by having your site's main index page contain only a message saying "Loading". From here you could use ajax to fetch the contents of your next page and embed it into the current one, on completion removing the "Loading" message.

You might be able to get away with just including a loading message container at the top of your page which is 100% width/height and then removing the said div on load complete.

The latter may not work perfectly in both situations and will depends on how the browser renders content.

I'm not entirely sure if its a good idea. For simple static sites I would say not. However, I have seen a lot of heavy javascript sites lately from design companies that use complex animation and are one page. These sites use a loading message to wait for all scripts/html/css to be loaded so that the page functions as expected.

How to run .sh on Windows Command Prompt?

you can use also cmder

Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout, looking sexy from the start

Screenshot

cmder.net

Permission denied error on Github Push

See the github help on cloning URL. With HTTPS, if you are not authorized to push, you would basically have a read-only access. So yes, you need to ask the author to give you permission.

If the author doesn't give you permission, you can always fork (clone) his repository and work on your own. Once you made a nice and tested feature, you can then send a pull request to the original author.

Pagination on a list using ng-repeat

I just made a JSFiddle that show pagination + search + order by on each column using Build with Twitter Bootstrap code: http://jsfiddle.net/SAWsA/11/

Casting variables in Java

The right way is this:

Integer i = Integer.class.cast(obj);

The method cast() is a much safer alternative to compile-time casting.

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

How to close a GUI when I push a JButton?

JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) { 
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .     
if(closing.getSource()==close)
   System.exit(0);
   // This exit Your GUI 
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */

How do I get first element rather than using [0] in jQuery?

You can use the first selector.

var header = $('.header:first')

How to change indentation mode in Atom?

OS X:

  1. Go to Atom -> prefrences or CMD + ,

  2. Scroll down and select "Tab Length" that you prefer.

enter image description here

SQL Server: use CASE with LIKE

You can also do like this

select *
from table
where columnName like '%' + case when @varColumn is null then '' else @varColumn end  +  ' %'

What's the best way to get the last element of an array without deleting it?

$lastValue = end(array_values($array))

No modification is made to $array pointers. This avoids the

reset($array)

which might not be desired in certain conditions.

No Network Security Config specified, using platform default - Android Log

I had also the same problem. Please add this line in application tag in manifest. I hope it will also help you.

android:usesCleartextTraffic="true"

How to loop through array in jQuery?

Alternative ways of iteration through array/string with side effects

_x000D_
_x000D_
var str = '21,32,234,223';_x000D_
var substr = str.split(',');_x000D_
_x000D_
substr.reduce((a,x)=> console.log('reduce',x), 0)        // return undefined_x000D_
_x000D_
substr.every(x=> { console.log('every',x); return true}) // return true_x000D_
_x000D_
substr.some(x=> { console.log('some',x); return false})  // return false_x000D_
_x000D_
substr.map(x=> console.log('map',x));                    // return array_x000D_
 _x000D_
str.replace(/(\d+)/g, x=> console.log('replace',x))      // return string
_x000D_
_x000D_
_x000D_

Get file from project folder java

Well, there are many different ways to get a file in Java, but that's the general gist.

Don't forget that you'll need to wrap that up inside a try {} catch (Exception e){} at the very least, because File is part of java.io which means it must have try-catch block.

Not to step on Ericson's question, but if you are using actual packages, you'll have issues with locations of files, unless you explicitly use it's location. Relative pathing gets messed up with Packages.

ie,

src/
    main.java
    x.txt

In this example, using File f = new File("x.txt"); inside of main.java will throw a file-not-found exception.

However, using File f = new File("src/x.txt"); will work.

Hope that helps!

How to undo a git merge with conflicts

Latest Git:

git merge --abort

This attempts to reset your working copy to whatever state it was in before the merge. That means that it should restore any uncommitted changes from before the merge, although it cannot always do so reliably. Generally you shouldn't merge with uncommitted changes anyway.

Prior to version 1.7.4:

git reset --merge

This is older syntax but does the same as the above.

Prior to version 1.6.2:

git reset --hard

which removes all uncommitted changes, including the uncommitted merge. Sometimes this behaviour is useful even in newer versions of Git that support the above commands.

How to move all files including hidden files into parent directory via *

I think this is the most elegant, as it also does not try to move ..:

mv /source/path/{.[!.],}* /destination/path

SQL Error: ORA-12899: value too large for column

This answer still comes up high in the list for ORA-12899 and lot of non helpful comments above, even if they are old. The most helpful comment was #4 for any professional trying to find out why they are getting this when loading data.

Some characters are more than 1 byte in length, especially true on SQL Server. And what might fit in a varchar(20) in SQLServer won't fit into a similar varchar2(20) in Oracle.

I ran across this error yesterday with SSIS loading an Oracle database with the Attunity drivers and thought I would save folks some time.

remote rejected master -> master (pre-receive hook declined)

I got the same error and looked into activity. Where I found that I had two package lock files which was causing the error.

What does '&' do in a C++ declaration?

Here, & is not used as an operator. As part of function or variable declarations, & denotes a reference. The C++ FAQ Lite has a pretty nifty chapter on references.

Generate an integer that is not among four billion given ones

If you don't assume the 32-bit constraint, just return a randomly generated 64-bit number (or 128-bit if you're a pessimist). The chance of collision is 1 in 2^64/(4*10^9) = 4611686018.4 (roughly 1 in 4 billion). You'd be right most of the time!

(Joking... kind of.)

Remove border from buttons

Add this as css,

button[type=submit]{border:none;}

What is the right way to POST multipart/form-data using curl?

This is what worked for me

curl --form file='@filename' URL

It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.

So firstly, the only mistake the OP made was in not using the @ symbol before the file name. Secondly, my answer which uses file=... only worked for me because the form field I was trying to do the upload for was called file. If your form field is called something else, use that name instead.

Explanation

From the curl manpages; under the description for the option --form it says:

This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

Chances are that if you are trying to do a form upload, you will most likely want to use the @ prefix to upload the file rather than < which uploads the contents of the file.

Addendum

Now I must also add that one must be careful with using the < symbol because in most unix shells, < is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl command does not behave the way you expect.

On that same note, I will also recommend quoting the @ symbol.


You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?

I say this because curl offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.

Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.

How to insert data into elasticsearch

Simple fundamentals, Elastic community has exposed indexing, searching, deleting operation as rest web service. You can interact elastic using curl or sense(chrome plugin) or any rest client like postman.

If you are just testing few commands, I would recommend can use of sense chrome plugin which has simple UI and pretty mature plugin now.

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

I know this question is very old, but just having implemented an msb() function myself, I found that most solutions presented here and on other websites are not necessarily the most efficient - at least for my personal definition of efficiency (see also Update below). Here's why:

Most solutions (especially those which employ some sort of binary search scheme or the naïve approach which does a linear scan from right to left) seem to neglect the fact that for arbitrary binary numbers, there are not many which start with a very long sequence of zeros. In fact, for any bit-width, half of all integers start with a 1 and a quarter of them start with 01. See where i'm getting at? My argument is that a linear scan starting from the most significant bit position to the least significant (left to right) is not so "linear" as it might look like at first glance.

It can be shown1, that for any bit-width, the average number of bits that need to be tested is at most 2. This translates to an amortized time complexity of O(1) with respect to the number of bits (!).

Of course, the worst case is still O(n), worse than the O(log(n)) you get with binary-search-like approaches, but since there are so few worst cases, they are negligible for most applications (Update: not quite: There may be few, but they might occur with high probability - see Update below).

Here is the "naïve" approach i've come up with, which at least on my machine beats most other approaches (binary search schemes for 32-bit ints always require log2(32) = 5 steps, whereas this silly algorithm requires less than 2 on average) - sorry for this being C++ and not pure C:

template <typename T>
auto msb(T n) -> int
{
    static_assert(std::is_integral<T>::value && !std::is_signed<T>::value,
        "msb<T>(): T must be an unsigned integral type.");

    for (T i = std::numeric_limits<T>::digits - 1, mask = 1 << i; i >= 0; --i, mask >>= 1)
    {
        if ((n & mask) != 0)
            return i;
    }

    return 0;
}

Update: While what i wrote here is perfectly true for arbitrary integers, where every combination of bits is equally probable (my speed test simply measured how long it took to determine the MSB for all 32-bit integers), real-life integers, for which such a function will be called, usually follow a different pattern: In my code, for example, this function is used to determine whether an object size is a power of 2, or to find the next power of 2 greater or equal than an object size. My guess is that most applications using the MSB involve numbers which are much smaller than the maximum number an integer can represent (object sizes rarely utilize all the bits in a size_t). In this case, my solution will actually perform worse than a binary search approach - so the latter should probably be preferred, even though my solution will be faster looping through all integers.
TL;DR: Real-life integers will probably have a bias towards the worst case of this simple algorithm, which will make it perform worse in the end - despite the fact that it's amortized O(1) for truly arbitrary integers.

1The argument goes like this (rough draft): Let n be the number of bits (bit-width). There are a total of 2n integers wich can be represented with n bits. There are 2n - 1 integers starting with a 1 (first 1 is fixed, remaining n - 1 bits can be anything). Those integers require only one interation of the loop to determine the MSB. Further, There are 2n - 2 integers starting with 01, requiring 2 iterations, 2n - 3 integers starting with 001, requiring 3 iterations, and so on.

If we sum up all the required iterations for all possible integers and divide them by 2n, the total number of integers, we get the average number of iterations needed for determining the MSB for n-bit integers:

(1 * 2n - 1 + 2 * 2n - 2 + 3 * 2n - 3 + ... + n) / 2n

This series of average iterations is actually convergent and has a limit of 2 for n towards infinity

Thus, the naïve left-to-right algorithm has actually an amortized constant time complexity of O(1) for any number of bits.

How to mount the android img file under linux?

I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img files all the time.

Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount

"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...

So, how to get the file from the inside of userdata.img?" To load .img files you have to select loop and load the .img Select loop

Next you select mount Select mount

Furius ISO mount handles all the other options loading the .img file to your /home/dir.

Python int to binary string?

numpy.binary_repr(num, width=None)

Examples from the documentation link above:

>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> np.binary_repr(3, width=4)
'0011'

The two’s complement is returned when the input number is negative and width is specified:

>>> np.binary_repr(-3, width=3)
'101'
>>> np.binary_repr(-3, width=5)
'11101'

Regular expression include and exclude special characters

You haven't actually asked a question, but assuming you have one, this could be your answer...

Assuming all characters, except the "Special Characters" are allowed you can write

String regex = "^[^<>'\"/;`%]*$";

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

In SQL Developer ..Go to Preferences-->NLS-->and change your date format accordingly