Programs & Examples On #Spuserfield

How to force a UIViewController to Portrait orientation in iOS 6

So I ran into the same problem when displaying portrait only modal views. Normally, I'd create a UINavigationController, set the viewController as the rootViewController, then display the UINavigationController as a modal view. But with iOS 6, the viewController will now ask the navigationController for its supported interface orientations (which, by default, is now all for iPad and everything but upside down for iPhone).

Solution: I had to subclass UINavigationController and override the autorotation methods. Kind of lame.

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
// pre-iOS 6 support 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

Include CSS,javascript file in Yii Framework

In Yii framework, You can include js and css using below method.

Including CSS:

{Yii::app()->request->baseUrl}/css/styles.css

Including JS:

{Yii::app()->request->baseUrl}/js/script.js

Including Image:

{Yii::app()->request->baseUrl}/images/logo.jpg

Note: By using layout concept in yii, You can add css and js instead of specifying in view template.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

After a long reserch and digging too deep i found the solution of certificate pinning in android and yes its different from iOS where we need a certificate itself but in android we just need a hash pin and that's it.

How to get hash pin for certificate?

Initially just use a wrong hash pin and your java class will throw an error with correct hash pins or pin chain, just copy and paste into your code thats it.

This solution fixed my problem : https://stackoverflow.com/a/45853669/3448003

What is meant by Ems? (Android TextView)

em is the typography unit of font width. one em in a 16-point typeface is 16 points

Repeat command automatically in Linux

Running commands periodically without cron is possible when we go with while.

As a command:

while true ; do command ; sleep 100 ; done &
[ ex: # while true;  do echo `date` ; sleep 2 ; done & ]

Example:

while true
do echo "Hello World"
sleep 100
done &

Do not forget the last & as it will put your loop in the background. But you need to find the process id with command "ps -ef | grep your_script" then you need to kill it. So kindly add the '&' when you running the script.

# ./while_check.sh &

Here is the same loop as a script. Create file "while_check.sh" and put this in it:

#!/bin/bash
while true; do 
    echo "Hello World" # Substitute this line for whatever command you want.
    sleep 100
done

Then run it by typing bash ./while_check.sh &

pythonic way to do something N times without an index variable?

since function is first-class citizen, you can write small wrapper (from Alex answers)

def repeat(f, N):
    for _ in itertools.repeat(None, N): f()

then you can pass function as argument.

Using bootstrap with bower

I finally ended using the following : bower install --save http://twitter.github.com/bootstrap/assets/bootstrap.zip

Seems cleaner to me since it doesn't clone the whole repo, it only unzip the required assests.

The downside of that is that it breaks the bower philosophy since a bower update will not update bootstrap.

But I think it's still cleaner than using bower install bootstrap and then building bootstrap in your workflow.

It's a matter of choice I guess.

Update : seems they now version a dist folder (see: https://github.com/twbs/bootstrap/pull/6342), so just use bower install bootstrap and point to the assets in the dist folder

Download file from web in Python 3

I use requests package whenever I want something related to HTTP requests because its API is very easy to start with:

first, install requests

$ pip install requests

then the code:

from requests import get  # to make GET request


def download(url, file_name):
    # open in binary mode
    with open(file_name, "wb") as file:
        # get request
        response = get(url)
        # write to file
        file.write(response.content)

How do I revert an SVN commit?

Alex, try this: svn merge [WorkingFolderPath] -r 1944:1943

Bootstrap 3 - How to load content in modal body via AJAX?

Check this SO answer out.

It looks like the only way is to provide the whole modal structure with your ajax response.

As you can check from the bootstrap source code, the load function is binded to the root element.

In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..) plugin on your body element, even though it will probably break the show/hide functions of the root element.

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

How to pass parameters to a Script tag?

It's better to Use feature in html5 5 data Attributes

<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>

Inside the script file http://path.to/widget.js you can get the paremeters in that way:

<script>
function getSyncScriptParams() {
         var scripts = document.getElementsByTagName('script');
         var lastScript = scripts[scripts.length-1];
         var scriptName = lastScript;
         return {
             width : scriptName.getAttribute('data-width'),
             height : scriptName.getAttribute('data-height')
         };
 }
</script>

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How do you completely remove the button border in wpf?

What you have to do is something like this:

<Button Name="MyFlatImageButton"
        Background="Transparent"
        BorderBrush="Transparent"
        BorderThickness="0" 
        Padding="-4">
   <Image Source="MyImage.png"/>
</Button>

Hope this is what you were looking for.

Edit: Sorry, forgot to mention that if you want to see the button-border when you hover over the image, all you have to do is skip the Padding="-4".

downcast and upcast

In case you need to check each of the Employee object whether it is a Manager object, use the OfType method:

List<Employee> employees = new List<Employee>();

//Code to add some Employee or Manager objects..

var onlyManagers = employees.OfType<Manager>();

foreach (Manager m in onlyManagers) {
  // Do Manager specific thing..
}

Disable spell-checking on HTML textfields

The following code snippet disables it for all textarea and input[type=text] elements:

(function () {
    function disableSpellCheck() {
        let selector = 'input[type=text], textarea';
        let textFields = document.querySelectorAll(selector);

        textFields.forEach(
            function (field, _currentIndex, _listObj) {
                field.spellcheck = false;
            }
        );
    }

    disableSpellCheck();
})();

Split a List into smaller lists of N size

Serj-Tm solution is fine, also this is the generic version as extension method for lists (put it into a static class):

public static List<List<T>> Split<T>(this List<T> items, int sliceSize = 30)
{
    List<List<T>> list = new List<List<T>>();
    for (int i = 0; i < items.Count; i += sliceSize)
        list.Add(items.GetRange(i, Math.Min(sliceSize, items.Count - i)));
    return list;
} 

convert string into array of integers

let idsArray = ids.split(',').map((x) => parseInt(x));

How to turn off magic quotes on shared hosting?

As per the manual you can often install a custom php.ini on shared hosting, where mod_php isn't used and the php_value directive thus leads to an error. For suexec/FastCGI setups it is quite common to have a per-webspace php.ini in any case.

--

I don't think O (uppercase letter o) is a valid value to set an ini flag. You need to use a true/false, 1/0, or "on"/"off" value.

ini_set( 'magic_quotes_gpc', 0 );   // doesn't work

EDIT

After checking the list of ini settings, I see that magic_quotes_gpc is a PHP_INI_PERDIR setting (after 4.2.3), which means you can't change it with ini_set() (only PHP_INI_ALL settings can be changed with ini_set())

What this means is you have to use an .htaccess file to do this - OR - implement a script to reverse the effects of magic quotes. Something like this

if ( in_array( strtolower( ini_get( 'magic_quotes_gpc' ) ), array( '1', 'on' ) ) )
{
    $_POST = array_map( 'stripslashes', $_POST );
    $_GET = array_map( 'stripslashes', $_GET );
    $_COOKIE = array_map( 'stripslashes', $_COOKIE );
}

How to print Boolean flag in NSLog?

Here's how I do it:

BOOL flag = YES;
NSLog(flag ? @"Yes" : @"No");

?: is the ternary conditional operator of the form:

condition ? result_if_true : result_if_false

Substitute actual log strings accordingly where appropriate.

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

I followed the sample code from @codeslord, but for some reason I had to access my screenshot data differently:

 # Open the Firefox webdriver
 driver = webdriver.Firefox()
 # Find the element that you're interested in
 imagepanel = driver.find_element_by_class_name("panel-height-helper")
 # Access the data bytes for the web element
 datatowrite = imagepanel.screenshot_as_png
 # Write the byte data to a file
 outfile = open("imagepanel.png", "wb")
 outfile.write(datatowrite)
 outfile.close()

(using Python 3.7, Selenium 3.141.0 and Mozilla Geckodriver 71.0.0.7222)

Find out where MySQL is installed on Mac OS X

It will be found in /usr/local/mysql if you use the mysql binaries or dmg to install it on your system instead of using MAMP

How to explain callbacks in plain english? How are they different from calling one function from another function?

There's two points to explain, one is how a callback works (passing around a function that can be called without any knowledge of its context), the other what it's used for (handling events asynchronously).

The analogy of waiting for a parcel to arrive that has been used by other answers is a good one to explain both. In a computer program, you would tell the computer to expect a parcel. Ordinarily, it would now sit there and wait (and do nothing else) until the parcel arrives, possibly indefinitely if it never arrives. To humans, this sounds silly, but without further measures, this is totally natural to a computer.

Now the callback would be the bell at your front door. You provide the parcel service with a way to notify you of the parcel's arrival without them having to know where (even if) you are in the house, or how the bell works. (For instance, some "bells" actually dispatch a phone call.) Because you provided a "callback function" that can be "called" at any time, out of context, you can now stop sitting at the front porch and "handle the event" (of parcel arrival) whenever it's time.

PHP function to make slug (URL string)

The most elegant way I think is using a Behat\Transliterator\Transliterator.

I need to extends this class by your class because it is an Abstract, some like this:

<?php
use Behat\Transliterator\Transliterator;

class Urlizer extends Transliterator
{
}

And then, just use it:

$text = "Master Ápiu";
$urlizer = new Urlizer();
$slug = $urlizer->transliterate($slug, "-");
echo $slug; // master-apiu

Of course you should put this things in your composer as well.

composer require behat/transliterator

More info here https://github.com/Behat/Transliterator

SQL Group By with an Order By

In Oracle, something like this works nicely to separate your counting and ordering a little better. I'm not sure if it will work in MySql 4.

select 'Tag', counts.cnt
from
  (
  select count(*) as cnt, 'Tag'
  from 'images-tags'
  group by 'tag'
  ) counts
order by counts.cnt desc

Convert the first element of an array to a string in PHP

A simple way to create a array to a PHP string array is:

<?PHP
    $array = array("firstname"=>"John", "lastname"=>"doe");
    $json = json_encode($array);
    $phpStringArray = str_replace(array("{", "}", ":"), 
                                  array("array(", "}", "=>"), $json);
    echo phpStringArray;
?>

Comments in Markdown

I believe that all the previously proposed solutions (apart from those that require specific implementations) result in the comments being included in the output HTML, even if they are not displayed.

If you want a comment that is strictly for yourself (readers of the converted document should not be able to see it, even with "view source") you could (ab)use the link labels (for use with reference style links) that are available in the core Markdown specification:

http://daringfireball.net/projects/markdown/syntax#link

That is:

[comment]: <> (This is a comment, it will not be included)
[comment]: <> (in  the output file unless you use it in)
[comment]: <> (a reference style link.)

Or you could go further:

[//]: <> (This is also a comment.)

To improve platform compatibility (and to save one keystroke) it is also possible to use # (which is a legitimate hyperlink target) instead of <>:

[//]: # (This may be the most platform independent comment)

For maximum portability it is important to insert a blank line before and after this type of comments, because some Markdown parsers do not work correctly when definitions brush up against regular text. The most recent research with Babelmark shows that blank lines before and after are both important. Some parsers will output the comment if there is no blank line before, and some parsers will exclude the following line if there is no blank line after.

In general, this approach should work with most Markdown parsers, since it's part of the core specification. (even if the behavior when multiple links are defined, or when a link is defined but never used, is not strictly specified).

How do I disable "missing docstring" warnings at a file-level in Pylint?

I found this here.

You can add "--errors-only" flag for Pylint to disable warnings.

To do this, go to settings. Edit the following line:

"python.linting.pylintArgs": []

As

"python.linting.pylintArgs": ["--errors-only"]

And you are good to go!

How do I format a Microsoft JSON date?

Posting in awesome thread:

var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));
alert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));

