Programs & Examples On #Words

A word is a single distinct meaningful element of a data. Programming-related questions concerning Microsoft Word should NOT use this tag - use the tag [ms-word] instead. Questions on general usage of Microsoft Word are off-topic for Stack Overflow and should be asked on Super User instead.

Can grep show only words that match search pattern?

Cross distribution safe answer (including windows minGW?)

grep -h "[[:alpha:]]*th[[:alpha:]]*" 'filename' | tr ' ' '\n' | grep -h "[[:alpha:]]*th[[:alpha:]]*"

If you're using older versions of grep (like 2.4.2) which do not include the -o option, then use the above. Else use the simpler to maintain version below.

Linux cross distribution safe answer

grep -oh "[[:alpha:]]*th[[:alpha:]]*" 'filename'

To summarize: -oh outputs the regular expression matches to the file content (and not its filename), just like how you would expect a regular expression to work in vim/etc... What word or regular expression you would be searching for then, is up to you! As long as you remain with POSIX and not perl syntax (refer below)

More from the manual for grep

-o      Print each match, but only the match, not the entire line.
-h      Never print filename headers (i.e. filenames) with output lines.
-w      The expression is searched for as a word (as if surrounded by
         `[[:<:]]' and `[[:>:]]';

The reason why the original answer does not work for everyone

The usage of \w varies from platform to platform, as it's an extended "perl" syntax. As such, those grep installations that are limited to work with POSIX character classes use [[:alpha:]] and not its perl equivalent of \w. See the Wikipedia page on regular expression for more

Ultimately, the POSIX answer above will be a lot more reliable regardless of platform (being the original) for grep

As for support of grep without -o option, the first grep outputs the relevant lines, the tr splits the spaces to new lines, the final grep filters only for the respective lines.

(PS: I know most platforms by now would have been patched for \w.... but there are always those that lag behind)

Credit for the "-o" workaround from @AdamRosenfield answer

Converting a String to a List of Words?

list=mystr.split(" ",mystr.count(" "))

Replace new lines with a comma delimiter with Notepad++?

USE Chrome's Search Bar

1-press CTRL F
2-paste the copied text in search bar
3-press CTRL A followed by CTRL C to copy the text again from search
4-paste in Notepad++
5-replace 'space' with ','

1-click for image
2-click for image

How to get english language word database?

You may check *spell en-GB dictionary used by Mozilla, OpenOffice, plenty of other software.

Converting a sentence string to a string array of words in Java

String.split() will do most of what you want. You may then need to loop over the words to pull out any punctuation.

For example:

String s = "This is a sample sentence.";
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
    // You may want to check for a non-word character before blindly
    // performing a replacement
    // It may also be necessary to adjust the character class
    words[i] = words[i].replaceAll("[^\\w]", "");
}

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

Selecting with complex criteria from pandas.DataFrame

And remember to use parenthesis!

Keep in mind that & operator takes a precedence over operators such as > or < etc. That is why

4 < 5 & 6 > 4

evaluates to False. Therefore if you're using pd.loc, you need to put brackets around your logical statements, otherwise you get an error. That's why do:

df.loc[(df['A'] > 10) & (df['B'] < 15)]

instead of

df.loc[df['A'] > 10 & df['B'] < 15]

which would result in

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

centos: Another MySQL daemon already running with the same unix socket

My solution to this was a left over mysql.sock in the /var/lib/mysql/ directory from a hard shutdown. Mysql thought it was already running when it was not running.

TypeError: 'str' object cannot be interpreted as an integer

x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

P.S. Add function int()

How to write loop in a Makefile?

THE major reason to use make IMHO is the -j flag. make -j5 will run 5 shell commands at once. This is good if you have 4 CPUs say, and a good test of any makefile.

Basically, you want make to see something like:

.PHONY: all
all: job1 job2 job3

.PHONY: job1
job1: ; ./a.out 1

.PHONY: job2
job2: ; ./a.out 2

.PHONY: job3
job3: ; ./a.out 3

This is -j friendly (a good sign). Can you spot the boiler-plate? We could write:

.PHONY: all job1 job2 job3
all: job1 job2 job3
job1 job2 job3: job%:
    ./a.out $*

for the same effect (yes, this is the same as the previous formulation as far as make is concerned, just a bit more compact).

A further bit of parameterisation so that you can specify a limit on the command-line (tedious as make does not have any good arithmetic macros, so I'll cheat here and use $(shell ...))

LAST := 1000
NUMBERS := $(shell seq 1 ${LAST})
JOBS := $(addprefix job,${NUMBERS})
.PHONY: all ${JOBS}
all: ${JOBS} ; echo "$@ success"
${JOBS}: job%: ; ./a.out $*

You run this with make -j5 LAST=550, with LAST defaulting to 1000.

jQuery changing font family and font size

In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class.
don't know if that's an option in your case though.

Getting a random value from a JavaScript array

Prototype Method

If you plan on getting a random value a lot, you might want to define a function for it.

First, put this in your code somewhere:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

Now:

[1,2,3,4].sample() //=> a random element

Code released into the public domain under the terms of the CC0 1.0 license.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Came here looking for a solution to a similar issue, which I just introduced by changing Schannel settings of our IIS server using "IIS Crypto" by Nartac... By disabling the SHA-1 hash, the local SQL Server was not able to be reached anymore, even though I didn't use an encrypted connection (not useful for an ASP.Net site accessing a local SQL Express instance using shared memory).

The 'SHA' hash algorithm needs to be active for SQL Server to connect

Thanks Count Zero for pointing me in the right direction :-)

So, lesson learned: do not disable SHA-1 on your IIS server if you have a local SQL Server instance.

How to enable file upload on React's Material UI simple input?

It is work for me ("@material-ui/core": "^4.3.1"):

    <Fragment>
        <input
          color="primary"
          accept="image/*"
          type="file"
          onChange={onChange}
          id="icon-button-file"
          style={{ display: 'none', }}
        />
        <label htmlFor="icon-button-file">
          <Button
            variant="contained"
            component="span"
            className={classes.button}
            size="large"
            color="primary"
          >
            <ImageIcon className={classes.extendedIcon} />
          </Button>
        </label>
      </Fragment>

When to use "ON UPDATE CASCADE"

  1. Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10 all children parent_id's of 10 will also be updated to 20

  2. If you don't update the field the foreign key refers to, this setting is not needed

  3. Can't think of any other use.

  4. You can't do that as the foreign key constraint would fail.

How to test if a string is JSON or not?

Well... It depends the way you are receiving your data. I think the server is responding with a JSON formated string (using json_encode() in PHP,e.g.). If you're using JQuery post and set response data to be a JSON format and it is a malformed JSON, this will produce an error:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        //Supposing x is a JSON property...
        alert(response.x);

  },
  dataType: 'json',
  //Invalid JSON
  error: function (){ alert("error!"); }
});

But, if you're using the type response as text, you need use $.parseJSON. According jquery site: "Passing in a malformed JSON string may result in an exception being thrown". Thus your code will be:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        try {
            parsedData = JSON.parse(response);
        } catch (e) {
            // is not a valid JSON string
        }

  },
  dataType: 'text',
});

How to determine an interface{} value's "real" type?

Here is an example of decoding a generic map using both switch and reflection, so if you don't match the type, use reflection to figure it out and then add the type in next time.

var data map[string]interface {}

...

for k, v := range data {
    fmt.Printf("pair:%s\t%s\n", k, v)   

    switch t := v.(type) {
    case int:
        fmt.Printf("Integer: %v\n", t)
    case float64:
        fmt.Printf("Float64: %v\n", t)
    case string:
        fmt.Printf("String: %v\n", t)
    case bool:
        fmt.Printf("Bool: %v\n", t)
    case []interface {}:
        for i,n := range t {
            fmt.Printf("Item: %v= %v\n", i, n)
        }
    default:
        var r = reflect.TypeOf(t)
        fmt.Printf("Other:%v\n", r)             
    }
}

Perform debounce in React.js

If you are using redux you can do this in a very elegant way with middleware. You can define a Debounce middleware as:

var timeout;
export default store => next => action => {
  const { meta = {} } = action;
  if(meta.debounce){
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      next(action)
    }, meta.debounce)
  }else{
    next(action)
  }
}

You can then add debouncing to action creators, such as:

export default debouncedAction = (payload) => ({
  type : 'DEBOUNCED_ACTION',
  payload : payload,
  meta : {debounce : 300}
}

There's actually already middleware you can get off npm to do this for you.

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Solution to the original question

You called a non-static method statically. To make a public function static in the model, would look like this:

public static function {
  
}

In General:

Post::get()

In this particular instance:

Post::take(2)->get()

One thing to be careful of, when defining relationships and scope, that I had an issue with that caused a 'non-static method should not be called statically' error is when they are named the same, for example:

public function category(){
    return $this->belongsTo('App\Category');
}

public function scopeCategory(){
    return $query->where('category', 1);
}

When I do the following, I get the non-static error:

Event::category()->get();

The issue, is that Laravel is using my relationship method called category, rather than my category scope (scopeCategory). This can be resolved by renaming the scope or the relationship. I chose to rename the relationship:

public function cat(){
    return $this->belongsTo('App\Category', 'category_id');
}

Please observe that I defined the foreign key (category_id) because otherwise Laravel would have looked for cat_id instead, and it wouldn't have found it, as I had defined it as category_id in the database.

How to use hex color values

extension UIColor {

      convenience init(hex: Int, alpha: Double = 1.0) {

      self.init(red: CGFloat((hex>>16)&0xFF)/255.0, green:CGFloat((hex>>8)&0xFF)/255.0, blue: CGFloat((hex)&0xFF)/255.0, alpha:  CGFloat(255 * alpha) / 255)
     }
}

Use this extension like:

let selectedColor = UIColor(hex: 0xFFFFFF)
let selectedColor = UIColor(hex: 0xFFFFFF, alpha: 0.5)

How to use the TextWatcher class in Android?

For use of the TextWatcher...

et1.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

        // TODO Auto-generated method stub
    }
});

JavaScript Promises - reject vs. throw

The difference is ternary operator

  • You can use
return condition ? someData : Promise.reject(new Error('not OK'))
  • You can't use
return condition ? someData  : throw new Error('not OK')

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);
    }

"Gradle Version 2.10 is required." Error

Latest gradle

Download the latest gradle-3.3-all.zip from

http://gradle.org/gradle-download/

1.download from Complete Distribution link

2.open in android studio file ->settings ->gradle

3.open the path and paste the downloaded zip folder gradle-3.3 in that folder

4.change your gradle 2.8 to gradle 3.3 in file ->settings ->gradle

5.Or you can change your gradle wrapper in the project

6.edit YourProject\gradle\wrapper\gradle-wrapper.properties file and edit the field distributionUrl in to

distributionUrl= https://services.gradle.org/distributions/gradle-3.0-all.zip

shown in android studio's gradle files

How do I change JPanel inside a JFrame on the fly?

The layout.replace() answer only exists/works on the GroupLayout Manager.

Other LayoutManagers (CardLayout, BoxLayout etc) do NOT support this feature, but require you to first RemoveLayoutComponent( and then AddLayoutComponent( back again. :-) [Just setting the record straight]

Multiple submit buttons in the same form calling different Servlets

You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.

function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});

Delete directory with files in it?

Litle bit modify of alcuadrado's code - glob don't see files with name from points like .htaccess so I use scandir and script deletes itself - check __FILE__.

function deleteDir($dirPath) {
    if (!is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = scandir($dirPath); 
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        if (is_dir($dirPath.$file)) {
            deleteDir($dirPath.$file);
        } else {
            if ($dirPath.$file !== __FILE__) {
                unlink($dirPath.$file);
            }
        }
    }
    rmdir($dirPath);
}

Load different application.yml in SpringBoot Test

A simple working configuration using

@TestPropertySource and properties

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {"spring.config.location=classpath:another.yml"})
public class TestClass {


    @Test

    public void someTest() {
    }
}

How do I check if the mouse is over an element in jQuery?

Thanks to both of you. At some point I had to give up on trying to detect if the mouse was still over the element. I know it's possible, but may require too much code to accomplish.

It took me a little while but I took both of your suggestions and came up with something that would work for me.

Here's a simplified (but functional) example:

$("[HoverHelp]").hover (
    function () {
        var HelpID = "#" + $(this).attr("HoverHelp");
        $(HelpID).css("top", $(this).position().top + 25);
        $(HelpID).css("left", $(this).position().left);
        $(HelpID).attr("fadeout", "false");
        $(HelpID).fadeIn();
    },
    function () {
        var HelpID = "#" + $(this).attr("HoverHelp");
        $(HelpID).attr("fadeout", "true");
        setTimeout(function() { if ($(HelpID).attr("fadeout") == "true") $(HelpID).fadeOut(); }, 100);
    }
);

And then to make this work on some text this is all I have to do:

<div id="tip_TextHelp" style="display: none;">This help text will show up on a mouseover, and fade away 100 milliseconds after a mouseout.</div>

This is a <span class="Help" HoverHelp="tip_TextHelp">mouse over</span> effect.

Along with a lot of fancy CSS, this allows some very nice mouseover help tooltips. By the way, I needed the delay in the mouseout because of tiny gaps between checkboxes and text that was causing the help to flash as you move the mouse across. But this works like a charm. I also did something similar for the focus/blur events.

Error: Jump to case label

C++11 standard on jumping over some initializations

JohannesD gave an explanation, now for the standards.

The C++11 N3337 standard draft 6.7 "Declaration statement" says:

3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

[ Example:

void f() {
   // ...
  goto lx;    // ill-formed: jump into scope of a
  // ...
ly:
  X a = 1;
  // ...
lx:
  goto ly;    // OK, jump implies destructor
              // call for a followed by construction
              // again immediately following label ly
}

— end example ]

As of GCC 5.2, the error message now says:

crosses initialization of

C

C allows it: c99 goto past initialization

The C99 N1256 standard draft Annex I "Common warnings" says:

2 A block with initialization of an object that has automatic storage duration is jumped into

android: changing option menu items programmatically

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.calendar, menu);
        if(show_list == true) {         

        if(!locale.equalsIgnoreCase("sk")) menu.findItem(R.id.action_cyclesn).setVisible(false);

        return true;
    }

Removing trailing newline character from fgets() input

 for(int i = 0; i < strlen(Name); i++ )
{
    if(Name[i] == '\n') Name[i] = '\0';
}

You should give it a try. This code basically loop through the string until it finds the '\n'. When it's found the '\n' will be replaced by the null character terminator '\0'

Note that you are comparing characters and not strings in this line, then there's no need to use strcmp():

if(Name[i] == '\n') Name[i] = '\0';

since you will be using single quotes and not double quotes. Here's a link about single vs double quotes if you want to know more

How to have an auto incrementing version number (Visual Studio)?

If you add an AssemblyInfo class to your project and amend the AssemblyVersion attribute to end with an asterisk, for example:

[assembly: AssemblyVersion("2.10.*")]

Visual studio will increment the final number for you according to these rules (thanks galets, I had that completely wrong!)

To reference this version in code, so you can display it to the user, you use reflection. For example,

Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
DateTime buildDate = new DateTime(2000, 1, 1)
                        .AddDays(version.Build).AddSeconds(version.Revision * 2);
string displayableVersion = $"{version} ({buildDate})";

Three important gotchas that you should know

From @ashes999:

It's also worth noting that if both AssemblyVersion and AssemblyFileVersion are specified, you won't see this on your .exe.

From @BrainSlugs83:

Setting only the 4th number to be * can be bad, as the version won't always increment. The 3rd number is the number of days since the year 2000, and the 4th number is the number of seconds since midnight (divided by 2) [IT IS NOT RANDOM]. So if you built the solution late in a day one day, and early in a day the next day, the later build would have an earlier version number. I recommend always using X.Y.* instead of X.Y.Z.* because your version number will ALWAYS increase this way.

Newer versions of Visual Studio give this error:

(this thread begun in 2009)

The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation.

See this SO answer which explains how to remove determinism (https://stackoverflow.com/a/58101474/1555612)

How to increment datetime by custom months in python without using library

A solution without the use of calendar:

def add_month_year(date, years=0, months=0):
    year, month = date.year + years, date.month + months + 1
    dyear, month = divmod(month - 1, 12)
    rdate = datetime.date(year + dyear, month + 1, 1) - datetime.timedelta(1)
    return rdate.replace(day = min(rdate.day, date.day))

How can I autoplay a video using the new embed code style for Youtube?

None of the above worked for me in the current youtube embed. Try this, it actually worked for me :)

Hope it helps!

<iframe width="925" height="315" src="https://www.youtube.com/embed/iD5zxjySOzw?rel=0&amp;autoplay=1&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>

Java method to sum any number of ints

public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

Rename file with Git

Note that, from March 15th, 2013, you can move or rename a file directly from GitHub:

(you don't even need to clone that repo, git mv xx and git push back to GitHub!)

renaming

You can also move files to entirely new locations using just the filename field.
To navigate down into a folder, just type the name of the folder you want to move the file into followed by /.
The folder can be one that’s already part of your repository, or it can even be a brand-new folder that doesn’t exist yet!

moving

Integrity constraint violation: 1452 Cannot add or update a child row:

Maybe you have some rows in the table that you want to create de FK.

Run the migration with foreign_key_checks OFF Insert only those records that have corresponding id field in contents table.

Chmod recursively

Adding executable permissions, recursively, to all files (not folders) within the current folder with sh extension:

find . -name '*.sh' -type f | xargs chmod +x

* Notice the pipe (|)

How to get rid of blank pages in PDF exported from SSRS

On the properties tab of the report (myReport.rdlc), change the "Keep Together" attribute to False. I've been struggling with this issue for a while and this seems to have solved my issue. enter image description here

jdk7 32 bit windows version to download

Go to the download page and download the Windows x86 version with filename jdk-7-windows-i586.exe.

What is the difference between --save and --save-dev?

Clear answers are already provided. But it's worth mentioning how devDependencies affects installing packages:

By default, npm install will install all modules listed as dependencies in package.json . With the --production flag (or when the NODE_ENV environment variable is set to production ), npm will not install modules listed in devDependencies .

See: https://docs.npmjs.com/cli/install

How to asynchronously call a method in Java

This is not really related but if I was to asynchronously call a method e.g. matches(), I would use:

private final static ExecutorService service = Executors.newFixedThreadPool(10);
public static Future<Boolean> matches(final String x, final String y) {
    return service.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return x.matches(y);
        }

    });
}

Then to call the asynchronous method I would use:

String x = "somethingelse";
try {
    System.out.println("Matches: "+matches(x, "something").get());
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

I have tested this and it works. Just thought it may help others if they just came for the "asynchronous method".

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

using BETWEEN in WHERE condition

$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');

this is my solution

How to stop the task scheduled in java.util.Timer class

Keep a reference to the timer somewhere, and use:

timer.cancel();
timer.purge();

to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

In Android Studio, if you open the Design window for the app, there is error message about Gradle being not synched properly. Next to the error, there is a 'Try Again' button. If you click on that, Android studio tries to sycn up again.

That worked for me.

C# equivalent of C++ map<string,double>

This code is all you need:

   static void Main(string[] args) {
        String xml = @"
            <transactions>
                <transaction name=""Fred"" amount=""5,20"" />
                <transaction name=""John"" amount=""10,00"" />
                <transaction name=""Fred"" amount=""3,00"" />
            </transactions>";

        XDocument xmlDocument = XDocument.Parse(xml);

        var query = from x in xmlDocument.Descendants("transaction")
                    group x by x.Attribute("name").Value into g
                    select new { Name = g.Key, Amount = g.Sum(t => Decimal.Parse(t.Attribute("amount").Value)) };

        foreach (var item in query) {
            Console.WriteLine("Name: {0}; Amount: {1:C};", item.Name, item.Amount);
        }
    }

And the content is:

Name: Fred; Amount: R$ 8,20;
Name: John; Amount: R$ 10,00;

That is the way of doing this in C# - in a declarative way!

I hope this helps,

Ricardo Lacerda Castelo Branco

How to select rows for a specific date, ignoring time in SQL Server

I know this is an old topic, but I managed to do it in this simple way:

select count(*) from `tablename`
where date(`datecolumn`) = '2021-02-17';

Changing background color of selected cell?

var last_selected:IndexPath!

define last_selected:IndexPath inside the class

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! Cell
    cell.contentView.backgroundColor = UIColor.lightGray
    cell.txt.textColor = UIColor.red

    if(last_selected != nil){
        //deselect
        let deselect_cell = tableView.cellForRow(at: last_selected) as! Cell
        deselect_cell.contentView.backgroundColor = UIColor.white
        deselect_cell.txt.textColor = UIColor.black
    }

    last_selected = indexPath
}

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