How to compare a local git branch with its remote branch?

If you're on a given branch, and you want to compare your working copy with the upstream branch you're tracking, use:

git diff @{upstream}

If you want to compare your current HEAD with the upstream branch (thanks @Arijoon):

git diff @ @{upstream}

If your upstream isn't set, you can use @{push} to get a diff against the branch you are set to push to (also from @Arijoon's comment):

git diff @{push}

Courtesy of this answer, the git documentation for specifying revisions has:

<branchname>@{upstream}, e.g. master@{upstream}, @{u}
The suffix @{upstream} to a branchname (short form <branchname>@{u}) refers to the branch that the branch specified by branchname is set to build on top of (configured with branch.<name>.remote and branch.<name>.merge). A missing branchname defaults to the current one.

Do HttpClient and HttpClientHandler have to be disposed between requests?

If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.

Code:

// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
    HttpRequestHeaders DefaultRequestHeaders { get; }
    Uri BaseAddress { get; set; }
    // ...
    // All the other methods from peeking at HttpClient
}

public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
    public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
    public static HashSet<Uri> _uris;

    static HttpClientHander()
    {
        _httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
        _uris = new HashSet<Uri>();
        SetupGlobalPoolFinalizer();
    }

    private DateTime _delayFinalization = DateTime.MinValue;
    private bool _isDisposed = false;

    public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
    {
        HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
        _uris.Add(baseUrl);
        httpClient._delayFinalization = DateTime.MinValue;
        httpClient.BaseAddress = baseUrl;

        return httpClient;
    }

    void IDisposable.Dispose()
    {
        _isDisposed = true;
        GC.SuppressFinalize(this);

        base.Dispose();
    }

    ~HttpClientHander()
    {
        if (_delayFinalization == DateTime.MinValue)
            _delayFinalization = DateTime.UtcNow;
        if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
            GC.ReRegisterForFinalize(this);
    }

    private static void SetupGlobalPoolFinalizer()
    {
        AppDomain.CurrentDomain.ProcessExit +=
            (sender, eventArgs) => { FinalizeGlobalPool(); };
    }

    private static void FinalizeGlobalPool()
    {
        foreach (var key in _uris)
        {
            HttpClientHander value = null;
            if (_httpClientsPool.TryGetValue(key, out value))
                try { value.Dispose(); } catch { }
        }

        _uris.Clear();
        _httpClientsPool = null;
    }
}

var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).

  • HttpClient, as an interface, can't call Dispose().
  • Dispose() will be called in a delayed fashion by the Garbage Collector. Or when the program cleans up the object through its destructor.
  • Uses Weak References + delayed cleanup logic so it remains in use so long as it is being reused frequently.
  • It only allocates a new HttpClient for each base URL passed to it. Reasons explained by Ohad Schneider answer below. Bad behavior when changing base url.
  • HttpClientHandle allows for Mocking in tests

Why do I get permission denied when I try use "make" to install something?

I had a very similar error message as you, although listing a particular file:

$ make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

$ sudo make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

In my case, I forgot to add a trailing slash to indicate continuation of the line as shown:

${LINEDETECTOR_OBJECTS}:\
    ../HoughLineAccumulator/houghlineaccumulator.hh  # <-- missing slash!!
    ../HoughLineExtractor/houghlineextractor.hh

Hope that helps someone else who lands here from a search engine.

Capture Video of Android's Screen

If you are on a PC then you can run My Phone Explorer on the PC, the MyPhoneExplorer Client on the phone, set the screen capture to refresh continuously, and use Wink to capture a custom rectangular area of your screen over the My Phone Explorer window with your own capture rate. Then convert to a FLV in Wink, then convert from Flash video to MPG with WinFF.

Making the Android emulator run faster

I've been using the Intel(86) CPU/ABI. I created another emulator using the ARM(armeabi-v7a) and i found quite an improvement with the speed. I'm using platform 4.1.2 API level 16

How to set width and height dynamically using jQuery

As @Misha Moroshko has already posted himself, this works:

$("#mainTable").css("width", 100);
$("#mainTable").css("height", 200);

There's some advantage to this technique over @Nick Craver's accepted answer - you can also specifiy different units:

$("#mainTable").css("width", "100%");

So @Nick Craver's method might actually be the wrong choice for some users. From the jquery API (http://api.jquery.com/width/):

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

How to create a foreign key in phpmyadmin

To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab. Storage Engine Configuration

Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.

Index list

Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.

enter image description here

See attachments. I hope this could be useful for anyone.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

How to generate a unique hash code for string input in android...?

For me it worked

   public static long getUniqueLongFromString (String value){
       return  UUID.nameUUIDFromBytes(value.getBytes()).getMostSignificantBits();
    }

How to split a string after specific character in SQL Server and update this value to specific column

I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int) function.

How do I break a string across more than one line of code in JavaScript?

The backslash operator is not reliable. Try pasting this function in your browser console:

function printString (){
  const s = "someLongLineOfText\
  ThatShouldNotBeBroken";
  console.log(s);
}

and then run it. Because of the conventional (and correct) indentation within the function, two extra spaces will be included, resulting in someLongLineOfText ThatShouldNotBeBroken.

Even using backticks will not help in this case. Always use the concatenation "+" operator to prevent this type of issue.

What is the purpose of mvnw and mvnw.cmd files?

Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.

URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties:

distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

To update or change Maven version invoke the following (remember about --non-recursive for multi-module projects):

./mvnw io.takari:maven:wrapper -Dmaven=3.3.9 

or just modify .mvn/wrapper/maven-wrapper.properties manually.

To generate wrapper from scratch using Maven (you need to have it already in PATH run:

mvn io.takari:maven:wrapper -Dmaven=3.3.9 

How to select the Date Picker In Selenium WebDriver

try to SendKeys instead of picking the date

driver.FindElement(yourBy).SendKeys(yourDateTime.ToString("ddd, dd.MM.yyyy",CultureInfo.CreateSpecificCulture("en-US")));

If it does not work, try to send native 'tab'

element.SendKeys(OpenQA.Selenium.Keys.Tab);

nodemon not found in npm

heroku runs in a production environment by default so it does not install the dev dependencies.

if you don't want to reinstall nodemon as a dependency which I think shouldn't because its right place is in devDependencies not in dependencies.

instead, you can create two npm script to avoid this error by running nodemon only in your localhost like that:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js",
    "start:dev": "nodemon --watch"
},

and when you want to run the project locally just run in your terminal npm run start:dev and it will load app.js by nodemon.

while in heroku npm start runs by default and load app.js from a normal node command and you get rid of that error.

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

You might be launching your application from a Product file which is not linked to the plugin file. Reset your workspace and launch using the MANIFEST.MF > Overview > Testing > Launch.

Combine multiple results in a subquery into a single comma-separated value

Even this will serve the purpose

Sample data

declare @t table(id int, name varchar(20),somecolumn varchar(MAX))
insert into @t
    select 1,'ABC','X' union all
    select 1,'ABC','Y' union all
    select 1,'ABC','Z' union all
    select 2,'MNO','R' union all
    select 2,'MNO','S'

Query:

SELECT ID,Name,
    STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))
     FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name
     FOR XML PATH('')),1,1,'') SOMECOLUMN
FROM @T T1
GROUP BY id,Name

Output:

ID  Name    SomeColumn
1   ABC     X,Y,Z
2   MNO     R,S

How do I compile jrxml to get jasper?

In iReport 5.5.0, just right click the report base hierarchy in Report Inspector Bloc Window viewer, then click Compile Report

In iReport, just right click the report base hierachy in Report

You can now see the result in the console down. If no Errors, you may see something like this.

enter image description here

Stacked Bar Plot in R

I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:

data<- rbind(c(480, 780, 431, 295, 670, 360,  190),
             c(720, 350, 377, 255, 340, 615,  345),
             c(460, 480, 179, 560,  60, 735, 1260),
             c(220, 240, 876, 789, 820, 100,   75))

a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))

data           <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type      <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))

library(ggplot2)

ggplot(data = data, aes(x = Type, y = Time, fill = Group)) + 
       geom_bar(stat = "identity") +
       opts(legend.position = "none")

enter image description here

Is SMTP based on TCP or UDP?

Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!

How do I get a Cron like scheduler in Python?

I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html

The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.

Create a list with initial capacity in Python

For some applications, a dictionary may be what you are looking for. For example, in the find_totient method, I found it more convenient to use a dictionary since I didn't have a zero index.

def totient(n):
    totient = 0

    if n == 1:
        totient = 1
    else:
        for i in range(1, n):
            if math.gcd(i, n) == 1:
                totient += 1
    return totient

def find_totients(max):
    totients = dict()
    for i in range(1,max+1):
        totients[i] = totient(i)

    print('Totients:')
    for i in range(1,max+1):
        print(i,totients[i])

This problem could also be solved with a preallocated list:

def find_totients(max):
    totients = None*(max+1)
    for i in range(1,max+1):
        totients[i] = totient(i)

    print('Totients:')
    for i in range(1,max+1):
        print(i,totients[i])

I feel that this is not as elegant and prone to bugs because I'm storing None which could throw an exception if I accidentally use them wrong, and because I need to think about edge cases that the map lets me avoid.

It's true the dictionary won't be as efficient, but as others have commented, small differences in speed are not always worth significant maintenance hazards.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

How to count the frequency of the elements in an unordered list?

One more way is to use a dictionary and the list.count, below a naive way to do it.

dicio = dict()

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

b = list()

c = list()

for i in a:

   if i in dicio: continue 

   else:

      dicio[i] = a.count(i)

      b.append(a.count(i))

      c.append(i)

print (b)

print (c)

How to convert integer to char in C?

Just assign the int to a char variable.

int i = 65;
char c = i;
printf("%c", c); //prints A

How can I use different certificates on specific connections?

I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

So this is in our LocalSSLSocketFactory:

static {
    try {
        SSL_CONTEXT = SSLContext.getInstance("SSL");
        SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    } catch (KeyManagementException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });

    return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}

Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

What HTTP traffic monitor would you recommend for Windows?

Try Wireshark:

Wireshark is the world's foremost network protocol analyzer, and is the de facto (and often de jure) standard across many industries and educational institutions.

There is a bit of a learning curve but it is far and away the best tool available.

Removing viewcontrollers from navigation stack

You can first get all the view controllers in the array and then after checking with the corresponding view controller class, you can delete the one you want.

Here is small piece of code:

NSArray* tempVCA = [self.navigationController viewControllers];

for(UIViewController *tempVC in tempVCA)
{
    if([tempVC isKindOfClass:[urViewControllerClass class]])
    {
        [tempVC removeFromParentViewController];
    }
}

I think this will make your work easier.

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.

I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure replaced by $ ./configure --enable-shared (first make sure to delete all the folders and files including the .so files from the previous attempt).

Apparently this works because https://stackoverflow.com/a/13812368/10593190.

Dynamically Dimensioning A VBA Array?

You can use a dynamic array when you don't know the number of values it will contain until run-time:

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)

Or you could do everything with one statement if you're creating an array that's local to a procedure:

ReDim Zombies(NumberOfZombies) As Integer

Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.

You could use a constant if you knew the value of the variable was not going to change:

Const NumberOfZombies = 2000

but there's no way to cast between constants and variables. They have distinctly different meanings.

Difference between malloc and calloc?

A less known difference is that in operating systems with optimistic memory allocation, like Linux, the pointer returned by malloc isn't backed by real memory until the program actually touches it.

calloc does indeed touch the memory (it writes zeroes on it) and thus you'll be sure the OS is backing the allocation with actual RAM (or swap). This is also why it is slower than malloc (not only does it have to zero it, the OS must also find a suitable memory area by possibly swapping out other processes)

See for instance this SO question for further discussion about the behavior of malloc

How can I increase the JVM memory?

Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE

I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args

Converting XDocument to XmlDocument and vice versa

For me this single line solution works very well

XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument

Importing Excel files into R, xlsx or xls

For me the openxlx package worked in the easiest way.

install.packages("openxlsx")
library(openxlsx)
rawData<-read.xlsx("your.xlsx");

What is the best way to get all the divisors of a number?

Assuming that the factors function returns the factors of n (for instance, factors(60) returns the list [2, 2, 3, 5]), here is a function to compute the divisors of n:

function divisors(n)
    divs := [1]
    for fact in factors(n)
        temp := []
        for div in divs
            if fact * div not in divs
                append fact * div to temp
        divs := divs + temp
    return divs

Does 'position: absolute' conflict with Flexbox?

No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.

That means that

  • If you add absolute positioning to an element with display: inline-flex, it will become block-level (like display: flex), but will still generate a flex formatting context.

  • If you add absolute positioning to an element with display: flex, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.

That said, absolutely positioning conflicts with flex children.

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

Get child Node of another Node, given node name

You should read it recursively, some time ago I had the same question and solve with this code:

public void proccessMenuNodeList(NodeList nl, JMenuBar menubar) {
    for (int i = 0; i < nl.getLength(); i++) {
        proccessMenuNode(nl.item(i), menubar);
    }
}

public void proccessMenuNode(Node n, Container parent) {
    if(!n.getNodeName().equals("menu"))
        return;
    Element element = (Element) n;
    String type = element.getAttribute("type");
    String name = element.getAttribute("name");
    if (type.equals("menu")) {
        NodeList nl = element.getChildNodes();
        JMenu menu = new JMenu(name);

        for (int i = 0; i < nl.getLength(); i++)
            proccessMenuNode(nl.item(i), menu);

        parent.add(menu);
    } else if (type.equals("item")) {
        JMenuItem item = new JMenuItem(name);
        parent.add(item);
    }
}

Probably you can adapt it for your case.

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

well i found out the mistake i was committing i was adding a group to the project instead of adding real directory for more instructions

What is cardinality in Databases?

A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.

In data modelling terms, cardinality is how one table relates to another.

  • 1-1 (one row in table A relates to one row in tableB)
  • 1-Many (one row in table A relates to many rows in tableB)
  • Many-Many (Many rows in table A relate to many rows in tableB)

There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).

See Wikipedia on Cardinality (data modelling).


When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.

See Wikipedia on Cardinality (SQL statements).

How to find out mySQL server ip address from phpmyadmin

The SQL query SHOW VARIABLES WHERE Variable_name = 'hostname' will show you the hostname of the MySQL server which you can easily resolve to its IP address.

SHOW VARIABLES WHERE Variable_name = 'port' Will give you the port number.

You can find details about this in MySQL's manual: 12.4.5.41. SHOW VARIABLES Syntax and 5.1.4. Server System Variables

How to make a countdown timer in Android?

Try this way:

private void startTimer() {
    startTimer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {

            long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
 TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

            Log.e(TAG, "onTick: "+sec );
            tv_timer.setText(String.format("( %02d SEC )", sec));
            if(sec == 1)
            {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("( 00 SEC )");
                    }
                }, 1000);
            }


        }

        public void onFinish() {
            tv_timer.setText("Timer finish");
        }
    }.start();
}

extra qualification error in C++

This means a class is redundantly mentioned with a class function. Try removing JSONDeserializer::

How to resize array in C++?

Raw arrays aren't resizable in C++.

You should be using something like a Vector class which does allow resizing..

std::vector allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Encounter the same error today and solved it with:

npm i --save-dev  @types/es6-promise

Update:

add:

import {Promise} from 'es6-promise'

Defining and using a variable in batch file

Consider also using SETX - it will set variable on user or machine (available for all users) level though the variable will be usable with the next opening of the cmd.exe ,so often it can be used together with SET :

::setting variable for the current user
if not defined My_Var (
  set "My_Var=My_Value"
  setx My_Var My_Value
)