How to put an image in div with CSS?

This answer by Jaap :

<div class="image"></div>?

and in CSS :

div.image {
   content:url(http://placehold.it/350x150);
}?

you can try it on this link : http://jsfiddle.net/XAh2d/

this is a link about css content http://css-tricks.com/css-content/

This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)

'str' object does not support item assignment in Python

Hi you should try the string split method:

i = "Hello world"
output = i.split()

j = 'is not enough'

print 'The', output[1], j

Selenium WebDriver: Wait for complex page with JavaScript to load

I had a same issue. This solution works for me from WebDriverDoku:

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

Removing "http://" from a string

preg_replace('/^[^:\/?]+:\/\//','',$url); 

some results:

input: http://php.net/preg_replace output: php.net/preg_replace  input: https://www.php.net/preg_replace output: www.php.net/preg_replace  input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace  input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com 

Using jQuery to build table rows from AJAX response(json)

Use .append instead of .html

var response = "[{
      "rank":"9",
      "content":"Alon",
      "UID":"5"
     },
     {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
    }]";

// convert string to JSON
response = $.parseJSON(response);

$(function() {
    $.each(response, function(i, item) {
        var $tr = $('<tr>').append(
            $('<td>').text(item.rank),
            $('<td>').text(item.content),
            $('<td>').text(item.UID)
        ); //.appendTo('#records_table');
        console.log($tr.wrap('<p>').html());
    });
});

Detect click inside/outside of element with single event handler

Instead of using the body you could create a curtain with z-index of 100 (to pick a number) and give the inside element a higher z-index while all other elements have a lower z-index than the curtain.

See working example here: http://jsfiddle.net/Flandre/6JvFk/

jQuery:

$('#curtain').on("click", function(e) {

    $(this).hide();
    alert("clicked ouside of elements that stand out");

});

CSS:

.aboveCurtain
{
    z-index: 200; /* has to have a higher index than the curtain */
    position: relative;
    background-color: pink;
}

#curtain
{
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    background-color: black;
    width: 100%;
    z-index:100;   
    opacity:0.5 /* change opacity to 0 to make it a true glass effect */
}

Limitations of SQL Server Express

If you switch from Web to Express you will no longer be able to use the SQL Server Agent service so you need to set up a different scheduler for maintenance and backups.

Copying a HashMap in Java

In Java, when you write:

Object objectA = new Object();
Object objectB = objectA;

objectA and objectB are the same and point to the same reference. Changing one will change the other. So if you change the state of objectA (not its reference) objectB will reflect that change too.

However, if you write:

objectA = new Object()

Then objectB is still pointing to the first object you created (original objectA) while objectA is now pointing to a new Object.

Laravel: How do I parse this json data in view blade?

The catch all for me is taking an object, encoding it, and then passing the string into a javascript script tag. To do this you have to do some replacements.

First replace every \ with a double slash \\ and then every quote" with a \".

$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
  ->with('payload', $payload)

Then in the blade template

@if(isset($payload))
<script>
  window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif

This basically allows you to take an object on the php side, and then have an object on the javascript side.

Android – Listen For Incoming SMS Messages

The accepted answer is correct and works on older versions of Android where Android OS asks for permissions at the app install, However on newer versions Android it doesn't work straight away because newer Android OS asks for permissions during runtime when the app requires that feature. Therefore in order to receive SMS on newer versions of Android using technique mentioned in accepted answer programmer must also implement code that will check and ask for permissions from user during runtime. In this case permissions checking functionality/code can be implemented in onCreate() of app's first activity. Just copy and paste following two methods in your first activity and call checkForSmsReceivePermissions() method at the end of onCreate().

    void checkForSmsReceivePermissions(){
    // Check if App already has permissions for receiving SMS
    if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.RECEIVE_SMS") == PackageManager.PERMISSION_GRANTED) {
        // App has permissions to listen incoming SMS messages
        Log.d("adnan", "checkForSmsReceivePermissions: Allowed");
    } else {
        // App don't have permissions to listen incoming SMS messages
        Log.d("adnan", "checkForSmsReceivePermissions: Denied");

        // Request permissions from user 
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECEIVE_SMS}, 43391);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 43391){
        if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Log.d("adnan", "Sms Receive Permissions granted");
        } else {
            Log.d("adnan", "Sms Receive Permissions denied");
        }
    }
}

Change icon on click (toggle)

Here is a very easy way of doing that

 $(function () {
    $(".glyphicon").unbind('click');
    $(".glyphicon").click(function (e) {
        $(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down");
});

Hope this helps :D

How to get a substring of text?

if you need it in rails you can use first (source code)

'1234567890'.first(5) # => "12345"

there is also last (source code)

'1234567890'.last(2) # => "90"

alternatively check from/to (source code):

"hello".from(1).to(-2) # => "ell"

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".

Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."

My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.

As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.

Swift error : signal SIGABRT how to solve it

A common reason for this type of error is that you might have changed the name of your IBOutlet or IBAction you can simply check this by going to source code.

Click on the main.storyboard and then select open as and then select source code enter image description here

source code will open

and then check whether there is the name of the iboutlet or ibaction that you have changed , if there is then select the part and delete it and then again create iboutlet or ibaction. This should resolve your problem

How to get row data by clicking a button in a row in an ASP.NET gridview

            <asp:Button  ID="btnEdit" Text="Edit" runat="server"  OnClick="btnEdit_Click" CssClass="CoolButtons"/>


protected void btnEdit_Click(object sender, EventArgs e)
{
       Button btnEdit = (Button)sender;
       GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
      TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
      HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
      TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
     //Get the gridview Row Details
}

And Same As for Delete button

PHP multidimensional array search by value

Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):

function searcharray($value, $key, $array) {
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
           return $k;
       }
   }
   return null;
}

Usage: $results = searcharray('searchvalue', searchkey, $array);

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

Below section add in to your web.config

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
       <dependentAssembly>
           <assemblyIdentity name="Newtonsoft.Json"
               publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
           <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
       </dependentAssembly>
    </assemblyBinding>
</runtime>

How to round down to nearest integer in MySQL?

It can be done in the following two ways:

  • select floor(desired_field_value) from table
  • select round(desired_field_value-0.5) from table

The 2nd-way explanation: Assume 12345.7344 integer. So, 12345.7344 - 0.5 = 12345.2344 and rounding off the result will be 12345.

How to check if a table exists in MS Access for vb macros

Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))

SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

Understanding INADDR_ANY for socket programming

  1. bind() of INADDR_ANY does NOT "generate a random IP". It binds the socket to all available interfaces.

  2. For a server, you typically want to bind to all interfaces - not just "localhost".

  3. If you wish to bind your socket to localhost only, the syntax would be my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");, then call bind(my_socket, (SOCKADDR *) &my_sockaddr, ...).

  4. As it happens, INADDR_ANY is a constant that happens to equal "zero":

    http://www.castaglia.org/proftpd/doc/devel-guide/src/include/inet.h.html

    # define INADDR_ANY ((unsigned long int) 0x00000000)
    ...
    # define INADDR_NONE    0xffffffff
    ...
    # define INPORT_ANY 0
    ...
    
  5. If you're not already familiar with it, I urge you to check out Beej's Guide to Sockets Programming:

    http://beej.us/guide/bgnet/

Since people are still reading this, an additional note:

man (7) ip:

When a process wants to receive new incoming packets or connections, it should bind a socket to a local interface address using bind(2).

In this case, only one IP socket may be bound to any given local (address, port) pair. When INADDR_ANY is specified in the bind call, the socket will be bound to all local interfaces.

When listen(2) is called on an unbound socket, the socket is automatically bound to a random free port with the local address set to INADDR_ANY.

When connect(2) is called on an unbound socket, the socket is automatically bound to a random free port or to a usable shared port with the local address set to INADDR_ANY...

There are several special addresses: INADDR_LOOPBACK (127.0.0.1) always refers to the local host via the loopback device; INADDR_ANY (0.0.0.0) means any address for binding...

Also:

bind() — Bind a name to a socket:

If the (sin_addr.s_addr) field is set to the constant INADDR_ANY, as defined in netinet/in.h, the caller is requesting that the socket be bound to all network interfaces on the host. Subsequently, UDP packets and TCP connections from all interfaces (which match the bound name) are routed to the application. This becomes important when a server offers a service to multiple networks. By leaving the address unspecified, the server can accept all UDP packets and TCP connection requests made for its port, regardless of the network interface on which the requests arrived.

ffprobe or avprobe not found. Please install one

  1. update your version of youtube-dl to the lastest as older version might not support palylists.

    sudo youtube-dl -U if u installed via .deb

    sudo pip install --upgrade youtube_dl via pip

  2. use this to download the playlist as an MP3 file

    youtube-dl --extract-audio --audio-format mp3 #url_to_playlist

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

List of all users that can connect via SSH

Read man sshd_config for more details, but you can use the AllowUsers directive in /etc/ssh/sshd_config to limit the set of users who can login.

e.g.

AllowUsers boris

would mean that only the boris user could login via ssh.

How do I get NuGet to install/update all the packages in the packages.config?

Don't know since when, but in VS2019 you can do it in an easier way:

  1. right click solution in Solution Explorer
  2. select Manage Nuget Packages for Solution
  3. there are 4 tabs, Browse, Installed, Updates, Consolidate
  4. the Consolidate shows if there is any projects using different version of packages (and in most cases, that's why we want to update all the packages)
  5. the Updates shows if there is any update available in ANY projects. Select all and click update, the job will be done.

Object cannot be cast from DBNull to other types

You need to check for DBNull, not null. Additionally, two of your three ReplaceNull methods don't make sense. double and DateTime are non-nullable, so checking them for null will always be false...

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

How to express a One-To-Many relationship in Django

To be more clear - there's no OneToMany in Django, only ManyToOne - which is Foreignkey described above. You can describe OneToMany relation using Foreignkey but that is very inexpressively.

A good article about it: https://amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/

Detect if the app was launched/opened from a push notification

If you are running iOS 13 or above use this code in your SceneDelegate:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let notificationResponse = connectionOptions.notificationResponse else { return }
    
    let pushTitle = notificationResponse.notification.request.content.title
    let pushSubtitle = notificationResponse.notification.request.content.subtitle
    let pushBody = notificationResponse.notification.request.content.body
    
    // do your staff here
}