::setting machine defined variable
if not defined Global_Var (
  set "Global_Var=Global_Value"
  SetX Global_Var Global_Value /m
)

You can also edit directly the registry values:

User Variables: HKEY_CURRENT_USER\Environment

System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Which will allow to avoid some restrictions of SET and SETX like the variables containing = in their names.

"unexpected token import" in Nodejs5 and babel?

if you use the preset for react-native it accepts the import

npm i babel-preset-react-native --save-dev

and put it inside your .babelrc file

{
  "presets": ["react-native"]
}

in your project root directory

https://www.npmjs.com/package/babel-preset-react-native

Make a table fill the entire window

That is because, of course, there is no ACTUAL page height. Keep in mind that you scroll throughout the contents of a page vertically not horizontally, creating a limited width but unlimited height. What the selected answer did was to make the table take up the visible area and stay there no matter what(absolute positioning).So theoretically what you were trying to do was impossible

Replacing a character from a certain index

You can also Use below method if you have to replace string between specific index

def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
    try:
       singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
    except Exception as e:
        exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
        BuiltIn.log_to_console(exception)
    return singleLine

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

In my context, just developed a class abstraction. When my application is launched, i check if localStorage is working by calling getStorage(). This function also return :

  • either localStorage if localStorage is working
  • or an implementation of a custom class LocalStorageAlternative

In my code i never call localStorage directly. I call cusStoglobal var, i had initialised by calling getStorage().

This way, it works with private browsing or specific Safari versions

function getStorage() {

    var storageImpl;

     try { 
        localStorage.setItem("storage", ""); 
        localStorage.removeItem("storage");
        storageImpl = localStorage;
     }
     catch (err) { 
         storageImpl = new LocalStorageAlternative();
     }

    return storageImpl;

}

function LocalStorageAlternative() {

    var structureLocalStorage = {};

    this.setItem = function (key, value) {
        structureLocalStorage[key] = value;
    }

    this.getItem = function (key) {
        if(typeof structureLocalStorage[key] != 'undefined' ) {
            return structureLocalStorage[key];
        }
        else {
            return null;
        }
    }

    this.removeItem = function (key) {
        structureLocalStorage[key] = undefined;
    }
}

cusSto = getStorage();

How to find Control in TemplateField of GridView?

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

How to smooth a curve in the right way?

I prefer a Savitzky-Golay filter. It uses least squares to regress a small window of your data onto a polynomial, then uses the polynomial to estimate the point in the center of the window. Finally the window is shifted forward by one data point and the process repeats. This continues until every point has been optimally adjusted relative to its neighbors. It works great even with noisy samples from non-periodic and non-linear sources.

Here is a thorough cookbook example. See my code below to get an idea of how easy it is to use. Note: I left out the code for defining the savitzky_golay() function because you can literally copy/paste it from the cookbook example I linked above.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
yhat = savitzky_golay(y, 51, 3) # window size 51, polynomial order 3

plt.plot(x,y)
plt.plot(x,yhat, color='red')
plt.show()

optimally smoothing a noisy sinusoid

UPDATE: It has come to my attention that the cookbook example I linked to has been taken down. Fortunately, the Savitzky-Golay filter has been incorporated into the SciPy library, as pointed out by @dodohjk. To adapt the above code by using SciPy source, type:

from scipy.signal import savgol_filter
yhat = savgol_filter(y, 51, 3) # window size 51, polynomial order 3

How to open a local disk file with JavaScript?

Consider reformatting your file into javascript. Then you can simply load it using good old...

<script src="thefileIwantToLoad.js" defer></script>

What is the default maximum heap size for Sun's JVM from Java SE 6?

With JDK, You can also use jinfo to connect to the JVM for the <PROCESS_ID> in question and get the value for MaxHeapSize:

jinfo -flag MaxHeapSize <PROCESS_ID>

Android WebView not loading URL

Note : Make sure internet permission is given.

In android 9.0,

Webview or Imageloader can not load url or image because android 9 have network security issue which need to be enable by manifest file for all sub domain. so either you can add security config file.

  1. Add @xml/network_security_config into your resources:

_x000D_
_x000D_
<network-security-config>_x000D_
    <domain-config cleartextTrafficPermitted="true">_x000D_
    <domain includeSubdomains="true">www.google.com</domain>_x000D_
    </domain-config>_x000D_
</network-security-config>
_x000D_
_x000D_
_x000D_

  1. Add this security config to your Manifest like this:

_x000D_
_x000D_
<application_x000D_
   _x000D_
    android:networkSecurityConfig="@xml/network_security_config"_x000D_
    ...>_x000D_
</application>
_x000D_
_x000D_
_x000D_

if you want to allow all sub domain

_x000D_
_x000D_
<application_x000D_
   android:usesCleartextTraffic="true"_x000D_
    ...>_x000D_
</application>
_x000D_
_x000D_
_x000D_

Note: To solve the problem, don't use both of point 2 (android:networkSecurityConfig="@xml/network_security_config" and android:usesCleartextTraffic="true") choose one of them

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

The type or namespace name could not be found

It is also possible, that the referenced projects targets .NET 4.0, while the Console App Project targets .NET 4.0 Client Library.

While it might not have been related to this particular case, I think someone else can find this information useful.

Equivalent of Oracle's RowID in SQL Server

Several of the answers above will work around the lack of a direct reference to a specific row, but will not work if changes occur to the other rows in a table. That is my criteria for which answers fall technically short.

A common use of Oracle's ROWID is to provide a (somewhat) stable method of selecting rows and later returning to the row to process it (e.g., to UPDATE it). The method of finding a row (complex joins, full-text searching, or browsing row-by-row and applying procedural tests against the data) may not be easily or safely re-used to qualify the UPDATE statement.

The SQL Server RID seems to provide the same functionality, but does not provide the same performance. That is the only issue I see, and unfortunately the purpose of retaining a ROWID is to avoid repeating an expensive operation to find the row in, say, a very large table. Nonetheless, performance for many cases is acceptable. If Microsoft adjusts the optimizer in a future release, the performance issue could be addressed.

It is also possible to simply use FOR UPDATE and keep the CURSOR open in a procedural program. However, this could prove expensive in large or complex batch processing.

Caveat: Even Oracle's ROWID would not be stable if the DBA, between the SELECT and the UPDATE, for example, were to rebuild the database, because it is the physical row identifier. So the ROWID device should only be used within a well-scoped task.

String.equals versus ==

a==b

Compares references, not values. The use of == with object references is generally limited to the following:

  1. Comparing to see if a reference is null.

  2. Comparing two enum values. This works because there is only one object for each enum constant.

  3. You want to know if two references are to the same object

"a".equals("b")

Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

Share Text on Facebook from Android App via ACTION_SEND

First you need query Intent to handler sharing option. Then use package name to filter Intent then we will have only one Intent that handler sharing option!

Share via Facebook

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
    if ((app.activityInfo.name).contains("facebook")) {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shareIntent.setComponent(name);
        v.getContext().startActivity(shareIntent);
        break;
   }
}

Bonus - Share via Twitter

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
    if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shareIntent.setComponent(name);
        v.getContext().startActivity(shareIntent);
        break;
   }
}

And if you want to find how to share via another sharing application, find it there Tép Blog - Advance share via Android

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

I had the same issue, and the solution is very simple, just change to git bash from cmd or other windows command line tools. Windows sometimes does not work well with git npm dependencies.

How to Select Every Row Where Column Value is NOT Distinct

select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1

How do I open a new window using jQuery?

It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:

window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');

That's it.

The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener later if there was no window name specified (just a little FYI), and the last two params are width/height.

EDIT: Full specification can be found in the link mmmshuddup provided.

How to convert int to QString?

Moreover to convert whatever you want, you can use QVariant. For an int to a QString you get:

QVariant(3).toString();

A float to a string or a string to a float:

QVariant(3.2).toString();
QVariant("5.2").toFloat();

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

Trigger insert old values- values that was updated

    createTRIGGER [dbo].[Table] ON [dbo].[table] 
FOR UPDATE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);
    declare @old_v varchar(100)

    select @empid=i.Col_Name1 from inserted i;  
    select @empname=i.Col_Name2  from inserted i;   
    select @empsal=i.Col_Name2 from inserted i;
    select @old_v=d.Col_Name from deleted d

    if update(Col_Name1)
        set @audit_action='Updated Record -- After Update Trigger.';
    if update(Col_Name2)
        set @audit_action='Updated Record -- After Update Trigger.';

    insert into Employee_Test_Audit1(Col_name1,Col_name2,Col_name3,Col_name4,Col_name5,Col_name6(Old_values)) 
    values(@empid,@empname,@empsal,@audit_action,getdate(),@old_v);

    PRINT '----AFTER UPDATE Trigger fired-----.'

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

Their main functions are:

Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.

How to set a default entity property value with Hibernate

You can use @PrePersist anotation and set the default value in pre-persist stage.

Something like that:

//... some code
private String myProperty;
//... some code

@PrePersist
public void prePersist() {
    if(myProperty == null) //We set default value in case if the value is not set yet.
        myProperty = "Default value";
}

// property methods
@Column(nullable = false) //restricting Null value on database level.
public String getMyProperty() {
    return myProperty;
}