Batch files - number of command line arguments

The function :getargc below may be what you're looking for.

@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof

:getargc
    set getargc_v0=%1
    set /a "%getargc_v0% = 0"
:getargc_l0
    if not x%2x==xx (
        shift
        set /a "%getargc_v0% = %getargc_v0% + 1"
        goto :getargc_l0
    )
    set getargc_v0=
    goto :eof

It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.

It also uses a nifty trick, passing the name of the return variable to be set by the function.

The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:

C:\Here> xx.cmd 1 2 3 4 5
    Count is 5
    Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
    Count is 11
    Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
    Count is 1
    Args are 1
C:\Here> xx.cmd
    Count is 0
    Args are
C:\Here> xx.cmd 1 2 "3 4 5"
    Count is 3
    Args are 1 2 "3 4 5"

How to make EditText not editable through XML in Android?

Use this simple code:

textView.setKeyListener(null);

It works.

Edit : To add KeyListener later, do following

1 : set key listener to tag of textView

textView.setTag(textView.getKeyListener());
textView.setKeyListener(null);

2 : get key listener from tag and set it back to textView

textView.setKeyListener((KeyListener) textView.getTag());

Check file uploaded is in csv format

So I ran into this today.

Was attempting to validate an uploaded CSV file's MIME type by looking at $_FILES['upload_file']['type'], but for certain users on various browsers (and not necessarily the same browsers between said users; for instance it worked fine for me in FF but for another user it didn't work on FF) the $_FILES['upload_file']['type'] was coming up as "application/vnd.ms-excel" instead of the expected "text/csv" or "text/plain".

So I resorted to using the (IMHO) much more reliable finfo_* functions something like this:

$acceptable_mime_types = array('text/plain', 'text/csv', 'text/comma-separated-values');

if (!empty($_FILES) && array_key_exists('upload_file', $_FILES) && $_FILES['upload_file']['error'] == UPLOAD_ERR_OK) {
    $tmpf = $_FILES['upload_file']['tmp_name'];

    // Make sure $tmpf is kosher, then:

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $tmpf);

    if (!in_array($mime_type, $acceptable_mime_types)) {
        // Unacceptable mime type.
    }
}

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Maven needs to be able to access various Maven repositories in order to download artifacts to the local repository. If your local system is accessing the Internet through a proxy host, you might need to explicitly specify the proxy settings for Maven by editing the Maven settings.xml file. Maven builds ignore the IDE proxy settings that are set in the Options window. For many common cases, just passing -Djava.net.useSystemProxies=true to Maven should suffice to download artifacts through the system's configured proxy. NetBeans 7.1 will offer to configure this flag for you if it detects a possible proxy problem. https://netbeans.org/bugzilla/show_bug.cgi?id=194916 has discussion.

Polynomial time and exponential time

o(n sequre) is polynimal time complexity while o(2^n) is exponential time complexity if p=np when best case , in the worst case p=np not equal becasue when input size n grow so long or input sizer increase so longer its going to worst case and handling so complexity growth rate increase and depend on n size of input when input is small it is polynimal when input size large and large so p=np not equal it means growth rate depend on size of input "N". optimization, sat, clique, and independ set also met in exponential to polynimal.

How to access ssis package variables inside script component

  • On the front properties page of the variable script, amend the ReadOnlyVariables (or ReadWriteVariables) property and select the variables you are interested in. This will enable the selected variables within the script task
  • Within code you will now have access to read the variable as

    string myString = Variables.MyVariableName.ToString();

How do I script a "yes" response for installing programs?

Although this may be more complicated/heavier-weight than you want, one very flexible way to do it is using something like Expect (or one of the derivatives in another programming language).

Expect is a language designed specifically to control text-based applications, which is exactly what you are looking to do. If you end up needing to do something more complicated (like with logic to actually decide what to do/answer next), Expect is the way to go.

Show/hide image with JavaScript

HTML

<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>

JavaScript:

document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.display = "block";
}

CSS:

#theImage { display:none; }

Div with margin-left and width:100% overflowing on the right side

Just remove the width from both divs.

A div is a block level element and will use all available space (unless you start floating or positioning them) so the outer div will automatically be 100% wide and the inner div will use all remaining space after setting the left margin.

I have added an example with a textarea on jsfiddle.

Updated example with an input.

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

How best to include other scripts?

This should work reliably:

source_relative() {
 local dir="${BASH_SOURCE%/*}"
 [[ -z "$dir" ]] && dir="$PWD"
 source "$dir/$1"
}

source_relative incl.sh

How can I view the contents of an ElasticSearch index?

You can even add the size of the terms (indexed terms). Have a look at Elastic Search: how to see the indexed data

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

How to comment and uncomment blocks of code in the Office VBA Editor

In the VBA editor, go to View, Toolbars, Customise... or right click on the tool bar and select Customise...

Under the Commands tab, select the Edit menu on the left.

Then approximately two thirds of the way down there's two icons, Comment Block and Uncomment Block.

Drag and drop these onto your toolbar and then you have easy access to highlight a block of code, and comment it out and uncomment with the click of a button!


See GauravSingh's answer if you want to assign keyboard shortcuts.

Fastest way to list all primes below N

Sorry to bother but erat2() has a serious flaw in the algorithm.

While searching for the next composite, we need to test odd numbers only. q,p both are odd; then q+p is even and doesn't need to be tested, but q+2*p is always odd. This eliminates the "if even" test in the while loop condition and saves about 30% of the runtime.

While we're at it: instead of the elegant 'D.pop(q,None)' get and delete method use 'if q in D: p=D[q],del D[q]' which is twice as fast! At least on my machine (P3-1Ghz). So I suggest this implementation of this clever algorithm:

def erat3( ):
    from itertools import islice, count

    # q is the running integer that's checked for primeness.
    # yield 2 and no other even number thereafter
    yield 2
    D = {}
    # no need to mark D[4] as we will test odd numbers only
    for q in islice(count(3),0,None,2):
        if q in D:                  #  is composite
            p = D[q]
            del D[q]
            # q is composite. p=D[q] is the first prime that
            # divides it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next
            # multiple of its witnesses to prepare for larger
            # numbers.
            x = q + p+p        # next odd(!) multiple
            while x in D:      # skip composites
                x += p+p
            D[x] = p
        else:                  # is prime
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations.
            D[q*q] = q
            yield q

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

How to set div's height in css and html

<div style="height: 100px;"> </div>

OR

<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px;  }

Why do multiple-table joins produce duplicate rows?

If one of the tables M, S, D, or H has more than one row for a given Id (if just the Id column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).

References:

Related Question on MSDN Forum

How do you set autocommit in an SQL Server session?

Autocommit is SQL Server's default transaction management mode. (SQL 2000 onwards)

Ref: Autocommit Transactions

How to get all key in JSON object (javascript)

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "[email protected]" };

for (x in jsonData) {   
  console.log(x +" => "+ jsonData[x]);  
  alert(x +" => "+  jsonData[x]);  
  }

How do I escape special characters in MySQL?

MySQL has the string function QUOTE, and it should solve this problem:

Serializing with Jackson (JSON) - getting "No serializer found"?

Please use this at class level for the bean:

@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})

How to Set the Background Color of a JButton on the Mac OS

If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:

 try {
    UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
 } catch (Exception e) {
            e.printStackTrace();
 }

That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Besides changing it to Console (/SUBSYSTEM:CONSOLE) as others have said, you may need to change the entry point in Properties -> Linker -> Advanced -> Entry Point. Set it to mainCRTStartup.

It seems that Visual Studio might be searching for the WinMain function instead of main, if you don't specify otherwise.