public void setMyProperty(String myProperty) {
    this.myProperty= myProperty;
}

This method is not depend on database type/version underneath the Hibernate. Default value is set before persisting the mapping object.

How stable is the git plugin for eclipse?

You can integrate Git-GUI with Eclipse as an alternative to EGit.

See this two part YouTube tutorial specific to Windows:
http://www.youtube.com/watch?v=DcM1xOiaidk
http://www.youtube.com/watch?v=1OrPJClD92s

How to delete directory content in Java?

for(File f : files) {
    f.delete();
}    
files.delete(); // will work

Is there a NumPy function to return the first index of something in an array?

For one-dimensional sorted arrays, it would be much more simpler and efficient O(log(n)) to use numpy.searchsorted which returns a NumPy integer (position). For example,

arr = np.array([1, 1, 1, 2, 3, 3, 4])
i = np.searchsorted(arr, 3)

Just make sure the array is already sorted

Also check if returned index i actually contains the searched element, since searchsorted's main objective is to find indices where elements should be inserted to maintain order.

if arr[i] == 3:
    print("present")
else:
    print("not present")

Why is the console window closing immediately once displayed my output?

The program is closing as soon as it's execution is complete. In this case when you return 0;. This is expected functionality. If you want to see the output then either run it in a terminal manually or set a wait at the end of the program so that it will stay open for a few seconds ( using the threading library ).

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

This error you are receiving :

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

is because the number of elements in $values & $matches is not the same or $matches contains more than 1 element.

If $matches contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash)

If $values & $matches do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches.

I believe you will also need to ensure the column hash has a unique index on it as well.

Try the code here:

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }


$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
    $values[] = '?';
}

// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);

//Error reporting if something went wrong...
var_dump($dbh->errorInfo());

?>

You will need to adapt it a little.

Table structure I used is here:

CREATE TABLE IF NOT EXISTS `hashes` (
  `hashid` int(11) NOT NULL AUTO_INCREMENT,
  `hash` varchar(250) NOT NULL,
  PRIMARY KEY (`hashid`),
  UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.

I hope this helps.

Escaping regex string

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

Basic example for sharing text or image with UIActivityViewController in Swift

You may use the following functions which I wrote in one of my helper class in a project.

just call

showShareActivity(msg:"message", image: nil, url: nil, sourceRect: nil) 

and it will work for both iPhone and iPad. If you pass any view's CGRect value by sourceRect it will also shows a little arrow in iPad.

func topViewController()-> UIViewController{
    var topViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!

    while ((topViewController.presentedViewController) != nil) {
        topViewController = topViewController.presentedViewController!;
    }

    return topViewController
}

func showShareActivity(msg:String?, image:UIImage?, url:String?, sourceRect:CGRect?){
    var objectsToShare = [AnyObject]()

    if let url = url {
        objectsToShare = [url as AnyObject]
    }

    if let image = image {
        objectsToShare = [image as AnyObject]
    }

    if let msg = msg {
        objectsToShare = [msg as AnyObject]
    }

    let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
    activityVC.modalPresentationStyle = .popover
    activityVC.popoverPresentationController?.sourceView = topViewController().view
    if let sourceRect = sourceRect {
        activityVC.popoverPresentationController?.sourceRect = sourceRect
    }

    topViewController().present(activityVC, animated: true, completion: nil)
}

How can I select an element in a component template?

In case you are using Angular Material, you can take advantage of cdkFocusInitial directive.

Example: <input matInput cdkFocusInitial>

Read more here: https://material.angular.io/cdk/a11y/overview#regions

PHP - concatenate or directly insert variables in string

Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!

//syntax error!!
//$s = "Hello {trim($world)}!"

//the only option
$s = "Hello " . trim($world) . "!";

jQuery $(document).ready and UpdatePanels?

<script type="text/javascript">

        function BindEvents() {
            $(document).ready(function() {
                $(".tr-base").mouseover(function() {
                    $(this).toggleClass("trHover");
                }).mouseout(function() {
                    $(this).removeClass("trHover");
                });
         }
</script>

The area which is going to be updated.

<asp:UpdatePanel...
<ContentTemplate
     <script type="text/javascript">
                    Sys.Application.add_load(BindEvents);
     </script>
 *// Staff*
</ContentTemplate>
    </asp:UpdatePanel>

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

How to check date of last change in stored procedure or function in SQL server

Try this for stored procedures:

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = 'myProc'

How to edit binary file on Unix systems

you can check wikipedia.

I prefer BIEW especially.

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).


On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

NSOperation vs Grand Central Dispatch

Well, NSOperations are simply an API built on top of Grand Central Dispatch. So when you’re using NSOperations, you’re really still using Grand Central Dispatch. It’s just that NSOperations give you some fancy features that you might like. You can make some operations dependent on other operations, reorder queues after you sumbit items, and other things like that. In fact, ImageGrabber is already using NSOperations and operation queues! ASIHTTPRequest uses them under the hood, and you can configure the operation queue it uses for different behavior if you’d like. So which should you use? Whichever makes sense for your app. For this app it’s pretty simple so we just used Grand Central Dispatch directly, no need for the fancy features of NSOperation. But if you need them for your app, feel free to use it!

How to dynamically allocate memory space for a string and get that string from user?

char* load_string()
 {

char* string = (char*) malloc(sizeof(char));
*string = '\0';

int key;
int sizer = 2;

char sup[2] = {'\0'};

while( (key = getc(stdin)) != '\n')
{
    string = realloc(string,sizer * sizeof(char));
    sup[0] = (char) key;
    strcat(string,sup);
    sizer++

}
return string;

}

int main()
  {
char* str;
str = load_string();

return 0;
  }

database attached is read only

You need to go to the new folder properties > security tab, and give permissions to the SQL user that has rights on the DATA folder from the SQL server installation folder.

replace anchor text with jquery

Try this, in case of id

$("#YourId").text('Your text');

OR this, in case of class

$(".YourClassName").text('Your text');

How to close a Tkinter window by pressing a Button?

from tkinter import *

def close_window():
    import sys
    sys.exit()

root = Tk()

frame = Frame (root)
frame.pack()

button = Button (frame, text="Good-bye", command=close_window)
button.pack()

mainloop()

How to keep a Python script output window open?

The simplest way:

import time

#Your code here
time.sleep(60)
#end of code (and console shut down)

this will leave the code up for 1 minute then close it.

Converting a generic list to a CSV string

As the code in the link given by @Frank Create a CSV File from a .NET Generic List there was a little issue of ending every line with a , I modified the code to get rid of it.Hope it helps someone.

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
    if (list == null || list.Count == 0) return;

    //get type from 0th member
    Type t = list[0].GetType();
    string newLine = Environment.NewLine;

    if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));

    if (!File.Exists(csvCompletePath)) File.Create(csvCompletePath);

    using (var sw = new StreamWriter(csvCompletePath))
    {
        //make a new instance of the class name we figured out to get its props
        object o = Activator.CreateInstance(t);
        //gets all properties
        PropertyInfo[] props = o.GetType().GetProperties();

        //foreach of the properties in class above, write out properties
        //this is the header row
        sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);

        //this acts as datarow
        foreach (T item in list)
        {
            //this acts as datacolumn
            var row = string.Join(",", props.Select(d => item.GetType()
                                                            .GetProperty(d.Name)
                                                            .GetValue(item, null)
                                                            .ToString())
                                                    .ToArray());
            sw.Write(row + newLine);

        }
    }
}

Iterate over the lines of a string

I suppose you could roll your own:

def parse(string):
    retval = ''
    for char in string:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

I'm not sure how efficient this implementation is, but that will only iterate over your string once.

Mmm, generators.

Edit:

Of course you'll also want to add in whatever type of parsing actions you want to take, but that's pretty simple.

How to check if JavaScript object is JSON

you can also try to parse the data and then check if you got object:

var testIfJson = JSON.parse(data);
if (typeOf testIfJson == "object")
{
//Json
}
else
{
//Not Json
}

Is it possible to disable scrolling on a ViewPager

There is an easy fix for this one:

When you want to disable the viewpager scrolling then:

mViewPager.setOnTouchListener(new OnTouchListener() {

   public boolean onTouch(View arg0, MotionEvent arg1) {
      return true;
   }
}); 

And when you want to re-enable it then:

mViewPager.setOnTouchListener(null);

That will do the trick.

What is the "right" way to iterate through an array in Ruby?

In Ruby 2.1, each_with_index method is removed. Instead you can use each_index

Example:

a = [ "a", "b", "c" ]
a.each_index {|x| print x, " -- " }

produces:

0 -- 1 -- 2 --

Plot multiple lines in one graph

You should bring your data into long (i.e. molten) format to use it with ggplot2:

library("reshape2")
mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year")

And then you have to use aes( ... , group = Company ) to group them:

ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

enter image description here

jQuery Determine if a matched class has a given id

$('#' + theMysteryId + '.someClass').each(function() { /* do stuff */ });

NameError: name 'reduce' is not defined in Python

You can add

from functools import reduce

before you use the reduce.

Counting number of words in a file

Hack solution