jQuery: Change button text on click

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore2');
    if($this.hasClass('SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

This should do it. You have to make sure you toggle the correct class and take out the "." from the hasClass

http://jsfiddle.net/V4u5X/2/

Background color of text in SVG

You could use a filter to generate the background.

_x000D_
_x000D_
<svg width="100%" height="100%">
  <defs>
    <filter x="0" y="0" width="1" height="1" id="solid">
      <feFlood flood-color="yellow" result="bg" />
      <feMerge>
        <feMergeNode in="bg"/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
  </defs>
  <text filter="url(#solid)" x="20" y="50" font-size="50">solid background</text>
</svg>
_x000D_
_x000D_
_x000D_

How can I use xargs to copy files that have spaces and quotes in their names?

If find and xarg versions on your system doesn't support -print0 and -0 switches (for example AIX find and xargs) you can use this terribly looking code:

 find . -name "*foo*" | sed -e "s/'/\\\'/g" -e 's/"/\\"/g' -e 's/ /\\ /g' | xargs cp /your/dest

Here sed will take care of escaping the spaces and quotes for xargs.

Tested on AIX 5.3

How to run a script at a certain time on Linux?

Usually in Linux you use crontab for this kind of scduled tasks. But you have to specify the time when you "setup the timer" - so if you want it to be configurable in the file itself, you will have to create some mechanism to do that.

But in general, you would use for example:

30 1 * * 5 /path/to/script/script.sh

Would execute the script every Friday at 1:30 (AM) Here:

30 is minutes

1 is hour

next 2 *'s are day of month and month (in that order) and 5 is weekday

Python: CSV write by column rather than row

what about Result_* there also are generated in the loop (because i don't think it's possible to add to the csv file)

i will go like this ; generate all the data at one rotate the matrix write in the file:

A = []

A.append(range(1, 5))  # an Example of you first loop

A.append(range(5, 9))  # an Example of you second loop

data_to_write = zip(*A)

# then you can write now row by row

Regex to match string containing two names in any order

Its short and sweet

(?=.*jack)(?=.*james)

Test Cases:

_x000D_
_x000D_
[
  "xxx james xxx jack xxx",
  "jack xxx james ",
  "jack xxx jam ",
  "  jam and jack",
  "jack",
  "james",
]
.forEach(s => console.log(/(?=.*james)(?=.*jack)/.test(s)) )
_x000D_
_x000D_
_x000D_

Chrome not rendering SVG referenced via <img> tag

The svg-tag needs the namespace attribute xmlns:

<svg xmlns="http://www.w3.org/2000/svg"></svg>

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Android: converting String to int

// Convert String to Integer

// String s = "fred";  // use this if you want to test the exception below


String s = "100"; 
try
{
  // the String to int conversion happens here
  int i = Integer.parseInt(s.trim());

  // print out the value after the conversion
  System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
  System.out.println("NumberFormatException: " + nfe.getMessage());
}

Compare and contrast REST and SOAP web services?

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

By way of illustration here are few calls and their appropriate home with commentary.

getUser(User);

This is a rest operation as you are accessing a resource (data).

switchCategory(User, OldCategory, NewCategory)

REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because you need to handle multiple formats, in my experience it has actually been quite beneficial. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.

Eclipse won't compile/run java file

I was also in the same problem, check your build path in eclipse by Right Click on Project > build path > configure build path

Now check for Excluded Files, it should not have your file specified there by any means or by regex.

Cheers!image for error fix view, see Excluded field

What does numpy.random.seed(0) do?

Imagine you are showing someone how to code something with a bunch of "random" numbers. By using numpy seed they can use the same seed number and get the same set of "random" numbers.

So it's not exactly random because an algorithm spits out the numbers but it looks like a randomly generated bunch.

Deleting row from datatable in C#

This question will give you good insights on how to delete a record from a DataTable:

DataTable, How to conditionally delete rows

It would look like this:

DataRow[] drr = dt.Select("Student=' " + id + " ' "); 
foreach (var row in drr)
   row.Delete();

Don't forget that if you want to update your database, you are going to need to call the Update command. For more information on that, see this link:

http://www.codeguru.com/forum/showthread.php?t=471027

Python: Ignore 'Incorrect padding' error when base64 decoding

You can simply use base64.urlsafe_b64decode(data) if you are trying to decode a web image. It will automatically take care of the padding.

MVC Redirect to View from jQuery with parameters

This would also work I believe:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = '@Html.Raw(Url.Action("Artists", new { NestId = @NestId }))';
            window.location.href = url; 
        })

C - determine if a number is prime

Stephen Canon answered it very well!

But

  • The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3.
  • This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3).
  • So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1 = vn.
  • This is 3 times as fast as testing all m up to vn.

    int IsPrime(unsigned int number) {
        if (number <= 3 && number > 1) 
            return 1;            // as 2 and 3 are prime
        else if (number%2==0 || number%3==0) 
            return 0;     // check if number is divisible by 2 or 3
        else {
            unsigned int i;
            for (i=5; i*i<=number; i+=6) {
                if (number % i == 0 || number%(i + 2) == 0) 
                    return 0;
            }
            return 1; 
        }
    }
    

Footnotes for tables in LaTeX

What @dmckee said.

It's not difficult to write your own bespoke footnote-queuing code. What you need to do is:

  1. Write code to queue Latex code — like a hook in emacs: very standard technique, if not every Latex hacker can actually do this right;
  2. Temporarily redefine \footnote to add a footnote macro to your queue;
  3. Ensure that the hook gets called when the table/figure exits and we return to regular vertical mode.

If this is interesting, I show some code that does this.

Is a Java hashmap search really O(1)?

A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate.

pcollision = n / capacity

So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.

O(n) = O(k * n)

We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions.

pcollision x 2 = (n / capacity)2

This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to

pcollision x k = (n / capacity)k

And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.

We talk about this by saying that the hash-map has O(1) access with high probability

How do I make a C++ console program exit?

#include <cstdlib>
...
/*wherever you want it to end, e.g. in an if-statement:*/
if (T == 0)
{
exit(0);
}

Disable activity slide-in animation when launching new activity?

This works for me when disabling finish Activity animation.

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(0, 0);
}

NHibernate.MappingException: No persister for: XYZ

Make sure you have called the CreateCriteria(typeof(DomainObjectType)) method on Session for the domain object which you intent to fetch from DB.

Joda DateTime to Timestamp conversion

Actually this is not a duplicate question. And this how i solve my problem after several times :

   int offset = DateTimeZone.forID("anytimezone").getOffset(new DateTime());

This is the way to get offset from desired timezone.

Let's return to our code, we were getting timestamp from a result set of query, and using it with timezone to create our datetime.

   DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
                         DateTimeZone.forID("anytimezone"));

Now we will add our offset to the datetime, and get the timestamp from it.

    dt = dt.plusMillis(offset);
    Timestamp ts = new Timestamp(dt.getMillis());

May be this is not the actual way to get it, but it solves my case. I hope it helps anyone who is stuck here.

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

How to install pywin32 module in windows 7

are you just trying to install it, or are you looking to build from source?

If you just need to install, the easiest way is to use the MSI installers provided here:

http://sourceforge.net/projects/pywin32/files/pywin32/ (for updated versions)

make sure you get the correct version (matches Python version, 32bit/64bit, etc)

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

If you're using MVC 3 and Razor you can also use the following:

@Html.RadioButtonFor(model => model.blah, true) Yes
@Html.RadioButtonFor(model => model.blah, false) No

SELECT * FROM in MySQLi

You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.

How do I set the selected item in a drop down box

A Simple Solution: It work's for me

<div class="form-group">
    <label for="mcategory">Select Category</label>
    <select class="form-control" id="mcategory" name="mcategory" required>
        <option value="">Please select category</option>
        <?php foreach ($result_cat as $result): ?>
        <option value="<?php echo $result['name'];?>"<?php 
           if($result['name']==$mcategory){
               echo 'selected';
           } ?>><?php echo $result['name']; ?></option>
                                        }
        <?php endforeach; ?>
    </select>
</div>

How to build PDF file from binary string returned from a web-service using javascript

Detect the browser and use Data-URI for Chrome and use PDF.js as below for other browsers.

PDFJS.getDocument(url_of_pdf)
.then(function(pdf) {
    return pdf.getPage(1);
})
.then(function(page) {
    // get a viewport
    var scale = 1.5;
    var viewport = page.getViewport(scale);
    // get or create a canvas
    var canvas = ...;
    canvas.width = viewport.width;
    canvas.height = viewport.height;

    // render a page
    page.render({
        canvasContext: canvas.getContext('2d'),
        viewport: viewport
    });
})
.catch(function(err) {
    // deal with errors here!
});

How can I check if a MySQL table exists with PHP?

DO NOT USE MYSQL ANY MORE. If you must use mysqli but PDO is best:

$pdo = new PDO($dsn, $username, $pdo); // proper PDO init string here
if ($pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name'")->fetch()) // table exists.

HTTP Basic: Access denied fatal: Authentication failed

For my case, I initially tried with

git config --system --unset credential.helper

But I was getting error

error: could not lock config file C:/Program Files/Git/etc/gitconfig: Permission denied

Then tried with

git config --global --unset credential.helper

No error, but still got access denied error while git pulling.

Then went to Control Panel -> Credentials Manager > Windows Credential and deleted git account.

After that when I tried git pull again, it asked for the credentials and a new git account added in Credentails manager.

Comprehensive methods of viewing memory usage on Solaris

The command free is nice. Takes a short while to understand the "+/- buffers/cache", but the idea is that cache and buffers doesn't really count when evaluating "free", as it can be dumped right away. Therefore, to see how much free (and used) memory you have, you need to remove the cache/buffer usage - which is conveniently done for you.

curl : (1) Protocol https not supported or disabled in libcurl

I solve it just by changing 'http://webname...' to "http://webname..."

Notice the quote. It should be double (") instead of single (').

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

How to create a GUID / UUID

I adjusted my own UUID/GUID generator with some extras here.

I'm using the following Kybos random number generator to be a bit more cryptographically sound.

Below is my script with the Mash and Kybos methods from baagoe.com excluded.

//UUID/Guid Generator
// use: UUID.create() or UUID.createSequential()
// convenience:  UUID.empty, UUID.tryParse(string)
(function(w){
  // From http://baagoe.com/en/RandomMusings/javascript/
  // Johannes Baagøe <[email protected]>, 2010
  //function Mash() {...};

  // From http://baagoe.com/en/RandomMusings/javascript/
  //function Kybos() {...};

  var rnd = Kybos();

  //UUID/GUID Implementation from http://frugalcoder.us/post/2012/01/13/javascript-guid-uuid-generator.aspx
  var UUID = {
    "empty": "00000000-0000-0000-0000-000000000000"
    ,"parse": function(input) {
      var ret = input.toString().trim().toLowerCase().replace(/^[\s\r\n]+|[\{\}]|[\s\r\n]+$/g, "");
      if ((/[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}/).test(ret))
        return ret;
      else
        throw new Error("Unable to parse UUID");
    }
    ,"createSequential": function() {
      var ret = new Date().valueOf().toString(16).replace("-","")
      for (;ret.length < 12; ret = "0" + ret);
      ret = ret.substr(ret.length-12,12); //only least significant part
      for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));
      return [ret.substr(0,8), ret.substr(8,4), "4" + ret.substr(12,3), "89AB"[Math.floor(Math.random()*4)] + ret.substr(16,3),  ret.substr(20,12)].join("-");
    }
    ,"create": function() {
      var ret = "";
      for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));
      return [ret.substr(0,8), ret.substr(8,4), "4" + ret.substr(12,3), "89AB"[Math.floor(Math.random()*4)] + ret.substr(16,3),  ret.substr(20,12)].join("-");
    }
    ,"random": function() {
      return rnd();
    }
    ,"tryParse": function(input) {
      try {
        return UUID.parse(input);
      } catch(ex) {
        return UUID.empty;
      }
    }
  };
  UUID["new"] = UUID.create;

  w.UUID = w.Guid = UUID;
}(window || this));

What is the id( ) function used for?

The answer is pretty much never. IDs are mainly used internally to Python.

The average Python programmer will probably never need to use id() in their code.

How to integrate SAP Crystal Reports in Visual Studio 2017

Crystal Reports SP 19 does not support Visual Studio 2017. According to SAP they are targeting Visual Studio 2017 compatibility in SP 20 which is tentatively scheduled for June 2017.

How to see the values of a table variable at debug time in T-SQL?

DECLARE @v XML = (SELECT * FROM <tablename> FOR XML AUTO)

Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add @v to the watches window.

enter image description here

How to free memory from char array in C

char arr[3] = "bo";

The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.

Android ADB device offline, can't issue commands

late but I found the easiest way just go to DDMS and follow as shown in image...

enter image description here

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Should image size be defined in the img tag height/width attributes or in CSS?

Definitely not both. Other than that I'd have to say it's a personal preference. I'd use css if I had many images the same size to reduce code.

.my_images img {width: 20px; height:20px}

In the long term CSS may win out due to HTML attribute deprecation and more likely due to the growth of vector image formats like SVG where it can actually make sense to scale images using non-pixel based units like % or em.

How to align input forms in HTML

Clément's answer is by far the best. Here's a somewhat improved answer, showing different possible alignments, including left-center-right aligned buttons:

_x000D_
_x000D_
label_x000D_
{ padding-right:8px;_x000D_
}_x000D_
_x000D_
.FAligned,.FAlignIn_x000D_
{ display:table;_x000D_
}_x000D_
_x000D_
.FAlignIn_x000D_
{ width:100%;_x000D_
}_x000D_
_x000D_
.FRLeft,.FRRight,.FRCenter_x000D_
{ display:table-row;_x000D_
 white-space:nowrap;_x000D_
}_x000D_
_x000D_
.FCLeft,.FCRight,.FCCenter_x000D_
{ display:table-cell;_x000D_
}_x000D_
_x000D_
.FRLeft,.FCLeft,.FILeft_x000D_
{ text-align:left;_x000D_
}_x000D_
_x000D_
.FRRight,.FCRight,.FIRight_x000D_
{ text-align:right;_x000D_
}_x000D_
_x000D_
.FRCenter,.FCCenter,.FICenter_x000D_
{ text-align:center;_x000D_
}
_x000D_
<form class="FAligned">_x000D_
 <div class="FRLeft">_x000D_
  <p class="FRLeft">_x000D_
   <label for="Input0" class="FCLeft">Left:</label>_x000D_
   <input id="Input0" type="text" size="30"  placeholder="Left Left Left" class="FILeft"/>_x000D_
  </p>_x000D_
  <p class="FRLeft">_x000D_
   <label for="Input1" class="FCRight">Left Right Left:</label>_x000D_
   <input id="Input1" type="text" size="30"  placeholder="Left Right Left" class="FILeft"/>_x000D_
  </p>_x000D_
  <p class="FRRight">_x000D_
   <label for="Input2" class="FCLeft">Right Left Left:</label>_x000D_
   <input id="Input2" type="text" size="30"  placeholder="Right Left Left" class="FILeft"/>_x000D_
  </p>_x000D_
  <p class="FRRight">_x000D_
   <label for="Input3" class="FCRight">Right Right Left:</label>_x000D_
   <input id="Input3" type="text" size="30"  placeholder="Right Right Left" class="FILeft"/>_x000D_
  </p>_x000D_
  <p class="FRLeft">_x000D_
   <label for="Input4" class="FCLeft">Left Left Right:</label>_x000D_
   <input id="Input4" type="text" size="30"  placeholder="Left Left Right" class="FIRight"/>_x000D_
  </p>_x000D_
  <p class="FRLeft">_x000D_
   <label for="Input5" class="FCRight">Left Right Right:</label>_x000D_
   <input id="Input5" type="text" size="30"  placeholder="Left Right Right" class="FIRight"/>_x000D_
  </p>_x000D_
  <p class="FRRight">_x000D_
   <label for="Input6" class="FCLeft">Right Left Right:</label>_x000D_
   <input id="Input6" type="text" size="30"  placeholder="Right Left Right" class="FIRight"/>_x000D_
  </p>_x000D_
  <p class="FRRight">_x000D_
   <label for="Input7" class="FCRight">Right:</label>_x000D_
   <input id="Input7" type="text" size="30"  placeholder="Right Right Right" class="FIRight"/>_x000D_
  </p>_x000D_
  <p class="FRCenter">_x000D_
   <label for="Input8" class="FCCenter">And centralised is also possible:</label>_x000D_
   <input id="Input8" type="text" size="60"  placeholder="Center in the centre" class="FICenter"/>_x000D_
  </p>_x000D_
 </div>_x000D_
 <div class="FAlignIn">_x000D_
  <div class="FRCenter">_x000D_
   <div class="FCLeft"><button type="button">Button on the Left</button></div>_x000D_
   <div class="FCCenter"><button type="button">Button on the Centre</button></div>_x000D_
   <div class="FCRight"><button type="button">Button on the Right</button></div>_x000D_
  </div>_x000D_
 </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

I added some padding on the right of all labels (padding-right:8px) just to make the example slight less horrible looking, but that should be done more carefully in a real project (adding padding to all other elements would also be a good idea).

What's the best way to convert a number to a string in JavaScript?

It seems similar results when using node.js. I ran this script:

let bar;
let foo = ["45","foo"];

console.time('string concat testing');
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo;
}
console.timeEnd('string concat testing');


console.time("string obj testing");
for (let i = 0; i < 10000000; i++) {
    bar = String(foo);
}
console.timeEnd("string obj testing");

console.time("string both");
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo + "";
}
console.timeEnd("string both");

and got the following results:

? node testing.js
string concat testing: 2802.542ms
string obj testing: 3374.530ms
string both: 2660.023ms

Similar times each time I ran it.

Drop all data in a pandas dataframe

My favorite:

df = df.iloc[0:0]

But be aware df.index.max() will be nan. To add items I use:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data

How do I set vertical space between list items?

HTML

<ul>
   <li>A</li>
   <li>B</li>
   <li>C</li>
   <li>D</li>
   <li>E</li>
</ul>

CSS

li:not(:last-child) {
    margin-bottom: 5px;
}

EDIT: If you don't use the special case for the last li element your list will have a small spacing afterwards which you can see here: http://jsfiddle.net/wQYw7/

Now compare that with my solution: http://jsfiddle.net/wQYw7/1/

Sure this doesn't work in older browsers but you can easily use js extensions which will enable this for older browsers.

How to pass variables from one php page to another without form?

If you are trying to access the variable from another PHP file directly, you can include that file with include() or include_once(), giving you access to that variable. Note that this will include the entire first file in the second file.

What is the difference between a stored procedure and a view?

Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view

CREATE View vw_user_profile AS 
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id

I CAN update the data ... as an example I can do either of these ...

Update vw_user_profile Set profile_description='Manager' where user_id=4

or

Update tbl_profile Set profile_description='Manager' where user_id=4

You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL. However you can sometimes INSERT into a view ...

I created a view on an existing table using ...

Create View Junk as SELECT * from [TableName]

THEN

Insert into junk (Code,name) values 
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')

and

DELETE from Junk Where ID>4

Both the INSERT and the DELETE worked in this case

Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.

If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.

jQuery check if <input> exists and has a value

You can create your own custom selector :hasValue and then use that to find, filter, or test any other jQuery elements.

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

Then you can find elements like this:

var data = $("form input:hasValue").serialize();

Or test the current element with .is()

var elHasValue = $("#name").is(":hasValue");

_x000D_
_x000D_
jQuery.expr[':'].hasValue = function(el) {_x000D_
  return el.value != "";_x000D_
};_x000D_
_x000D_
_x000D_
var data = $("form input:hasValue").serialize();_x000D_
console.log(data)_x000D_
_x000D_
_x000D_
var elHasValue = $("[name='LastName']").is(":hasValue");_x000D_
console.log(elHasValue)
_x000D_
label { display: block; margin-top:10px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
  <label>_x000D_
    First Name:_x000D_
    <input type="text" name="FirstName" value="Frida" />_x000D_
  </label>_x000D_
_x000D_
  <label>_x000D_
    Last Name:_x000D_
    <input type="text" name="LastName" />_x000D_
  </label>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Further Reading:

How to SELECT WHERE NOT EXIST using LINQ?

How about..

var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)

Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest

Should I use <i> tag for icons instead of <span>?

I also found this to be useful when i wanted to place an icon with absolute positioning inside a link <a> tag.

I thought about the <img> tag first, but default styling of those tags inside links typically have border styling and/or shadow effects. Plus, it feels wrong to use an <img> tag without defining an "src" attribute whereas i'm using a background-image style sheet declaration so that the image doesn't ghost and drag.

At this point you're thinking of tags like <span> or <i> - in which case <i> makes so much sense as this type of icon.

All in all i think its benefit besides being intuitive is that it requires minimal style sheet adjustments to make this tag work as an icon.

Deep-Learning Nan loss reasons

There are lots of things I have seen make a model diverge.

  1. Too high of a learning rate. You can often tell if this is the case if the loss begins to increase and then diverges to infinity.

  2. I am not to familiar with the DNNClassifier but I am guessing it uses the categorical cross entropy cost function. This involves taking the log of the prediction which diverges as the prediction approaches zero. That is why people usually add a small epsilon value to the prediction to prevent this divergence. I am guessing the DNNClassifier probably does this or uses the tensorflow opp for it. Probably not the issue.

  3. Other numerical stability issues can exist such as division by zero where adding the epsilon can help. Another less obvious one if the square root who's derivative can diverge if not properly simplified when dealing with finite precision numbers. Yet again I doubt this is the issue in the case of the DNNClassifier.

  4. You may have an issue with the input data. Try calling assert not np.any(np.isnan(x)) on the input data to make sure you are not introducing the nan. Also make sure all of the target values are valid. Finally, make sure the data is properly normalized. You probably want to have the pixels in the range [-1, 1] and not [0, 255].

  5. The labels must be in the domain of the loss function, so if using a logarithmic-based loss function all labels must be non-negative (as noted by evan pu and the comments below).

Git 'fatal: Unable to write new index file'

If you're on a Windows box, make sure the program you're using, whether it's Source Tree or a git terminal, is running as administrator. I was getting the same exact error message. You can either right click on the program to run as administrator or change its properties to always run as administrator.