You can read the text file into a String var. Then split the String into an array using a single whitespace as the delimiter StringVar.Split(" ").

The Array count would equal the number of "Words" in the file. Of course this wouldnt give you a count of line numbers.

fetch in git doesn't get all branches

Remote update

You need to run

git remote update

or

git remote update <remote> 

Then you can run git branch -r to list the remote branches.

Checkout a new branch

To track a (new) remote branch as a local branch:

git checkout -b <local branch> <remote>/<remote branch>

or (sometimes it doesn't work without the extra remotes/):

git checkout -b <local branch> remotes/<remote>/<remote branch>

Helpful git cheatsheets

malloc an array of struct pointers

There's a lot of typedef going on here. Personally I'm against "hiding the asterisk", i.e. typedef:ing pointer types into something that doesn't look like a pointer. In C, pointers are quite important and really affect the code, there's a lot of difference between foo and foo *.

Many of the answers are also confused about this, I think.

Your allocation of an array of Chess values, which are pointers to values of type chess (again, a very confusing nomenclature that I really can't recommend) should be like this:

Chess *array = malloc(n * sizeof *array);

Then, you need to initialize the actual instances, by looping:

for(i = 0; i < n; ++i)
  array[i] = NULL;

This assumes you don't want to allocate any memory for the instances, you just want an array of pointers with all pointers initially pointing at nothing.

If you wanted to allocate space, the simplest form would be:

for(i = 0; i < n; ++i)
  array[i] = malloc(sizeof *array[i]);

See how the sizeof usage is 100% consistent, and never starts to mention explicit types. Use the type information inherent in your variables, and let the compiler worry about which type is which. Don't repeat yourself.

Of course, the above does a needlessly large amount of calls to malloc(); depending on usage patterns it might be possible to do all of the above with just one call to malloc(), after computing the total size needed. Then you'd still need to go through and initialize the array[i] pointers to point into the large block, of course.

Python Prime number checker

# is digit prime? we will see (Coder: Chikak)

def is_prime(x): flag = False if x < 2: return False else: for count in range(2, x): if x % count == 0: flag = True break if flag == True: return False return True

How do you launch the JavaScript debugger in Google Chrome?

Windows: CTRL-SHIFT-J OR F12

Mac: ?-?-J

Also available through the wrench menu (Tools > JavaScript Console):

JavaScript Console Menu

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

How to send objects through bundle

Figuring out what path to take requires answering not only CommonsWare's key question of "why" but also the question of "to what?" are you passing it.

The reality is that the only thing that can go through bundles is plain data - everything else is based on interpretations of what that data means or points to. You can't literally pass an object, but what you can do is one of three things:

1) You can break the object down to its constitute data, and if what's on the other end has knowledge of the same sort of object, it can assemble a clone from the serialized data. That's how most of the common types pass through bundles.

2) You can pass an opaque handle. If you are passing it within the same context (though one might ask why bother) that will be a handle you can invoke or dereference. But if you pass it through Binder to a different context it's literal value will be an arbitrary number (in fact, these arbitrary numbers count sequentially from startup). You can't do anything but keep track of it, until you pass it back to the original context which will cause Binder to transform it back into the original handle, making it useful again.

3) You can pass a magic handle, such as a file descriptor or reference to certain os/platform objects, and if you set the right flags Binder will create a clone pointing to the same resource for the recipient, which can actually be used on the other end. But this only works for a very few types of objects.

Most likely, you are either passing your class just so the other end can keep track of it and give it back to you later, or you are passing it to a context where a clone can be created from serialized constituent data... or else you are trying to do something that just isn't going to work and you need to rethink the whole approach.

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

How to remove underline from a link in HTML?

I suggest to use :hover to avoid underline if mouse pointer is over an anchor

a:hover {
   text-decoration:none;
}

Centering a div block without the width

I found interesting solution, I was making slider and had to center slide controls and I did this and works fine. You can also add relative position to parent and move child position vertical. Take a look http://jsfiddle.net/bergb/6DvJz/

CSS:

#parent{
        width:600px;
        height:400px;
        background:#ffcc00;
        text-align:center;
    }

#child{
        display:inline-block;
        margin:0 auto;
        background:#fff;
    }  

HTML:

<div id="parent">
    <div id="child">voila</div>
</div>

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

change cursor from block or rectangle to line?

You're in replace mode. Press the Insert key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.

How to simulate a mouse click using JavaScript?

Here's a pure JavaScript function which will simulate a click (or any mouse event) on a target element:

function simulatedClick(target, options) {

  var event = target.ownerDocument.createEvent('MouseEvents'),
      options = options || {},
      opts = { // These are the default values, set up for un-modified left clicks
        type: 'click',
        canBubble: true,
        cancelable: true,
        view: target.ownerDocument.defaultView,
        detail: 1,
        screenX: 0, //The coordinates within the entire page
        screenY: 0,
        clientX: 0, //The coordinates within the viewport
        clientY: 0,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
        button: 0, //0 = left, 1 = middle, 2 = right
        relatedTarget: null,
      };

  //Merge the options with the defaults
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      opts[key] = options[key];
    }
  }

  //Pass in the options
  event.initMouseEvent(
      opts.type,
      opts.canBubble,
      opts.cancelable,
      opts.view,
      opts.detail,
      opts.screenX,
      opts.screenY,
      opts.clientX,
      opts.clientY,
      opts.ctrlKey,
      opts.altKey,
      opts.shiftKey,
      opts.metaKey,
      opts.button,
      opts.relatedTarget
  );

  //Fire the event
  target.dispatchEvent(event);
}

Here's a working example: http://www.spookandpuff.com/examples/clickSimulation.html

You can simulate a click on any element in the DOM. Something like simulatedClick(document.getElementById('yourButtonId')) would work.

You can pass in an object into options to override the defaults (to simulate which mouse button you want, whether Shift/Alt/Ctrl are held, etc. The options it accepts are based on the MouseEvents API.

I've tested in Firefox, Safari and Chrome. Internet Explorer might need special treatment, I'm not sure.

What is the idiomatic Go equivalent of C's ternary operator?

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2
}

However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.

I used an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()

This ensures that both branches are not evaluated as well.

JPA: How to get entity based on field value other than ID?

Edit: Just realized that @Chinmoy was getting at basically the same thing, but I think I may have done a better job ELI5 :)

If you're using a flavor of Spring Data to help persist / fetch things from whatever kind of Repository you've defined, you can probably have your JPA provider do this for you via some clever tricks with method names in your Repository interface class. Allow me to explain.

(As a disclaimer, I just a few moments ago did/still am figuring this out for myself.)

For example, if I am storing Tokens in my database, I might have an entity class that looks like this:

@Data // << Project Lombok convenience annotation
@Entity
public class Token {
    @Id
    @Column(name = "TOKEN_ID")
    private String tokenId;

    @Column(name = "TOKEN")
    private String token;

    @Column(name = "EXPIRATION")
    private String expiration;

    @Column(name = "SCOPE")
    private String scope;
}

And I probably have a CrudRepository<K,V> interface defined like this, to give me simple CRUD operations on that Repository for free.

@Repository
// CrudRepository<{Entity Type}, {Entity Primary Key Type}>
public interface TokenRepository extends CrudRepository<Token, String> { }

And when I'm looking up one of these tokens, my purpose might be checking the expiration or scope, for example. In either of those cases, I probably don't have the tokenId handy, but rather just the value of a token field itself that I want to look up.

To do that, you can add an additional method to your TokenRepository interface in a clever way to tell your JPA provider that the value you're passing in to the method is not the tokenId, but the value of another field within the Entity class, and it should take that into account when it is generating the actual SQL that it will run against your database.

@Repository
// CrudRepository<{Entity Type}, {Entity Primary Key Type}>
public interface TokenRepository extends CrudRepository<Token, String> { 
    List<Token> findByToken(String token);
}

I read about this on the Spring Data R2DBC docs page, and it seems to be working so far within a SpringBoot 2.x app storing in an embedded H2 database.

Find records with a date field in the last 24 hours

To get records from the last 24 hours:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

How to have conditional elements and keep DRY with Facebook React's JSX?

Most examples are with one line of "html" that is rendered conditionally. This seems readable for me when I have multiple lines that needs to be rendered conditionally.

render: function() {
  // This will be renered only if showContent prop is true
  var content = 
    <div>
      <p>something here</p>
      <p>more here</p>
      <p>and more here</p>
    </div>;

  return (
    <div>
      <h1>Some title</h1>

      {this.props.showContent ? content : null}
    </div>
  );
}

First example is good because instead of null we can conditionally render some other content like {this.props.showContent ? content : otherContent}

But if you just need to show/hide content this is even better since Booleans, Null, and Undefined Are Ignored

render: function() {
  return (
    <div>
      <h1>Some title</h1>

      // This will be renered only if showContent prop is true
      {this.props.showContent &&
        <div>
          <p>something here</p>
          <p>more here</p>
          <p>and more here</p>
        </div>
      }
    </div>
  );
}

Difference between socket and websocket?