How to mount a single file in a volume

You can also use a relative path in your docker-compose.yml file like this (tested on Windows host, Linux container):

volumes:
    - ./test.conf:/fluentd/etc/test.conf

Change background color of iframe issue

just building on what Chetabahana wrote, I found that adding a short delay to the JS function helped on a site I was working on. It meant that the function kicked in after the iframe loaded. You can play around with the delay.

var delayInMilliseconds = 500; // half a second

setTimeout(function() { 

   var iframe = document.getElementsByTagName('iframe')[0];
   iframe.style.background = 'white';
   iframe.contentWindow.document.body.style.backgroundColor = 'white';

}, delayInMilliseconds);

I hope this helps!

How to compare only date in moment.js

The docs are pretty clear that you pass in a second parameter to specify granularity.

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

For your case you would pass 'day' as the second parameter.

unix diff side-to-side results?

You should have sdiff for side-by-side merge of file differences. Take a read of man sdiff for the full story.

hibernate: LazyInitializationException: could not initialize proxy

I think Piko means in his response that there is the hbm file. I have a file called Tax.java. The mapping information are saved in the hbm (=hibernate mapping) file. In the class tag there is a property called lazy. Set that property to true. The following hbm example shows a way to set the lazy property to false.

` id ...'

If you are using Annotations instead look in the hibernate documenation. http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

I hope that helped.

Ignoring SSL certificate in Apache HttpClient 4.3

As an addition to the answer of @mavroprovato, if you want to trust all certificates instead of just self-signed, you'd do (in the style of your code)

builder.loadTrustMaterial(null, new TrustStrategy(){
    public boolean isTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        return true;
    }
});

or (direct copy-paste from my own code):

import javax.net.ssl.SSLContext;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.ssl.SSLContexts;

// ...

        SSLContext sslContext = SSLContexts
                .custom()
                //FIXME to contain real trust store
                .loadTrustMaterial(new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                        return true;
                    }
                })
                .build();

And if you want to skip hostname verification as well, you need to set

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
            sslsf).setSSLHostnameVerifier( NoopHostnameVerifier.INSTANCE).build();

as well. (ALLOW_ALL_HOSTNAME_VERIFIER is deprecated).

Obligatory warning: you shouldn't really do this, accepting all certificates is a bad thing. However there are some rare use cases where you want to do this.

As a note to code previously given, you'll want to close response even if httpclient.execute() throws an exception

CloseableHttpResponse response = null;
try {
    response = httpclient.execute(httpGet);
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
}
finally {
    if (response != null) {
        response.close();
    }
}

Code above was tested using

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

And for the interested, here's my full test set:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class TrustAllCertificatesTest {
    final String expiredCertSite = "https://expired.badssl.com/";
    final String selfSignedCertSite = "https://self-signed.badssl.com/";
    final String wrongHostCertSite = "https://wrong.host.badssl.com/";

    static final TrustStrategy trustSelfSignedStrategy = new TrustSelfSignedStrategy();
    static final TrustStrategy trustAllStrategy = new TrustStrategy(){
        public boolean isTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            return true;
        }
    };

    @Test
    public void testSelfSignedOnSelfSignedUsingCode() throws Exception {
        doGet(selfSignedCertSite, trustSelfSignedStrategy);
    }
    @Test(expected = SSLHandshakeException.class)
    public void testExpiredOnSelfSignedUsingCode() throws Exception {
        doGet(expiredCertSite, trustSelfSignedStrategy);
    }
    @Test(expected = SSLPeerUnverifiedException.class)
    public void testWrongHostOnSelfSignedUsingCode() throws Exception {
        doGet(wrongHostCertSite, trustSelfSignedStrategy);
    }

    @Test
    public void testSelfSignedOnTrustAllUsingCode() throws Exception {
        doGet(selfSignedCertSite, trustAllStrategy);
    }
    @Test
    public void testExpiredOnTrustAllUsingCode() throws Exception {
        doGet(expiredCertSite, trustAllStrategy);
    }
    @Test(expected = SSLPeerUnverifiedException.class)
    public void testWrongHostOnTrustAllUsingCode() throws Exception {
        doGet(wrongHostCertSite, trustAllStrategy);
    }

    @Test
    public void testSelfSignedOnAllowAllUsingCode() throws Exception {
        doGet(selfSignedCertSite, trustAllStrategy, NoopHostnameVerifier.INSTANCE);
    }
    @Test
    public void testExpiredOnAllowAllUsingCode() throws Exception {
        doGet(expiredCertSite, trustAllStrategy, NoopHostnameVerifier.INSTANCE);
    }
    @Test
    public void testWrongHostOnAllowAllUsingCode() throws Exception {
        doGet(expiredCertSite, trustAllStrategy, NoopHostnameVerifier.INSTANCE);
    }

    public void doGet(String url, TrustStrategy trustStrategy, HostnameVerifier hostnameVerifier) throws Exception {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(trustStrategy);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
                sslsf).setSSLHostnameVerifier(hostnameVerifier).build();

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        try {
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    }
    public void doGet(String url, TrustStrategy trustStrategy) throws Exception {

        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(trustStrategy);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
                sslsf).build();

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        try {
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    }
}

(working test project in github)

Efficiency of Java "Double Brace Initialization"?

To create sets you can use a varargs factory method instead of double-brace initialisation:

public static Set<T> setOf(T ... elements) {
    return new HashSet<T>(Arrays.asList(elements));
}

The Google Collections library has lots of convenience methods like this, as well as loads of other useful functionality.

As for the idiom's obscurity, I encounter it and use it in production code all the time. I'd be more concerned about programmers who get confused by the idiom being allowed to write production code.

What does collation mean?

Besides the "accented letters are sorted differently than unaccented ones" in some Western European languages, you must take into account the groups of letters, which sometimes are sorted differently, also.

Traditionally, in Spanish, "ch" was considered a letter in its own right, same with "ll" (both of which represent a single phoneme), so a list would get sorted like this:

  • caballo
  • cinco
  • coche
  • charco
  • chocolate
  • chueco
  • dado
  • (...)
  • lámpara
  • luego
  • llanta
  • lluvia
  • madera

Notice all the words starting with single c go together, except words starting with ch which go after them, same with ll-starting words which go after all the words starting with a single l. This is the ordering you'll see in old dictionaries and encyclopedias, sometimes even today by very conservative organizations.

The Royal Academy of the Language changed this to make it easier for Spanish to be accomodated in the computing world. Nevertheless, ñ is still considered a different letter than n and goes after it, and before o. So this is a correctly ordered list:

  • Namibia
  • número
  • ñandú
  • ñú
  • obra
  • ojo

By selecting the correct collation, you get all this done for you, automatically :-)

How to append a date in batch files

I've found two ways that work regardless of the date settings.

On my pc, date/t returns 2009-05-27

You can either access the registry and read the regional settings (HKEY_CURRENT_USER\Control Panel\International)

Or use a vbscript. This is the ugly batch file/vbscript hybrid I created some time ago....

@Echo Off
set rnd=%Random%
set randfilename=x%rnd%.vbs

::create temp vbscript file
Echo Dim DayofWeek(7) >  %temp%\%randfilename%
Echo DayofWeek(1)="Sun" >> %temp%\%randfilename%
Echo DayofWeek(2)="Mon" >> %temp%\%randfilename%
Echo DayofWeek(3)="Tue" >> %temp%\%randfilename%
Echo DayofWeek(4)="Wed" >> %temp%\%randfilename%
Echo DayofWeek(5)="Thu" >> %temp%\%randfilename%
Echo DayofWeek(6)="Fri" >> %temp%\%randfilename%
Echo DayofWeek(7)="Sat" >> %temp%\%randfilename%
Echo DayofWeek(0)=DayofWeek(Weekday(now)) >> %temp%\%randfilename%
Echo Mon=Left(MonthName(Month(now),1),3) >> %temp%\%randfilename%
Echo MonNumeric=right ( "00" ^& Month(now) , 2) >> %temp%\%randfilename%
Echo wscript.echo ( Year(Now) ^& " " ^& MonNumeric ^& " " ^& Mon ^& " "  _ >> %temp%\%randfilename%
Echo ^& right("00" ^& Day(now),2) ^& " "^& dayofweek(0) ^& " "^& _ >> %temp%\%randfilename%
Echo right("00" ^& Hour(now),2)) _ >> %temp%\%randfilename%
Echo ^&":"^& Right("00" ^& Minute(now),2) ^&":"^& Right("00" ^& Second(Now),2)  >> %temp%\%randfilename%

::set the output into vars
if "%1" == "" FOR /f "usebackq tokens=1,2,3,4,5,6" %%A in (`start /wait /b cscript //nologo %temp%\%randfilename%`) do Set Y2KYear=%%A& Set MonthNumeric=%%B& Set Month=%%C& Set Day=%%D& Set DayofWeek=%%E& Set Time=%%F
set year=%y2kyear:~2,2%

::cleanup
del %temp%\%randfilename%

It's not pretty, but it works.

SQL Server 2008: how do I grant privileges to a username?

If you really want them to have ALL rights:

use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go

git clone from another directory

It's as easy as it looks.