To answer your questions.

  1. Even though they achieve (in general) similar things, yes, they are really different. WebSockets typically run from browsers connecting to Application Server over a protocol similar to HTTP that runs over TCP/IP. So they are primarily for Web Applications that require a permanent connection to its server. On the other hand, plain sockets are more powerful and generic. They run over TCP/IP but they are not restricted to browsers or HTTP protocol. They could be used to implement any kind of communication.
  2. No. There is no reason.

Storing and displaying unicode string (??????) using PHP and MySQL

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">


<?php 
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');

mysql_select_db('onlinetest',$con);

$nith = "CREATE TABLE IF NOT EXISTS `TAMIL` (
  `data` varchar(1000) character set utf8 collate utf8_bin default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";

if (!mysql_query($nith,$con))
{
  die('Error: ' . mysql_error());
}

$nithi = "INSERT INTO `TAMIL` VALUES ('??????? ???????? ?????????')";

if (!mysql_query($nithi,$con))
{
  die('Error: ' . mysql_error());
}

$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
while($myrow = mysql_fetch_row($result))
{
    echo ($myrow[0]);
}
?>
</body>
</html>

OAuth: how to test with local URLs?

Set your local domain to mywebsite.example.com (and redirect it to localhost) -- even though the usual is to use mywebsite.dev. This will allow robust automatic testing.

Although authorizing .test and .dev is not allowed, authorizing example.com is allowed in google oauth2.

(You can redirect any domain to localhost in your hosts file (unix/linux: /etc/hosts))

Why mywebsite.example.com?
Because example.com is a reserved domain name. So

  1. there would be no naming conflicts on your machine.
  2. no data-risk if your test system exposes data to not-redirected-by-mistake.example.com.

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

For getting the last value from Array :

array_slice($arr,-1,1) ;

For Removing last value form array :

array_slice($arr,0,count($arr)-1) ;

Calculating distance between two points, using latitude longitude?

Note: this solution only works for short distances.

I tried to use dommer's posted formula for an application and found it did well for long distances but in my data I was using all very short distances, and dommer's post did very poorly. I needed speed, and the more complex geo calcs worked well but were too slow. So, in the case that you need speed and all the calculations you're making are short (maybe < 100m or so). I found this little approximation to work great. it assumes the world is flat mind you, so don't use it for long distances, it works by approximating the distance of a single Latitude and Longitude at the given Latitude and returning the Pythagorean distance in meters.

public class FlatEarthDist {
    //returns distance in meters
    public static double distance(double lat1, double lng1, 
                                      double lat2, double lng2){
     double a = (lat1-lat2)*FlatEarthDist.distPerLat(lat1);
     double b = (lng1-lng2)*FlatEarthDist.distPerLng(lat1);
     return Math.sqrt(a*a+b*b);
    }

    private static double distPerLng(double lat){
      return 0.0003121092*Math.pow(lat, 4)
             +0.0101182384*Math.pow(lat, 3)
                 -17.2385140059*lat*lat
             +5.5485277537*lat+111301.967182595;
    }

    private static double distPerLat(double lat){
            return -0.000000487305676*Math.pow(lat, 4)
                -0.0033668574*Math.pow(lat, 3)
                +0.4601181791*lat*lat
                -1.4558127346*lat+110579.25662316;
    }
}

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

SQL grouping by all the columns

The DISTINCT Keyword


I believe what you are trying to do is:

SELECT DISTINCT * FROM MyFooTable;

If you group by all columns, you are just requesting that duplicate data be removed.

For example a table with the following data:

 id |     value      
----+----------------
  1 | foo
  2 | bar
  1 | foo
  3 | something else

If you perform the following query which is essentially the same as SELECT * FROM MyFooTable GROUP BY * if you are assuming * means all columns:

SELECT * FROM MyFooTable GROUP BY id, value;

 id |     value      
----+----------------
  1 | foo
  3 | something else
  2 | bar

It removes all duplicate values, which essentially makes it semantically identical to using the DISTINCT keyword with the exception of the ordering of results. For example:

SELECT DISTINCT * FROM MyFooTable;

 id |     value      
----+----------------
  1 | foo
  2 | bar
  3 | something else

Benefits of inline functions in C++?

inline allows you to place a function definition in a header file and #include that header file in multiple source files without violating the one definition rule.

Is an entity body allowed for an HTTP DELETE request?

The spec does not explicitly forbid or discourage it, so I would tend to say it is allowed.

Microsoft sees it the same way (I can hear murmuring in the audience), they state in the MSDN article about the DELETE Method of ADO.NET Data Services Framework:

If a DELETE request includes an entity body, the body is ignored [...]

Additionally here is what RFC2616 (HTTP 1.1) has to say in regard to requests:

  • an entity-body is only present when a message-body is present (section 7.2)
  • the presence of a message-body is signaled by the inclusion of a Content-Length or Transfer-Encoding header (section 4.3)
  • a message-body must not be included when the specification of the request method does not allow sending an entity-body (section 4.3)
  • an entity-body is explicitly forbidden in TRACE requests only, all other request types are unrestricted (section 9, and 9.8 specifically)

For responses, this has been defined:

  • whether a message-body is included depends on both request method and response status (section 4.3)
  • a message-body is explicitly forbidden in responses to HEAD requests (section 9, and 9.4 specifically)
  • a message-body is explicitly forbidden in 1xx (informational), 204 (no content), and 304 (not modified) responses (section 4.3)
  • all other responses include a message-body, though it may be of zero length (section 4.3)

IIS - can't access page by ip address instead of localhost

Maybe it helps someone too:)

I'm not allowed to post images, so here goes extra link to my blog. Sorry.

IIS webpage by using IP address

In IIS Management : Choose Site, then Bindings.

Add

  • Type : http
  • HostName : Empty
  • Port : 80
  • IP Address : Choose from drop-down menu the IP you need (usually there is only one IP)