14:27:05 ~$ mkdir gittests
14:27:11 ~$ cd gittests/
14:27:13 ~/gittests$ mkdir localrepo
14:27:20 ~/gittests$ cd localrepo/
14:27:21 ~/gittests/localrepo$ git init
Initialized empty Git repository in /home/andwed/gittests/localrepo/.git/
14:27:22 ~/gittests/localrepo (master #)$ cd ..
14:27:35 ~/gittests$ git clone localrepo copyoflocalrepo
Cloning into 'copyoflocalrepo'...
warning: You appear to have cloned an empty repository.
done.
14:27:42 ~/gittests$ cd copyoflocalrepo/
14:27:46 ~/gittests/copyoflocalrepo (master #)$ git status
On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)
14:27:46 ~/gittests/copyoflocalrepo (master #)$ 

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>:

This tells Spring that I am going to use Annotated beans as spring bean and those would be wired through @Autowired annotation, instead of declaring in spring config xml file.

<context:component-scan base-package="com.test..."> :

This tells Spring container, where to start searching those annotated beans. Here spring will search all sub packages of the base package.

How to get the Power of some Integer in Swift language?

Other than that your variable declarations have syntax errors, this works exactly how you expected it to. All you have to do is cast a and b to Double and pass the values to pow. Then, if you're working with 2 Ints and you want an Int back on the other side of the operation, just cast back to Int.

import Darwin 

let a: Int = 3
let b: Int = 3

let x: Int = Int(pow(Double(a),Double(b)))

Is there a minlength validation attribute in HTML5?

The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.

An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
        <script type="text/javascript">
            jQuery.validator.setDefaults({
                debug: true,
                success: "valid"
            });;
        </script>

        <script>
            $(document).ready(function(){
                $("#myform").validate({
                    rules: {
                        field: {
                            required: true,
                            minlength: 3
                        }
                    }
                });
            });
        </script>
    </head>

    <body>
        <form id="myform">
            <label for="field">Required, Minimum length 3: </label>
            <input class="left" id="field" name="field" />
            <br/>
            <input type="submit" value="Validate!" />
        </form>
    </body>

</html>

Watching variables in SSIS during debug

I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )

How do I increment a DOS variable in a FOR /F loop?

What about this simple code, works for me and on Windows 7

set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin

:end

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

bootstrap multiselect get selected values

the solution what I found to work in my case

$('#multiselect1').multiselect({
    selectAllValue: 'multiselect-all',
    enableCaseInsensitiveFiltering: true,
    enableFiltering: true,
    maxHeight: '300',
    buttonWidth: '235',
    onChange: function(element, checked) {
        var brands = $('#multiselect1 option:selected');
        var selected = [];
        $(brands).each(function(index, brand){
            selected.push([$(this).val()]);
        });

        console.log(selected);
    }
}); 

Best way to check for IE less than 9 in JavaScript without library

Using conditional comments, you can create a script block that will only get executed in IE less than 9.

<!--[if lt IE 9 ]>
<script>
var is_ie_lt9 = true;
</script>
<![endif]--> 

Of course, you could precede this block with a universal block that declares var is_ie_lt9=false, which this would override for IE less than 9. (In that case, you'd want to remove the var declaration, as it would be repetitive).

EDIT: Here's a version that doesn't rely on in-line script blocks (can be run from an external file), but doesn't use user agent sniffing:

Via @cowboy:

with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}

Execute JavaScript code stored as a string

eval(s);

But this can be dangerous if you are taking data from users, although I suppose if they crash their own browser thats their problem.

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

How to automatically generate getters and setters in Android Studio

Use Ctrl+Enter on Mac to get list of options to generate setter, getter, constructor etc

enter image description here

Efficient way to do batch INSERTS with JDBC

You can use addBatch and executeBatch for batch insert in java See the Example : Batch Insert In Java

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

How do I compile C++ with Clang?

I do not know why there is no answer directly addressing the problem. When you want to compile C++ program, it is best to use clang++. For example, the following works for me:

clang++ -Wall -std=c++11 test.cc -o test

If compiled correctly, it will produce the executable file test, and you can run the file by using ./test.

Or you can just use clang++ test.cc to compile the program. It will produce a default executable file named a.out. Use ./a.out to run the file.

The whole process is a lot like g++ if you are familiar with g++. See this post to check which warnings are included with -Wall option. This page shows a list of diagnostic flags supported by Clang.

A note on using clang -x c++: Kim Gräsman says that you can also use clang -x c++ to compile cpp programs, but that may not be true. For example, I am having a simple program below:

#include <iostream>
#include <vector>

int main() {
    /* std::vector<int> v = {1, 2, 3, 4, 5}; */
    std::vector<int> v(10, 5);
    int sum = 0;
    for (int i = 0; i < v.size(); i++){
        sum += v[i]*2;
    }
    std::cout << "sum is " << sum << std::endl;
    return 0;
}                                                      

clang++ test.cc -o test will compile successfully, but clang -x c++ will not, showing a lot undefined references errors. So I guess they are not exactly equivalent. It is best to use clang++ instead of clang -x c++ when compiling c++ programs to avoid extra troubles.

  • clang version: 11.0.0
  • Platform: Ubuntu 16.04

How to find out when a particular table was created in Oracle?

Try this query:

SELECT sysdate FROM schema_name.table_name;

This should display the timestamp that you might need.

How to change Jquery UI Slider handle

You also should set border:none to that css class.

How do I limit the number of results returned from grep?

For 2 use cases:

  1. I only want n overall results, not n results per file, the grep -m 2 is per file max occurrence.
  2. I often use git grep which doesn't take -m

A good alternative in these scenarios is grep | sed 2q to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html

Convert a date format in PHP

There are two ways to implement this:

1.

    $date = strtotime(date);
    $new_date = date('d-m-Y', $date);

2.

    $cls_date = new DateTime($date);
    echo $cls_date->format('d-m-Y');

Determine the number of rows in a range

Why not use an Excel formula to determine the rows? For instance, if you are looking for how many cells contain data in Column A use this:

=COUNTIFS(A:A,"<>")

You can replace <> with any value to get how many rows have that value in it.

=COUNTIFS(A:A,"2008")

This can be used for finding filled cells in a row too.

Create a symbolic link of directory in Ubuntu

In script is usefull something like this:

if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi

it prevents before re-create "bad" looped symlink after re-run script

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

Oracle insert from select into table with more columns

Put 0 as default in SQL or add 0 into your area of table

Using other keys for the waitKey() function of opencv

You can use ord() function in Python for that.

For example, if you want to trigger 'a' key press, do as follows :

if cv2.waitKey(33) == ord('a'):
   print "pressed a"

See a sample code here: Drawing Histogram

UPDATE :

To find the key value for any key is to print the key value using a simple script as follows :

import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
    cv2.imshow('img',img)
    k = cv2.waitKey(33)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue
    else:
        print k # else print its value

With this code, I got following values :

Upkey : 2490368
DownKey : 2621440
LeftKey : 2424832
RightKey: 2555904
Space : 32
Delete : 3014656
...... # Continue yourself :)

What are the safe characters for making URLs?

From the context you describe, I suspect that what you're actually trying to make is something called an 'SEO slug'. The best general known practice for those is:

  1. Convert to lower-case
  2. Convert entire sequences of characters other than a-z and 0-9 to one hyphen (-) (not underscores)
  3. Remove 'stop words' from the URL, i.e. not-meaningfully-indexable words like 'a', 'an', and 'the'; Google 'stop words' for extensive lists

So, as an example, an article titled "The Usage of !@%$* to Represent Swearing In Comics" would get a slug of "usage-represent-swearing-comics".

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

If you are using rbenv then make sure that you run the "rbenv rehash" command after you set local or global ruby version. It solved the issue for me.

rbenv rehash

Can HTTP POST be limitless?

Different IIS web servers can process different amounts of data in the 'header', according to this (now deleted) article; http://classicasp.aspfaq.com/forms/what-is-the-limit-on-form/post-parameters.html;

Note that there is no limit on the number of FORM elements you can pass via POST, but only on the aggregate size of all name/value pairs. While GET is limited to as low as 1024 characters, POST data is limited to 2 MB on IIS 4.0, and 128 KB on IIS 5.0. Each name/value is limited to 1024 characters, as imposed by the SGML spec. Of course this does not apply to files uploaded using enctype='multipart/form-data' ... I have had no problems uploading files in the 90 - 100 MB range using IIS 5.0, aside from having to increase the server.scriptTimeout value as well as my patience!

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Assign a synthesizable initial value to a reg in Verilog

The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?

module top (
    input wire clk,
    output wire [7:0] led   
);

wire [7:0] data_reg ; 
assign data_reg   = 8'b10101011;
assign led        = data_reg;

endmodule

If you actually want a flop where you can change the value, the default would be in the reset clause.

module top
(
    input        clk,
    input        rst_n,
    input  [7:0] data,
    output [7:0] led   
 );

reg [7:0] data_reg ; 
always @(posedge clk or negedge rst_n) begin
  if (!rst_n)
    data_reg <= 8'b10101011;
  else
    data_reg <= data ; 
end

assign led = data_reg;

endmodule

Hope this helps

ENOENT, no such file or directory

I was also plagued by this error, and after trying all the other answers, magically found the following solution:

Delete package-lock.json and the node_modules folder, then run npm install again.

If that doesn't work, try running these in order:

npm install
npm cache clean --force
npm install -g npm
npm install

(taken from @Thisuri's answer and @Mathias Falci's comment respectively)

and then re-deleting the above files and re-running npm install.

Worked for me!

UILabel - auto-size label to fit text?

I created some methods based Daniel's reply above.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
    CGSize maximumLabelSize     = CGSizeMake(290, FLT_MAX);

    CGSize expectedLabelSize    = [text sizeWithFont:label.font
                                constrainedToSize:maximumLabelSize
                                    lineBreakMode:label.lineBreakMode];

    return expectedLabelSize.height;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label
{
    CGRect newFrame         = label.frame;
    newFrame.size.height    = [self heightForLabel:label withText:label.text];
    label.frame             = newFrame;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
    label.text              = text;
    [self resizeHeightToFitForLabel:label];
}

Comments in Android Layout xml

As other said, the comment in XML are like this

<!-- this is a comment -->

Notice that they can span on multiple lines

<!--
    This is a comment
    on multiple lines
-->

But they cannot be nested

<!-- This <!-- is a comment --> This is not -->

Also you cannot use them inside tags

<EditText <!--This is not valid--> android:layout_width="fill_parent" />

CodeIgniter: Create new helper?

To create a new helper you can follow the instructions from The Pixel Developer, but my advice is not to create a helper just for the logic required by a particular part of a particular application. Instead, use that logic in the controller to set the arrays to their final intended values. Once you got that, you pass them to the view using the Template Parser Class and (hopefully) you can keep the view clean from anything that looks like PHP using simple variables or variable tag pairs instead of echos and foreachs. i.e:

{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}

instead of

<?php foreach ($blog_entries as $blog_entry): ?>
<h5><?php echo $blog_entry['title']; ?></h5>
<p><?php echo $blog_entry['body']; ?></p>
<?php endforeach; ?>

Another benefit from this approach is that you don't have to worry about adding the CI instance as you would if you use custom helpers to do all the work.