wget: unable to resolve host address `http'

The DNS server seems out of order. You can use another DNS server such as 8.8.8.8. Put nameserver 8.8.8.8 to the first line of /etc/resolv.conf.

What is the largest possible heap size with a 64-bit JVM?

The answer clearly depends on the JVM implementation. Azul claim that their JVM

can scale ... to more than a 1/2 Terabyte of memory

By "can scale" they appear to mean "runs wells", as opposed to "runs at all".

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

Accessing session from TWIG template

{{app.session}} refers to the Session object and not the $_SESSION array. I don't think the $_SESSION array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.

Symfony2 is object-oriented, so you should use the Session object to set session attributes and not rely on the array. The Session object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.

So, set your attribute in the session and retrieve the value in your twig template by using the Session object.

// In a controller
$session = $this->get('session');
$session->set('filter', array(
    'accounts' => 'value',
));

// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}

Hope this helps.

Regards,
Matt

How to destroy JWT Tokens on logout?

The JWT is stored on browser, so remove the token deleting the cookie at client side

If you need also to invalidate the token from server side before its expiration time, for example account deleted/blocked/suspended, password changed, permissions changed, user logged out by admin, take a look at Invalidating JSON Web Tokens for some commons techniques like creating a blacklist or rotating tokens

How to convert a set to a list in python?

I'm not sure that you're creating a set with this ([1, 2]) syntax, rather a list. To create a set, you should use set([1, 2]).

These brackets are just envelopping your expression, as if you would have written:

if (condition1
    and condition2 == 3):
    print something

There're not really ignored, but do nothing to your expression.

Note: (something, something_else) will create a tuple (but still no list).

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How do I find which program is using port 80 in Windows?

If you want to be really fancy, download TCPView from Sysinternals:

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, and XP, TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows.

regex pattern to match the end of a string

Use following pattern:

/([^/]+)$

Insert node at a certain position in a linked list C++

Just have something like this where you traverse till the given position and then insert:

void addNodeAtPos(int data, int pos)
{
  Node* prev = new Node();
  Node* curr = new Node();
  Node* newNode = new Node();
  newNode->data = data;

  int tempPos = 0;   // Traverses through the list

  curr = head;      // Initialize current to head;
  if(head != NULL)
  {
    while(curr->next != NULL && tempPos != pos)
    {
        prev = curr;
        curr = curr->next;
        tempPos++;
    }
    if(pos==0)
    {
       cout << "Adding at Head! " << endl;
       // Call function to addNode from head;
    }
    else if(curr->next == NULL && pos == tempPos+1)
    {
      cout << "Adding at Tail! " << endl;
      // Call function to addNode at tail;
    }
    else if(pos > tempPos+1)
      cout << " Position is out of bounds " << endl;
     //Position not valid

    else
    {
        prev->next = newNode;
        newNode->next = curr;
        cout << "Node added at position: " << pos << endl;
    }
 }
 else
 {
    head = newNode;
    newNode->next=NULL;
    cout << "Added at head as list is empty! " << endl;
 }
}

How do I do an OR filter in a Django query?

It is worth to note that it's possible to add Q expressions.

For example:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='[email protected]'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)

queryset = User.objects.filter(query)

This ends up with a query like :

(first_name = 'mark' or email = '[email protected]') and last_name = 'doe'

This way there is no need to deal with or operators, reduce's etc.

What does the keyword "transient" mean in Java?

Transient variables in Java are never serialized.

ng if with angular for string contains

ES2015 UPDATE

ES2015 have String#includes method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true if the needle is found in haystack else returns false.

ng-if="haystack.includes(needle)"

Here, needle is the string that is to be searched in haystack.

See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.


You can use String#indexOf to get the index of the needle in haystack.

  1. If the needle is not present in the haystack -1 is returned.
  2. If needle is present at the beginning of the haystack 0 is returned.
  3. Else the index at which needle is, is returned.

The index can be compared with -1 to check whether needle is found in haystack.

ng-if="haystack.indexOf(needle) > -1" 

For Angular(2+)

*ngIf="haystack.includes(needle)"

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

Difference between BYTE and CHAR in column datatypes

Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.

If you define the field as VARCHAR2(11 BYTE), Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.

By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.

Write-back vs Write-Through caching?

Let's look at this with the help of an example. Suppose we have a direct mapped cache and the write back policy is used. So we have a valid bit, a dirty bit, a tag and a data field in a cache line. Suppose we have an operation : write A ( where A is mapped to the first line of the cache).

What happens is that the data(A) from the processor gets written to the first line of the cache. The valid bit and tag bits are set. The dirty bit is set to 1.

Dirty bit simply indicates was the cache line ever written since it was last brought into the cache!

Now suppose another operation is performed : read E(where E is also mapped to the first cache line)

Since we have direct mapped cache, the first line can simply be replaced by the E block which will be brought from memory. But since the block last written into the line (block A) is not yet written into the memory(indicated by the dirty bit), so the cache controller will first issue a write back to the memory to transfer the block A to memory, then it will replace the line with block E by issuing a read operation to the memory. dirty bit is now set to 0.

So write back policy doesnot guarantee that the block will be the same in memory and its associated cache line. However whenever the line is about to be replaced, a write back is performed at first.

A write through policy is just the opposite. According to this, the memory will always have a up-to-date data. That is, if the cache block is written, the memory will also be written accordingly. (no use of dirty bits)

Javascript AES encryption

JSAES is a powerful implementation of AES in JavaScript. http://point-at-infinity.org/jsaes/

UIAlertView first deprecated IOS 9

I tried the above methods, and no one can show the alert view, only when I put the presentViewController: method in a dispatch_async sentence:

dispatch_async(dispatch_get_main_queue(), ^ { [self presentViewController:alert animated:YES completion:nil]; });

Refer to Alternative to UIAlertView for iOS 9?.

nodeJS - How to create and read session with express

It is cumbersome to interoperate socket.io and connect sessions support. The problem is not because socket.io "hijacks" request somehow, but because certain socket.io transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:

  1. Implement a separate session store for socket.io that stores data in the same format as connect-redis
  2. Make connect session cookie not http-only so it's accessible from client JS
  3. Upon a socket.io connection, send session cookie over socket.io from browser to server
  4. Store the session id in a socket.io connection, and use it to access session data from redis.

How do I hide an element when printing a web page?

CSS FILE

@media print
{
    #pager,
    form,
    .no-print
    {
        display: none !important;
        height: 0;
    }


    .no-print, .no-print *{
        display: none !important;
        height: 0;
    }
}

HTML HEADER

<link href="/theme/css/ui/ui.print.css?version=x.x.x" media="print" rel="stylesheet" type="text/css" >

ELEMENT

<div class="no-print"></div>

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

log4net vs. Nlog

I think the general consensus is that nlog is a bit easier to configure and use. Both are quite capable, though.

How to use format() on a moment.js duration?

You can use numeral.js to format your duration:

numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss

How to put more than 1000 values into an Oracle IN clause

Yes, very weird situation for oracle.

if you specify 2000 ids inside the IN clause, it will fail. this fails:

select ... 
where id in (1,2,....2000) 

but if you simply put the 2000 ids in another table (temp table for example), it will works below query:

select ... 
where id in (select userId 
             from temptable_with_2000_ids ) 

what you can do, actually could split the records into a lot of 1000 records and execute them group by group.

How to make a function wait until a callback has been called using node.js

If you want it very simple and easy, no fancy libraries, to wait for callback functions to be executed in node, before executing some other code, is like this:

//initialize a global var to control the callback state
var callbackCount = 0;
//call the function that has a callback
someObj.executeCallback(function () {
    callbackCount++;
    runOtherCode();
});
someObj2.executeCallback(function () {
    callbackCount++;
    runOtherCode();
});

//call function that has to wait
continueExec();

function continueExec() {
    //here is the trick, wait until var callbackCount is set number of callback functions
    if (callbackCount < 2) {
        setTimeout(continueExec, 1000);
        return;
    }
    //Finally, do what you need
    doSomeThing();
}

How to convert a private key to an RSA private key?

To Convert BEGIN OPENSSH PRIVATE KEY to BEGIN RSA PRIVATE KEY:

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

Build query string for System.Net.HttpClient get

Or simply using my Uri extension

Code

public static Uri AttachParameters(this Uri uri, NameValueCollection parameters)
{
    var stringBuilder = new StringBuilder();
    string str = "?";
    for (int index = 0; index < parameters.Count; ++index)
    {
        stringBuilder.Append(str + parameters.AllKeys[index] + "=" + parameters[index]);
        str = "&";
    }
    return new Uri(uri + stringBuilder.ToString());
}

Usage

Uri uri = new Uri("http://www.example.com/index.php").AttachParameters(new NameValueCollection
                                                                           {
                                                                               {"Bill", "Gates"},
                                                                               {"Steve", "Jobs"}
                                                                           });

Result

http://www.example.com/index.php?Bill=Gates&Steve=Jobs

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

How to enter ssh password using bash?

Double check if you are not able to use keys.

Otherwise use expect:

#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact

CASE (Contains) rather than equal statement

CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

The leading ', ' and trailing ',' are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).

That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.

In addition: don't use 'single quotes' as identifier delimiters; this syntax is deprecated. Use [square brackets] (preferred) or "double quotes" if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx

EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE syntax variant or by using something like IN()):

CASE 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

If you have more values, it might be worthwhile to use a split function, e.g.

USE tempdb;
GO

CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
   RETURN ( SELECT DISTINCT Item FROM
       ( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
         FROM ( SELECT [XML] = CONVERT(XML, '<i>'
         + REPLACE(@List,',', '</i><i>') + '</i>').query('.')
           ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
       WHERE Item IS NOT NULL
   );
GO

CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO

INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');

SELECT t.ID
  FROM dbo.[Table] AS t
  INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
  ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
  GROUP BY t.ID;
GO

Results:

ID
----
1
2
4

Way to create multiline comments in Bash?

Multiline comment in bash

: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines.  Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2 
comment3
END_COMMENT

JavaScript naming conventions

I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

Generate preview image from Video file?

Solution #1 (Older) (not recommended)

Firstly install ffmpeg-php project (http://ffmpeg-php.sourceforge.net/)

And then you can use of this simple code:

<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
    $gd_image = $frame->toGDImage();
    if ($gd_image) {
        imagepng($gd_image, $thumbnail);
        imagedestroy($gd_image);
        echo '<img src="'.$thumbnail.'">';
    }
}
?>

Description: This project use binary extension .so file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg or PHP.


Solution #2 (Update 2018) (recommended)

Firstly install PHP-FFMpeg project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg)

And then you can use of this simple code:

<?php
require 'vendor/autoload.php';

$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';

Description: It's newer and more modern project and works with latest version of FFMpeg and PHP. Note that it's required to proc_open() PHP function.

JQuery - how to select dropdown item based on value

In your case $("#mySelect").val("fg") :)

Postgresql SQL: How check boolean field with null and True,False Value?

  1. select *from table_name where boolean_column is False or Null;

    Is interpreted as "( boolean_column is False ) or (null)".

    It returns only rows where boolean_column is False as the second condition is always false.

  2. select *from table_name where boolean_column is Null or False;

    Same reason. Interpreted as "(boolean_column is Null) or (False)"

  3. select *from table_name where boolean_column is Null or boolean_column = False;

    This one is valid and returns 2 rows: false and null.

I just created the table to confirm. You might have typoed somewhere.

jQuery validate: How to add a rule for regular expression validation?

This worked for me, being one of the validation rules:

    Zip: {
                required: true,
                regex: /^\d{5}(?:[-\s]\d{4})?$/
            }

Hope it helps

Working with TIFFs (import, export) in Python using numpy

You could also use GDAL to do this. I realize that it is a geospatial toolkit, but nothing requires you to have a cartographic product.

Link to precompiled GDAL binaries for windows (assuming windows here) http://www.gisinternals.com/sdk/

To access the array:

from osgeo import gdal

dataset = gdal.Open("path/to/dataset.tiff", gdal.GA_ReadOnly)
for x in range(1, dataset.RasterCount + 1):
    band = dataset.GetRasterBand(x)
    array = band.ReadAsArray()

IE8 support for CSS Media Query

Prior to Internet Explorer 8 there were no support for Media queries. But depending on your case you can try to use conditional comments to target only Internet Explorer 8 and lower. You just have to use a proper CSS files architecture.

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

How to convert Strings to and from UTF8 byte arrays in Java

I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).

Extend contigency table with proportions (percentages)

Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>%
    as.data.frame() %>% 
    rename({{colName}} :=1, Freq=2) %>% 
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","